0&&void 0!==arguments[0]?arguments[0]:{},n=r.duration,i=void 0===n?500:n,o=r.easing,a=void 0===o?easeInOutQuad:o,c=r.delay,l=void 0===c?0:c,u=null,s=!0,d=!1,p=null,f=createObject({interpolate:function(r){s||null===p||(null===u&&(u=r),r-u=0?a(d?1-t:t):0)*p)):(e=1,t=d?0:1,f.onupdate(t*p),f.oncomplete(t*p),s=!0)))},target:{get:function(){return d?0:p},set:function(e){if(null===p)return p=e,f.onupdate(e),void f.oncomplete(e);e3&&void 0!==arguments[3]&&arguments[3];(t=Array.isArray(t)?t:[t]).forEach(function(t){e.forEach(function(e){var i=e,o=function(){return r[e]},a=function(t){return r[e]=t};\"object\"===_typeof(e)&&(i=e.key,o=e.getter||o,a=e.setter||a),t[i]&&!n||(t[i]={get:o,set:a})})})},animations=function(e){var t=e.mixinConfig,r=e.viewProps,n=e.viewInternalAPI,i=e.viewExternalAPI,o=_objectSpread({},r),a=[];return forin(t,function(e,t){var c=createAnimator(t);c&&(c.onupdate=function(t){r[e]=t},c.target=o[e],addGetSet([{key:e,setter:function(e){c.target!==e&&(c.target=e)},getter:function(){return r[e]}}],[n,i],r,!0),a.push(c))}),{write:function(e){var t=!0;return a.forEach(function(r){r.resting||(t=!1),r.interpolate(e)}),t},destroy:function(){}}},addEvent=function(e){return function(t,r){e.addEventListener(t,r)}},removeEvent=function(e){return function(t,r){e.removeEventListener(t,r)}},listeners=function(e){var t=e.viewExternalAPI,r=e.view,n=[],i=addEvent(r.element),o=removeEvent(r.element);return t.on=function(e,t){n.push({type:e,fn:t}),i(e,t)},t.off=function(e,t){n.splice(n.findIndex(function(r){return r.type===e&&r.fn===t}),1),o(e,t)},{write:function(){return!0},destroy:function(){n.forEach(function(e){o(e.type,e.fn)})}}},apis=function(e){var t=e.mixinConfig,r=e.viewProps,n=e.viewExternalAPI;addGetSet(t,n,r)},defaults={opacity:1,scaleX:1,scaleY:1,translateX:0,translateY:0,rotateX:0,rotateY:0,rotateZ:0,originX:0,originY:0},styles=function(e){var t=e.mixinConfig,r=e.viewProps,n=e.viewInternalAPI,i=e.viewExternalAPI,o=e.view,a=_objectSpread({},r),c={};addGetSet(t,[n,i],r);var l=function(){return o.rect?getViewRect(o.rect,o.childViews,[r.translateX||0,r.translateY||0],[r.scaleX||0,r.scaleY||0]):null};return n.rect={get:l},i.rect={get:l},t.forEach(function(e){r[e]=void 0===a[e]?defaults[e]:a[e]}),{write:function(){if(propsHaveChanged(c,r))return applyStyles(o.element,r),Object.assign(c,_objectSpread({},r)),!0},destroy:function(){}}},propsHaveChanged=function(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!0;for(var r in t)if(t[r]!==e[r])return!0;return!1},applyStyles=function(e,t){var r=t.opacity,n=t.perspective,i=t.translateX,o=t.translateY,a=t.scaleX,c=t.scaleY,l=t.rotateX,u=t.rotateY,s=t.rotateZ,d=t.originX,p=t.originY,f=t.width,h=t.height,g=\"\",m=\"\";null==d&&null==p||(m+=\"transform-origin: \".concat(d||0,\"px \").concat(p||0,\"px;\")),null!=n&&(g+=\"perspective(\".concat(n,\"px) \")),null==i&&null==o||(g+=\"translate3d(\".concat(i||0,\"px, \").concat(o||0,\"px, 0) \")),null==a&&null==c||(g+=\"scale3d(\".concat(null!=a?a:1,\", \").concat(null!=c?c:1,\", 1) \")),null!=s&&(g+=\"rotateZ(\".concat(s,\"rad) \")),null!=l&&(g+=\"rotateX(\".concat(l,\"rad) \")),null!=u&&(g+=\"rotateY(\".concat(u,\"rad) \")),\"\"!=g&&(m+=\"transform:\".concat(g,\";\")),null!=r&&(m+=\"opacity:\".concat(r,\";\"),r<1&&(m+=\"pointer-events:none;\"),0===r&&\"BUTTON\"===e.nodeName&&(m+=\"visibility:hidden;\")),null!=f&&(m+=\"width:\".concat(f,\"px;\")),null!=h&&(m+=\"height:\".concat(h,\"px;\"));var v=e.elementCurrentStyle||\"\";m.length===v.length&&m===v||(e.style.cssText=m,e.elementCurrentStyle=m)},Mixins={styles:styles,listeners:listeners,animations:animations,apis:apis},updateRect=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return t.layoutCalculated||(e.paddingTop=parseInt(r.paddingTop,10)||0,e.marginTop=parseInt(r.marginTop,10)||0,e.marginRight=parseInt(r.marginRight,10)||0,e.marginBottom=parseInt(r.marginBottom,10)||0,e.marginLeft=parseInt(r.marginLeft,10)||0,t.layoutCalculated=!0),e.left=t.offsetLeft||0,e.top=t.offsetTop||0,e.width=t.offsetWidth||0,e.height=t.offsetHeight||0,e.right=e.left+e.width,e.bottom=e.top+e.height,e.scrollTop=t.scrollTop,e.hidden=null===t.offsetParent&&\"fixed\"!==r.position,e},IS_BROWSER=\"undefined\"!=typeof window&&void 0!==window.document,isBrowser=function(){return IS_BROWSER},testElement=isBrowser()?createElement(\"svg\"):{},getChildCount=\"children\"in testElement?function(e){return e.children.length}:function(e){return e.childNodes.length},createView=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.tag,r=void 0===t?\"div\":t,n=e.name,i=void 0===n?null:n,o=e.attributes,a=void 0===o?{}:o,c=e.read,l=void 0===c?function(){}:c,u=e.write,s=void 0===u?function(){}:u,d=e.create,p=void 0===d?function(){}:d,f=e.destroy,h=void 0===f?function(){}:f,g=e.filterFrameActionsForChild,m=void 0===g?function(e,t){return t}:g,v=e.didCreateView,y=void 0===v?function(){}:v,E=e.didWriteView,T=void 0===E?function(){}:E,_=e.shouldUpdateChildViews,R=void 0===_?function(){return!0}:_,w=e.ignoreRect,A=void 0!==w&&w,I=e.ignoreRectUpdate,S=void 0!==I&&I,C=e.mixins,O=void 0===C?[]:C;return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=createElement(r,i?\"doka--\".concat(i):null,a),o=window.getComputedStyle(n,null),c=updateRect(),u=null,d=!1,f=[],g=[],v={},E={},_=[s],w=[l],I=[h],C=function(){return n},x=function(){return[].concat(f)},b=function(){return u||(u=getViewRect(c,f,[0,0],[1,1]))},M=function(){return n.layoutCalculated=!1},L={element:{get:C},style:{get:function(){return o}},childViews:{get:x}},P=_objectSpread({},L,{rect:{get:b},ref:{get:function(){return v}},is:function(e){return i===e},appendChild:appendChild(n),createChildView:function(e){return function(t,r){return t(e,r)}}(e),linkView:function(e){return f.push(e),e},unlinkView:function(e){f.splice(f.indexOf(e),1)},appendChildView:appendChildView(n,f),removeChildView:removeChildView(n,f),registerWriter:function(e){return _.push(e)},registerReader:function(e){return w.push(e)},registerDestroyer:function(e){return I.push(e)},invalidateLayout:M,dispatch:e.dispatch,query:e.query}),G={element:{get:C},childViews:{get:x},rect:{get:b},resting:{get:function(){return d}},isRectIgnored:function(){return A},invalidateLayout:M,_read:function(){u=null,R({root:D,props:t})&&f.forEach(function(e){return e._read()}),!(S&&c.width&&c.height)&&updateRect(c,n,o);var e={root:D,props:t,rect:c};w.forEach(function(t){return t(e)})},_write:function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=0===r.length;return _.forEach(function(i){!1===i({props:t,root:D,actions:r,timestamp:e})&&(n=!1)}),g.forEach(function(t){!1===t.write(e)&&(n=!1)}),R({props:t,root:D,actions:r,timestamp:e})&&(f.filter(function(e){return!!e.element.parentNode}).forEach(function(t){t._write(e,m(t,r))||(n=!1)}),f.forEach(function(t,i){t.element.parentNode||(D.appendChild(t.element,i),t._read(),t._write(e,m(t,r)),n=!1)})),d=n,T({props:t,root:D,actions:r,timestamp:e}),n},_destroy:function(){g.forEach(function(e){return e.destroy()}),I.forEach(function(e){e({root:D})}),f.forEach(function(e){return e._destroy()})}},k=_objectSpread({},L,{rect:{get:function(){return c}}});Object.keys(O).sort(function(e,t){return\"styles\"===e?1:\"styles\"===t?-1:0}).forEach(function(e){var r=Mixins[e]({mixinConfig:O[e],viewProps:t,viewState:E,viewInternalAPI:P,viewExternalAPI:G,view:createObject(k)});r&&g.push(r)});var D=createObject(P);p({root:D,props:t});var U=getChildCount(n)||0;return f.forEach(function(e,t){D.appendChild(e.element,U+t)}),y(D),createObject(G,t)}},createPainter=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:60,n=\"__framePainter\";if(window[n])return window[n].readers.push(e),void window[n].writers.push(t);window[n]={readers:[e],writers:[t]};var i=window[n],o=1e3/r,a=null,c=null,l=null,u=null,s=function(){document.hidden?(l=function(){return window.setTimeout(function(){return d(performance.now())},o)},u=function(){return window.clearTimeout(c)}):(l=function(){return window.requestAnimationFrame(d)},u=function(){return window.cancelAnimationFrame(c)})};document.addEventListener(\"visibilitychange\",function(){u&&u(),s(),d(performance.now())});var d=function e(t){c=l(e),a||(a=t);var r=t-a;r<=o||(a=t-r%o,i.readers.forEach(function(e){return e()}),i.writers.forEach(function(e){return e(t)}))};return s(),d(performance.now()),{pause:function(){u(c)}}},createRoute=function(e,t){return function(r){var n=r.root,i=r.props,o=r.actions,a=void 0===o?[]:o,c=r.timestamp;if(a.filter(function(t){return e[t.type]}).forEach(function(t){return e[t.type]({root:n,props:i,action:t.data,timestamp:c})}),t)return t({root:n,props:i,actions:a,timestamp:c})}},isArray=function(e){return Array.isArray(e)},isEmpty=function(e){return null==e},trim=function(e){return e.trim()},toString=function(e){return\"\"+e},toArray=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\",\";return isEmpty(e)?[]:isArray(e)?e:toString(e).split(t).map(trim).filter(function(e){return e.length})},isBoolean=function(e){return\"boolean\"==typeof e},toBoolean=function(e){return isBoolean(e)?e:\"true\"===e},isString=function(e){return\"string\"==typeof e},toNumber=function(e){return isNumber(e)?e:isString(e)?toString(e).replace(/[a-z]+/gi,\"\"):0},toInt=function(e){return parseInt(toNumber(e),10)},toFloat=function(e){return parseFloat(toNumber(e))},isInt=function(e){return isNumber(e)&&isFinite(e)&&Math.floor(e)===e},toBytes=function(e){if(isInt(e))return e;var t=toString(e).trim();return/MB$/i.test(t)?(t=t.replace(/MB$i/,\"\").trim(),1e3*toInt(t)*1e3):/KB/i.test(t)?(t=t.replace(/KB$i/,\"\").trim(),1e3*toInt(t)):toInt(t)},isFunction=function(e){return\"function\"==typeof e},toFunctionReference=function(e){for(var t=self,r=e.split(\".\"),n=null;n=r.shift();)if(!(t=t[n]))return null;return t},isNull=function(e){return null===e},getType=function(e){return isArray(e)?\"array\":isNull(e)?\"null\":isInt(e)?\"int\":/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(e)?\"bytes\":_typeof(e)},replaceSingleQuotes=function(e){return e.replace(/{\\s*'/g,'{\"').replace(/'\\s*}/g,'\"}').replace(/'\\s*:/g,'\":').replace(/:\\s*'/g,':\"').replace(/,\\s*'/g,',\"').replace(/'\\s*,/g,'\",')},conversionTable={array:toArray,boolean:toBoolean,int:function(e){return\"bytes\"===getType(e)?toBytes(e):toInt(e)},float:toFloat,bytes:toBytes,number:toFloat,string:function(e){return isFunction(e)?e:toString(e)},object:function(e){try{return JSON.parse(replaceSingleQuotes(e))}catch(t){return e}},file:function(e){return e},function:function(e){return toFunctionReference(e)}},convertTo=function(e,t){return conversionTable[t](e)},getValueByType=function(e,t,r){if(e===t)return e;var n=getType(e);if(n!==r){var i=convertTo(e,r);if(n=getType(i),null===i)throw'Trying to assign value with incorrect type, allowed type: \"'.concat(r,'\"');e=i}return e},createOption=function(e,t){var r=e;return{enumerable:!0,get:function(){return r},set:function(n){r=getValueByType(n,e,t)}}},createOptions=function(e){var t={};return forin(e,function(r){var n=isString(e[r])?e[r]:r,i=e[n];t[r]=n===r?createOption(i[0],i[1]):t[n]}),createObject(t)},resetState=function(e){e.file=null,e.activeView=null,e.markup=[],e.markupToolValues={},e.rootRect={x:0,y:0,left:0,top:0,width:0,height:0},e.stage=null,e.stageOffset=null,e.image=null,e.zoomTimeoutId=null,e.instantUpdate=!1,e.filePromise=null,e.fileLoader=null,e.instructions={size:null,crop:null,filter:null,color:null},e.filter=null,e.filterName=null,e.filterValue=null,e.colorValues={},e.colorMatrices={},e.size={width:!1,height:!1,aspectRatioLocked:!0,aspectRatioPrevious:!1},e.crop={rectangle:null,transforms:null,rotation:null,flip:null,aspectRatio:null,isRotating:!1,isDirty:!1,limitToImageBounds:!0,draft:{rectangle:null,transforms:null}}},createInitialState=function(e){var t={noImageTimeout:null,options:createOptions(e)};return resetState(t),t},fromCamels=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"-\";return e.split(/(?=[A-Z])/).map(function(e){return e.toLowerCase()}).join(t)},createOptionAPI=function(e,t){var r={};return forin(t,function(n){var i=isString(t[n])?t[n]:n;r[n]={get:function(){return e.getState().options[i]},set:function(t){e.dispatch(\"SET_\".concat(fromCamels(i,\"_\").toUpperCase()),{value:t})}}}),r},createOptionActions=function(e){return function(t,r,n){var i={};return forin(e,function(e){var r=fromCamels(e,\"_\").toUpperCase();i[\"SET_\".concat(r)]=function(i){var o;try{o=n.options[e],n.options[e]=i.value}catch(e){}t(\"DID_SET_\".concat(r),{value:n.options[e],prevValue:o})}}),i}},createOptionQueries=function(e){return function(t){var r={};return forin(e,function(e){r[\"GET_\".concat(fromCamels(e,\"_\").toUpperCase())]=function(){return t.options[e]}}),r}},getUniqueId=function(){return Math.random().toString(36).substr(2,9)},arrayRemove=function(e,t){return e.splice(t,1)},on=function(){var e=[],t=function(t,r){arrayRemove(e,e.findIndex(function(e){return e.event===t&&(e.cb===r||!r)}))};return{fire:function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1)&&!window.MSStream),testResult},getOptions=function(){return _objectSpread({},defaultOptions)},setOptions=function(e){forin(e,function(e,t){defaultOptions[e]&&setOption(e,t)})},correctDeprecatedOption=function(e){return isString(defaultOptions[e])?defaultOptions[e]:e},setOption=function(e,t){e=correctDeprecatedOption(e),defaultOptions[e][0]=getValueByType(t,defaultOptions[e][0],defaultOptions[e][1])},defaultOptions={id:[null,Type.STRING],className:[null,Type.STRING],src:[null,Type.FILE],storageName:[\"doka\",Type.STRING],maxImagePreviewWidth:[1500,Type.INT],maxImagePreviewHeight:[1500,Type.INT],imagePreviewScaleMode:[\"stage\",Type.STRING],allowPreviewFitToView:[!0,Type.BOOLEAN],allowButtonCancel:[!0,Type.BOOLEAN],allowButtonConfirm:[!0,Type.BOOLEAN],allowButtonReset:[!0,Type.BOOLEAN],allowDropFiles:[!1,Type.BOOLEAN],allowBrowseFiles:[!0,Type.BOOLEAN],allowAutoClose:[!0,Type.BOOLEAN],allowAutoDestroy:[!1,Type.BOOLEAN],utils:[[\"crop\",\"filter\",\"color\",\"markup\"],Type.ARRAY],util:[null,Type.STRING],initialState:[null,Type.OBJECT],outputData:[!1,Type.BOOLEAN],outputFile:[!0,Type.BOOLEAN],outputCorrectImageExifOrientation:[!0,Type.BOOLEAN],outputStripImageHead:[!0,Type.BOOLEAN],outputType:[null,Type.STRING],outputQuality:[null,Type.INT],outputFit:[\"cover\",Type.STRING],outputUpscale:[!0,Type.BOOLEAN],outputWidth:[null,Type.INT],outputHeight:[null,Type.INT],outputCanvasBackgroundColor:[null,Type.STRING],outputCanvasMemoryLimit:[isBrowser()&&isIOS()?16777216:null,Type.INT],outputCanvasSyncTarget:[null,Type.OBJECT],size:[null,Type.OBJECT],sizeMin:[{width:1,height:1},Type.OBJECT],sizeMax:[{width:9999,height:9999},Type.OBJECT],filter:[null,Type.OBJECT],filters:[{original:{label:\"Original\",matrix:function(){return null}},chrome:{label:\"Chrome\",matrix:function(){return[1.398,-.316,.065,-.273,.201,-.051,1.278,-.08,-.273,.201,-.051,.119,1.151,-.29,.215,0,0,0,1,0]}},fade:{label:\"Fade\",matrix:function(){return[1.073,-.015,.092,-.115,-.017,.107,.859,.184,-.115,-.017,.015,.077,1.104,-.115,-.017,0,0,0,1,0]}},mono:{label:\"Mono\",matrix:function(){return[.212,.715,.114,0,0,.212,.715,.114,0,0,.212,.715,.114,0,0,0,0,0,1,0]}},noir:{label:\"Noir\",matrix:function(){return[.15,1.3,-.25,.1,-.2,.15,1.3,-.25,.1,-.2,.15,1.3,-.25,.1,-.2,0,0,0,1,0]}}},Type.OBJECT],crop:[null,Type.OBJECT],cropShowSize:[!1,Type.BOOLEAN],cropZoomTimeout:[null,Type.INT],cropMask:[null,Type.FUNCTION],cropMaskInset:[0,Type.INT],cropAllowResizeRect:[!0,Type.BOOLEAN],cropAllowImageTurnLeft:[!0,Type.BOOLEAN],cropAllowImageTurnRight:[!1,Type.BOOLEAN],cropAllowImageFlipHorizontal:[!0,Type.BOOLEAN],cropAllowImageFlipVertical:[!0,Type.BOOLEAN],cropAllowToggleLimit:[!1,Type.BOOLEAN],cropLimitToImageBounds:[!0,Type.BOOLEAN],cropAllowInstructionZoom:[!1,Type.BOOLEAN],cropAllowRotate:[!0,Type.BOOLEAN],cropResizeMatchImageAspectRatio:[!1,Type.BOOLEAN],cropResizeKeyCodes:[[18,91,92,93],Type.ARRAY],cropResizeScrollRectOnly:[!1,Type.BOOLEAN],cropAspectRatio:[null,Type.STRING],cropAspectRatioOptions:[null,Type.ARRAY],cropMinImageWidth:[1,Type.INT],cropMinImageHeight:[1,Type.INT],color:[void 0,Type.OBJECT],colorBrightness:[0,Type.NUMBER],colorBrightnessRange:[[-.25,.25],Type.ARRAY],colorContrast:[1,Type.NUMBER],colorContrastRange:[[.5,1.5],Type.ARRAY],colorExposure:[1,Type.NUMBER],colorExposureRange:[[.5,1.5],Type.ARRAY],colorSaturation:[1,Type.NUMBER],colorSaturationRange:[[0,2],Type.ARRAY],markup:[null,Type.ARRAY],markupUtil:[\"select\",Type.STRING],markupFilter:[function(){return!0},Type.FUNCTION],markupAllowAddMarkup:[!0,Type.BOOLEAN],markupAllowCustomColor:[!0,Type.BOOLEAN],markupDrawDistance:[4,Type.NUMBER],beforeAddMarkup:[null,Type.FUNCTION],beforeRemoveMarkup:[null,Type.FUNCTION],onselectmarkup:[null,Type.FUNCTION],onremovemarkup:[null,Type.FUNCTION],onaddmarkup:[null,Type.FUNCTION],markupColor:[\"#000\",Type.STRING],markupColorOptions:[[[\"White\",\"#fff\",\"#f6f6f6\"],[\"Silver\",\"#9e9e9e\"],[\"Black\",\"#000\",\"#333\"],[\"Red\",\"#f44336\"],[\"Orange\",\"#ff9800\"],[\"Yellow\",\"#ffeb3b\"],[\"Green\",\"#4caf50\"],[\"Blue\",\"#2196f3\"],[\"Violet\",\"#3f51b5\"],[\"Purple\",\"#9c27b0\"]],Type.ARRAY],markupFontSize:[.1,Type.NUMBER],markupFontSizeOptions:[[[\"XL\",.15],[\"L\",.125],[\"M\",.1],[\"S\",.075],[\"XS\",.05]],Type.ARRAY],markupFontFamily:[\"Helvetica, Arial, Verdana\",Type.STRING],markupFontFamilyOptions:[[[\"Serif\",\"Palatino, 'Times New Roman', serif\"],[\"Sans Serif\",\"Helvetica, Arial, Verdana\"],[\"Monospaced\",\"Monaco, 'Lucida Console', monospaced\"]],Type.ARRAY],markupShapeStyle:[[.015,null],Type.ARRAY],markupShapeStyleOptions:[[[\"Fill\",0,null,0],[\"Outline thick\",.025,null,4],[\"Outline default\",.015,null,2],[\"Outline thin\",.005,null,1],[\"Outline dashed\",.005,[.01],1]],Type.ARRAY],markupLineStyle:[[.015,null],Type.ARRAY],markupLineStyleOptions:[[[\"Thick\",.025,null,4],[\"Default\",.015,null,2],[\"Thin\",.005,null,1],[\"Dashed\",.005,[.01],1]],Type.ARRAY],markupLineDecoration:[[\"arrow-end\"],Type.ARRAY],markupLineDecorationOptions:[[[\"None\",[]],[\"Single arrow\",[\"arrow-end\"]],[\"Double arrow\",[\"arrow-begin\",\"arrow-end\"]]],Type.ARRAY],stickers:[null,Type.ARRAY],afterUpdateStickerItem:[null,Type.FUNCTION],beforeReset:[null,Type.FUNCTION],beforeLoadImage:[null,Type.FUNCTION],beforeCreateBlob:[null,Type.FUNCTION],afterCreateBlob:[null,Type.FUNCTION],afterCreateOutput:[null,Type.FUNCTION],onconfirm:[null,Type.FUNCTION],oncancel:[null,Type.FUNCTION],onclose:[null,Type.FUNCTION],onloadstart:[null,Type.FUNCTION],onload:[null,Type.FUNCTION],onloaderror:[null,Type.FUNCTION],oninit:[null,Type.FUNCTION],onready:[null,Type.FUNCTION],onupdate:[null,Type.FUNCTION],ondestroy:[null,Type.FUNCTION],labelButtonReset:[\"Reset\",Type.STRING],labelButtonCancel:[\"Cancel\",Type.STRING],labelButtonConfirm:[\"Done\",Type.STRING],labelButtonUtilCrop:[\"Crop\",Type.STRING],labelButtonUtilResize:[\"Resize\",Type.STRING],labelButtonUtilFilter:[\"Filter\",Type.STRING],labelButtonUtilColor:[\"Colors\",Type.STRING],labelButtonUtilMarkup:[\"Markup\",Type.STRING],labelButtonUtilSticker:[\"Stickers\",Type.STRING],labelStatusMissingWebGL:[\"WebGL is required but is disabled on your browser\",Type.STRING],labelStatusAwaitingImage:[\"Waiting for image…\",Type.STRING],labelStatusLoadImageError:[\"Error loading image…\",Type.STRING],labelStatusLoadingImage:[\"Loading image…\",Type.STRING],labelStatusProcessingImage:[\"Processing image…\",Type.STRING],labelColorBrightness:[\"Brightness\",Type.STRING],labelColorContrast:[\"Contrast\",Type.STRING],labelColorExposure:[\"Exposure\",Type.STRING],labelColorSaturation:[\"Saturation\",Type.STRING],labelMarkupTypeRectangle:[\"Square\",Type.STRING],labelMarkupTypeEllipse:[\"Circle\",Type.STRING],labelMarkupTypeText:[\"Text\",Type.STRING],labelMarkupTypeLine:[\"Arrow\",Type.STRING],labelMarkupSelectFontSize:[\"Size\",Type.STRING],labelMarkupSelectFontFamily:[\"Font\",Type.STRING],labelMarkupSelectLineDecoration:[\"Decoration\",Type.STRING],labelMarkupSelectLineStyle:[\"Style\",Type.STRING],labelMarkupSelectShapeStyle:[\"Style\",Type.STRING],labelMarkupRemoveShape:[\"Remove\",Type.STRING],labelMarkupToolSelect:[\"Select\",Type.STRING],labelMarkupToolDraw:[\"Draw\",Type.STRING],labelMarkupToolLine:[\"Arrow\",Type.STRING],labelMarkupToolText:[\"Text\",Type.STRING],labelMarkupToolRect:[\"Square\",Type.STRING],labelMarkupToolEllipse:[\"Circle\",Type.STRING],labelResizeWidth:[\"Width\",Type.STRING],labelResizeHeight:[\"Height\",Type.STRING],labelResizeApplyChanges:[\"Apply\",Type.STRING],labelCropInstructionZoom:[\"Zoom in and out with your scroll wheel or touchpad.\",Type.STRING],labelButtonCropZoom:[\"Zoom\",Type.STRING],labelButtonCropRotateLeft:[\"Rotate left\",Type.STRING],labelButtonCropRotateRight:[\"Rotate right\",Type.STRING],labelButtonCropRotateCenter:[\"Center rotation\",Type.STRING],labelButtonCropFlipHorizontal:[\"Flip horizontal\",Type.STRING],labelButtonCropFlipVertical:[\"Flip vertical\",Type.STRING],labelButtonCropAspectRatio:[\"Aspect ratio\",Type.STRING],labelButtonCropToggleLimit:[\"Crop selection\",Type.STRING],labelButtonCropToggleLimitEnable:[\"Limited to image\",Type.STRING],labelButtonCropToggleLimitDisable:[\"Select outside image\",Type.STRING],pointerEventsPolyfillScope:[\"root\",Type.STRING],styleCropCorner:[\"circle\",Type.STRING],styleFullscreenSafeArea:[isBrowser()&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream?\"bottom\":\"none\",Type.STRING],styleLayoutMode:[null,Type.STRING]},limit=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;return Math.min(r,Math.max(t,e))},roundFloat=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;return parseFloat(e.toFixed(t))},vectorEqual=function(e,t){return roundFloat(e.x)===roundFloat(t.x)&&roundFloat(e.y)===roundFloat(t.y)},roundVector=function(e,t){return{x:roundFloat(e.x,t),y:roundFloat(e.y,t)}},vectorSubtract=function(e,t){return createVector(e.x-t.x,e.y-t.y)},vectorDot=function(e,t){return e.x*t.x+e.y*t.y},vectorDistanceSquared=function(e,t){return vectorDot(vectorSubtract(e,t),vectorSubtract(e,t))},vectorDistance=function(e,t){return Math.sqrt(vectorDistanceSquared(e,t))},vectorAngleBetween=function(e,t){var r=vectorSubtract(e,t);return Math.atan2(r.y,r.x)},vectorLimit=function(e,t){return createVector(limit(e.x,t.x,t.x+t.width),limit(e.y,t.y,t.y+t.height))},vectorRotate=function(e,t,r){var n=Math.cos(t),i=Math.sin(t),o=createVector(e.x-r.x,e.y-r.y);return createVector(r.x+n*o.x-i*o.y,r.y+i*o.x+n*o.y)},createVector=function(){return{x:arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,y:arguments.length>1&&void 0!==arguments[1]?arguments[1]:0}},rectEqualsRect=function(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height},rectFitsInRect=function(e,t){var r=rectBounds(e),n=rectBounds(t);return r.left>=n.left&&r.top>=n.top&&r.bottom<=n.bottom&&r.right<=n.right},rotateRectCorners=function(e,t,r){return 0===t?{tl:e.tl,tr:e.tr,br:e.br,bl:e.bl}:{tl:vectorRotate(e.tl,t,r),tr:vectorRotate(e.tr,t,r),br:vectorRotate(e.br,t,r),bl:vectorRotate(e.bl,t,r)}},rectRotate=function(e,t,r){var n=rotateRectCorners(rectCorners(e),t,r),i=n.tl,o=n.tr,a=n.br,c=n.bl,l=Math.min(i.x,o.x,a.x,c.x),u=Math.min(i.y,o.y,a.y,c.y),s=Math.max(i.x,o.x,a.x,c.x),d=Math.max(i.y,o.y,a.y,c.y);return createRect(l,u,s-l,d-u)},rectScale=function(e,t,r){return createRect(t*(e.x-r.x)+r.x,t*(e.y-r.y)+r.y,t*e.width,t*e.height)},rectTranslate=function(e,t){return createRect(e.x+t.x,e.y+t.y,e.width,e.height)},TRANSFORM_MAP={translate:rectTranslate,rotate:rectRotate,scale:rectScale},rectTransform=function(e,t,r){return t.reduce(function(e,t){return(0,TRANSFORM_MAP[t[0]])(e,t[1],r)},e)},rectClone=function(e){return createRect(e.x,e.y,e.width,e.height)},rectBounds=function(e){return{top:e.y,right:e.x+e.width,bottom:e.y+e.height,left:e.x}},rectFromBounds=function(e){var t=e.top,r=e.right,n=e.bottom,i=e.left;return{x:i,y:t,width:r-i,height:n-t}},rectCenter=function(e){return createVector(e.x+.5*e.width,e.y+.5*e.height)},rectCorners=function(e){return{tl:{x:e.x,y:e.y},tr:{x:e.x+e.width,y:e.y},br:{x:e.x+e.width,y:e.y+e.height},bl:{x:e.x,y:e.y+e.height}}},createRect=function(e,t,r,n){return{x:e,y:t,width:r,height:n}},getNumericAspectRatioFromString=function(e){if(isEmpty(e))return e;if(/:/.test(e)){var t=e.split(\":\"),r=t[0];return t[1]/r}return parseFloat(e)},getCenteredCropRect=function(e,t){var r=e.width,n=r*t;return n>e.height&&(r=(n=e.height)/t),{x:.5*(e.width-r),y:.5*(e.height-n),width:r,height:n}},calculateCanvasSize=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=e.height/e.width,i=t,o=1,a=n;a>i&&(o=(a=i)/n);var c=Math.max(1/o,i/a),l=e.width/(r*c*o);return{width:l,height:l*t}},createVector$1=function(e,t){return{x:e,y:t}},vectorDot$1=function(e,t){return e.x*t.x+e.y*t.y},vectorSubtract$1=function(e,t){return createVector$1(e.x-t.x,e.y-t.y)},vectorDistanceSquared$1=function(e,t){return vectorDot$1(vectorSubtract$1(e,t),vectorSubtract$1(e,t))},vectorDistance$1=function(e,t){return Math.sqrt(vectorDistanceSquared$1(e,t))},getOffsetPointOnEdge=function(e,t){var r=e,n=t,i=1.5707963267948966-t,o=Math.sin(1.5707963267948966),a=Math.sin(n),c=Math.sin(i),l=Math.cos(i),u=r/o;return createVector$1(l*(u*a),l*(u*c))},getRotatedRectSize=function(e,t){var r=e.width,n=e.height,i=getOffsetPointOnEdge(r,t),o=getOffsetPointOnEdge(n,t),a=createVector$1(e.x+Math.abs(i.x),e.y-Math.abs(i.y)),c=createVector$1(e.x+e.width+Math.abs(o.y),e.y+Math.abs(o.x)),l=createVector$1(e.x-Math.abs(o.y),e.y+e.height-Math.abs(o.x));return{width:vectorDistance$1(a,c),height:vectorDistance$1(a,l)}},getImageRectZoomFactor=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{x:.5,y:.5},i=n.x>.5?1-n.x:n.x,o=n.y>.5?1-n.y:n.y,a=2*i*e.width,c=2*o*e.height,l=getRotatedRectSize(t,r);return Math.max(l.width/a,l.height/c)},getAxisAlignedImageRect=function(e,t){var r=t.origin,n=t.translation,i=t.scale;return rectTransform(e,[[\"scale\",i],[\"translate\",n]],r)},getOffsetPointOnEdge$1=function(e,t){var r=e,n=t,i=1.5707963267948966-t,o=Math.sin(1.5707963267948966),a=Math.sin(n),c=Math.sin(i),l=Math.cos(i),u=r/o;return createVector(l*(u*a),l*(u*c))},getRotatedRectCorners=function(e,t){var r=e.width,n=e.height,i=t%(Math.PI/2),o=getOffsetPointOnEdge$1(r,i),a=getOffsetPointOnEdge$1(n,i),c=rectCorners(e);return{tl:createVector(c.tl.x+Math.abs(o.x),c.tl.y-Math.abs(o.y)),tr:createVector(c.tr.x+Math.abs(a.y),c.tr.y+Math.abs(a.x)),br:createVector(c.br.x-Math.abs(o.x),c.br.y+Math.abs(o.y)),bl:createVector(c.bl.x-Math.abs(a.y),c.bl.y-Math.abs(a.x))}},getAxisAlignedCropRect=function(e,t,r,n){var i={x:e.x+t.x,y:e.y+t.y},o=getRotatedRectCorners(n,r),a=vectorRotate(o.tl,-r,i),c=vectorRotate(o.tr,-r,i),l=vectorRotate(o.br,-r,i);return createRect(Math.min(a.x,c.x,l.x),Math.min(a.y,c.y,l.y),Math.max(a.x,c.x,l.x)-Math.min(a.x,c.x,l.x),Math.max(a.y,c.y,l.y)-Math.min(a.y,c.y,l.y))},getCropFromView=function(e,t,r){var n=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=r.origin,o=r.translation,a=getAxisAlignedImageRect(e,r),c=2*Math.PI+r.rotation%(2*Math.PI),l=getAxisAlignedCropRect(i,o,c,t),u=rectCenter(l),s=t.height/t.width,d={x:(u.x-a.x)/a.width,y:(u.y-a.y)/a.height},p=d.y>.5?1-d.y:d.y,f=2*(d.x>.5?1-d.x:d.x)*a.width,h=2*p*a.height;return{center:d,zoom:n?Math.min(f/l.width,h/l.height):Math.min(a.width/l.width,a.height/l.height),rotation:r.rotation,aspectRatio:s,scaleToFit:n}},getCropFromStateRounded=function(e,t){var r=getCropFromState(e,t);return{center:{x:roundFloat(r.center.x),y:roundFloat(r.center.y)},rotation:roundFloat(r.rotation),zoom:roundFloat(r.zoom),aspectRatio:roundFloat(r.aspectRatio),flip:_objectSpread({},t.flip),scaleToFit:r.scaleToFit}},getCropFromState=function(e,t){var r=getCropFromView(e,t.rectangle,t.transforms,t.limitToImageBounds);return{center:{x:r.center.x,y:r.center.y},rotation:r.rotation,zoom:r.zoom,aspectRatio:r.aspectRatio,flip:_objectSpread({},t.flip),scaleToFit:r.scaleToFit}},limitSize=function(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:\"width\",o=e.width,a=e.height;if(!o&&!a)return{width:o,height:a};if(o=o&&limit(o,t.width,r.width),a=a&&limit(a,t.height,r.height),!n)return{width:o,height:a};if(a)if(o)\"width\"===i?a=o/n:\"height\"===i?o=a*n:(a*nr.width?a=(o=r.width)/n:o/n>r.height&&(o=(a=r.height)*n));else{a=limit(a*n,t.width,r.width)/n}else o=limit(o/n,t.height,r.height)*n;return{width:o,height:a}},dotColorMatrix=function(e,t){var r=new Array(20);return r[0]=e[0]*t[0]+e[1]*t[5]+e[2]*t[10]+e[3]*t[15],r[1]=e[0]*t[1]+e[1]*t[6]+e[2]*t[11]+e[3]*t[16],r[2]=e[0]*t[2]+e[1]*t[7]+e[2]*t[12]+e[3]*t[17],r[3]=e[0]*t[3]+e[1]*t[8]+e[2]*t[13]+e[3]*t[18],r[4]=e[0]*t[4]+e[1]*t[9]+e[2]*t[14]+e[3]*t[19]+e[4],r[5]=e[5]*t[0]+e[6]*t[5]+e[7]*t[10]+e[8]*t[15],r[6]=e[5]*t[1]+e[6]*t[6]+e[7]*t[11]+e[8]*t[16],r[7]=e[5]*t[2]+e[6]*t[7]+e[7]*t[12]+e[8]*t[17],r[8]=e[5]*t[3]+e[6]*t[8]+e[7]*t[13]+e[8]*t[18],r[9]=e[5]*t[4]+e[6]*t[9]+e[7]*t[14]+e[8]*t[19]+e[9],r[10]=e[10]*t[0]+e[11]*t[5]+e[12]*t[10]+e[13]*t[15],r[11]=e[10]*t[1]+e[11]*t[6]+e[12]*t[11]+e[13]*t[16],r[12]=e[10]*t[2]+e[11]*t[7]+e[12]*t[12]+e[13]*t[17],r[13]=e[10]*t[3]+e[11]*t[8]+e[12]*t[13]+e[13]*t[18],r[14]=e[10]*t[4]+e[11]*t[9]+e[12]*t[14]+e[13]*t[19]+e[14],r[15]=e[15]*t[0]+e[16]*t[5]+e[17]*t[10]+e[18]*t[15],r[16]=e[15]*t[1]+e[16]*t[6]+e[17]*t[11]+e[18]*t[16],r[17]=e[15]*t[2]+e[16]*t[7]+e[17]*t[12]+e[18]*t[17],r[18]=e[15]*t[3]+e[16]*t[8]+e[17]*t[13]+e[18]*t[18],r[19]=e[15]*t[4]+e[16]*t[9]+e[17]*t[14]+e[18]*t[19]+e[19],r},toRGBColorArray=function(e){var t;if(/^#/.test(e)){if(4===e.length){var r=e.split(\"\");e=\"#\"+r[1]+r[1]+r[2]+r[2]+r[3]+r[3]}var n=/^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(e);t=[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16)]}else if(/^rgb/.test(e)){(t=e.match(/\\d+/g).map(function(e){return parseInt(e,10)})).length=3}return t},viewCache=[],getColorMatrixFromMatrices=function(e){var t=[];return forin(e,function(e,r){return t.push(r)}),t.length?t.reduce(function(e,t){return dotColorMatrix(_toConsumableArray(e),t)},t.shift()):[]},getImageScalar=function(e){return e.crop.draft.transforms?e.crop.draft.transforms.scale:e.crop.transforms.scale},getMinCropSize=function(e){var t=e.image.width/e.image.naturalWidth,r=getImageScalar(e);return{width:e.options.cropMinImageWidth*r*t,height:e.options.cropMinImageHeight*r*t}},getMaxCropSize=function(e){var t=getImageScalar(e);return{width:e.image.width*t,height:e.image.height*t}},getWidth=function(e){return e.options.size?e.options.size.width:null},getHeight=function(e){return e.options.size?e.options.size.height:null},getOutputSizeWidth=function(e){return!1===e.size.width?getWidth(e):e.size.width},getOutputSizeHeight=function(e){return!1===e.size.height?getHeight(e):e.size.height},getAspectRatioOptions=function(e){return e.options.cropAspectRatioOptions?e.options.cropAspectRatioOptions.map(function(e){var t={aspectRatio:null,width:null,height:null};return\"number\"==typeof e.value&&(t.aspectRatio=e.value),\"string\"==typeof e.value&&(t.aspectRatio=getNumericAspectRatioFromString(e.value)),\"object\"===_typeof(e.value)&&null!==e.value&&(t.width=e.value.width,t.height=e.value.height,t.aspectRatio=t.height/t.width),{label:e.label,value:t}}):null},getCropStageRect=function(e,t){t.aspectRatio||(t.aspectRatio=e.image.height/e.image.width);var r=getCurrentCropSize(e.image,t,t.scaleToFit),n=r.width/r.height;return e.stage.width1&&void 0!==arguments[1]?arguments[1]:{},r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=t.zoom,i=t.rotation,o=t.center,a=t.aspectRatio,c=calculateCanvasSize(e,a,n),l={x:.5*c.width,y:.5*c.height},u={x:0,y:0,width:c.width,height:c.height,center:l},s=n*getImageRectZoomFactor(e,getCenteredCropRect(u,a),i,r?o:{x:.5,y:.5});return{widthFloat:c.width/s,heightFloat:c.height/s,width:Math.round(c.width/s),height:Math.round(c.height/s)}},canZoom=function(e,t){var r=rectCenter(t),n=rectCenter(e);return!vectorEqual(n,r)},getCropView=function(e){if(!e.stage||!e.image)return null;var t=e.crop.draft.rectangle||{free:e.crop.rectangle,limited:e.crop.rectangle},r=e.crop.draft.transforms||e.crop.transforms,n=r.origin,i=r.translation,o=r.scale,a=r.interaction,c=e.crop.rotation,l=e.crop.flip,u=!(!e.crop.draft.rectangle&&!e.crop.draft.transforms),s=u||e.instantUpdate,d=canZoom(t.limited,e.stage),p=e.crop.isDirty||u,f=e.crop.isRotating,h=void 0===e.crop.limitToImageBounds||e.crop.limitToImageBounds,g={width:e.image.naturalWidth,height:e.image.naturalHeight},m=getColorMatrixFromMatrices(e.colorMatrices),v=getCropFromState(e.image,{rectangle:t.limited,transforms:{origin:n,translation:i,scale:o,rotation:c.main+c.sub},flip:l,limitToImageBounds:e.crop.limitToImageBounds}),y={props:v,crop:getCurrentCropSize(g,v,e.crop.limitToImageBounds),image:getCurrentImageSize(e,t.limited)},E=y.image,T=y.crop,_=T.width,R=T.height,w=T.widthFloat/T.heightFloat;E.width&&E.height?(_=E.width,R=E.height):E.width&&!E.height?(_=E.width,R=E.width/w):E.height&&!E.width&&(R=E.height,_=E.height*w),y.currentWidth=Math.round(_),y.currentHeight=Math.round(R);var A={x:0,y:0},I=0,S=0;if(s&&a){if(a.translation){var C=a.translation.x-i.x,O=a.translation.y-i.y;A.x=100*Math.sign(C)*Math.log10(1+Math.abs(C)/100),A.y=100*Math.sign(O)*Math.log10(1+Math.abs(O)/100)}if(a.scale){var x=a.scale-o;I=.25*Math.sign(x)*Math.log10(1+Math.abs(x)/.25)}if(a.rotation){var b=a.rotation-(c.main+c.sub);S=.05*Math.sign(b)*Math.log10(1+Math.abs(b)/.05)}}var M={},L=t.free,P=rectBounds(L),G=rectBounds(t.limited);return forin(P,function(e){var t=P[e]-G[e];M[e]=G[e]+5*Math.sign(t)*Math.log10(1+Math.abs(t)/5)}),{canRecenter:d,canReset:p,isDraft:s,isRotating:f,isLimitedToImageBounds:h,cropRect:{x:M.left,y:M.top,width:M.right-M.left,height:M.bottom-M.top},origin:n,translation:i,translationBand:A,scale:o,scaleBand:I,rotation:c,rotationBand:S,flip:l,interaction:a,cropStatus:y,colorMatrix:m,markup:e.markup,previewSize:{width:e.image.width,height:e.image.height}}},isImage=function(e){return/^image/.test(e)},MATRICES={1:function(){return[1,0,0,1,0,0]},2:function(e){return[-1,0,0,1,e,0]},3:function(e,t){return[-1,0,0,-1,e,t]},4:function(e,t){return[1,0,0,-1,0,t]},5:function(){return[0,1,1,0,0,0]},6:function(e,t){return[0,1,-1,0,t,0]},7:function(e,t){return[0,-1,-1,0,t,e]},8:function(e){return[0,-1,1,0,0,e]}},getImageOrientationMatrix=function(e,t,r){return-1===r&&(r=1),MATRICES[r](e,t)},canvasRelease=function(e){e.width=1,e.height=1,e.getContext(\"2d\").clearRect(0,0,1,1)},isFlipped=function(e){return e&&(e.horizontal||e.vertical)},getBitmap=function(e,t,r){if(t<=1&&!isFlipped(r))return e.width=e.naturalWidth,e.height=e.naturalHeight,e;var n=document.createElement(\"canvas\"),i=e.naturalWidth,o=e.naturalHeight,a=t>=5&&t<=8;a?(n.width=o,n.height=i):(n.width=i,n.height=o);var c=n.getContext(\"2d\");if(t&&c.transform.apply(c,getImageOrientationMatrix(i,o,t)),isFlipped(r)){var l=[1,0,0,1,0,0];(!a&&r.horizontal||a&r.vertical)&&(l[0]=-1,l[4]=i),(!a&&r.vertical||a&&r.horizontal)&&(l[3]=-1,l[5]=o),c.transform.apply(c,l)}return c.drawImage(e,0,0,i,o),n},imageToImageData=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=n.canvasMemoryLimit,o=n.background,a=void 0===o?null:o,c=r.zoom||1,l=getBitmap(e,t,r.flip),u={width:l.width,height:l.height},s=r.aspectRatio||u.height/u.width,d=calculateCanvasSize(u,s,c);if(i){var p=d.width*d.height;if(p>i){var f=Math.sqrt(i)/Math.sqrt(p);u.width=Math.floor(u.width*f),u.height=Math.floor(u.height*f),d=calculateCanvasSize(u,s,c)}}var h=document.createElement(\"canvas\"),g={x:.5*d.width,y:.5*d.height},m={x:0,y:0,width:d.width,height:d.height,center:g},v=void 0===r.scaleToFit||r.scaleToFit,y=c*getImageRectZoomFactor(u,getCenteredCropRect(m,s),r.rotation,v?r.center:{x:.5,y:.5});h.width=Math.round(d.width/y),h.height=Math.round(d.height/y),g.x/=y,g.y/=y;var E=g.x-u.width*(r.center?r.center.x:.5),T=g.y-u.height*(r.center?r.center.y:.5),_=h.getContext(\"2d\");a&&(_.fillStyle=a,_.fillRect(0,0,h.width,h.height)),_.translate(g.x,g.y),_.rotate(r.rotation||0),_.drawImage(l,E-g.x,T-g.y,u.width,u.height);var R=_.getImageData(0,0,h.width,h.height);return canvasRelease(h),R},IS_BROWSER$1=\"undefined\"!=typeof window&&void 0!==window.document;IS_BROWSER$1&&(HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,\"toBlob\",{value:function(e,t,r){var n=this.toDataURL(t,r).split(\",\")[1];setTimeout(function(){for(var r=atob(n),i=r.length,o=new Uint8Array(i),a=0;a2&&void 0!==arguments[2]?arguments[2]:null;return new Promise(function(n){var i=r?r(e):e;Promise.resolve(i).then(function(e){e.toBlob(n,t.type,t.quality)})})},vectorMultiply$1=function(e,t){return createVector$2(e.x*t,e.y*t)},vectorAdd$1=function(e,t){return createVector$2(e.x+t.x,e.y+t.y)},vectorNormalize$1=function(e){var t=Math.sqrt(e.x*e.x+e.y*e.y);return 0===t?{x:0,y:0}:createVector$2(e.x/t,e.y/t)},vectorRotate$1=function(e,t,r){var n=Math.cos(t),i=Math.sin(t),o=createVector$2(e.x-r.x,e.y-r.y);return createVector$2(r.x+n*o.x-i*o.y,r.y+i*o.x+n*o.y)},createVector$2=function(){return{x:arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,y:arguments.length>1&&void 0!==arguments[1]?arguments[1]:0}},getMarkupValue=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3?arguments[3]:void 0;return\"string\"==typeof e?parseFloat(e)*r:\"number\"==typeof e?e*(n?t[n]:Math.min(t.width,t.height)):void 0},getMarkupStyles=function(e,t,r){var n=e.borderStyle||e.lineStyle||\"solid\",i=e.backgroundColor||e.fontColor||\"transparent\",o=e.borderColor||e.lineColor||\"transparent\",a=getMarkupValue(e.borderWidth||e.lineWidth,t,r);return{\"stroke-linecap\":e.lineCap||\"round\",\"stroke-linejoin\":e.lineJoin||\"round\",\"stroke-width\":a||0,\"stroke-dasharray\":\"string\"==typeof n?\"\":n.map(function(e){return getMarkupValue(e,t,r)}).join(\",\"),stroke:o,fill:i,opacity:e.opacity||1}},isDefined=function(e){return null!=e},getMarkupRect=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=getMarkupValue(e.x,t,r,\"width\")||getMarkupValue(e.left,t,r,\"width\"),i=getMarkupValue(e.y,t,r,\"height\")||getMarkupValue(e.top,t,r,\"height\"),o=getMarkupValue(e.width,t,r,\"width\"),a=getMarkupValue(e.height,t,r,\"height\"),c=getMarkupValue(e.right,t,r,\"width\"),l=getMarkupValue(e.bottom,t,r,\"height\");return isDefined(i)||(i=isDefined(a)&&isDefined(l)?t.height-a-l:l),isDefined(n)||(n=isDefined(o)&&isDefined(c)?t.width-o-c:c),isDefined(o)||(o=isDefined(n)&&isDefined(c)?t.width-n-c:0),isDefined(a)||(a=isDefined(i)&&isDefined(l)?t.height-i-l:0),{x:n||0,y:i||0,width:o||0,height:a||0}},pointsToPathShape=function(e){return e.map(function(e,t){return\"\".concat(0===t?\"M\":\"L\",\" \").concat(e.x,\" \").concat(e.y)}).join(\" \")},setAttributes=function(e,t){return Object.keys(t).forEach(function(r){return e.setAttribute(r,t[r])})},ns$1=\"http://www.w3.org/2000/svg\",svg=function(e,t){var r=document.createElementNS(ns$1,e);return t&&setAttributes(r,t),r},updateRect$1=function(e){return setAttributes(e,_objectSpread({},e.rect,e.styles))},updateEllipse=function(e){var t=e.rect.x+.5*e.rect.width,r=e.rect.y+.5*e.rect.height,n=.5*e.rect.width,i=.5*e.rect.height;return setAttributes(e,_objectSpread({cx:t,cy:r,rx:n,ry:i},e.styles))},IMAGE_FIT_STYLE={contain:\"xMidYMid meet\",cover:\"xMidYMid slice\"},updateImage=function(e,t){setAttributes(e,_objectSpread({},e.rect,e.styles,{preserveAspectRatio:IMAGE_FIT_STYLE[t.fit]||\"none\"}))},TEXT_ANCHOR={left:\"start\",center:\"middle\",right:\"end\"},updateText=function(e,t,r,n){var i=getMarkupValue(t.fontSize,r,n),o=t.fontFamily||\"sans-serif\",a=t.fontWeight||\"normal\",c=TEXT_ANCHOR[t.textAlign]||\"start\";setAttributes(e,_objectSpread({},e.rect,e.styles,{\"stroke-width\":0,\"font-weight\":a,\"font-size\":i,\"font-family\":o,\"text-anchor\":c})),e.text!==t.text&&(e.text=t.text,e.textContent=t.text.length?t.text:\" \")},updateLine=function(e,t,r,n){setAttributes(e,_objectSpread({},e.rect,e.styles,{fill:\"none\"}));var i=e.childNodes[0],o=e.childNodes[1],a=e.childNodes[2],c=e.childNodes[3],l=e.rect,u={x:e.rect.x+e.rect.width,y:e.rect.y+e.rect.height};if(setAttributes(i,{x1:l.x,y1:l.y,x2:u.x,y2:u.y}),setAttributes(c,{x1:l.x,y1:l.y,x2:u.x,y2:u.y}),t.lineDecoration){o.style.display=\"none\",a.style.display=\"none\";var s=vectorNormalize$1({x:u.x-l.x,y:u.y-l.y}),d=getMarkupValue(.05,r,n);if(-1!==t.lineDecoration.indexOf(\"arrow-begin\")){var p=vectorMultiply$1(s,d),f=vectorAdd$1(l,p),h=vectorRotate$1(l,2,f),g=vectorRotate$1(l,-2,f);setAttributes(o,{style:\"display:block;\",d:\"M\".concat(h.x,\",\").concat(h.y,\" L\").concat(l.x,\",\").concat(l.y,\" L\").concat(g.x,\",\").concat(g.y)})}if(-1!==t.lineDecoration.indexOf(\"arrow-end\")){var m=vectorMultiply$1(s,-d),v=vectorAdd$1(u,m),y=vectorRotate$1(u,2,v),E=vectorRotate$1(u,-2,v);setAttributes(a,{style:\"display:block;\",d:\"M\".concat(y.x,\",\").concat(y.y,\" L\").concat(u.x,\",\").concat(u.y,\" L\").concat(E.x,\",\").concat(E.y)})}}},updatePath=function(e,t,r,n){setAttributes(e,_objectSpread({},e.styles,{fill:\"none\"}));var i=e.childNodes[0],o=e.childNodes[1],a=pointsToPathShape(t.points.map(function(e){return{x:getMarkupValue(e.x,r,n,\"width\"),y:getMarkupValue(e.y,r,n,\"height\")}}));setAttributes(i,{d:a}),setAttributes(o,{d:a})},createShape=function(e){return function(t){return svg(e,{id:t.id})}},createImage=function(e){var t=svg(\"image\",{id:e.id,\"stroke-linecap\":\"round\",\"stroke-linejoin\":\"round\",opacity:\"0\"});return t.onload=function(){t.setAttribute(\"opacity\",e.opacity||1)},t.setAttributeNS(\"http://www.w3.org/1999/xlink\",\"xlink:href\",e.src),t},createLine=function(e){var t=svg(\"g\",{id:e.id,\"stroke-linecap\":\"round\",\"stroke-linejoin\":\"round\"}),r=svg(\"line\");t.appendChild(r);var n=svg(\"path\");t.appendChild(n);var i=svg(\"path\");t.appendChild(i);var o=svg(\"line\",{style:\"stroke-width: 40; stroke-opacity: 0;\"});return t.appendChild(o),t},createPath=function(e){var t=svg(\"g\",{id:e.id}),r=svg(\"path\");t.appendChild(r);var n=svg(\"path\",{style:\"stroke-width: 40; stroke-opacity: 0;\"});return t.appendChild(n),t},CREATE_TYPE_ROUTES={image:createImage,rect:createShape(\"rect\"),ellipse:createShape(\"ellipse\"),text:createShape(\"text\"),path:createPath,line:createLine},UPDATE_TYPE_ROUTES={rect:updateRect$1,ellipse:updateEllipse,image:updateImage,text:updateText,path:updatePath,line:updateLine},createMarkupByType=function(e,t){return CREATE_TYPE_ROUTES[e](t)},updateMarkupByType=function(e,t,r,n,i){\"path\"!==t&&(e.rect=getMarkupRect(r,n,i)),e.styles=getMarkupStyles(r,n,i),UPDATE_TYPE_ROUTES[t](e,r,n,i)},sortMarkupByZIndex=function(e,t){return e[1].zIndex>t[1].zIndex?1:e[1].zIndex\".concat(_.replace(/ /g,\" \"),\"\\n\\n\")}var w=t.aspectRatio||T/E,A=E,I=A*w,S=void 0===t.scaleToFit||t.scaleToFit,C=getImageRectZoomFactor({width:E,height:T},getCenteredCropRect({width:A,height:I},w),t.rotation,S?t.center:{x:.5,y:.5}),O=t.zoom*C,x=t.rotation*(180/Math.PI),b={x:.5*A,y:.5*I},M={x:b.x-E*t.center.x,y:b.y-T*t.center.y},L=[\"rotate(\".concat(x,\" \").concat(b.x,\" \").concat(b.y,\")\"),\"translate(\".concat(b.x,\" \").concat(b.y,\")\"),\"scale(\".concat(O,\")\"),\"translate(\".concat(-b.x,\" \").concat(-b.y,\")\"),\"translate(\".concat(M.x,\" \").concat(M.y,\")\")],P=[\"scale(\".concat(t.flip.horizontal?-1:1,\" \").concat(t.flip.vertical?-1:1,\")\"),\"translate(\".concat(t.flip.horizontal?-E:0,\" \").concat(t.flip.vertical?-T:0,\")\")],G='\\n\");i(G)},c.readAsText(e)})},objectToImageData=function(e){var t;try{t=new ImageData(e.width,e.height)}catch(r){t=document.createElement(\"canvas\").getContext(\"2d\").createImageData(e.width,e.height)}return t.data.set(e.data),t},TransformWorker=function(){var e={resize:function(e,t){var r=t.mode,n=void 0===r?\"contain\":r,i=t.upscale,a=void 0!==i&&i,u=t.width,s=t.height,d=t.matrix;if(d=!d||c(d)?null:d,!u&&!s)return l(e,d);null===u?u=s:null===s&&(s=u);if(\"force\"!==n){var p=u/e.width,f=s/e.height,h=1;if(\"cover\"===n?h=Math.max(p,f):\"contain\"===n&&(h=Math.min(p,f)),h>1&&!1===a)return l(e,d);u=e.width*h,s=e.height*h}for(var g=e.width,m=e.height,v=Math.round(u),y=Math.round(s),E=e.data,T=new Uint8ClampedArray(v*y*4),_=g/v,R=m/y,w=Math.ceil(.5*_),A=Math.ceil(.5*R),I=0;I=-1&&z<=1&&(O=2*z*z*z-3*z*z+1)>0){var W=E[(F=4*(N+D*g))+3];G+=O*W,b+=O,W<255&&(O=O*W/250),M+=O*E[F],L+=O*E[F+1],P+=O*E[F+2],x+=O}}T[C]=M/x,T[C+1]=L/x,T[C+2]=P/x,T[C+3]=G/b,d&&o(C,T,d)}return{data:T,width:v,height:y}},filter:l},t=function(t,r){var n=t.transforms,i=null;if(n.forEach(function(e){\"filter\"===e.type&&(i=e)}),i){var o=null;n.forEach(function(e){\"resize\"===e.type&&(o=e)}),o&&(o.data.matrix=i.data,n=n.filter(function(e){return\"filter\"!==e.type}))}r(function(t,r){return t.forEach(function(t){r=e[t.type](r,t.data)}),r}(n,t.imageData))};self.onmessage=function(e){t(e.data.message,function(t){self.postMessage({id:e.data.id,message:t},[t.data.buffer])})};var r=1,n=1,i=1;function o(e,t,o){var a=t[e]/255,c=t[e+1]/255,l=t[e+2]/255,u=t[e+3]/255,s=a*o[0]+c*o[1]+l*o[2]+u*o[3]+o[4],d=a*o[5]+c*o[6]+l*o[7]+u*o[8]+o[9],p=a*o[10]+c*o[11]+l*o[12]+u*o[13]+o[14],f=a*o[15]+c*o[16]+l*o[17]+u*o[18]+o[19],h=Math.max(0,s*f)+r*(1-f),g=Math.max(0,d*f)+n*(1-f),m=Math.max(0,p*f)+i*(1-f);t[e]=255*Math.max(0,Math.min(1,h)),t[e+1]=255*Math.max(0,Math.min(1,g)),t[e+2]=255*Math.max(0,Math.min(1,m))}var a=self.JSON.stringify([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]);function c(e){return self.JSON.stringify(e||[])===a}function l(e,t){if(!t||c(t))return e;for(var o=e.data,a=o.length,l=t[0],u=t[1],s=t[2],d=t[3],p=t[4],f=t[5],h=t[6],g=t[7],m=t[8],v=t[9],y=t[10],E=t[11],T=t[12],_=t[13],R=t[14],w=t[15],A=t[16],I=t[17],S=t[18],C=t[19],O=0,x=0,b=0,M=0,L=0,P=0,G=0,k=0,D=0,U=0,B=0,V=0;O=65504&&r<=65519||65534===r))break;if(o||(o=correctOrientation(t,i,n)),i+n>t.byteLength)break;i+=n}return e.slice(0,i)},getImageHead=function(e){return new Promise(function(t){var r=new FileReader;r.onload=function(){return t(readData(r.result)||null)},r.readAsArrayBuffer(e.slice(0,262144))})},getBlobBuilder=function(){return window.BlobBuilder=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder},createBlob=function(e,t){var r=getBlobBuilder();if(r){var n=new r;return n.append(e),n.getBlob(t)}return new Blob([e],{type:t})},getUniqueId$1=function(){return Math.random().toString(36).substr(2,9)},createWorker=function(e){var t=new Blob([\"(\",e.toString(),\")()\"],{type:\"application/javascript\"}),r=URL.createObjectURL(t),n=new Worker(r),i=[];return{transfer:function(){},post:function(e,t,r){var o=getUniqueId$1();i[o]=t,n.onmessage=function(e){var t=i[e.data.id];t&&(t(e.data.message),delete i[e.data.id])},n.postMessage({id:o,message:e},r)},terminate:function(){n.terminate(),URL.revokeObjectURL(r)}}},loadImage=function(e){return new Promise(function(t,r){var n=new Image;n.onload=function(){t(n)},n.onerror=function(e){r(e)},n.src=e})},chain=function(e){return e.reduce(function(e,t){return e.then(function(e){return t().then(Array.prototype.concat.bind(e))})},Promise.resolve([]))},canvasApplyMarkup=function(e,t){return new Promise(function(r){var n={width:e.width,height:e.height},i=e.getContext(\"2d\"),o=t.sort(sortMarkupByZIndex).map(function(e){return function(){return new Promise(function(t){TYPE_DRAW_ROUTES[e[0]](i,n,e[1],t)&&t()})}});chain(o).then(function(){return r(e)})})},applyMarkupStyles=function(e,t){e.beginPath(),e.lineCap=t[\"stroke-linecap\"],e.lineJoin=t[\"stroke-linejoin\"],e.lineWidth=t[\"stroke-width\"],t[\"stroke-dasharray\"].length&&e.setLineDash(t[\"stroke-dasharray\"].split(\",\")),e.fillStyle=t.fill,e.strokeStyle=t.stroke,e.globalAlpha=t.opacity||1},drawMarkupStyles=function(e){e.fill(),e.stroke(),e.globalAlpha=1},drawRect=function(e,t,r){var n=getMarkupRect(r,t),i=getMarkupStyles(r,t);return applyMarkupStyles(e,i),e.rect(n.x,n.y,n.width,n.height),drawMarkupStyles(e,i),!0},drawEllipse=function(e,t,r){var n=getMarkupRect(r,t),i=getMarkupStyles(r,t);applyMarkupStyles(e,i);var o=n.x,a=n.y,c=n.width,l=n.height,u=c/2*.5522848,s=l/2*.5522848,d=o+c,p=a+l,f=o+c/2,h=a+l/2;return e.moveTo(o,h),e.bezierCurveTo(o,h-s,f-u,a,f,a),e.bezierCurveTo(f+u,a,d,h-s,d,h),e.bezierCurveTo(d,h+s,f+u,p,f,p),e.bezierCurveTo(f-u,p,o,h+s,o,h),drawMarkupStyles(e,i),!0},drawImage=function(e,t,r,n){var i=getMarkupRect(r,t),o=getMarkupStyles(r,t);applyMarkupStyles(e,o);var a=new Image;new URL(r.src,window.location.href).origin!==window.location.origin&&(a.crossOrigin=\"\"),a.onload=function(){if(\"cover\"===r.fit){var t=i.width/i.height,c=t>1?a.width:a.height*t,l=t>1?a.width/t:a.height,u=.5*a.width-.5*c,s=.5*a.height-.5*l;e.drawImage(a,u,s,c,l,i.x,i.y,i.width,i.height)}else if(\"contain\"===r.fit){var d=Math.min(i.width/a.width,i.height/a.height),p=d*a.width,f=d*a.height,h=i.x+.5*i.width-.5*p,g=i.y+.5*i.height-.5*f;e.drawImage(a,0,0,a.width,a.height,h,g,p,f)}else e.drawImage(a,0,0,a.width,a.height,i.x,i.y,i.width,i.height);drawMarkupStyles(e,o),n()},a.src=r.src},drawText=function(e,t,r){var n=getMarkupRect(r,t),i=getMarkupStyles(r,t);applyMarkupStyles(e,i);var o=getMarkupValue(r.fontSize,t),a=r.fontFamily||\"sans-serif\",c=r.fontWeight||\"normal\",l=r.textAlign||\"left\";return e.font=\"\".concat(c,\" \").concat(o,\"px \").concat(a),e.textAlign=l,e.fillText(r.text,n.x,n.y),drawMarkupStyles(e,i),!0},drawPath=function(e,t,r){var n=getMarkupStyles(r,t);applyMarkupStyles(e,n),e.beginPath();var i=r.points.map(function(e){return{x:getMarkupValue(e.x,t,1,\"width\"),y:getMarkupValue(e.y,t,1,\"height\")}});e.moveTo(i[0].x,i[0].y);for(var o=i.length,a=1;a2&&void 0!==arguments[2]?arguments[2]:{};return new Promise(function(n,i){if(!e||!isImage(e.type))return i({status:\"not an image file\",file:e});var o=r.stripImageHead,a=r.beforeCreateBlob,c=r.afterCreateBlob,l=r.canvasMemoryLimit,u=t.crop,s=t.size,d=t.filter,p=t.markup,f=t.output,h=t.image&&t.image.orientation?Math.max(1,Math.min(8,t.image.orientation)):null,g=f&&f.quality,m=null===g?null:g/100,v=f&&f.type||null,y=f&&f.background||null,E=[];!s||\"number\"!=typeof s.width&&\"number\"!=typeof s.height||E.push({type:\"resize\",data:s}),d&&20===d.length&&E.push({type:\"filter\",data:d});var T=function(e){var t=c?c(e):e;Promise.resolve(t).then(n)},_=function(t,r){var n=imageDataToCanvas(t),c=p.length?canvasApplyMarkup(n,p):n;Promise.resolve(c).then(function(t){canvasToBlob(t,r,a).then(function(r){if(canvasRelease(t),o)return T(r);getImageHead(e).then(function(e){null!==e&&(r=new Blob([e,r.slice(20)],{type:r.type})),T(r)})}).catch(i)})};if(/svg/.test(e.type)&&null===v)return cropSVG(e,u,p,{background:y}).then(function(e){n(createBlob(e,\"image/svg+xml\"))});var R=URL.createObjectURL(e);loadImage(R).then(function(t){URL.revokeObjectURL(R);var r=imageToImageData(t,h,u,{canvasMemoryLimit:l,background:y}),n={quality:m,type:v||e.type};if(!E.length)return _(r,n);var i=createWorker(TransformWorker);i.post({transforms:E,imageData:r},function(e){_(objectToImageData(e),n),i.terminate()},[r.data.buffer])}).catch(i)})},readExif=function(e,t){if(1165519206!==e.getUint32(t+=2,!1))return-1;var r=18761===e.getUint16(t+=6,!1);t+=e.getUint32(t+4,r);var n=e.getUint16(t,r);t+=2;for(var i=0;i3&&void 0!==arguments[3])||arguments[3],i=e.center,o=e.zoom,a=e.aspectRatio,c=rectCenter(t),l={x:c.x-r.width*i.x,y:c.y-r.height*i.y},u=2*Math.PI+e.rotation%(2*Math.PI),s=o*getImageRectZoomFactor(r,getCenteredCropRect(t,a||r.height/r.width),u,n?i:{x:.5,y:.5});return{origin:{x:i.x*r.width,y:i.y*r.height},translation:l,scale:s,rotation:e.rotation}},copyImageTransforms=function(e){return{origin:_objectSpread({},e.origin),translation:_objectSpread({},e.translation),rotation:e.rotation,scale:e.scale}},limitImageTransformsToCropRect=function(e,t,r,n){var i=r.translation,o=r.scale,a=r.rotation,c=r.origin,l={origin:_objectSpread({},c),translation:_objectSpread({},i),scale:o,rotation:2*Math.PI+a%(2*Math.PI)},u=e.height/e.width,s=getAxisAlignedCropRect(c,i,l.rotation,t),d=rectCenter(s),p=rectBounds(s),f=getAxisAlignedImageRect(e,r),h=rectCenter(f),g={x:f.x,y:f.y},m={x:h.x,y:h.y},v=d.x,y=d.y,E={x:g.x,y:g.y,width:f.width,height:f.height};if(!rectFitsInRect(s,f))if(\"moving\"===n){E.y>s.y?E.y=s.y:E.y+E.heights.x?E.x=s.x:E.x+E.widths.y?E.y=s.y:E.y+E.heights.x?E.x=s.x:E.x+E.widths.y?E.y=s.y:E.y+E.heights.x?E.x=s.x:E.x+E.widths.y?E.y=s.y:E.y+E.heights.x?E.x=s.x:E.x+E.widths.y){var x=E.y-s.y;E.y=s.y,E.height+=2*x,O=!0}if(E.y+E.heights.x){var M=E.x-s.x;E.x=s.x,E.width+=2*M,O=!0}if(E.x+E.widths.right||u.bottom>s.bottom||u.left=p.bottom){var y=p.bottom-p.top,E=p.right-p.left,T=Math.max(1,l.height/y),_=y*T,R=E*T-E;p.bottom=u.bottom,p.top=u.bottom-_,p.left-=.5*R,p.right+=.5*R}if(u.left<=p.left){var w=p.bottom-p.top,A=p.right-p.left,I=Math.max(1,l.width/A),S=A*I,C=w*I-w;p.right=u.left+S,p.left=u.left,p.top-=.5*C,p.bottom+=.5*C}if(u.right>=p.right){var O=p.bottom-p.top,x=p.right-p.left,b=Math.max(1,l.width/x),M=x*b,L=O*b-O;p.right=u.right,p.left=u.right-M,p.top-=.5*L,p.bottom+=.5*L}d=createRect(p.left,p.top,p.right-p.left,p.bottom-p.top)}var P=rectCorners(d),G=rectCenter(d),k=vectorRotate(P.tl,o,c),D=vectorRotate(P.br,o,c),U=k.x+.5*(D.x-k.x),B=k.y+.5*(D.y-k.y),V=rectTranslate(d,{x:U-G.x,y:B-G.y}),N=rectTranslate(l,{x:U-G.x,y:B-G.y}),F=rectCenter(N),z={x:V.x,y:V.y},W=V.width,q=V.height,H=(F.x-z.x)/W,Y=(F.y-z.y)/q,j=W/e.width,X={x:H*e.width,y:Y*e.height},Z=1-j,$=X.x*Z,K=X.y*Z,Q={x:z.x+W*H,y:z.y+q*Y},J=vectorRotate(z,o,{x:z.x+.5*W,y:z.y+.5*q}),ee=vectorRotate(z,o,Q),te=J.x-ee.x,re=J.y-ee.y;return{origin:X,translation:{x:z.x-$+te,y:z.y-K+re},scale:j,rotation:r.rotation}},getEdgeTargetRect=function(e,t,r,n,i,o,a,c,l){var u=o.left,s=o.right,d=o.top,p=o.bottom,f=s-u,h=p-d,g=i.left,m=i.right,v=i.top,y=i.bottom;if(r===Direction.VERTICAL){if(v=e.y>0?n.y:Math.min(n.y,Math.max(t.y,d)),y=e.y>0?Math.max(n.y,Math.min(t.y,p)):n.y,a){var E=(y-v)/a;g=n.x-.5*E,m=n.x+.5*E}}else if(g=e.x>0?n.x:Math.min(n.x,Math.max(t.x,u)),m=e.x>0?Math.max(n.x,Math.min(t.x,s)):n.x,a){var T=(m-g)*a;v=n.y-.5*T,y=n.y+.5*T}var _,R,w,A,I=c.width,S=c.height;if(r===Direction.VERTICAL?(_=n.x-.5*I,R=n.x+.5*I,e.y<0?(w=n.y-S,A=n.y):e.y>0&&(w=n.y,A=n.y+S)):(w=n.y-.5*S,A=n.y+.5*S,e.x<0?(_=n.x-I,R=n.x):e.x>0&&(_=n.x,R=n.x+I)),a)if(r===Direction.VERTICAL){var C=Math.min((y-v)/a,f),O=C*a;gs&&(g=(m=s)-C),n.x=g+.5*C,e.y<0?v=n.y-O:e.y>0&&(y=n.y+O)}else{var x=Math.min((m-g)*a,h),b=x/a;vp&&(v=(y=p)-x),n.y=v+.5*x,e.x<0?g=n.x-b:e.x>0&&(m=n.x+b)}var M=rectFromBounds({top:v,right:m,bottom:y,left:g}),L=function(){var t=I*a;r===Direction.HORIZONTAL?(v=n.y-.5*t,y=n.y+.5*t):e.y<0?(y=n.y,v=y-t):e.y>0&&(v=n.y,y=v+t)},P=function(){var t=S/a;r===Direction.VERTICAL?(g=n.x-.5*t,m=n.x+.5*t):e.x<0?(m=n.x,g=m-t):e.x>0&&(g=n.x,m=g+t)};m_&&(g=_,m=_+I,a&&L()),v>w&&(v=w,y=w+S,a&&P()),yG&&(e.x<0?g=n.x-G:m=n.x+G),y-v>k&&(e.y<0?v=n.y-k:y=n.y+k),m-g==0&&(e.x>0?m=n.x+2:g=n.x-2),y-v==0&&(e.y>0?y=n.y+2:v=n.y-2),Math.round(g)s||Math.round(v)p){var D=p-d,U=s-u;if(gs){m=s;var V=Math.min(m-g,U);g=m-V}if(vp){y=p;var F=Math.min(y-v,D);v=y-F}M=rectFromBounds({top:v,right:m,bottom:y,left:g})}return{free:M,limited:rectFromBounds({top:v,right:m,bottom:y,left:g})}},CornerMap={nw:function(e){return{x:e.x,y:e.y}},ne:function(e){return{x:e.x+e.width,y:e.y}},se:function(e){return{x:e.x+e.width,y:e.y+e.height}},sw:function(e){return{x:e.x,y:e.y+e.height}}},getCornerCoordinates=function(e,t){return CornerMap[e](t)},getCornerTargetRect=function(e,t,r,n,i,o,a){var c=rectBounds(n),l=c.left,u=c.right,s=c.top,d=c.bottom,p=vectorLimit({x:t.x,y:t.y},n),f=e.x>0?r.x:Math.min(p.x,r.x),h=e.x>0?Math.max(r.x,p.x):r.x,g=e.y>0?r.y:Math.min(p.y,r.y),m=e.y>0?Math.max(r.y,p.y):r.y;if(i){var v=p.x-r.x;e.x>0?h=Math.max(r.x,r.x+e.x*v):f=Math.min(r.x,r.x-e.x*v),e.y>0?m=Math.max(r.y,r.y+e.x*v*i):g=Math.min(r.y,r.y-e.x*v*i)}var y=rectFromBounds({top:g,right:h,bottom:m,left:f});rectFromBounds({top:g,right:h,bottom:m,left:f});if(o.width&&o.height){var E=o.width,T=o.height;i&&(1===i?T=E=Math.max(E,T):ET?T=E*i:E=T/i),h-f0?h=r.x+E:f=r.x-E),m-g0?m=r.y+T:g=r.y-T);var _=a.width,R=a.height;i&&(i<1?_=R/i:R=_*i),h-f>_&&(e.x<0?f=r.x-_:h=r.x+_),m-g>R&&(e.y<0?g=r.y-R:m=r.y+R)}if(h-f==0&&(e.x>0?h=r.x+2:f=r.x-2),m-g==0&&(e.y>0?m=r.y+2:g=r.y-2),Math.round(f)u||Math.round(g)d){var w=d-s,A=u-l;if(f0&&(m=r.y+I*i),e.y<0&&(g=r.y-I*i))}if(h>u){h=u;var S=Math.min(h-f,A);f=h-S,i&&(e.y>0&&(m=r.y+S*i),e.y<0&&(g=r.y-S*i))}if(g0&&(h=r.x+C/i),e.x<0&&(f=r.x-C/i))}if(m>d){m=d;var O=Math.min(m-g,w);g=m-O,i&&(e.x>0&&(h=r.x+O/i),e.x<0&&(f=r.x-O/i))}y=rectFromBounds({top:g,right:h,bottom:m,left:f})}return{free:y,limited:rectFromBounds({top:g,right:h,bottom:m,left:f})}},getTargetRect=function(e,t,r){var n=rectClone(e);return n.width=Math.min(n.height,n.width),n.height=n.width,n.height=n.width*t,n.heightt&&(o-=r,i+=r),{main:i,sub:o}},getImageSize=function(e){return new Promise(function(t,r){var n=new Image;n.src=URL.createObjectURL(e),n.onerror=function(e){clearInterval(i),r(e)};var i=setInterval(function(){n.naturalWidth&&n.naturalHeight&&(clearInterval(i),URL.revokeObjectURL(n.src),t({width:n.naturalWidth,height:n.naturalHeight}))},1)})},scaleImageSize=function(e,t){var r={width:e.width,height:e.height};if(e.width>t.width||e.height>t.height){var n=e.height/e.width,i=t.width/e.width,o=t.height/e.height;i1&&void 0!==arguments[1]?arguments[1]:\"\";return(t+e).slice(-t.length)},getDateString=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;return\"\".concat(e.getFullYear(),\"-\").concat(leftPad(e.getMonth()+1,\"00\"),\"-\").concat(leftPad(e.getDate(),\"00\"),\"_\").concat(leftPad(e.getHours(),\"00\"),\"-\").concat(leftPad(e.getMinutes(),\"00\"),\"-\").concat(leftPad(e.getSeconds(),\"00\"))},getBaseCropInstructions=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=e(\"GET_CROP_ASPECT_RATIO\"),o={center:{x:.5,y:.5},flip:{horizontal:!1,vertical:!1},zoom:1,rotation:0,aspectRatio:null};r?Object.assign(o,r):t.options.crop?Object.assign(o,t.options.crop):o.aspectRatio=i;var a=n.width,c=n.height;if(a&&c)o.aspectRatio=c/a;else if(t.instructions.size){var l=t.instructions.size,u=l.width,s=l.height;u&&s&&(o.aspectRatio=s/u)}return o},capitalizeFirstLetter=function(e){return e.charAt(0).toUpperCase()+e.slice(1)},getExtensionFromFilename=function(e){return e.split(\".\").pop()},guesstimateExtension=function(e){if(\"string\"!=typeof e)return\"\";var t=e.split(\"/\").pop();return/svg/.test(t)?\"svg\":/zip|compressed/.test(t)?\"zip\":/plain/.test(t)?\"txt\":/msword/.test(t)?\"doc\":/[a-z]+/.test(t)?\"jpeg\"===t?\"jpg\":t:\"\"},getFileFromBlob=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=\"string\"==typeof r?e.slice(0,e.size,r):e.slice(0,e.size,e.type);return i.lastModifiedDate=new Date,isString(t)||(t=getDateString()),t&&null===n&&getExtensionFromFilename(t)?i.name=t:(n=n||guesstimateExtension(i.type),i.name=t+(n?\".\"+n:\"\")),i},getFilenameWithoutExtension=function(e){return e.substr(0,e.lastIndexOf(\".\"))||e},ExtensionMap={jpeg:\"jpg\",\"svg+xml\":\"svg\"},renameFileToMatchMimeType=function(e,t){var r=getFilenameWithoutExtension(e),n=t.split(\"/\")[1],i=ExtensionMap[n]||n;return\"\".concat(r,\".\").concat(i)},getValidOutputMimeType=function(e){return/jpeg|png|svg\\+xml/.test(e)?e:\"image/jpeg\"},isColorMatrix=function(e){return Array.isArray(e)&&20===e.length},MARKUP_RECT=[\"x\",\"y\",\"left\",\"top\",\"right\",\"bottom\",\"width\",\"height\"],toOptionalFraction=function(e){return\"string\"==typeof e&&/%/.test(e)?parseFloat(e)/100:e},getUniqueId$2=function(){return Math.random().toString(36).substr(2,9)},prepareMarkup=function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1],i=!1!==n.allowSelect,o=!1!==n.allowMove,a=!1!==n.allowResize,c=!1!==n.allowInput,l=!1!==n.allowDestroy,u=void 0===n.allowEdit||n.allowEdit;(!0===n.allowResize||!0===n.allowMove||!0===n.allowInput||n.allowEdit)&&(i=!0),!1===n.allowMove&&(a=!1),!0===n.allowResize&&(o=!0);var s=n.points?{}:MARKUP_RECT.reduce(function(e,t){return e[t]=toOptionalFraction(n[t]),e},{});return n.points&&(a=!1),[r,_objectSpread({zIndex:0,id:getUniqueId$2()},n,s,{isDestroyed:!1,isSelected:!1,isDirty:!0,allowDestroy:l,allowSelect:i,allowMove:o,allowResize:a,allowInput:c,allowEdit:u})]},getFilenameFromHeader=function(e){if(!e)return null;var t=e.split(/filename=|filename\\*=.+''/).splice(1).map(function(e){return e.trim().replace(/^[\"']|[;\"']{0,2}$/g,\"\")}).filter(function(e){return e.length});return t.length?decodeURI(t[t.length-1]):null},brightness=function(e){return[1,0,0,0,e,0,1,0,0,e,0,0,1,0,e,0,0,0,1,0]},contrast=function(e){return[e,0,0,0,.5*(1-e),0,e,0,0,.5*(1-e),0,0,e,0,.5*(1-e),0,0,0,1,0]},saturation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return[.213+.787*e,.715-.715*e,.072-.072*e,0,0,.213-.213*e,.715+.285*e,.072-.072*e,0,0,.213-.213*e,.715-.715*e,.072+.928*e,0,0,0,0,0,1,0]},exposure=function(e){return[e,0,0,0,0,0,e,0,0,0,0,0,e,0,0,0,0,0,1,0]},testSrc=\"data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/4QA6RXhpZgAATU0AKgAAAAgAAwESAAMAAAABAAYAAAEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wAALCAABAAIBASIA/8QAJgABAAAAAAAAAAAAAAAAAAAAAxABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAAPwBH/9k=\",shouldCorrect=void 0,testImage=isBrowser()?new Image:{};testImage.onload=function(){shouldCorrect=testImage.naturalWidth>testImage.naturalHeight,testImage=void 0},testImage.src=testSrc;var shouldCorrectImageExifOrientation=function(){return shouldCorrect},testResult$1=null,isIE=function(){return null===testResult$1&&(testResult$1=/MSIE|Trident/.test(window.navigator.userAgent)),testResult$1},COLOR_TOOLS={contrast:contrast,exposure:exposure,brightness:brightness,saturation:saturation},getColorProperty=function(e){return e.borderWidth?\"borderColor\":e.lineWidth?\"lineColor\":e.fontColor?\"fontColor\":e.backgroundColor?\"backgroundColor\":void 0},getColor=function(e){var t=e.fontColor,r=e.backgroundColor,n=e.lineColor,i=e.borderColor;return t||r||n||i},TURN$1=Math.PI/2,getOutputSize=function(e){var t={upscale:e(\"GET_OUTPUT_UPSCALE\"),mode:e(\"GET_OUTPUT_FIT\"),width:e(\"GET_OUTPUT_WIDTH\"),height:e(\"GET_OUTPUT_HEIGHT\")},r=e(\"GET_SIZE_INPUT\");if(r.width||r.height){var n=r.width,i=r.height,o=e(\"GET_CROP_RECTANGLE_ASPECT_RATIO\");n&&!i?i=n/o:i&&!n&&(n=i*o),t.width=n,t.height=i,t.upscale=!0,t.mode=\"force\"}return t},getPreparedImageSize=function(e,t){var r=t(\"GET_UID\"),n=t(\"GET_CROP\",r,Date.now()),i={width:n.cropStatus.currentWidth,height:n.cropStatus.currentHeight},o=e.mode,a=e.width,c=e.height,l=e.upscale;if(!a&&!c)return i;if(null===a?a=c:null===c&&(c=a),\"force\"!==o){var u=a/i.width,s=c/i.height,d=1;if(\"cover\"===o?d=Math.max(u,s):\"contain\"===o&&(d=Math.min(u,s)),d>1&&!1===l)return i;a=i.width*d,c=i.height*d}return{width:Math.round(a),height:Math.round(c)}},getActiveMarkupFromState=function(e){return e.markup.filter(function(e){return!e[1].isDestroyed})},cleanMarkupForExport=function(e){return e.map(function(e){var t=_objectSpread({},e[1]);return Object.keys(t).forEach(function(e){void 0===t[e]&&delete t[e]}),delete t.isDestroyed,delete t.isSelected,delete t.isDirty,[e[0],t]})},prepareOutput=function(e,t,r){return new Promise(function(n,i){var o={data:null,file:null},a=getCropFromStateRounded(t.image,t.crop),c=getOutputSize(r),l={crop:a,image:_objectSpread({},getPreparedImageSize(c,r),{orientation:t.file.orientation}),size:c,output:{type:r(\"GET_OUTPUT_TYPE\"),quality:r(\"GET_OUTPUT_QUALITY\"),background:t.options.outputCanvasBackgroundColor},filter:t.colorMatrices.filter?{id:t.filterName,value:t.filterValue,matrix:t.colorMatrices.filter}:null,color:Object.keys(t.colorValues).length?Object.keys(t.colorValues).reduce(function(e,r){return e[r]={value:t.colorValues[r],matrix:t.colorMatrices[r].map(function(e){return roundFloat(e,5)})},e},{}):null,markup:cleanMarkupForExport(getActiveMarkupFromState(t).map(function(e){return[e[0],_objectSpread({},e[1])]})),colorMatrix:r(\"GET_COLOR_MATRIX\")};if(e.data&&(o.data=l),e.file){var u={beforeCreateBlob:r(\"GET_BEFORE_CREATE_BLOB\"),afterCreateBlob:r(\"GET_AFTER_CREATE_BLOB\"),stripImageHead:r(\"GET_OUTPUT_STRIP_IMAGE_HEAD\"),canvasMemoryLimit:r(\"GET_OUTPUT_CANVAS_MEMORY_LIMIT\")},s=t.file.data,d=_objectSpread({},l,{filter:l.colorMatrix,markup:l.markup});transformImage(s,d,u).then(function(e){o.file=getFileFromBlob(e,renameFileToMatchMimeType(s.name,getValidOutputMimeType(e.type))),n(o)}).catch(i)}else n(o)})},resetRotationScale=function(e){e.crop.draft.rotateMinScale=null},storeRotationScale=function(e){e.crop.draft.rotateMinScale||(e.crop.draft.rotateMinScale=e.crop.transforms.scale)},rotate=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];storeRotationScale(e);var o=_objectSpread({},e.crop.transforms,{scale:e.crop.draft.rotateMinScale});e.crop.draft.transforms=getRotateTransforms(e.image,e.crop.rectangle,o,t.main+t.sub,r,e.crop.draft.transforms?e.crop.draft.transforms.rotation:e.crop.rotation.main+e.crop.rotation.sub,n,i),e.crop.rotation=splitRotation(e.crop.draft.transforms.rotation)},resetCrop=function(e,t){if(null!==e.stage){var r=void 0===e.instructions.crop.scaleToFit?void 0===e.crop.limitToImageBounds?e.options.cropLimitToImageBounds:e.crop.limitToImageBounds:e.instructions.crop.scaleToFit,n=t(\"GET_STAGE_RECT\",e.instructions.crop);e.crop.rectangle=getCenteredCropRect(n.fits?n:e.stage,e.instructions.crop.aspectRatio||e.image.aspectRatio),e.crop.draft.rectangle=null,\"stage\"!==n.mode&&n.fits&&(e.crop.rectangle.x=n.x,e.crop.rectangle.y=n.y),e.crop.transforms=getImageTransformsFromCrop(e.instructions.crop,n,e.image,r),e.crop.draft.transforms=null,e.crop.rotation=splitRotation(e.instructions.crop.rotation),e.crop.flip=_objectSpread({},e.instructions.crop.flip);var i=t(\"GET_CROP_ASPECT_RATIO_OPTIONS\")||[],o=i.map(function(e){return e.value.aspectRatio}).find(function(t){return t===e.instructions.crop.aspectRatio}),a=i.find(function(e){return null===e.value.aspectRatio});o?e.crop.aspectRatio=o:a&&i.length?e.crop.aspectRatio=null:e.crop.aspectRatio=t(\"GET_CROP_ASPECT_RATIO\"),e.crop.isDirty=!1}},reset=function(e,t,r){if(null!==e.stage){clearCenterTimeout(e),e.size.width=!!e.instructions.size&&e.instructions.size.width,e.size.height=!!e.instructions.size&&e.instructions.size.height,e.size.aspectRatioLocked=!0,e.size.aspectRatioPrevious=!1;var n=void 0===e.instructions.crop.scaleToFit?void 0===e.crop.limitToImageBounds?e.options.cropLimitToImageBounds:e.crop.limitToImageBounds:e.instructions.crop.scaleToFit;resetCrop(e,t),e.instructions.markup&&r(\"MARKUP_SET_VALUE\",{value:e.instructions.markup}),r(\"CROP_SET_LIMIT\",{value:n,silent:!0}),Object.keys(e.instructions.color).forEach(function(t){return r(\"COLOR_SET_VALUE\",{key:t,value:e.instructions.color[t]})}),r(\"FILTER_SET_VALUE\",{value:e.instructions.filter}),resetRotationScale(e)}},recenter=function(e,t){if(e.stage){clearCenterTimeout(e);var r=e.crop.rectangle,n=r.height/r.width,i=e.crop.aspectRatio;if(null!==i&&roundFloat(n,3)!==roundFloat(i,3)){var o=t(\"GET_MIN_CROP_SIZE\");o.width=roundFloat(o.width),o.height=roundFloat(o.height);var a=Math.min(r.width,r.height);Math.min(a*i,a/i)roundFloat(s,5)?(a&&(o+=2*a),_objectSpread({},copyImageTransforms(r),{rotation:o,interaction:{rotation:u.rotation}})):(u.scale=Math.min(s,u.scale),u.interaction={rotation:u.rotation},u)},getResizeTransforms=function(e,t,r,n,i,o){var a=Math.max(1e-10,n),c=_objectSpread({},copyImageTransforms(r),{scale:a}),l=o?limitImageTransformsToCropRect(e,t,c,\"resizing\"):c,u=getMinScale(t,i);return l.scale=Math.min(u,l.scale),l.interaction={scale:a},l},getTranslateTransforms=function(e,t,r,n,i){var o={x:r.translation.x+n.x,y:r.translation.y+n.y},a=_objectSpread({},copyImageTransforms(r),{translation:o}),c=i?limitImageTransformsToCropRect(e,t,a,\"moving\"):a;return c.interaction={translation:o},c},correctCropRectangleByResize=function(e,t){var r=roundFloat(e.crop.draft.transforms.scale,5);if(!(roundFloat(e.crop.draft.targetSize,5)=0?e.getResponseHeader(t):null},ImageExtensionMap={svg:\"svg+xml\",jpg:\"jpeg\"},getImageMimeType=function(e,t){if(isImage(e))return e;if(!t)return e;var r=getExtensionFromFilename(t);return r?\"image/\".concat(ImageExtensionMap[r]||r):e},getFilenameFromURL=function(e){return e.split(\"/\").pop().split(\"?\").shift()},loadImageFromURL=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.progress,n=void 0===r?function(e){}:r,i=t.load,o=void 0===i?function(e,t){}:i,a=t.error,c=void 0===a?function(){}:a,l=new XMLHttpRequest;l.onprogress=function(e){return n(e.lengthComputable?e.loaded/e.total:null)},l.onerror=function(){return c(l)},l.onload=function(){var t=l.status>=200&&l.status<300,r=l.response;if(!t||!r)return c(l);var n=getResponseHeaderSilent(l,\"Content-Disposition\"),i=n?getFilenameFromHeader(n):getFilenameFromURL(e),a=getImageMimeType(l.getResponseHeader(\"Content-Type\"),i),u=getResponseHeaderSilent(l,\"Content-Doka\"),s=null;if(u)try{s=JSON.parse(u)}catch(e){}!isImage(r.type)&&a&&(r=r.slice(0,r.size,a)),\"name\"in r||!i||(r.name=i),o(r,s)},l.open(\"GET\",e),l.responseType=\"blob\",l.send()},dataURIToBlob=function(e){for(var t=e.split(\",\"),r=t[0].match(/([a-z]+\\/[a-z]+)/)[0],n=atob(t[1]),i=n.length,o=new ArrayBuffer(n.length),a=new Uint8Array(o),c=0;c-1){var d=u.width,p=u.height;s>=5&&s<=8&&(u.width=p,u.height=d)}var f=t(\"GET_MIN_IMAGE_SIZE\");if(u.width1?.5/o:.5,c=o>1?.5:.5*o,l=function(){return{width:a,height:c,x:.5+.5*i()-.5*a,y:.5+.5*i()-.5*c}},u=function(e){return t(\"GET_MARKUP_TOOL_VALUES\")[e]},s=function(){var e=u(\"shapeStyle\"),t=u(\"color\"),r=e[0]||e[1]?null:t;return{backgroundColor:r,borderWidth:e[0],borderStyle:e[1]?e[1]:null,borderColor:null!==r?null:t}},d={rect:function(){return _objectSpread({},l(),s())},ellipse:function(){return _objectSpread({},l(),s())},text:function(){return{x:.5+.5*i()-.1,y:.5+.5*i(),width:0,height:0,fontColor:u(\"color\"),fontSize:u(\"fontSize\"),fontFamily:u(\"fontFamily\"),text:\"Text\"}},line:function(){var e=u(\"lineStyle\");return _objectSpread({},l(),{lineColor:u(\"color\"),lineWidth:e[0],lineStyle:e[1]?e[1]:null,lineDecoration:u(\"lineDecoration\")})}}[n]();e(\"MARKUP_ADD\",[n,d])},MARKUP_ADD:function(n){var i=t(\"GET_BEFORE_ADD_MARKUP\");if(!i||(n=i(n))){r.markup.forEach(function(e){return e[1].isSelected=!1}),r.markup=r.markup.filter(function(e){return!e[1].isDestroyed});var o=prepareMarkup(n);r.markup.push(o),r.markup.sort(sortMarkupByZIndex);var a=t(\"GET_ONADDMARKUP\");a&&a(o),\"draw\"!==t(\"GET_MARKUP_UTIL\")&&e(\"MARKUP_SELECT\",{id:o[1].id}),r.crop.isDirty=!0}},MARKUP_SELECT:function(e){var n=e.id;r.markup.forEach(function(e){e[1].isSelected=e[1].id===n,e[1].isDirty=!0});var i=t(\"GET_ONSELECTMARKUP\");i&&i(t(\"GET_MARKUP_BY_ID\",n))},MARKUP_ELEMENT_DRAG:function(e){var t=e.id,n=e.origin,i=e.offset,o=e.size,a=r.markup.find(function(e){return e[1].id===t});if(a){var c=a[1],l=n.x/o.width,u=n.y/o.height,s=n.width/o.width,d=n.height/o.height,p=i.x/o.width,f=i.y/o.height;c.x=l+p,c.y=u+f,c.width=s,c.height=d,c.left=void 0,c.top=void 0,c.right=void 0,c.bottom=void 0,c.isDirty=!0,r.crop.isDirty=!0}},MARKUP_ELEMENT_RESIZE:function(e){var t=e.id,n=e.corner,i=e.origin,o=e.offset,a=e.size,c=r.markup.find(function(e){return e[1].id===t});if(c){var l=_slicedToArray(c,2),u=l[0],s=l[1],d=(i.x+o.x)/a.width,p=(i.y+o.y)/a.height;if(/n/.test(n))if(\"line\"===u)s.height=s.height-(p-s.y),s.y=p;else{var f=s.y+s.height;p>f&&(p=f),s.height=s.height-(p-s.y),s.y=p}if(/w/.test(n))if(\"line\"===u)s.width=s.width-(d-s.x),s.x=d;else{var h=s.x+s.width;d>h&&(d=h),s.width=s.width-(d-s.x),s.x=d}/s/.test(n)&&(s.height=\"line\"===u?p-s.y:Math.max(0,p-s.y)),/e/.test(n)&&(s.width=\"line\"===u?d-s.x:Math.max(0,d-s.x)),s.left=void 0,s.top=void 0,s.right=void 0,s.bottom=void 0,s.isDirty=!0,r.crop.isDirty=!0}},MARKUP_DELETE:function(n){var i=n.id,o=r.markup.find(function(e){return e[1].id===i});if(o){var a=t(\"GET_BEFORE_REMOVE_MARKUP\");if(!a||(o=a(o))){var c=o[1];c.allowDestroy&&(c.isDestroyed=!0,c.isSelected=!1,c.isDirty=!0);for(var l=null,u=r.markup.length;u>0;){u--;var s=r.markup[u][1];if(!s.isDestroyed&&s.allowDestroy){l=s.id;break}}var d=t(\"GET_ONREMOVEMARKUP\");d&&d(o),e(\"MARKUP_SELECT\",{id:l})}}},MARKUP_UPDATE:function(e){var t=e.style,n=e.value;r.markupToolValues[t]=n,r.markup.map(function(e){return e[1]}).filter(function(e){return e.isSelected}).forEach(function(e){if(\"color\"===t)e[getColorProperty(e)]=n;else if(\"shapeStyle\"===t){var r=getColor(e);e.borderColor=r,e.borderWidth=n[0],e.borderStyle=n[1],e.backgroundColor=n[0]||n[1]?null:r,null!==e.backgroundColor&&(e.borderColor=null)}else\"lineStyle\"===t?(e.lineWidth=n[0],e.lineStyle=n[1]):e[t]=n;e.isDirty=!0}),r.crop.isDirty=!0}},[\"color\",\"shapeStyle\",\"lineStyle\",\"textDecoration\",\"fontSize\",\"fontFamily\"].reduce(function(t,n){var i=n.split(/(?=[A-Z])/).join(\"_\").toUpperCase(),o=capitalizeFirstLetter(n);return t[\"SET_MARKUP_\"+i]=function(t){var i=t.value;i!==t.prevValue&&(r.options[\"markup\".concat(o)]=i,e(\"MARKUP_UPDATE\",{style:n,value:i}))},t},{}),{DID_SET_CROP:function(t){var r=t.value;r!==t.prevValue&&e(\"SET_DATA\",{crop:r})},COLOR_SET_COLOR_VALUE:function(t){var n=t.key,i=t.value;r.crop.isDirty=!0,e(\"COLOR_SET_VALUE\",{key:n,value:i})},COLOR_SET_VALUE:function(t){var n=t.key,i=t.value;r.colorValues[n]=i,e(\"SET_COLOR_MATRIX\",{key:n,matrix:COLOR_TOOLS[n](i)})}},Object.keys(COLOR_TOOLS).reduce(function(n,i){var o=i.toUpperCase(),a=capitalizeFirstLetter(i);return n[\"SET_COLOR_\".concat(o)]=function(n){var c=n.value;if(c!==n.prevValue){var l=_slicedToArray(t(\"GET_COLOR_\".concat(o,\"_RANGE\")),2),u=l[0],s=l[1],d=limit(c,u,s);r.options[\"color\".concat(a)]=d,r.instructions.color||(r.instructions.color={}),r.instructions.color[i]=d,e(\"COLOR_SET_VALUE\",{key:i,value:d})}},n},{}),{SET_COLOR_MATRIX:function(t){var n=t.key,i=t.matrix;i?r.colorMatrices[n]=_toConsumableArray(i):delete r.colorMatrices[n],e(\"DID_SET_COLOR_MATRIX\",{key:n,matrix:i})},FILTER_SET_FILTER:function(t){var n=t.value;r.crop.isDirty=!0,e(\"FILTER_SET_VALUE\",{value:n})},FILTER_SET_VALUE:function(n){var i=n.value,o=isColorMatrix(i)?i:null;if(isString(i)){var a=t(\"GET_FILTERS\");forin(a,function(e,t){e===i&&(o=t.matrix())})}r.filter=i,r.filterName=isString(i)?i:null,e(\"SET_COLOR_MATRIX\",{key:\"filter\",matrix:o})},DID_SET_UTIL:function(t){var n=t.value;t.prevValue;-1!==r.options.utils.indexOf(n)&&e(\"CHANGE_VIEW\",{id:n})},DID_SET_FILTER:function(t){var r=t.value;r!==t.prevValue&&(r&&r.id&&(r=r.id),e(\"FILTER_SET_VALUE\",{value:r}),e(\"SET_DATA\",{filter:r}))},DID_SET_SIZE:function(t){var r=t.value;r!==t.prevValue&&e(\"SET_DATA\",{size:r})},DID_SET_MARKUP_UTIL:function(t){var r=t.value;r!==t.prevValue&&r&&(/^(draw|line|text|rect|ellipse)$/.test(r)||(r=\"select\"),e(\"SWITCH_MARKUP_UTIL\",{util:r}))},DID_SET_MARKUP:function(t){var r=t.value,n=t.prevValue;r!==n&&JSON.stringify(r)===JSON.stringify(n)||(e(\"MARKUP_SET_VALUE\",{value:r}),e(\"SET_DATA\",{markup:r}))},SET_DATA:function(n){if(n.size){var i=_objectSpread({width:null,height:null},n.size),o=limitSize(i,t(\"GET_SIZE_MIN\"),t(\"GET_SIZE_MAX\"),null);r.instructions.size=_objectSpread({},o),e(\"RESIZE_SET_OUTPUT_SIZE\",o)}n.filter&&(r.instructions.filter=n.filter?n.filter.id||n.filter.matrix:n.colorMatrix),r.instructions.markup=n.markup||[],r.instructions.markup.forEach(function(e){return e[1].isDirty=!0}),r.instructions.color=Object.keys(COLOR_TOOLS).reduce(function(e,t){var i=void 0===n.color||void 0===n.color[t],o=r.options[\"color\".concat(capitalizeFirstLetter(t))];return e[t]=i?o:isNumber(n.color[t])?n.color[t]:n.color[t].value,e},{}),n.crop&&(r.instructions.crop=getBaseCropInstructions(t,r,n.crop,r.size),r.crop.limitToImageBounds=r.options.cropLimitToImageBounds,!1===r.instructions.crop.scaleToFit&&(r.crop.limitToImageBounds=r.instructions.crop.scaleToFit),resetCrop(r,t))},DID_SET_INITIAL_STATE:function(e){var n=e.value||{},i=n.crop,o=n.filter,a=n.color,c=n.size,l=void 0===c?{}:c,u=n.markup,s=void 0===u?[]:u,d=_objectSpread({width:null,height:null},l),p=limitSize(d,t(\"GET_SIZE_MIN\"),t(\"GET_SIZE_MAX\"),null);r.instructions.size=_objectSpread({},p),r.instructions.crop=getBaseCropInstructions(t,r,i),r.crop.limitToImageBounds=r.options.cropLimitToImageBounds,!1===r.instructions.crop.scaleToFit&&(r.crop.limitToImageBounds=r.instructions.crop.scaleToFit),r.instructions.filter=o||null,r.instructions.color=Object.keys(COLOR_TOOLS).reduce(function(e,t){return e[t]=void 0===a||void 0===a[t]?r.options[\"color\".concat(capitalizeFirstLetter(t))]:a[t],e},{}),r.instructions.markup=s,r.crop.isDirty=!0},GET_DATA:function(n){var i=n.success,o=n.failure,a=n.file,c=n.data;if(!r.file)return o(\"no-image-source\");if(!r.stage)return o(\"image-not-fully-loaded\");var l={file:isBoolean(a)?a:t(\"GET_OUTPUT_FILE\"),data:isBoolean(c)?c:t(\"GET_OUTPUT_DATA\"),success:i,failure:o};e(l.file?\"REQUEST_PREPARE_OUTPUT\":\"PREPARE_OUTPUT\",l)},REQUEST_PREPARE_OUTPUT:function(t){var r=t.file,n=t.data,i=t.success,o=t.failure;e(\"PREPARE_OUTPUT\",{file:r,data:n,success:i,failure:o},!0),e(\"DID_REQUEST_PREPARE_OUTPUT\")},PREPARE_OUTPUT:function(n){var i=n.file,o=n.data,a=n.success,c=void 0===a?function(){}:a,l=n.failure,u=void 0===l?function(){}:l;if(shouldAbortImageLoad(r))return e(\"ABORT_IMAGE\");var s=function(t){if(e(\"DID_PREPARE_OUTPUT\"),shouldAbortImageLoad(r))return e(\"ABORT_IMAGE\");c(t)};prepareOutput({file:i,data:o},r,t).then(function(t){var n=r.options.afterCreateOutput,i=n?n(t,function(t,r){return e(\"DID_REQUEST_POSTPROCESS_OUTPUT\",{label:t,progress:r}),function(t){e(\"DID_MAKE_PROGRESS\",{progress:t})}}):t;Promise.resolve(i).then(s).catch(function(t){e(\"DID_REQUEST_POSTPROCESS_OUTPUT_ERROR\",{error:t})})}).catch(function(t){if(shouldAbortImageLoad(r))return e(\"ABORT_IMAGE\");u(t)})},EDIT_RESET:function(){clearCenterTimeout(r),reset(r,t,e)},EDIT_CONFIRM:function(){if(r.file&&r.stage){clearCenterTimeout(r),e(\"CROP_ZOOM\");var n={file:t(\"GET_OUTPUT_FILE\"),data:t(\"GET_OUTPUT_DATA\"),success:function(t){r.filePromise.resolveOnConfirm&&r.filePromise.success(t),e(\"DID_CONFIRM\",{output:t})},failure:console.error};e(n.file?\"REQUEST_PREPARE_OUTPUT\":\"PREPARE_OUTPUT\",n)}},EDIT_CANCEL:function(){r.filePromise&&r.filePromise.success(null),e(\"DID_CANCEL\")},EDIT_CLOSE:function(){clearCenterTimeout(r)},EDIT_DESTROY:function(){resetState(r)},SET_OPTIONS:function(t){var r=t.options;forin(r,function(t,r){e(\"SET_\".concat(fromCamels(t,\"_\").toUpperCase()),{value:r})})}})},createIcon=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:24;return'\")},button=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"button\",mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"tween\",duration:250}},apis:[\"id\"],listeners:!0},tag:\"button\",create:function(e){var t=e.root,r=e.props;t.element.innerHTML=\"\".concat(r.icon||\"\",\"\").concat(r.label,\"\"),t.element.setAttribute(\"type\",r.type||\"button\"),r.name&&r.name.split(\" \").forEach(function(e){t.element.className+=\" doka--button-\".concat(e)}),t.ref.handleClick=function(){\"string\"==typeof r.action?t.dispatch(r.action):r.action()},t.element.addEventListener(\"click\",t.ref.handleClick),t.ref.handlePointer=function(e){return e.stopPropagation()},t.element.addEventListener(\"pointerdown\",t.ref.handlePointer),r.create&&r.create({root:t,props:r})},destroy:function(e){var t=e.root;t.element.removeEventListener(\"pointerdown\",t.ref.handlePointer),t.element.removeEventListener(\"click\",t.ref.handleClick)}}),textNode=function(e){return createView({ignoreRect:!0,tag:e,create:function(e){var t=e.root,r=e.props;t.element.textContent=r.text}})},progressIndicator=createView({name:\"status-progress\",tag:\"svg\",ignoreRect:!0,ignoreRectUpdate:!0,mixins:{apis:[\"progress\"],animations:{progress:{type:\"spring\",stiffness:.25,damping:.25,mass:2.5}}},create:function(e){var t=e.root,r=e.props;t.element.setAttribute(\"data-value\",0),t.element.setAttribute(\"width\",24),t.element.setAttribute(\"height\",24),t.element.setAttribute(\"viewBox\",\"0 0 20 20\");var n=t.ref.circle=document.createElementNS(\"http://www.w3.org/2000/svg\",\"circle\"),i={r:5,cx:10,cy:10,fill:\"none\",stroke:\"currentColor\",\"stroke-width\":10,transform:\"rotate(-90) translate(-20)\"};t.element.appendChild(n),Object.keys(i).forEach(function(e){n.setAttribute(e,i[e])}),t.ref.updateStroke=function(e){t.ref.circle.setAttribute(\"stroke-dasharray\",\"\".concat(31.42*Math.min(1,e),\" 31.42\"))},\"number\"==typeof r.progress?(t.progress=r.progress,t.element.setAttribute(\"data-value\",Math.max(r.progress,.001)),t.ref.updateStroke(t.progress)):t.progress=0},write:createRoute({DID_MAKE_PROGRESS:function(e){var t=e.root,r=e.action;t.progress=r.progress,t.element.setAttribute(\"data-value\",Math.max(r.progress,.001))}},function(e){var t=e.root;t.ref.updateStroke(t.progress)})}),statusBubbleInner=createView({name:\"status-bubble-inner\",create:function(e){var t=e.root,r=e.props;r.onClose?t.appendChildView(t.createChildView(button,{label:\"Close\",name:\"icon-only status-bubble-close\",icon:createIcon(''),action:r.onClose})):t.ref.progressIndicator=t.appendChildView(t.createChildView(progressIndicator,{progress:r.progress})),t.appendChildView(t.createChildView(textNode(\"p\"),{text:r.label}))}}),statusBubble=createView({name:\"status-bubble\",mixins:{styles:[\"opacity\",\"translateY\"],apis:[\"markedForRemoval\"],animations:{opacity:{type:\"tween\",duration:500},translateY:{type:\"spring\",mass:20}}},create:function(e){var t=e.root,r=e.props;return t.appendChildView(t.createChildView(statusBubbleInner,r))}}),hideBusyIndicators=function(e){e.element.dataset.viewStatus=\"idle\",hideBusyIndicatorsAnimated(e)},hideBusyIndicatorsAnimated=function(e){e.ref.busyIndicators.forEach(function(e){e.translateY=-10,e.opacity=0,e.markedForRemoval=!0})},showBusyIndicator=function(e,t,r,n){e.element.dataset.viewStatus=\"busy\";var i=addBusyIndicator(e,t,r,n);hideBusyIndicatorsAnimated(e),e.ref.busyIndicators.push(i),i.markedForRemoval=!1,i.translateY=0,i.opacity=1},addBusyIndicator=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;return e.appendChildView(e.createChildView(statusBubble,{translateY:20,opacity:0,label:t,onClose:r,progress:n}))},editStatus=createView({name:\"edit-status\",ignoreRect:!0,create:function(e){var t=e.root;t.ref.busyIndicators=[],t.element.setAttribute(\"tabindex\",-1)},write:createRoute({MISSING_WEBGL:function(e){var t=e.root,r=/fullscreen/.test(t.query(\"GET_STYLE_LAYOUT_MODE\"));showBusyIndicator(t,t.query(\"GET_LABEL_STATUS_MISSING_WEB_G_L\"),r?function(){t.dispatch(\"EDIT_CANCEL\")}:null)},AWAITING_IMAGE:function(e){var t=e.root;showBusyIndicator(t,t.query(\"GET_LABEL_STATUS_AWAITING_IMAGE\"))},DID_PRESENT_IMAGE:function(e){var t=e.root;hideBusyIndicators(t)},DID_LOAD_IMAGE_ERROR:function(e){var t=e.root,r=e.action,n=/fullscreen/.test(t.query(\"GET_STYLE_LAYOUT_MODE\")),i=t.query(\"GET_LABEL_STATUS_LOAD_IMAGE_ERROR\"),o=\"function\"==typeof i?i(r.error):i;showBusyIndicator(t,o,n?function(){t.dispatch(\"EDIT_CANCEL\")}:null)},DID_REQUEST_LOAD_IMAGE:function(e){var t=e.root;showBusyIndicator(t,t.query(\"GET_LABEL_STATUS_LOADING_IMAGE\"))},DID_REQUEST_PREPARE_OUTPUT:function(e){var t=e.root;showBusyIndicator(t,t.query(\"GET_LABEL_STATUS_PROCESSING_IMAGE\"))},DID_REQUEST_POSTPROCESS_OUTPUT:function(e){var t=e.root,r=e.action;showBusyIndicator(t,r.label,null,r.progress)},DID_REQUEST_POSTPROCESS_OUTPUT_ERROR:function(e){var t=e.root,r=e.action.error;showBusyIndicator(t,r,function(){return t.dispatch(\"DID_PREPARE_OUTPUT\")})},DID_PREPARE_OUTPUT:function(e){var t=e.root;hideBusyIndicators(t)}}),didWriteView:function(e){var t=e.root;t.ref.busyIndicators=t.ref.busyIndicators.filter(function(e){return!e.markedForRemoval||0!==e.opacity||(t.removeChildView(e),!1)})}}),Interaction={down:\"pointerdown\",move:\"pointermove\",up:\"pointerup\"},createPointerRegistry=function(){var e=[],t=function(t){return e.findIndex(function(e){return e.pointerId===t.pointerId})};return{update:function(r){var n=t(r);n<0||(e[n]=r)},multiple:function(){return e.length>1},count:function(){return e.length},active:function(){return e.concat()},push:function(r){(function(e){return t(e)>=0})(r)||e.push(r)},pop:function(r){var n=t(r);n<0||e.splice(n,1)}}},addEvent$1=function(e,t,r,n){return e.addEventListener(Interaction[t],r,n)},removeEvent$1=function(e,t,r){return e.removeEventListener(Interaction[t],r)},contains=function(e,t){if(\"contains\"in e)return e.contains(t);var r=t;do{if(r===e)return!0}while(r=r.parentNode);return!1},createDragger=function(e,t,r,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{stopPropagation:!0,cancelOnMultiple:!1},o={x:0,y:0},a={enabled:!0,origin:null,cancel:!1,cancelled:!1,pointers:createPointerRegistry()},c=null,l=function(e,t){t&&(c||u(e,t),cancelAnimationFrame(c),c=requestAnimationFrame(function(){u(e,t),c=null}))},u=function(e,t){return t.apply(null,[e,function(e){return{x:e.pageX-o.x,y:e.pageY-o.y}}(e)])},s=function(r){var n=0===a.pointers.count();n&&(a.active=!1,a.cancel=!1,a.cancelled=!1),(e===r.target||contains(e,r.target))&&(n?r.isPrimary&&(a.pointers.push(r),addEvent$1(document.documentElement,\"up\",p),r.preventDefault(),i.stopPropagation&&(r.stopPropagation(),r.stopImmediatePropagation()),a.active=!0,o.x=r.pageX,o.y=r.pageY,addEvent$1(document.documentElement,\"move\",d),t(r)):i.cancelOnMultiple&&(a.cancel=!0))},d=function(e){e.isPrimary&&(a.cancelled||(e.preventDefault(),i.stopPropagation&&e.stopPropagation(),l(e,r),a.cancel&&(a.cancelled=!0,l(e,n))))},p=function e(t){a.pointers.pop(t),0===a.pointers.count()&&(removeEvent$1(document.documentElement,\"move\",d),removeEvent$1(document.documentElement,\"up\",e)),a.active&&(a.cancelled||(t.preventDefault(),i.stopPropagation&&t.stopPropagation(),l(t,r),l(t,n)))};return addEvent$1(document.documentElement,\"down\",s),{enable:function(){a.enabled||addEvent$1(document.documentElement,\"down\",s),a.enabled=!0},disable:function(){a.enabled&&removeEvent$1(document.documentElement,\"down\",s),a.enabled=!1},destroy:function(){removeEvent$1(document.documentElement,\"up\",p),removeEvent$1(document.documentElement,\"move\",d),removeEvent$1(document.documentElement,\"down\",s)}}},imageOverlaySpring={type:\"spring\",stiffness:.4,damping:.65,mass:7},activateMarkupUtil=function(e,t,r){if(/^(line|text|ellipse|rect)$/.test(r))e.dispatch(\"MARKUP_ADD_DEFAULT\",{value:r}),e.dispatch(\"SET_MARKUP_UTIL\",{value:\"select\"});else if(\"draw\"===r&&!e.ref.drawInput){var n=e.ref,i=n.drawState,o=n.viewSize,a=0,c=0,l={},u=e.query(\"GET_MARKUP_DRAW_DISTANCE\");e.ref.drawInput=createDragger(e.element,function(r){var n=e.query(\"GET_MARKUP_TOOL_VALUES\"),u=n.lineStyle[0],s=n.lineStyle[1];i.lineColor=n.color,i.lineWidth=u,i.lineStyle=s;var d=e.query(\"GET_ROOT\"),p=void 0!==r.offsetX?r.offsetX:r.pageX-d.x-t.stageOffsetX-window.pageXOffset,f=void 0!==r.offsetY?r.offsetY:r.pageY-d.y-t.stageOffsetY-window.pageYOffset;a=p-e.markupX,c=f-e.markupY,l.x=0,l.y=0,i.points.push({x:a/o.width,y:c/o.height})},function(t,r){if(e.dispatch(\"KICK\"),u){var n=vectorDistance(r,l);if(n>u){var s=vectorAngleBetween(l,r)+Math.PI/2,d=u-n;l.x+=Math.sin(s)*d,l.y-=Math.cos(s)*d,i.points.push({x:(a+l.x)/o.width,y:(c+l.y)/o.height})}}else i.points.push({x:(a+r.x)/o.width,y:(c+r.y)/o.height})},function(t,r){i.points.length>1&&e.dispatch(\"MARKUP_ADD\",[\"path\",_objectSpread({},i)]),i.points=[]})}\"draw\"!==r&&e.ref.drawInput&&(e.ref.drawInput.destroy(),e.ref.drawInput=null)},getColor$1=function(e){var t=e.fontColor,r=e.backgroundColor,n=e.lineColor,i=e.borderColor;return t||r||n||i},MARKUP_MARGIN=10,setAttributes$1=function(e,t){return Object.keys(t).forEach(function(r){e.setAttribute(r,t[r])})},ns$2=\"http://www.w3.org/2000/svg\",svg$1=function(e,t){var r=document.createElementNS(ns$2,e);return t&&setAttributes$1(r,t),r},LINE_CORNERS=[\"nw\",\"se\"],RECT_CORNERS=[\"nw\",\"n\",\"ne\",\"w\",\"e\",\"sw\",\"s\",\"se\"],CORNER_CURSOR={nw:\"nwse\",n:\"ns\",ne:\"nesw\",w:\"ew\",e:\"ew\",sw:\"nesw\",s:\"ns\",se:\"nwse\"},CORNER_COORDINATES={nw:function(e){return{x:e.x,y:e.y}},n:function(e){return{x:e.x+.5*e.width,y:e.y}},ne:function(e){return{x:e.x+e.width,y:e.y}},w:function(e){return{x:e.x,y:e.y+.5*e.height}},e:function(e){return{x:e.x+e.width,y:e.y+.5*e.height}},sw:function(e){return{x:e.x,y:e.y+e.height}},s:function(e){return{x:e.x+.5*e.width,y:e.y+e.height}},se:function(e){return{x:e.x+e.width,y:e.y+e.height}}},HITBOX_OFFSET=5,HITBOX_COORDINATES={nw:function(e){return{x:e.x-HITBOX_OFFSET,y:e.y-HITBOX_OFFSET}},n:function(e){return{x:e.x+.5*e.width,y:e.y-HITBOX_OFFSET}},ne:function(e){return{x:e.x+e.width+HITBOX_OFFSET,y:e.y-HITBOX_OFFSET}},w:function(e){return{x:e.x-HITBOX_OFFSET,y:e.y+.5*e.height}},e:function(e){return{x:e.x+e.width+HITBOX_OFFSET,y:e.y+.5*e.height}},sw:function(e){return{x:e.x-HITBOX_OFFSET,y:e.y+e.height+HITBOX_OFFSET}},s:function(e){return{x:e.x+.5*e.width,y:e.y+e.height+HITBOX_OFFSET}},se:function(e){return{x:e.x+e.width+HITBOX_OFFSET,y:e.y+e.height+HITBOX_OFFSET}}},imageMarkup=createView({tag:\"div\",name:\"image-markup\",ignoreRect:!0,mixins:{styles:[\"opacity\"],animations:{opacity:\"spring\",markupX:imageOverlaySpring,markupY:imageOverlaySpring,markupWidth:imageOverlaySpring,markupHeight:imageOverlaySpring},listeners:!0,apis:[\"toolsReference\",\"onSelect\",\"onDrag\",\"markupX\",\"markupY\",\"markupWidth\",\"markupHeight\",\"allowInteraction\",\"stageOffsetX\",\"stageOffsetY\"]},create:function(e){var t=e.root,r=e.props,n=r.onSelect,i=void 0===n?function(){}:n,o=r.onUpdate,a=void 0===o?function(){}:o,c=svg$1(\"svg\",{xmlns:\"http://www.w3.org/2000/svg\",\"xmlns:xlink\":\"http://www.w3.org/1999/xlink\"});t.ref.canvas=c;var l=t.query(\"GET_ROOT_SIZE\");c.setAttribute(\"width\",l.width),c.setAttribute(\"height\",l.height);var u=document.createElement(\"input\");setAttributes$1(u,{type:\"text\",autocomplete:\"off\",autocapitalize:\"off\"}),u.addEventListener(\"keydown\",function(e){e.stopPropagation(),13===e.keyCode||9===e.keyCode?(e.target.blur(),d()):8!==e.keyCode||t.ref.input.value.length||t.dispatch(\"MARKUP_DELETE\",{id:t.ref.selected.id})}),t.ref.input=u,t.ref.elements=[],t.ref.viewSize={width:0,height:0,scale:0},t.ref.resetSelected=function(){return t.ref.selected={id:null,type:null,settings:{}},t.ref.selected},t.ref.resetSelected();var s=function(e){return e.id?e:e.parentNode},d=function(){t.ref.resetSelected(),i(null)};t.ref.handleDeselect=function(e){var n;(t.query(\"IS_ACTIVE_VIEW\",\"markup\")||t.query(\"IS_ACTIVE_VIEW\",\"sticker\"))&&(t.ref.selected.id&&e.target!==t.ref.removeButton.element&&(n=e.target,t.ref.selected.id!==s(n).id&&(function(e){return contains(t.ref.manipulatorGroup,e)||e===t.ref.input}(e.target)||r.isMarkupUtil(e.target)||d())))},addEvent$1(document.body,\"down\",t.ref.handleDeselect),t.ref.handleTextInput=function(){return a(\"text\",t.ref.input.value)},t.ref.input.addEventListener(\"input\",t.ref.handleTextInput),t.ref.handleAttemptDelete=function(e){(t.query(\"IS_ACTIVE_VIEW\",\"markup\")||t.query(\"IS_ACTIVE_VIEW\",\"sticker\"))&&(!t.ref.selected.id||8!==e.keyCode&&46!==e.keyCode||(e.stopPropagation(),e.preventDefault(),t.dispatch(\"MARKUP_DELETE\",{id:t.ref.selected.id})))},document.body.addEventListener(\"keydown\",t.ref.handleAttemptDelete);var p=svg$1(\"g\"),f=svg$1(\"g\",{class:\"doka--shape-group\"});p.appendChild(f),t.ref.shapeGroup=f;var h=svg$1(\"g\",{fill:\"none\",class:\"doka--manipulator-group\"}),g=svg$1(\"rect\",{x:0,y:0,width:0,height:0,fill:\"none\"}),m=svg$1(\"path\");h.appendChild(m),h.appendChild(g),t.ref.manipulatorPath=m,t.ref.manipulatorRect=g,t.ref.manipulators=[];for(var v=0;v<10;v++){var y=svg$1(\"circle\",{r:6,\"stroke-width\":2}),E=svg$1(\"circle\",{r:22,class:\"doka--hitbox\",style:\"opacity: 0\"});h.appendChild(E),h.appendChild(y),t.ref.manipulators.push({visual:y,hitbox:E,dragger:null})}p.appendChild(h),t.ref.manipulatorGroup=h,c.appendChild(p),t.ref.shapeOffsetGroup=p,t.ref.removeButton=t.appendChildView(t.createChildView(button,{label:t.query(\"GET_LABEL_MARKUP_REMOVE_SHAPE\"),name:\"destroy-shape\",action:function(){t.dispatch(\"MARKUP_DELETE\",{id:t.ref.selected.id})}})),(t.query(\"IS_ACTIVE_VIEW\",\"markup\")||t.query(\"IS_ACTIVE_VIEW\",\"sticker\"))&&(t.element.dataset.active=!0),t.ref.drawInput=null,t.ref.drawState={lineColor:null,lineWidth:null,lineStyle:null,points:[]};var T=svg$1(\"path\",{fill:\"none\",class:\"doka--draw-path\"});t.ref.drawPath=T,c.appendChild(T);var _=createElement(\"div\",\"doka--image-markup-clip\");_.appendChild(u),_.appendChild(c),t.ref.clip=_,t.element.appendChild(_),\"draw\"===t.query(\"GET_MARKUP_UTIL\")&&activateMarkupUtil(t,r,\"draw\")},destroy:function(e){var t=e.root;t.ref.elements.concat(t.ref.manipulators).forEach(function(e){e.dragger&&e.dragger.destroy()}),t.ref.input.removeEventListener(\"input\",t.ref.handleTextInput),document.body.removeEventListener(\"keydown\",t.ref.handleAttemptDelete),removeEvent$1(document.body,\"down\",t.ref.handleDeselect)},read:function(e){var t=e.root;if(!t.rect.element.hidden)for(var r in t.ref.elements){var n=t.ref.elements[r];if(n&&\"text\"===n.nodeName&&n.parentNode){var i=n.getBBox();n.bbox={x:i.x,y:i.y,width:i.width,height:i.height}}}},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.props,n=e.action;\"markup\"===n.id||\"sticker\"===n.id?t.element.dataset.active=!0:(t.element.dataset.active=!1,r.onSelect(null))},MARKUP_SET_VALUE:function(e){var t=e.root;forin(t.ref.elements,function(e,t){t&&t.dragger&&t.dragger.destroy()}),t.ref.elements=[],t.ref.shapeGroup.innerHTML=\"\"},UPDATE_ROOT_RECT:function(e){var t=e.root,r=e.action,n=t.ref.canvas;n.setAttribute(\"width\",r.rect.width),n.setAttribute(\"height\",r.rect.height),t.ref.previousScale=null},SWITCH_MARKUP_UTIL:function(e){var t=e.root,r=e.action,n=e.props,i=r.util;activateMarkupUtil(t,n,i)}},function(e){var t=e.root,r=e.props,n=e.timestamp;if(!(t.opacity<=0)){var i=t.query(\"GET_CROP\",r.id,n);if(i){var o=t.query(\"GET_MARKUP_UTIL\");t.element.dataset.util=o||\"\";var a=i.markup,c=i.cropStatus,l=r.onSelect,u=r.onDrag,s=t.ref,d=s.clip,p=s.manipulatorGroup,f=s.drawPath,h=s.viewSize,g=s.shapeOffsetGroup,m=s.manipulators,v=s.manipulatorPath,y=s.manipulatorRect,E=s.removeButton,T=s.drawState,_=t.query(\"GET_OUTPUT_WIDTH\"),R=t.query(\"GET_OUTPUT_HEIGHT\"),w=c.image,A=c.crop,I=A.width,S=A.height,C=A.widthFloat/A.heightFloat;if(_||R){var O=t.query(\"GET_OUTPUT_FIT\");_&&!R&&(R=_),R&&!_&&(_=R);var x,b=_/I,M=R/S;if(\"force\"===O)I=_,S=R;else\"cover\"===O?x=Math.max(b,M):\"contain\"===O&&(x=Math.min(b,M)),I*=x,S*=x}else w.width&&w.height?(I=w.width,S=w.height):w.width&&!w.height?(I=w.width,S=w.width/C):w.height&&!w.width&&(S=w.height,I=w.height*C);var L=T.points.length,P=roundFloat(t.markupX,3),G=roundFloat(t.markupY,3),k=roundFloat(t.markupWidth,3),D=roundFloat(t.markupHeight,3),U=roundFloat(Math.min(t.markupWidth/I,t.markupHeight/S),4);if(h.width=k,h.height=D,h.scale=U,stateHasChanged(t,{drawLength:L,markupX:P,markupY:G,scale:U,markup:a,currentWidth:I,currentHeight:S})){var B=P,V=t.rect.element.width-P-k,N=G,F=t.rect.element.height-G-D,z=\"inset(\".concat(N,\"px \").concat(V,\"px \").concat(F,\"px \").concat(B,\"px)\");if(d.style.clipPath=z,d.style.webkitClipPath=z,g.setAttribute(\"transform\",\"translate(\".concat(P,\" \").concat(G,\")\")),t.ref.previousDrawLength=L,t.ref.previousX=P,t.ref.previousY=G,t.ref.previousScale=U,t.ref.previousCurrentHeight=S,t.ref.previousCurrentWidth=I,t.ref.previousMarkupLength=a.length,!(h.width<1||h.height<1)){var W,q=a.find(function(e){return e[1].isSelected}),H=q&&t.ref.selected.id!==q[1].id||t.ref.selected.id&&!q;if(W=q?t.ref.selected={id:q[1].id,type:q[0],settings:q[1]}:t.ref.resetSelected(),T.points.length){var Y=getMarkupStyles(T,h,U);return Y.d=pointsToPathShape(T.points.map(function(e){return{x:P+e.x*h.width,y:G+e.y*h.height}})),void setAttributes$1(f,Y)}f.removeAttribute(\"d\"),t.ref.input.hidden=\"text\"!==t.ref.selected.type||!t.ref.selected.settings.allowInput,E.element.dataset.active=null!==t.ref.selected.id,v.setAttribute(\"style\",\"opacity:0\"),y.setAttribute(\"style\",\"opacity:0\"),m.forEach(function(e){e.visual.setAttribute(\"style\",\"opacity:0; pointer-events:none;\"),e.hitbox.setAttribute(\"style\",\"pointer-events:none;\")});var j=t.query(\"GET_MARKUP_FILTER\");a.filter(j).sort(sortMarkupByZIndex).forEach(function(e,n){var i=_slicedToArray(e,2),o=i[0],a=i[1],c=a.id,s=a.isDestroyed,d=a.isDirty,f=a.isSelected,g=a.allowSelect,T=a.allowMove,_=a.allowResize,R=a.allowInput;if(s){var w=t.ref.elements[c];w&&(w.dragger&&w.dragger.destroy(),t.ref.elements[c]=null,w.parentNode.removeChild(w))}else{var A,I,S,C=t.ref.elements[c];if(!C)if(C=createMarkupByType(o,a),t.ref.elements[c]=C,g)C.dragger=createDragger(C,function(){I=Date.now(),A=_objectSpread({},C.rect),(S=c===t.ref.selected.id)||l(c)},function(e,t){T&&u(c,A,t,h,U)},function(e,r){if(R&&\"text\"===o&&S){var n=vectorDistanceSquared({x:0,y:0},r),i=Date.now()-I;if(!(n>10||i>750)){t.ref.input.focus();var a=t.markupX+C.bbox.x,c=C.bbox.width,l=(e.offsetX-a)/c,u=Math.round(t.ref.input.value.length*l);t.ref.input.setSelectionRange(u,u)}}}),C.dragger.disable();else C.setAttribute(\"style\",\"pointer-events:none;\");if(C.dragger&&(r.allowInteraction?C.dragger.enable():C.dragger.disable()),n!==C.index){C.index=n;var O=t.ref.shapeGroup;O.insertBefore(C,O.childNodes[n+1])}if(d&&updateMarkupByType(C,o,a,h,U),f){var x=E.rect.element.width,b=E.rect.element.height,M=t.markupX-.5*x,L=t.markupY-b-15,P=\"text\"===o?C.bbox:C.rect,G=!1,k=getColor$1(a);if(k){var D=toRGBColorArray(k);G=(.2126*D[0]+.7152*D[1]+.0722*D[2])/255>.65,p.setAttribute(\"is-bright-color\",G)}\"line\"===o?(M+=P.x,L+=P.y,setAttributes$1(v,{d:\"M \".concat(P.x,\" \").concat(P.y,\" L \").concat(P.x+P.width,\" \").concat(P.y+P.height),style:\"opacity:1\"})):\"path\"===o?(M+=(P={x:a.points[0].x*h.width,y:a.points[0].y*h.height,width:0,height:0}).x,L+=P.y,setAttributes$1(v,{d:pointsToPathShape(a.points.map(function(e){return{x:e.x*h.width,y:e.y*h.height}})),style:\"opacity:1\"})):P&&(M+=P.x+.5*P.width,L+=P.y,setAttributes$1(y,{x:P.x-(\"text\"===o?5:0),y:P.y,width:P.width+(\"text\"===o?10:0),height:P.height,style:\"opacity:1\"}));var B=t.markupY+MARKUP_MARGIN,V=t.markupY+t.markupHeight-MARKUP_MARGIN,N=t.markupX+MARKUP_MARGIN,F=t.markupX+t.markupWidth-MARKUP_MARGIN;if(LV&&(L=V-b),MF&&(M=F-x),P||(E.element.dataset.active=\"false\"),E.element.setAttribute(\"style\",\"transform: translate3d(\".concat(M,\"px, \").concat(L,\"px, 0)\")),\"text\"===o&&P&&R){var z=P.width+65,W=t.markupWidth-P.x,q=\"\\n width: \".concat(Math.min(z,W),\"px;\\n height: \").concat(P.height,\"px;\\n color: \").concat(C.getAttribute(\"fill\"),\";\\n font-family: \").concat(C.getAttribute(\"font-family\"),\";\\n font-size: \").concat(C.getAttribute(\"font-size\").replace(/px/,\"\"),\"px;\\n font-weight: \").concat(C.getAttribute(\"font-weight\")||\"normal\",\";\\n \");isIOS()?q+=\"\\n left: \".concat(Math.round(t.markupX+P.x),\"px;\\n top: \").concat(Math.round(t.markupY+P.y),\"px;\\n \"):q+=\"\\n transform: translate3d(\".concat(Math.round(t.markupX+P.x),\"px,\").concat(Math.round(t.markupY+P.y),\"px,0);\\n \"),t.ref.input.setAttribute(\"style\",q),C.setAttribute(\"fill\",\"none\")}if(\"text\"===o)return;if(!_)return;var H=\"line\"===o?LINE_CORNERS:RECT_CORNERS;m.forEach(function(e,t){var r=H[t];if(r){var n=\"line\"===o?\"move\":\"\".concat(CORNER_CURSOR[r],\"-resize\"),i=CORNER_COORDINATES[r](C.rect),a=C.rect.width<100||C.rect.height<100,c=2===r.length?1:a?0:1;setAttributes$1(e.visual,{cx:i.x,cy:i.y,style:\"opacity:\".concat(c)});var l=HITBOX_COORDINATES[r](C.rect);setAttributes$1(e.hitbox,{cx:l.x,cy:l.y,style:\"cursor:\".concat(n,\";\")})}})}a.isDirty=!1}}),H&&(destroyElementControls(t),\"text\"===W.type&&t.ref.selected.settings.allowInput?t.ref.input.value=W.settings.text:t.ref.selected.id&&setupElementControls(t,r.onResize))}}}}})}),markAllAsDirty=function(e){return e.forEach(function(e){return e[1].isDirty=!0})},stateHasChanged=function(e,t){var r=t.drawLength,n=t.markup,i=t.markupX,o=t.markupY,a=t.currentWidth,c=t.currentHeight,l=t.scale;return r!==e.ref.previousDrawLength||(i!==e.ref.previousX?(markAllAsDirty(n),!0):o!==e.ref.previousY?(markAllAsDirty(n),!0):l!==e.ref.previousScale?(markAllAsDirty(n),!0):c!==e.ref.previousCurrentHeight?(markAllAsDirty(n),!0):a!==e.ref.previousCurrentWidth?(markAllAsDirty(n),!0):n.length!==e.ref.previousMarkupLength||!!n.find(function(e){return e[1].isDirty}))},setupElementControls=function(e,t){var r=e.ref.selected.id,n=\"g\"===e.ref.elements[r].nodeName?LINE_CORNERS:RECT_CORNERS;e.ref.manipulators.forEach(function(i,o){var a=n[o];if(a){var c=null;i.dragger=createDragger(i.hitbox,function(){c={x:parseFloat(attr(i.hitbox,\"cx\")),y:parseFloat(attr(i.hitbox,\"cy\"))}},function(n,i){t(r,a,c,i,e.ref.viewSize)},null,{stopPropagation:!0})}})},destroyElementControls=function(e){e.ref.manipulators.forEach(function(e){e.dragger&&(e.dragger.destroy(),e.dragger=null)})},KEY_MAP={38:\"up\",40:\"down\",37:\"left\",39:\"right\",189:\"minus\",187:\"plus\",72:\"h\",76:\"l\",81:\"q\",82:\"r\",84:\"t\",86:\"v\",90:\"z\",219:\"left_bracket\",221:\"right_bracket\"},createKeyboard=function(e,t,r,n,i){var o=null,a=!0,c={enabled:!0},l=function(e){var i=KEY_MAP[e.keyCode]||e.keyCode;r[i]&&(e.stopPropagation(),a&&(o=t(i),a=!1),r[i](o),n(o))},u=function(e){var t=KEY_MAP[e.keyCode]||e.keyCode;r[t]&&(e.stopPropagation(),i(o),a=!0)};return e.addEventListener(\"keydown\",l),e.addEventListener(\"keyup\",u),{enable:function(){c.enabled||(e.addEventListener(\"keydown\",l),e.addEventListener(\"keyup\",u)),c.enabled=!0},disable:function(){c.enabled&&(e.removeEventListener(\"keydown\",l),e.removeEventListener(\"keyup\",u)),c.enabled=!1},destroy:function(){e.removeEventListener(\"keydown\",l),e.removeEventListener(\"keyup\",u)}}},createPreviewImage=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4?arguments[4]:void 0;t=Math.round(t),r=Math.round(r);var o=i||document.createElement(\"canvas\"),a=o.getContext(\"2d\");return n>=5&&n<=8?(o.width=r,o.height=t):(o.width=t,o.height=r),a.save(),-1!==n&&a.transform.apply(a,getImageOrientationMatrix(t,r,n)),a.drawImage(e,0,0,t,r),a.restore(),o},BitmapWorker=function(){self.onmessage=function(e){createImageBitmap(e.data.message.file).then(function(t){self.postMessage({id:e.data.id,message:t},[t])})}},isBitmap=function(e){return/^image/.test(e.type)&&!/svg/.test(e.type)},canCreateImageBitmap=function(e){var t=window.navigator.userAgent.match(/Firefox\\/([0-9]+)\\./);return!((t?parseInt(t[1]):null)<=58)&&(\"createImageBitmap\"in window&&isBitmap(e))},loadImage$2=function(e){return new Promise(function(t,r){var n=new Image;n.onload=function(){t(n)},n.onerror=function(e){r(e)},n.src=e})},compileShader=function(e,t,r){var n=e.createShader(r);return e.shaderSource(n,t),e.compileShader(n),n},createProgram=function(e,t,r){var n=e.createProgram();return e.attachShader(n,compileShader(e,t,e.VERTEX_SHADER)),e.attachShader(n,compileShader(e,r,e.FRAGMENT_SHADER)),e.linkProgram(n),n},createTexture=function(e,t,r,n,i){var o=e.createTexture();e.activeTexture(e.TEXTURE0+n),e.bindTexture(e.TEXTURE_2D,o),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.uniform1i(t,n),e.uniform2f(r,i.width,i.height);try{e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,i)}catch(t){e.texImage2D(e.TEXTURE_2D,0,e.RGBA,i.width,i.height,0,e.RGBA,e.UNSIGNED_BYTE,null)}return o},create=function(){var e=new Float32Array(16);return e[0]=1,e[5]=1,e[10]=1,e[15]=1,e},perspective=function(e,t,r,n,i){var o=1/Math.tan(t/2),a=1/(n-i);e[0]=o/r,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=o,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,e[10]=(i+n)*a,e[14]=2*i*n*a},translate=function(e,t){var r=t[0],n=t[1],i=t[2];e[12]=e[0]*r+e[4]*n+e[8]*i+e[12],e[13]=e[1]*r+e[5]*n+e[9]*i+e[13],e[14]=e[2]*r+e[6]*n+e[10]*i+e[14],e[15]=e[3]*r+e[7]*n+e[11]*i+e[15]},scale=function(e,t){var r=t[0],n=t[1],i=t[2];e[0]=e[0]*r,e[1]=e[1]*r,e[2]=e[2]*r,e[3]=e[3]*r,e[4]=e[4]*n,e[5]=e[5]*n,e[6]=e[6]*n,e[7]=e[7]*n,e[8]=e[8]*i,e[9]=e[9]*i,e[10]=e[10]*i,e[11]=e[11]*i},rotateX=function(e,t){var r=Math.sin(t),n=Math.cos(t),i=e[4],o=e[5],a=e[6],c=e[7],l=e[8],u=e[9],s=e[10],d=e[11];e[4]=i*n+l*r,e[5]=o*n+u*r,e[6]=a*n+s*r,e[7]=c*n+d*r,e[8]=l*n-i*r,e[9]=u*n-o*r,e[10]=s*n-a*r,e[11]=d*n-c*r},rotateY=function(e,t){var r=Math.sin(t),n=Math.cos(t),i=e[0],o=e[1],a=e[2],c=e[3],l=e[8],u=e[9],s=e[10],d=e[11];e[0]=i*n-l*r,e[1]=o*n-u*r,e[2]=a*n-s*r,e[3]=c*n-d*r,e[8]=i*r+l*n,e[9]=o*r+u*n,e[10]=a*r+s*n,e[11]=c*r+d*n},rotateZ=function(e,t){var r=Math.sin(t),n=Math.cos(t),i=e[0],o=e[1],a=e[2],c=e[3],l=e[4],u=e[5],s=e[6],d=e[7];e[0]=i*n+l*r,e[1]=o*n+u*r,e[2]=a*n+s*r,e[3]=c*n+d*r,e[4]=l*n-i*r,e[5]=u*n-o*r,e[6]=s*n-a*r,e[7]=d*n-c*r},mat4={create:create,perspective:perspective,translate:translate,scale:scale,rotateX:rotateX,rotateY:rotateY,rotateZ:rotateZ},degToRad=function(e){return e*Math.PI/180},imageFragmentShader=\"\\nprecision mediump float;\\n\\nuniform sampler2D uTexture;\\nuniform vec2 uTextureSize;\\n\\nuniform float uColorOpacity;\\nuniform mat4 uColorMatrix;\\nuniform vec4 uColorOffset;\\n\\nuniform vec4 uOverlayColor;\\nuniform vec2 uOverlayLeftTop;\\nuniform vec2 uOverlayRightBottom;\\n\\nvarying vec2 vTexCoord;\\nvarying vec4 vPosition;\\n\\nvoid main () {\\n\\n vec3 cB = vec3(1.0);\\n\\n\\tvec4 cF = texture2D(uTexture, vTexCoord);\\n\\t\\n\\tvec4 cM = (cF * uColorMatrix) + uColorOffset;\\n\\n float r = max(0.0, cM.r * cM.a) + (cB.r * (1.0 - cM.a));\\n float g = max(0.0, cM.g * cM.a) + (cB.g * (1.0 - cM.a));\\n float b = max(0.0, cM.b * cM.a) + (cB.b * (1.0 - cM.a));\\n\\n\\tvec4 color = vec4(r, g, b, cF.a);\\n\\t\\n\\t// test if falls within\\n if ((gl_FragCoord.x < uOverlayLeftTop.x || gl_FragCoord.x > uOverlayRightBottom.x) || \\n (gl_FragCoord.y > uOverlayLeftTop.y || gl_FragCoord.y < uOverlayRightBottom.y)) {\\n\\t\\tcolor *= uOverlayColor;\\n\\t}\\n\\t\\n gl_FragColor = color * uColorOpacity;\\n}\\n\",imageVertexShader=\"\\nattribute vec4 aPosition;\\nattribute vec2 aTexCoord;\\nuniform mat4 uMatrix;\\n\\n// send to fragment shader\\nvarying vec2 vTexCoord;\\nvarying vec4 vPosition;\\n\\nvoid main () {\\n vPosition = uMatrix * aPosition;\\n gl_Position = vPosition;\\n vTexCoord = aTexCoord;\\n}\\n\",backgroundFragmentShader=\"\\nprecision mediump float;\\n\\nuniform vec2 uViewportSize;\\nuniform vec3 uColorStart;\\nuniform vec3 uColorEnd;\\nuniform vec2 uOverlayLeftTop;\\nuniform vec2 uOverlayRightBottom;\\nuniform vec4 uColorCanvasBackground;\\n\\nvoid main() {\\n\\n\\tfloat x = gl_FragCoord.x;\\n\\tfloat y = gl_FragCoord.y;\\n\\n\\tvec2 center = vec2(.5, .5);\\n\\tvec2 st = vec2(x / uViewportSize.x, y / uViewportSize.y);\\n\\tfloat mixValue = distance(st, center) * 1.5; // expand outside view (same as doka--root::after)\\n\\tvec3 color = mix(uColorStart, uColorEnd, mixValue);\\n\\n\\tif (uColorCanvasBackground[3] == 1.0) {\\n\\n\\t\\tfloat innerLeft = uOverlayLeftTop.x;\\n\\t\\tfloat innerRight = uOverlayRightBottom.x;\\n\\t\\tfloat innerTop = uOverlayRightBottom.y;\\n\\t\\tfloat innerBottom = uOverlayLeftTop.y;\\n\\n\\t\\tif (x < innerLeft || x > innerRight || y < innerTop || y > innerBottom) {\\n\\t\\t\\tgl_FragColor = vec4(color, 1.0);\\n\\t\\t\\treturn;\\n\\t\\t}\\n\\n\\t\\tgl_FragColor = uColorCanvasBackground;\\n\\t\\treturn;\\n\\t}\\n\\t\\n\\tgl_FragColor = vec4(color, 1.0);\\n}\\n\",outlineFragmentShader=\"\\nprecision mediump float;\\n\\nuniform vec2 uOverlayLeftTop;\\nuniform vec2 uOverlayRightBottom;\\nuniform vec4 uOutlineColor;\\nuniform float uOutlineWidth;\\n\\nvoid main() {\\n\\n\\tfloat x = gl_FragCoord.x;\\n\\tfloat y = gl_FragCoord.y;\\n\\n\\tfloat innerLeft = uOverlayLeftTop.x;\\n\\tfloat innerRight = uOverlayRightBottom.x;\\n\\tfloat innerTop = uOverlayRightBottom.y;\\n\\tfloat innerBottom = uOverlayLeftTop.y;\\n\\n\\tfloat outerLeft = innerLeft - uOutlineWidth;\\n\\tfloat outerRight = innerRight + uOutlineWidth;\\n\\tfloat outerTop = innerTop - uOutlineWidth;\\n\\tfloat outerBottom = innerBottom + uOutlineWidth;\\n\\t\\n\\tif (x < outerLeft || x >= outerRight || y < outerTop || y >= outerBottom) {\\n\\t\\tdiscard;\\n\\t}\\n\\n\\tif (x < innerLeft || x >= innerRight || y < innerTop || y >= innerBottom) {\\n\\t\\tgl_FragColor = uOutlineColor;\\n\\t}\\n}\\n\",simpleVertexShader=\"\\nattribute vec4 aPosition;\\nvoid main() {\\n\\tgl_Position = aPosition;\\n}\\n\",setup=function(e,t,r){var n={width:0,height:0},i={x:0,y:0},o=null,a=degToRad(30),c=Math.tan(a/2),l={antialias:!1,alpha:!1},u=e.getContext(\"webgl\",l)||e.getContext(\"experimental-webgl\",l);if(!u)return null;u.enable(u.BLEND),u.blendFunc(u.SRC_ALPHA,u.ONE_MINUS_SRC_ALPHA);var s=createProgram(u,simpleVertexShader,backgroundFragmentShader),d=u.getUniformLocation(s,\"uColorStart\"),p=u.getUniformLocation(s,\"uColorEnd\"),f=u.getUniformLocation(s,\"uViewportSize\"),h=u.getAttribLocation(s,\"aPosition\"),g=u.getUniformLocation(s,\"uOverlayLeftTop\"),m=u.getUniformLocation(s,\"uOverlayRightBottom\"),v=u.getUniformLocation(s,\"uColorCanvasBackground\"),y=u.createBuffer(),E=new Float32Array([1,-1,1,1,-1,-1,-1,1]);u.bindBuffer(u.ARRAY_BUFFER,y),u.bufferData(u.ARRAY_BUFFER,E,u.STATIC_DRAW),u.bindBuffer(u.ARRAY_BUFFER,null);var T=createProgram(u,simpleVertexShader,outlineFragmentShader),_=u.getAttribLocation(T,\"aPosition\"),R=u.getUniformLocation(T,\"uOutlineWidth\"),w=u.getUniformLocation(T,\"uOutlineColor\"),A=u.getUniformLocation(T,\"uOverlayLeftTop\"),I=u.getUniformLocation(T,\"uOverlayRightBottom\"),S=u.createBuffer(),C=new Float32Array([1,-1,1,1,-1,-1,-1,1]);u.bindBuffer(u.ARRAY_BUFFER,S),u.bufferData(u.ARRAY_BUFFER,C,u.STATIC_DRAW),u.bindBuffer(u.ARRAY_BUFFER,null);var O=createProgram(u,imageVertexShader,imageFragmentShader);u.useProgram(O);var x=u.getUniformLocation(O,\"uMatrix\"),b=u.getUniformLocation(O,\"uTexture\"),M=u.getUniformLocation(O,\"uTextureSize\"),L=u.getUniformLocation(O,\"uOverlayColor\"),P=u.getUniformLocation(O,\"uOverlayLeftTop\"),G=u.getUniformLocation(O,\"uOverlayRightBottom\"),k=u.getUniformLocation(O,\"uColorOpacity\"),D=u.getUniformLocation(O,\"uColorOffset\"),U=u.getUniformLocation(O,\"uColorMatrix\"),B=u.getAttribLocation(O,\"aPosition\"),V=u.getAttribLocation(O,\"aTexCoord\"),N=createTexture(u,b,M,0,t),F=t.width*r,z=t.height*r,W=-.5*F,q=.5*z,H=.5*F,Y=-.5*z,j=new Float32Array([W,q,W,Y,H,q,H,Y]),X=new Float32Array([0,0,0,1,1,0,1,1]),Z=j.length/2,$=u.createBuffer();u.bindBuffer(u.ARRAY_BUFFER,$),u.bufferData(u.ARRAY_BUFFER,j,u.STATIC_DRAW),u.bindBuffer(u.ARRAY_BUFFER,null);var K=u.createBuffer();u.bindBuffer(u.ARRAY_BUFFER,K),u.bufferData(u.ARRAY_BUFFER,X,u.STATIC_DRAW),u.bindBuffer(u.ARRAY_BUFFER,null);var Q=0,J=0,ee={release:function(){e.width=1,e.height=1},resize:function(t,a){e.width=t*r,e.height=a*r,e.style.width=\"\".concat(t,\"px\"),e.style.height=\"\".concat(a,\"px\"),n.width=t*r,n.height=a*r,i.x=.5*n.width,i.y=.5*n.height,o=n.width/n.height,u.viewport(0,0,u.canvas.width,u.canvas.height)},update:function(e,l,E,C,b,M,F,z,W,q,H,Y,j,X,te,re,ne,ie,oe){var ae=H?H.height*r:n.height;Q=t.width*r,J=t.height*r,e*=r,l*=r,E*=r,C*=r;var ce=J/2/c*(n.height/ae)*-1;ce/=-c*ce*2/n.height;var le=.5*Q,ue=.5*J;e-=le,l-=ue;var se=z,de=-(i.x-le)+E,pe=i.y-ue-C,fe=mat4.create();mat4.perspective(fe,a,o,1,2*-ce),mat4.translate(fe,[de,pe,ce]),mat4.translate(fe,[e,-l,0]),mat4.scale(fe,[se,se,se]),mat4.rotateZ(fe,-F),mat4.translate(fe,[-e,l,0]),mat4.rotateY(fe,M),mat4.rotateX(fe,b),u.clearColor(X[0],X[1],X[2],1),u.clear(u.COLOR_BUFFER_BIT);var he=Y.x*r,ge=Y.y*r,me=Y.width*r,ve=Y.height*r,ye=he,Ee=ye+me,Te=n.height-ge,_e=n.height-(ge+ve);u.useProgram(s),u.uniform3fv(d,te),u.uniform3fv(p,re),u.uniform4fv(v,oe.map(function(e,t){return t<3?e/255:e})),u.uniform2f(f,n.width,n.height),u.uniform2f(g,ye,Te),u.uniform2f(m,Ee,_e),u.bindBuffer(u.ARRAY_BUFFER,y),u.vertexAttribPointer(h,2,u.FLOAT,!1,0,0),u.enableVertexAttribArray(h),u.drawArrays(u.TRIANGLE_STRIP,0,4),u.useProgram(O),u.bindFramebuffer(u.FRAMEBUFFER,null),u.bindTexture(u.TEXTURE_2D,N),u.bindBuffer(u.ARRAY_BUFFER,$),u.vertexAttribPointer(B,2,u.FLOAT,!1,0,0),u.enableVertexAttribArray(B),u.bindBuffer(u.ARRAY_BUFFER,K),u.vertexAttribPointer(V,2,u.FLOAT,!1,0,0),u.enableVertexAttribArray(V),u.uniformMatrix4fv(x,!1,fe),u.uniform2f(P,ye,Te),u.uniform2f(G,Ee,_e),u.uniform4fv(L,j),u.uniform1f(k,q),u.uniform4f(D,W[4],W[9],W[14],W[19]),u.uniformMatrix4fv(U,!1,[].concat(_toConsumableArray(W.slice(0,4)),_toConsumableArray(W.slice(5,9)),_toConsumableArray(W.slice(10,14)),_toConsumableArray(W.slice(15,19)))),u.drawArrays(u.TRIANGLE_STRIP,0,Z),u.useProgram(T),u.uniform1f(R,ne),u.uniform4fv(w,ie),u.uniform2f(A,ye,Te),u.uniform2f(I,Ee,_e),u.bindBuffer(u.ARRAY_BUFFER,S),u.vertexAttribPointer(_,2,u.FLOAT,!1,0,0),u.enableVertexAttribArray(_),u.drawArrays(u.TRIANGLE_STRIP,0,4),ee.onupdate(u)},onupdate:function(){}};return ee},createSpringRect=function(e){var t=0,r={},n=spring(e),i=spring(e),o=spring(e),a=spring(e);return n.onupdate=function(e){return r.x=e},n.oncomplete=function(){return t++},i.onupdate=function(e){return r.y=e},i.oncomplete=function(){return t++},o.onupdate=function(e){return r.width=e},o.oncomplete=function(){return t++},a.onupdate=function(e){return r.height=e},a.oncomplete=function(){return t++},{interpolate:function(e){n.interpolate(e),i.interpolate(e),o.interpolate(e),a.interpolate(e)},setTarget:function(e){t=0,n.target=e?e.x:null,i.target=e?e.y:null,o.target=e?e.width:null,a.target=e?e.height:null},getRect:function(){return r},isStable:function(){return 4===t}}},createSpringColor=function(e){var t=0,r={},n=spring(e),i=spring(e),o=spring(e);return n.onupdate=function(e){return r.r=e},n.oncomplete=function(){return t++},i.onupdate=function(e){return r.g=e},i.oncomplete=function(){return t++},o.onupdate=function(e){return r.b=e},o.oncomplete=function(){return t++},{interpolate:function(e){n.interpolate(e),i.interpolate(e),o.interpolate(e)},setTarget:function(e){t=0,n.target=e?e[0]:null,i.target=e?e[1]:null,o.target=e?e[2]:null},getColor:function(){return[r.r,r.g,r.b]},isStable:function(){return 3===t}}},ColorSpring={stiffness:.25,damping:.25,mass:2.5},IdentityMatrix=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],imageGL=createView({name:\"image-gl\",ignoreRect:!0,ignoreRectUpdate:!0,mixins:{apis:[\"top\",\"left\",\"width\",\"height\",\"xOrigin\",\"yOrigin\",\"xTranslation\",\"yTranslation\",\"xRotation\",\"yRotation\",\"zRotation\",\"scale\",\"overlay\",\"stage\",\"colorMatrix\",\"colorOpacity\",\"overlayOpacity\",\"outlineWidth\",\"isDraft\"],animations:{xTranslation:imageOverlaySpring,yTranslation:imageOverlaySpring,xOrigin:imageOverlaySpring,yOrigin:imageOverlaySpring,scale:imageOverlaySpring,xRotation:{type:\"spring\",stiffness:.25,damping:.25,mass:2.5},yRotation:{type:\"spring\",stiffness:.25,damping:.25,mass:2.5},zRotation:{type:\"spring\",stiffness:.25,damping:.25,mass:2.5},colorOpacity:{type:\"tween\",delay:150,duration:750},overlayOpacity:\"spring\",introScale:{type:\"spring\",stiffness:.25,damping:.75,mass:15},outlineWidth:imageOverlaySpring}},create:function(e){var t=e.root;t.ref.canvas=document.createElement(\"canvas\"),t.ref.canvas.width=0,t.ref.canvas.height=0,t.appendChild(t.ref.canvas),t.ref.gl=null,t.introScale=1,t.ref.isPreview=\"preview\"===t.query(\"GET_STYLE_LAYOUT_MODE\"),t.ref.shouldZoom=!t.ref.isPreview,t.ref.didZoom=!1,t.ref.backgroundColor=null,t.ref.backgroundColorSpring=createSpringColor(ColorSpring),t.ref.backgroundColorCenter=null,t.ref.backgroundColorCenterSpring=createSpringColor(ColorSpring),t.ref.overlaySpring=createSpringRect(imageOverlaySpring),t.ref.stageSpring=createSpringRect(imageOverlaySpring),t.ref.outlineSpring=spring(imageOverlaySpring),t.ref.colorMatrixSpring=[],t.ref.colorMatrixStable=!0,t.ref.colorMatrixStableCount=0,t.ref.colorMatrixPositions=[];for(var r=0;r<20;r++)!function(){var e=r,n=spring(ColorSpring);n.target=IdentityMatrix[e],n.onupdate=function(r){t.ref.colorMatrixPositions[e]=r},n.oncomplete=function(){t.ref.colorMatrixStableCount++},t.ref.colorMatrixSpring[e]=n}();t.ref.dragger=createDragger(t.element,function(){t.dispatch(\"CROP_IMAGE_DRAG_GRAB\")},function(e,r){t.dispatch(\"CROP_IMAGE_DRAG\",{value:r})},function(){t.dispatch(\"CROP_IMAGE_DRAG_RELEASE\")},{cancelOnMultiple:!0});var n=0,i=0;t.ref.keyboard=createKeyboard(t.element,function(){return n=0,i=0,{x:0,y:0}},{up:function(e){e.y-=20},down:function(e){e.y+=20},left:function(e){e.x-=20},right:function(e){e.x+=20},plus:function(){n+=.1,t.dispatch(\"CROP_IMAGE_RESIZE_AMOUNT\",{value:n}),t.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\")},minus:function(){n-=.1,t.dispatch(\"CROP_IMAGE_RESIZE_AMOUNT\",{value:n}),t.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\")},left_bracket:function(){i-=Math.PI/128,t.dispatch(\"CROP_IMAGE_ROTATE_ADJUST\",{value:i})},right_bracket:function(){i+=Math.PI/128,t.dispatch(\"CROP_IMAGE_ROTATE_ADJUST\",{value:i})},h:function(){t.dispatch(\"CROP_IMAGE_FLIP_HORIZONTAL\")},l:function(){t.dispatch(\"CROP_IMAGE_ROTATE_LEFT\")},q:function(){t.dispatch(\"CROP_RESET\")},r:function(){t.dispatch(\"CROP_IMAGE_ROTATE_RIGHT\")},v:function(){t.dispatch(\"CROP_IMAGE_FLIP_VERTICAL\")},z:function(){t.dispatch(\"CROP_ZOOM\")}},function(e){e&&t.dispatch(\"CROP_IMAGE_DRAG\",{value:e})},function(e){e&&t.dispatch(\"CROP_IMAGE_DRAG_RELEASE\")});var o=t.query(\"GET_FILE\"),a=URL.createObjectURL(o.data),c=function(e){var r=scaleImageSize(e,{width:t.query(\"GET_MAX_IMAGE_PREVIEW_WIDTH\"),height:t.query(\"GET_MAX_IMAGE_PREVIEW_HEIGHT\")}),n=createPreviewImage(e,r.width,r.height,o.orientation),i=Math.max(1,.75*window.devicePixelRatio),a=n.height/n.width,c=96*i,l=createPreviewImage(n,a>1?c:c/a,a>1?c*a:c),u=n.getContext(\"2d\").getImageData(0,0,n.width,n.height),s=l.getContext(\"2d\").getImageData(0,0,l.width,l.height);canvasRelease(n),canvasRelease(l),t.ref.gl=setup(t.ref.canvas,u,i);var d=t.query(\"GET_OUTPUT_CANVAS_SYNC_TARGET\");d&&(t.ref.gl.onupdate=function(){var e=t.ref.overlaySpring.getRect();d.getContext(\"2d\").drawImage(t.ref.canvas,e.x*i,e.y*i,e.width*i,e.height*i,0,0,d.width,d.height)}),t.ref.gl?(t.dispatch(\"DID_RECEIVE_IMAGE_DATA\",{previewData:u,thumbData:s}),t.dispatch(\"DID_PRESENT_IMAGE\")):t.dispatch(\"MISSING_WEBGL\")},l=function(){loadImage$2(a).then(c)};if(canCreateImageBitmap(o.data)){var u=createWorker(BitmapWorker);u.post({file:o.data},function(e){u.terminate(),e?c(e):l()})}else l();t.ref.canvasStyle=getComputedStyle(t.ref.canvas),t.ref.previousBackgroundColor,t.ref.previousLeft,t.ref.previousTop,t.ref.previousWidth,t.ref.previousHeight,t.element.dataset.showInteractionIndicator=!1,t.ref.handleFocus=function(e){9===e.keyCode&&(t.element.dataset.showInteractionIndicator=!0)},t.ref.handleBlur=function(e){t.element.dataset.showInteractionIndicator=!1},addEvent(t.element)(\"keyup\",t.ref.handleFocus),addEvent(t.element)(\"blur\",t.ref.handleBlur)},destroy:function(e){var t=e.root;t.ref.gl&&(t.ref.gl.release(),t.ref.gl=null),t.ref.dragger.destroy(),removeEvent(t.element)(\"keyup\",t.ref.handleFocus),removeEvent(t.element)(\"blur\",t.ref.handleBlur)},read:function(e){var t=e.root,r=t.ref.canvasStyle.backgroundColor,n=t.ref.canvasStyle.color;if(\"transparent\"!==n&&\"\"!==n||(n=null),\"transparent\"!==r&&\"\"!==r||(r=null),r&&r!==t.ref.previousBackgroundColor){var i=toRGBColorArray(r).map(function(e){return e/255}),o=(i[0]+i[1]+i[2])/3;t.ref.backgroundColor=i,t.ref.backgroundColorCenter=i.map(function(e){return o>.5?e-.15:e+.15}),t.ref.previousBackgroundColor=r}n&&n!==t.ref.previousOutlineColor&&(t.ref.outlineColor=toRGBColorArray(n).map(function(e){return e/255}).concat(1),t.ref.previousOutlineColor=n)},write:createRoute({SHOW_VIEW:function(e){var t=e.root;\"crop\"===e.action.id?(t.ref.dragger.enable(),t.element.setAttribute(\"tabindex\",\"0\")):(t.ref.dragger.disable(),t.element.removeAttribute(\"tabindex\"))}},function(e){var t=e.root,r=e.props,n=(e.actions,e.timestamp);if(t.ref.gl&&r.width&&r.height){var i=t.ref,o=i.gl,a=i.previousWidth,c=i.previousHeight,l=i.shouldZoom,u=i.stageSpring,s=i.overlaySpring,d=i.backgroundColorSpring,p=i.backgroundColorCenterSpring;r.width===a&&r.height===c||(t.ref.gl.resize(r.width,r.height),t.ref.previousWidth=r.width,t.ref.previousHeight=r.height),r.left===t.ref.previousLeft&&r.top===t.ref.previousTop||(t.ref.canvas.style.transform=\"translate(\".concat(-r.left,\"px, \").concat(-r.top,\"px)\"),t.ref.previousLeft=r.left,t.ref.previousTop=r.top),l&&!t.ref.didZoom&&(t.introScale=null,t.introScale=1.15,t.introScale=1,t.ref.didZoom=!0),d.setTarget(t.ref.backgroundColor),d.interpolate(n);var f=d.isStable();p.setTarget(t.ref.backgroundColorCenter),p.interpolate(n);var h=p.isStable();t.ref.colorMatrixStableCount=0;var g=r.colorMatrix||IdentityMatrix,m=t.ref.colorMatrixSpring.map(function(e,r){return e.target=g[r],e.interpolate(n),t.ref.colorMatrixPositions[r]}),v=20===t.ref.colorMatrixStableCount;r.isDraft&&s.setTarget(null),s.setTarget(r.overlay),s.interpolate(n);var y=s.isStable();r.isDraft&&u.setTarget(null),u.setTarget(r.stage),u.interpolate(n);var E=u.isStable();return o.update(t.xOrigin,t.yOrigin,t.xTranslation+r.left,t.yTranslation+r.top,t.xRotation,t.yRotation,t.zRotation,t.scale*t.introScale,m,t.ref.isPreview?1:t.colorOpacity,u.getRect(),s.getRect(),[1,1,1,1-t.overlayOpacity],d.getColor(),p.getColor(),d.getColor(),t.outlineWidth,t.ref.outlineColor,t.query(\"GET_BACKGROUND_COLOR\")),y&&E&&v&&f&&h}})}),image=createView({name:\"image\",ignoreRect:!0,mixins:{apis:[\"offsetTop\"]},create:function(e){var t=e.root,r=e.props;t.ref.imageGL=t.appendChildView(t.createChildView(imageGL)),/markup|sticker/.test(t.query(\"GET_UTILS\"))&&(t.ref.markup=t.appendChildView(t.createChildView(imageMarkup,{id:r.id,opacity:0,onSelect:function(e){t.dispatch(\"MARKUP_SELECT\",{id:e})},onDrag:function(e,r,n,i,o){t.dispatch(\"MARKUP_ELEMENT_DRAG\",{id:e,origin:r,offset:n,size:i,scale:o})},onResize:function(e,r,n,i,o){t.dispatch(\"MARKUP_ELEMENT_RESIZE\",{id:e,corner:r,origin:n,offset:i,size:o})},onUpdate:function(e,r){t.dispatch(\"MARKUP_UPDATE\",{style:e,value:r})},isMarkupUtil:function(e){var t=e;do{if(\"doka--markup-tools\"===t.className)return!0}while(t=t.parentNode);return!1}}))),t.ref.isModal=/modal/.test(t.query(\"GET_STYLE_LAYOUT_MODE\"))},write:createRoute({DID_PRESENT_IMAGE:function(e){e.root.ref.imageGL.colorOpacity=1}},function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.ref.imageGL,o=t.ref.markup,a=t.query(\"GET_CROP\",r.id,n);if(a){var c=a.isDraft,l=a.cropRect,u=a.cropStatus,s=a.origin,d=a.translation,p=a.translationBand,f=a.scale,h=a.scaleBand,g=a.rotation,m=a.rotationBand,v=a.flip,y=a.colorMatrix,E=t.query(\"GET_ROOT\"),T=t.query(\"GET_STAGE\"),_=T.x,R=T.y;c&&(i.scale=null,i.zRotation=null,i.xTranslation=null,i.yTranslation=null,i.xOrigin=null,i.yOrigin=null),i.colorMatrix=y;var w=t.query(\"IS_ACTIVE_VIEW\",\"crop\"),A=t.query(\"IS_ACTIVE_VIEW\",\"markup\")||t.query(\"IS_ACTIVE_VIEW\",\"sticker\"),I=w?.75:.95,S=_objectSpread({},l),C=1,O=w?1:5;if(t.query(\"IS_ACTIVE_VIEW\",\"resize\")){var x=u.image.width,b=u.image.height;C=null===x&&null===b?u.crop.width/l.width:null===x?b/l.height:x/l.width,C/=window.devicePixelRatio;var M=l.width*C,L=l.height*C;S.x=S.x+(.5*l.width-.5*M),S.y=S.y+(.5*l.height-.5*L),S.width=M,S.height=L}var P=t.ref.isModal?0:E.left,G=t.ref.isModal?0:E.top,k=t.ref.isModal?0:E.width-t.rect.element.width,D=t.ref.isModal?0:E.height-t.rect.element.height-r.offsetTop,U=(f+h)*C;i.isDraft=c,i.overlayOpacity=I,i.xOrigin=s.x,i.yOrigin=s.y,i.xTranslation=d.x+p.x+_,i.yTranslation=d.y+p.y+R,i.left=P,i.top=G+r.offsetTop,i.width=t.rect.element.width+k,i.height=t.rect.element.height+D+r.offsetTop,i.scale=U,i.xRotation=v.vertical?Math.PI:0,i.yRotation=v.horizontal?Math.PI:0,i.zRotation=g.main+g.sub+m,i.stage={x:T.x+P,y:T.y+G+r.offsetTop,width:T.width,height:T.height},i.overlay={x:S.x+_+P,y:S.y+R+G+r.offsetTop,width:S.width,height:S.height},i.outlineWidth=O,o&&(c&&(o.translateX=null,o.translateY=null,o.markupX=null,o.markupY=null,o.markupWidth=null,o.markupHeight=null),o.opacity=w?.3:1,o.stageOffsetX=_,o.stageOffsetY=R,o.markupX=S.x+_,o.markupY=S.y+R,o.markupWidth=S.width,o.markupHeight=S.height,o.allowInteraction=A)}})}),createGroup=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:\"group\",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[\"opacity\"],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return createView({ignoreRect:!0,name:e,mixins:{styles:[\"opacity\"].concat(_toConsumableArray(t)),animations:_objectSpread({opacity:{type:\"spring\",stiffness:.25,damping:.5,mass:5}},r)},create:function(e){var t=e.root,r=e.props;(r.controls||[]).map(function(e){var r=t.createChildView(e.view,e);e.didCreateView&&e.didCreateView(r),t.appendChildView(r)}),r.element&&t.element.appendChild(r.element)}})},list=createView({ignoreRect:!0,tag:\"div\",name:\"dropdown-list\",mixins:{styles:[\"translateY\",\"opacity\"],apis:[\"selectedValue\",\"options\",\"onSelect\"],animations:{translateY:\"spring\",opacity:{type:\"tween\",duration:250}}},create:function(e){var t=e.root,r=e.props;t.element.setAttribute(\"role\",\"list\"),t.ref.handleClick=function(){return r.action&&r.action()},t.element.addEventListener(\"click\",t.ref.handleClick),t.ref.activeOptions=null,t.ref.activeSelectedValue},write:function(e){var t=e.root,r=e.props;if(r.options!==t.ref.activeOptions&&(t.ref.activeOptions=r.options,t.childViews.forEach(function(e){return t.removeChildView(e)}),r.options.map(function(e){var n=t.createChildView(button,_objectSpread({},e,{action:function(){return r.onSelect(e.value)}}));return t.appendChildView(n)})),r.selectedValue!==t.ref.activeSelectedValue){t.ref.activeSelectedValue=r.selectedValue;var n=r.options.findIndex(function(e){return\"object\"===_typeof(e.value)&&r.selectedValue?e.value[0]===e.label&&JSON.stringify(e.value.slice(1))===JSON.stringify(r.selectedValue)||JSON.stringify(e.value)===JSON.stringify(r.selectedValue):e.value===r.selectedValue});t.childViews.forEach(function(e,t){e.element.setAttribute(\"aria-selected\",t===n)})}},destroy:function(e){var t=e.root;t.element.removeEventListener(\"click\",t.ref.handleClick)}}),dropdown=createView({ignoreRect:!0,tag:\"div\",name:\"dropdown\",mixins:{styles:[\"opacity\"],animations:{opacity:\"spring\"},apis:[\"direction\",\"selectedValue\",\"options\",\"onSelect\"]},create:function(e){var t=e.root,r=e.props;t.ref.open=!1;var n=function(e){t.ref.open=e,t.dispatch(\"KICK\")};t.ref.button=t.appendChildView(t.createChildView(button,_objectSpread({},r,{action:function(){n(!t.ref.open)}}))),t.ref.list=t.appendChildView(t.createChildView(list,_objectSpread({},r,{opacity:0,action:function(){n(!1)}}))),t.ref.handleBodyClick=function(e){contains(t.element,e.target)||n(!1)},t.element.addEventListener(\"focusin\",function(e){e.target!==t.ref.button.element&&n(!0)}),t.element.addEventListener(\"focusout\",function(e){e.relatedTarget&&(contains(t.element,e.relatedTarget)||n(!1))}),document.body.addEventListener(\"click\",t.ref.handleBodyClick)},destroy:function(e){var t=e.root;document.body.removeEventListener(\"click\",t.ref.handleBodyClick)},write:function(e){var t=e.root,r=e.props;if(t.ref.list.opacity=t.ref.open?1:0,t.ref.list.selectedValue=r.selectedValue,t.ref.list.options=r.options,\"up\"===r.direction){var n=t.ref.list.rect.element.height;t.ref.list.translateY=(t.ref.open?-(n+5):-n)-t.rect.element.height}else t.ref.list.translateY=t.ref.open?0:-5}}),MAGIC=312,createDiv=function(e,t){return createView({name:e,ignoreRect:!0,create:t})},cropRotatorLine=createView({name:\"crop-rotator-line\",ignoreRect:!0,ignoreRectUpdate:!0,mixins:{styles:[\"translateX\"],animations:{translateX:\"spring\"}},create:function(e){for(var t=e.root,r='\",t.element.innerHTML=r}}),cropRotator=createView({name:\"crop-rotator\",ignoreRect:!0,mixins:{styles:[\"opacity\",\"translateY\"],animations:{opacity:{type:\"spring\",damping:.5,mass:5},translateY:\"spring\"},apis:[\"rotation\",\"animate\",\"setAllowInteraction\"]},create:function(e){var t=e.root,r=e.props;t.element.setAttribute(\"tabindex\",0);var n=document.createElement(\"button\");n.innerHTML=\"\".concat(t.query(\"GET_LABEL_BUTTON_CROP_ROTATE_CENTER\"),\"\"),n.className=\"doka--crop-rotator-center\",n.addEventListener(\"click\",function(){t.dispatch(\"CROP_IMAGE_ROTATE_CENTER\")}),t.appendChild(n);var i=null;t.appendChildView(t.createChildView(createDiv(\"crop-rotator-line-mask\",function(e){var t=e.root,r=e.props;i=t.appendChildView(t.createChildView(cropRotatorLine,{translateX:Math.round(r.rotation*MAGIC)}))}),r)),t.ref.line=i;var o=document.createElement(\"div\");o.className=\"doka--crop-rotator-bar\",t.appendChild(o);var a=Math.PI/4,c=0;t.ref.dragger=createDragger(o,function(){c=i.translateX/MAGIC,t.dispatch(\"CROP_IMAGE_ROTATE_GRAB\")},function(e,r){var n=r.x/t.rect.element.width*(Math.PI/2),i=limit(c+n,-a,a);t.dispatch(\"CROP_IMAGE_ROTATE\",{value:-i})},function(){t.dispatch(\"CROP_IMAGE_ROTATE_RELEASE\")},{stopPropagation:!0}),r.setAllowInteraction=function(e){e?t.ref.dragger.enable():t.ref.dragger.disable()},t.ref.keyboard=createKeyboard(t.element,function(){c=0},{left:function(){c+=Math.PI/128,t.dispatch(\"CROP_IMAGE_ROTATE_ADJUST\",{value:c})},right:function(){c-=Math.PI/128,t.dispatch(\"CROP_IMAGE_ROTATE_ADJUST\",{value:c})}},function(){},function(){}),t.ref.prevRotation},destroy:function(e){var t=e.root;t.ref.dragger.destroy(),t.ref.keyboard.destroy()},write:function(e){var t=e.root,r=e.props,n=e.timestamp,i=r.animate,o=r.rotation;if(t.ref.prevRotation!==o){t.ref.prevRotation=o,i||0===o||(t.ref.line.translateX=null);var a=0,c=t.query(\"GET_CROP\",r.id,n);if(c&&c.interaction&&c.interaction.rotation){var l=splitRotation(c.interaction.rotation).sub-o;a=.025*Math.sign(l)*Math.log10(1+Math.abs(l)/.025)}t.ref.line.translateX=Math.round((-o-a)*MAGIC)}}}),corners=[\"nw\",\"ne\",\"se\",\"sw\"],getOppositeCorner=function(e){return corners[(corners.indexOf(e)+2)%corners.length]},edges=[\"n\",\"e\",\"s\",\"w\"],getOppositeEdge=function(e){return edges[(edges.indexOf(e)+2)%edges.length]},autoPrecision=isBrowser()&&1===window.devicePixelRatio?function(e){return Math.round(e)}:function(e){return e},line=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"crop-rect-focal-line\",mixins:{styles:[\"translateX\",\"translateY\",\"scaleX\",\"scaleY\",\"opacity\"],animations:{translateX:\"spring\",translateY:\"spring\",scaleX:\"spring\",scaleY:\"spring\",opacity:\"spring\"}}}),createEdge=function(e){return createView({ignoreRect:!0,ignoreRectUpdate:!0,tag:\"div\",name:\"crop-rect-edge-\".concat(e),mixins:{styles:[\"translateX\",\"translateY\",\"scaleX\",\"scaleY\"],apis:[\"setAllowInteraction\"]},create:function(t){var r=t.root,n=t.props;r.element.classList.add(\"doka--crop-rect-edge\"),r.element.setAttribute(\"tabindex\",0),r.element.setAttribute(\"role\",\"button\");var i=e,o=getOppositeEdge(e);r.ref.dragger=createDragger(r.element,function(){r.dispatch(\"CROP_RECT_DRAG_GRAB\")},function(e,t){return r.dispatch(\"CROP_RECT_EDGE_DRAG\",{offset:t,origin:i,anchor:o})},function(){return r.dispatch(\"CROP_RECT_DRAG_RELEASE\")},{stopPropagation:!0,cancelOnMultiple:!0}),n.setAllowInteraction=function(e){e?r.ref.dragger.enable():r.ref.dragger.disable()},r.ref.keyboard=createKeyboard(r.element,function(){return{x:0,y:0}},{up:function(e){e.y-=20},down:function(e){e.y+=20},left:function(e){e.x-=20},right:function(e){e.x+=20}},function(e){r.dispatch(\"CROP_RECT_DRAG_GRAB\"),r.dispatch(\"CROP_RECT_EDGE_DRAG\",{offset:e,origin:i,anchor:o})},function(){r.dispatch(\"CROP_RECT_DRAG_RELEASE\")})},destroy:function(e){var t=e.root;t.ref.keyboard.destroy(),t.ref.dragger.destroy()}})},createCorner=function(e,t,r){return createView({ignoreRect:!0,ignoreRectUpdate:!0,tag:\"div\",name:\"crop-rect-corner-\".concat(e),mixins:{styles:[\"translateX\",\"translateY\",\"scaleX\",\"scaleY\"],animations:{translateX:imageOverlaySpring,translateY:imageOverlaySpring,scaleX:{type:\"spring\",delay:r},scaleY:{type:\"spring\",delay:r},opacity:{type:\"spring\",delay:t}},apis:[\"setAllowInteraction\"]},create:function(t){var r=t.root,n=t.props;r.element.classList.add(\"doka--crop-rect-corner\"),r.element.setAttribute(\"role\",\"button\"),r.element.setAttribute(\"tabindex\",-1);var i=e,o=getOppositeCorner(e);r.ref.dragger=createDragger(r.element,function(){r.dispatch(\"CROP_RECT_DRAG_GRAB\")},function(e,t){r.dispatch(\"CROP_RECT_CORNER_DRAG\",{offset:t,origin:i,anchor:o})},function(){r.dispatch(\"CROP_RECT_DRAG_RELEASE\")},{stopPropagation:!0,cancelOnMultiple:!0}),n.setAllowInteraction=function(e){e?r.ref.dragger.enable():r.ref.dragger.disable()}},destroy:function(e){e.root.ref.dragger.destroy()}})},cropRect=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"crop-rect\",mixins:{apis:[\"rectangle\",\"draft\",\"rotating\",\"enabled\"]},create:function(e){var t=e.root;t.ref.wasRotating=!1;corners.forEach(function(e,r){var n=10*r,i=250+n+50,o=250+n;t.ref[e]=t.appendChildView(t.createChildView(createCorner(e,i,o),{opacity:0,scaleX:.5,scaleY:.5}))}),edges.forEach(function(e){t.ref[e]=t.appendChildView(t.createChildView(createEdge(e)))}),t.ref.lines=[];for(var r=0;r<10;r++)t.ref.lines.push(t.appendChildView(t.createChildView(line,{opacity:0})));t.ref.animationDir=null,t.ref.previousRotating,t.ref.previousRect={},t.ref.previousEnabled,t.ref.previousDraft},write:function(e){var t=e.root,r=e.props,n=r.rectangle,i=r.draft,o=r.rotating,a=r.enabled;if(n&&(!rectEqualsRect(n,t.ref.previousRect)||o!==t.ref.previousRotating||a!==t.ref.previousEnabled||i!==t.ref.previousDraft)){t.ref.previousRect=n,t.ref.previousRotating=o,t.ref.previousEnabled=a,t.ref.previousDraft=i;var c=t.ref,l=c.n,u=c.e,s=c.s,d=c.w,p=c.nw,f=c.ne,h=c.se,g=c.sw,m=c.lines,v=c.animationDir,y=n.x,E=n.y,T=n.x+n.width,_=n.y+n.height,R=_-E,w=T-y,A=Math.min(w,R);t.element.dataset.indicatorSize=A<80?\"none\":\"default\",edges.forEach(function(e){return t.ref[e].setAllowInteraction(a)}),corners.forEach(function(e){return t.ref[e].setAllowInteraction(a)});var I=t.query(\"IS_ACTIVE_VIEW\",\"crop\");if(I&&\"in\"!==v?(t.ref.animationDir=\"in\",corners.map(function(e){return t.ref[e]}).forEach(function(e){e.opacity=1,e.scaleX=1,e.scaleY=1})):I||\"out\"===v||(t.ref.animationDir=\"out\",corners.map(function(e){return t.ref[e]}).forEach(function(e){e.opacity=0,e.scaleX=.5,e.scaleY=.5})),transformTranslate(i,p,y,E),transformTranslate(i,f,T,E),transformTranslate(i,h,T,_),transformTranslate(i,g,y,_),transformTranslateScale(i,l,y,E,w/100,1),transformTranslateScale(i,u,T,E,1,R/100),transformTranslateScale(i,s,y,_,w/100,1),transformTranslateScale(i,d,y,E,1,R/100),o){t.ref.wasRotating=!0;var S=m.slice(0,5),C=1/S.length;S.forEach(function(e,t){transformTranslateScale(i,e,y,E+R*(C+t*C),w/100,.01),e.opacity=.5});var O=m.slice(5);C=1/O.length,O.forEach(function(e,t){transformTranslateScale(i,e,y+w*(C+t*C),E,.01,R/100),e.opacity=.5})}else if(i){t.ref.wasRotating=!1;var x=m[0],b=m[1],M=m[2],L=m[3];transformTranslateScale(i,x,y,E+.333*R,w/100,.01),transformTranslateScale(i,b,y,E+.666*R,w/100,.01),transformTranslateScale(i,M,y+.333*w,E,.01,R/100),transformTranslateScale(i,L,y+.666*w,E,.01,R/100),x.opacity=.5,b.opacity=.5,M.opacity=.5,L.opacity=.5}else{var P=m[0],G=m[1],k=m[2],D=m[3];!t.ref.wasRotating&&P.opacity>0&&(transformTranslateScale(i,P,y,E+.333*R,w/100,.01),transformTranslateScale(i,G,y,E+.666*R,w/100,.01),transformTranslateScale(i,k,y+.333*w,E,.01,R/100),transformTranslateScale(i,D,y+.666*w,E,.01,R/100)),m.forEach(function(e){return e.opacity=0})}}}}),transformTranslateScale=function(e,t,r,n,i,o){e&&(t.translateX=null,t.translateY=null,t.scaleX=null,t.scaleY=null),t.translateX=autoPrecision(r),t.translateY=autoPrecision(n),t.scaleX=i,t.scaleY=o},transformTranslate=function(e,t,r,n){e&&(t.translateX=null,t.translateY=null),t.translateX=autoPrecision(r),t.translateY=autoPrecision(n)},setInnerHTML=function(e,t){if(!/svg/.test(e.namespaceURI)||\"innerHTML\"in e)e.innerHTML=t;else{var r=document.createElement(\"div\");r.innerHTML=\"\";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}},cropMask=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"crop-mask\",tag:\"svg\",mixins:{styles:[\"opacity\",\"translateX\",\"translateY\"],animations:{scale:imageOverlaySpring,maskWidth:imageOverlaySpring,maskHeight:imageOverlaySpring,translateX:imageOverlaySpring,translateY:imageOverlaySpring,opacity:{type:\"tween\",delay:0,duration:1e3}},apis:[\"rectangle\",\"animate\",\"maskWidth\",\"maskHeight\",\"scale\"]},create:function(e){e.root.ref.writer=null},write:function(e){var t=e.root,r=t.query(\"GET_CROP_MASK\");r!==t.ref.writer&&(t.ref.writer=r,t.ref.writerFn=r?r(t.element,setInnerHTML):null,t.ref.writer||setInnerHTML(t.element,\"\"))},didWriteView:function(e){var t=e.root,r=e.props,n=r.maskWidth,i=r.maskHeight,o=r.scale;if(t.ref.writer&&n&&i&&(t.element.setAttribute(\"width\",autoPrecision(n)),t.element.setAttribute(\"height\",autoPrecision(i)),t.ref.writerFn)){var a=t.query(\"GET_CROP_MASK_INSET\");t.ref.writerFn({x:o*a,y:o*a,width:n-o*a*2,height:i-o*a*2},{width:n,height:i})}}}),updateText$1=function(e,t){var r=e.childNodes[0];r?t!==r.nodeValue&&(r.nodeValue=t):(r=document.createTextNode(t),e.appendChild(r))},sizeSpring={type:\"spring\",stiffness:.25,damping:.1,mass:1},cropSize=createView({ignoreRect:!0,name:\"crop-size\",mixins:{styles:[\"translateX\",\"translateY\",\"opacity\"],animations:{translateX:\"spring\",translateY:\"spring\",opacity:\"spring\",sizeWidth:sizeSpring,sizeHeight:sizeSpring},apis:[\"sizeWidth\",\"sizeHeight\"],listeners:!0},create:function(e){var t=e.root,r=createElement(\"span\");r.className=\"doka--crop-size-info doka--crop-resize-percentage\",t.ref.resizePercentage=r,t.appendChild(r);var n=createElement(\"span\");n.className=\"doka--crop-size-info\";var i=createElement(\"span\");i.className=\"doka--crop-size-multiply\",i.textContent=\"×\";var o=createElement(\"span\"),a=createElement(\"span\");t.ref.outputWidth=o,t.ref.outputHeight=a,n.appendChild(o),n.appendChild(i),n.appendChild(a),t.appendChild(n),t.ref.previousValues={width:0,height:0,percentage:0}},write:function(e){var t=e.root,r=e.props,n=e.timestamp;if(!(t.opacity<=0)){var i=t.query(\"GET_CROP\",r.id,n);if(i){var o=i.cropStatus,a=i.isDraft,c=t.ref,l=c.outputWidth,u=c.outputHeight,s=c.resizePercentage,d=c.previousValues,p=o.image,f=o.crop,h=o.currentWidth,g=o.currentHeight,m=p.width?Math.round(p.width/f.width*100):0;a&&(t.sizeWidth=null,t.sizeHeight=null),t.sizeWidth=h,t.sizeHeight=g;var v=Math.round(t.sizeWidth),y=Math.round(t.sizeHeight);v!==d.width&&(updateText$1(l,v),d.width=v),y!==d.height&&(updateText$1(u,y),d.height=y),m!==d.percentage&&(p.width?updateText$1(s,\"\".concat(m,\"%\")):updateText$1(s,\"\"),d.percentage=m)}}}}),wrapper=function(e,t){return createView({ignoreRect:!0,name:e,mixins:t,create:function(e){var t=e.root,r=e.props;r.className&&t.element.classList.add(r.className),r.controls.map(function(e){var r=t.createChildView(e.view,e);e.didCreateView&&e.didCreateView(r),t.appendChildView(r)})}})},warn=function(){return console.log(\"Doka: localStorage not available\")},getData=function(e){try{JSON.parse(localStorage.getItem(e)||\"{}\")}catch(e){warn()}return{}},setStoredValue=function(e,t,r){var n=getData(e);n[t]=r;try{localStorage.setItem(e,JSON.stringify(n))}catch(e){warn()}return r},getStoredValue=function(e,t,r){var n=getData(e);return void 0===n[t]?r:n[t]},canHover=function(){return window.matchMedia(\"(pointer: fine) and (hover: hover)\").matches},instructionsBubble=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"instructions-bubble\",mixins:{styles:[\"opacity\",\"translateX\",\"translateY\"],animations:{opacity:{type:\"tween\",duration:400}},apis:[\"seen\"]},create:function(e){var t=e.root,r=e.props;return t.element.innerHTML=(r.iconBefore||\"\")+r.text},write:function(e){var t=e.root;e.props.seen&&(t.opacity=0)}}),SPRING_TRANSLATE={type:\"spring\",stiffness:.4,damping:.65,mass:7},cropSubject=createView({name:\"crop-subject\",ignoreRect:!0,mixins:{styles:[\"opacity\",\"translateX\",\"translateY\"],animations:{opacity:{type:\"tween\",duration:250},translateX:SPRING_TRANSLATE,translateY:SPRING_TRANSLATE}},create:function(e){var t=e.root,r=e.props;(t.opacity=1,t.ref.timestampOffset=null,t.query(\"GET_CROP_ALLOW_INSTRUCTION_ZOOM\")&&canHover())&&(getStoredValue(t.query(\"GET_STORAGE_NAME\"),\"instruction_zoom_shown\",!1)||(t.ref.instructions=t.appendChildView(t.createChildView(instructionsBubble,{opacity:0,seen:!1,text:t.query(\"GET_LABEL_CROP_INSTRUCTION_ZOOM\"),iconBefore:createIcon('')}))));t.ref.maskView=t.appendChildView(t.createChildView(cropMask)),t.query(\"GET_CROP_ALLOW_RESIZE_RECT\")&&(t.ref.cropView=t.appendChildView(t.createChildView(cropRect))),t.query(\"GET_CROP_SHOW_SIZE\")&&(t.ref.cropSize=t.appendChildView(t.createChildView(cropSize,{id:r.id,opacity:1,scaleX:1,scaleY:1,translateX:null}))),t.query(\"GET_CROP_ZOOM_TIMEOUT\")||(t.ref.btnZoom=t.appendChildView(t.createChildView(wrapper(\"zoom-wrapper\",{styles:[\"opacity\",\"translateX\",\"translateY\"],animations:{opacity:{type:\"tween\",duration:250}}}),{opacity:0,controls:[{view:button,label:t.query(\"GET_LABEL_BUTTON_CROP_ZOOM\"),name:\"zoom\",icon:createIcon('',26),action:function(){return t.dispatch(\"CROP_ZOOM\")}}]})))},write:createRoute({CROP_IMAGE_RESIZE_MULTIPLY:function(e){var t=e.root,r=t.ref.instructions;r&&!r.seen&&(r.seen=!0,setStoredValue(t.query(\"GET_STORAGE_NAME\"),\"instruction_zoom_shown\",!0))},CROP_RECT_DRAG_RELEASE:function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.ref.btnZoom;if(i){var o=t.query(\"GET_CROP\",r.id,n).cropRect,a=o.x+.5*o.width,c=o.y+.5*o.height;i.translateX=a,i.translateY=c}}},function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.ref,o=i.cropView,a=i.maskView,c=i.btnZoom,l=i.cropSize,u=i.instructions;if(!t.query(\"IS_ACTIVE_VIEW\",\"crop\")&&o)return o.enabled=!1,t.ref.timestampOffset=null,void(l&&(l.opacity=0));t.ref.timestampOffset||(t.ref.timestampOffset=n);var s=t.query(\"GET_CROP\",r.id,n);if(s){var d=s.cropRect,p=s.isRotating,f=s.isDraft,h=s.scale,g=t.query(\"GET_STAGE\");if(t.translateX=g.x-t.rect.element.left,t.translateY=g.y-t.rect.element.top,o&&(o.draft=f,o.rotating=p,o.rectangle=d,o.enabled=!0),l){l.opacity=1,f&&(l.translateX=null,l.translateY=null);var m=getCropSizeOffset(t.rect.element,l.rect.element,d);l.translateX=f?m.x:autoPrecision(m.x),l.translateY=f?m.y:autoPrecision(m.y)}if(t.query(\"GET_CROP_MASK\")&&(f&&(a.translateX=null,a.translateY=null,a.maskWidth=null,a.maskHeight=null),a.translateX=autoPrecision(d.x),a.translateY=autoPrecision(d.y),a.maskWidth=d.width,a.maskHeight=d.height,a.scale=h),s.canRecenter)u&&(u.opacity=0),c&&(c.opacity=s.isDraft?0:1);else if(c&&(c.opacity=0),u&&!u.seen&&!s.isDraft){var v=d.x+.5*d.width,y=d.y+.5*d.height;u.translateX=Math.round(v-.5*u.rect.element.width),u.translateY=Math.round(y-.5*u.rect.element.height),n-t.ref.timestampOffset>2e3&&(u.opacity=1)}}})}),getCropSizeOffset=function(e,t,r){var n=r.x,i=r.x+r.width,o=r.y+r.height,a=i-t.width-16,c=o-t.height-16;return t.width>r.width-32&&(a=n+(.5*r.width-.5*t.width),(c=o+16)>e.height-t.height&&(c=o-t.height-16)),{x:a=Math.max(0,Math.min(a,e.width-t.width)),y:c}},now=function(){return performance.now()},throttle=function(e,t){var r=null,n=null;return function(){var i=arguments;if(!n)return e.apply(null,Array.from(arguments)),void(n=now());clearTimeout(r),r=setTimeout(function(){now()-n>=t&&(e.apply(null,Array.from(i)),n=now())},t-(now()-n))}},climb=function(e,t){for(;1===e.nodeType&&!t(e);)e=e.parentNode;return 1===e.nodeType?e:null},isMyTarget=function(e,t){var r=climb(t,function(e){return e.classList.contains(\"doka--root\")});return!!r&&contains(r,e)},updateIndicators=function(e){var t=e.root,r=e.props,n=e.action.position,i=r.pivotPoint,o=t.ref,a=o.indicatorA,c=o.indicatorB,l=i.x-n.x,u=i.y-n.y,s={x:i.x+l,y:i.y+u},d={x:i.x-l,y:i.y-u};a.style.cssText=\"transform: translate3d(\".concat(s.x,\"px, \").concat(s.y,\"px, 0)\"),c.style.cssText=\"transform: translate3d(\".concat(d.x,\"px, \").concat(d.y,\"px, 0)\")},getPositionFromEvent=function(e){return{x:e.pageX,y:e.pageY}},cropResize=createView({ignoreRect:!0,ignoreRectUpdate:!0,name:\"crop-resizer\",mixins:{apis:[\"pivotPoint\",\"scrollRect\"]},create:function(e){var t=e.root,r=e.props;t.ref.isActive=!1,t.ref.isCropping=!1,t.ref.indicatorA=document.createElement(\"div\"),t.appendChild(t.ref.indicatorA),t.ref.indicatorB=document.createElement(\"div\"),t.appendChild(t.ref.indicatorB);var n=t.query(\"GET_CROP_RESIZE_KEY_CODES\");t.ref.hasEnabledResizeModifier=n.length>0;var i={origin:{x:null,y:null},position:{x:null,y:null},selecting:!1,enabled:!1,scrollY:0,offsetX:0,offsetY:0},o=now();t.ref.state=i;var a=createPointerRegistry(),c=0,l=!1;t.ref.resizeStart=function(e){if(t.ref.isActive&&(0===a.count()&&(l=!1),isMyTarget(t.element,e.target)&&(a.push(e),addEvent$1(document.documentElement,\"up\",t.ref.resizeEnd),a.multiple()))){e.stopPropagation(),e.preventDefault();var r=a.active(),n=getPositionFromEvent(r[0]),i=getPositionFromEvent(r[1]);c=vectorDistance(n,i),addEvent$1(document.documentElement,\"move\",t.ref.resizeMove),l=!0}},t.ref.resizeMove=function(e){if(t.ref.isActive&&l&&(e.preventDefault(),2===a.count())){a.update(e);var r=a.active(),n=getPositionFromEvent(r[0]),i=getPositionFromEvent(r[1]),o=(vectorDistance(n,i)-c)/c;t.dispatch(\"CROP_IMAGE_RESIZE\",{value:o})}},t.ref.resizeEnd=function(e){if(t.ref.isActive){a.pop(e);var r=0===a.count();r&&(removeEvent$1(document.documentElement,\"move\",t.ref.resizeMove),removeEvent$1(document.documentElement,\"up\",t.ref.resizeEnd)),l&&(e.preventDefault(),r&&t.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\"))}},addEvent$1(document.documentElement,\"down\",t.ref.resizeStart);var u=performance.now(),s=0,d=1,p=throttle(function(e){if(!t.ref.isCropping){var r=Math.sign(e.wheelDelta||e.deltaY),n=now(),i=n-u;u=n,(i>750||s!==r)&&(d=1,s=r),d+=.05*r,t.dispatch(\"CROP_IMAGE_RESIZE_MULTIPLY\",{value:Math.max(.1,d)}),t.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\")}},100);t.ref.wheel=function(e){if(t.ref.isActive&&isMyTarget(t.element,e.target)){if(r.scrollRect){var n=r.scrollRect,i=t.query(\"GET_ROOT\"),o=getPositionFromEvent(e),a={x:o.x-i.leftScroll,y:o.y-i.topScroll};if(a.xn.x+n.width||a.yn.y+n.height)return}e.preventDefault(),p(e)}},document.addEventListener(\"wheel\",t.ref.wheel,{passive:!1}),t.ref.hasEnabledResizeModifier&&(t.ref.move=function(e){if(t.ref.isActive&&!t.ref.isCropping&&(i.position.x=e.pageX-t.ref.state.offsetX,i.position.y=e.pageY-t.ref.state.scrollY-t.ref.state.offsetY,i.enabled))if(isMyTarget(t.element,e.target)){\"idle\"===t.element.dataset.state&&t.dispatch(\"RESIZER_SHOW\",{position:_objectSpread({},i.position)}),e.preventDefault(),t.dispatch(\"RESIZER_MOVE\",{position:_objectSpread({},i.position)});var n=r.pivotPoint,a=n.x-i.position.x,l=n.y-i.position.y,u={x:n.x+a,y:n.y+l},s=_objectSpread({},i.position);if(i.selecting){var d=(vectorDistance(u,s)-c)/c,p=performance.now();p-o>25&&(o=p,t.dispatch(\"CROP_IMAGE_RESIZE\",{value:d}))}}else t.dispatch(\"RESIZER_CANCEL\")},t.ref.select=function(e){if(t.ref.isActive&&isMyTarget(t.element,e.target)){var n=r.pivotPoint,o=n.x-i.position.x,a=n.y-i.position.y,l={x:n.x+o,y:n.y+a},u=i.position;c=vectorDistance(l,u),i.selecting=!0,i.origin.x=e.pageX,i.origin.y=e.pageY,t.dispatch(\"CROP_IMAGE_RESIZE_GRAB\")}},t.ref.confirm=function(e){t.ref.isActive&&isMyTarget(t.element,e.target)&&(i.selecting=!1,t.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\"))},t.ref.blur=function(){t.ref.isActive&&(i.selecting=!1,i.enabled=!1,document.removeEventListener(\"mousedown\",t.ref.select),document.removeEventListener(\"mouseup\",t.ref.confirm),t.dispatch(\"RESIZER_CANCEL\"))},window.addEventListener(\"blur\",t.ref.blur),document.addEventListener(\"mousemove\",t.ref.move),t.ref.keyDown=function(e){t.ref.isActive&&n.includes(e.keyCode)&&i.position&&(i.enabled=!0,document.addEventListener(\"mousedown\",t.ref.select),document.addEventListener(\"mouseup\",t.ref.confirm),t.dispatch(\"RESIZER_SHOW\",{position:_objectSpread({},i.position)}))},t.ref.keyUp=function(e){t.ref.isActive&&n.includes(e.keyCode)&&(i.enabled=!1,document.removeEventListener(\"mousedown\",t.ref.select),document.removeEventListener(\"mouseup\",t.ref.confirm),t.dispatch(\"RESIZER_CANCEL\"))},document.body.addEventListener(\"keydown\",t.ref.keyDown),document.body.addEventListener(\"keyup\",t.ref.keyUp))},destroy:function(e){var t=e.root;document.removeEventListener(\"touchmove\",t.ref.resizeMove),document.removeEventListener(\"touchend\",t.ref.resizeEnd),document.removeEventListener(\"touchstart\",t.ref.resizeStart),document.removeEventListener(\"wheel\",t.ref.wheel),document.removeEventListener(\"mousedown\",t.ref.select),document.removeEventListener(\"mouseup\",t.ref.confirm),t.ref.hasEnabledResizeModifier&&(document.removeEventListener(\"mousemove\",t.ref.move),document.body.removeEventListener(\"keydown\",t.ref.keyDown),document.body.removeEventListener(\"keyup\",t.ref.keyUp),window.removeEventListener(\"blur\",t.ref.blur))},read:function(e){var t=e.root;t.ref.state.scrollY=window.scrollY;var r=t.element.getBoundingClientRect();t.ref.state.offsetX=r.x,t.ref.state.offsetY=r.y},write:createRoute({CROP_RECT_DRAG_GRAB:function(e){e.root.ref.isCropping=!0},CROP_RECT_DRAG_RELEASE:function(e){e.root.ref.isCropping=!1},SHOW_VIEW:function(e){var t=e.root,r=e.action;t.ref.isActive=\"crop\"===r.id},RESIZER_SHOW:function(e){var t=e.root,r=e.props,n=e.action;t.element.dataset.state=\"multi-touch\",updateIndicators({root:t,props:r,action:n})},RESIZER_CANCEL:function(e){e.root.element.dataset.state=\"idle\"},RESIZER_MOVE:updateIndicators})}),setOpacity=function(e,t){return e.style.opacity=t},updateImageBoundsIcon=function(e,t){var r=Array.from(e.element.querySelectorAll(\".doka--icon-crop-limit rect\"));r.length&&(setOpacity(r[0],t?.3:0),setOpacity(r[1],t?1:0),setOpacity(r[2],t?0:.3),setOpacity(r[3],t?0:1))},updateAspectRatioIcon=function(e,t){var r=e.element.querySelectorAll(\".doka--icon-aspect-ratio rect\");if(r.length){if(!t)return setOpacity(r[0],.2),setOpacity(r[1],.3),void setOpacity(r[2],.4);setOpacity(r[0],t>1?1:.3),setOpacity(r[1],1===t?.85:.5),setOpacity(r[2],t<1?1:.3)}},updateTurnIcons=function(e,t){Array.from(e.element.querySelectorAll(\".doka--icon-turn rect\")).forEach(function(e){t>1&&(e.setAttribute(\"x\",e.previousElementSibling?5:4),e.setAttribute(\"width\",9)),t<1&&(e.setAttribute(\"y\",11),e.setAttribute(\"height\",10))})},createRectangle=function(e){var t,r;e>1?(r=14,t=Math.round(r/e)):(t=14,r=Math.round(t*e));var n=Math.round(.5*(23-t)),i=Math.round(.5*(23-r));return'')},cropRoot=createView({name:\"crop\",ignoreRect:!0,mixins:{apis:[\"viewId\",\"stagePosition\",\"hidden\",\"offsetTop\"]},create:function(e){var t=e.root,r=e.props;r.viewId=\"crop\",r.hidden=!1,t.ref.isHiding=!1;var n=[];t.query(\"GET_CROP_ALLOW_IMAGE_TURN_LEFT\")&&n.push({view:button,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_ROTATE_LEFT\"),icon:createIcon('',26),action:function(){return t.dispatch(\"CROP_IMAGE_ROTATE_LEFT\")}}),t.query(\"GET_CROP_ALLOW_IMAGE_TURN_RIGHT\")&&n.push({view:button,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_ROTATE_RIGHT\"),icon:createIcon('',26),action:function(){return t.dispatch(\"CROP_IMAGE_ROTATE_RIGHT\")}}),t.query(\"GET_CROP_ALLOW_IMAGE_FLIP_HORIZONTAL\")&&n.push({view:button,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_FLIP_HORIZONTAL\"),icon:createIcon('',26),action:function(){return t.dispatch(\"CROP_IMAGE_FLIP_HORIZONTAL\")}}),t.query(\"GET_CROP_ALLOW_IMAGE_FLIP_VERTICAL\")&&n.push({view:button,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_FLIP_VERTICAL\"),icon:createIcon('',26),action:function(){return t.dispatch(\"CROP_IMAGE_FLIP_VERTICAL\")}});var i=t.query(\"GET_CROP_ASPECT_RATIO_OPTIONS\");i&&i.length&&n.push({view:dropdown,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_ASPECT_RATIO\"),icon:createIcon('',26),options:null,onSelect:function(e){e.width&&e.height?t.dispatch(\"RESIZE_SET_OUTPUT_SIZE\",{width:e.width,height:e.height}):(t.query(\"GET_CROP_ASPECT_RATIO_OPTIONS\").find(function(e){return e.value&&e.value.width||e.value.height})&&t.dispatch(\"RESIZE_SET_OUTPUT_SIZE\",{width:null,height:null}),t.dispatch(\"CROP_SET_ASPECT_RATIO\",{value:e.aspectRatio}))},didCreateView:function(e){t.ref.aspectRatioDropdown=e}}),t.query(\"GET_CROP_ALLOW_TOGGLE_LIMIT\")&&n.push({view:dropdown,name:\"tool\",label:t.query(\"GET_LABEL_BUTTON_CROP_TOGGLE_LIMIT\"),icon:createIcon('\\n \\n \\n \\n \\n ',26),options:[{value:!0,label:t.query(\"GET_LABEL_BUTTON_CROP_TOGGLE_LIMIT_ENABLE\"),icon:''},{value:!1,label:t.query(\"GET_LABEL_BUTTON_CROP_TOGGLE_LIMIT_DISABLE\"),icon:''}],onSelect:function(e){t.dispatch(\"CROP_SET_LIMIT\",{value:e})},didCreateView:function(e){t.ref.cropToggleLimitDropdown=e}}),t.ref.menu=t.appendChildView(t.createChildView(createGroup(\"toolbar\",[\"opacity\"],{opacity:{type:\"spring\",mass:15,delay:50}}),{opacity:0,controls:n})),t.ref.menuItemsRequiredWidth=null,t.ref.subject=t.appendChildView(t.createChildView(cropSubject,_objectSpread({},r))),t.query(\"GET_CROP_ALLOW_ROTATE\")&&(t.ref.rotator=t.appendChildView(t.createChildView(cropRotator,{rotation:0,opacity:0,translateY:20,id:r.id}))),t.ref.resizer=t.appendChildView(t.createChildView(cropResize,{pivotPoint:{x:0,y:0}})),t.ref.updateControls=function(){var e=t.query(\"GET_IMAGE\");if(updateTurnIcons(t,e.height/e.width),t.ref.cropToggleLimitDropdown&&(t.ref.isLimitedToImageBounds=t.query(\"GET_CROP_LIMIT_TO_IMAGE_BOUNDS\"),updateImageBoundsIcon(t,t.ref.isLimitedToImageBounds),t.ref.cropToggleLimitDropdown.selectedValue=t.ref.isLimitedToImageBounds),t.ref.aspectRatioDropdown){var r=t.query(\"GET_MIN_IMAGE_SIZE\"),n=i.filter(function(t){if(!t.value.aspectRatio)return!0;if(t.value.aspectRatio<1){if(e.naturalWidth*t.value.aspectRatiot.ref.menu.rect.element.width?\"compact\":\"spacious\",t.query(\"GET_CROP_RESIZE_SCROLL_RECT_ONLY\")){var y=t.query(\"GET_STAGE\"),E=y.x,T=y.y,_=t.query(\"GET_ROOT\"),R=t.ref.isModal?_.left:0,w=t.ref.isModal?_.top:0;o.scrollRect={x:R+E+h.cropRect.x,y:w+T+h.cropRect.y+r.offsetTop,width:h.cropRect.width,height:h.cropRect.height}}}}})}),sizeInput=createView({name:\"size-input\",mixins:{listeners:!0,apis:[\"id\",\"value\",\"placeholder\",\"getValue\",\"setValue\",\"setPlaceholder\",\"hasFocus\",\"onChange\"]},create:function(e){var t=e.root,r=e.props,n=r.id,i=r.min,o=r.max,a=r.value,c=r.placeholder,l=r.onChange,u=void 0===l?function(){}:l,s=r.onBlur,d=void 0===s?function(){}:s,p=\"doka--\".concat(n,\"-\").concat(getUniqueId()),f=createElement(\"input\",{type:\"number\",step:1,id:p,min:i,max:o,value:a,placeholder:c}),h=f.getAttribute(\"max\").length,g=createElement(\"label\",{for:p});g.textContent=r.label;var m=function(e,t,r){return isString(e)?((e=e.replace(/[^0-9]/g,\"\")).length>h&&(e=e.slice(0,h)),e=parseInt(e,10)):e=Math.round(e),isNaN(e)?null:limit(e,t,r)},v=function(e){return e.length?parseInt(f.value,10):null};t.ref.handleInput=function(){f.value=m(f.value,1,o),u(v(f.value))},t.ref.handleBlur=function(){f.value=m(f.value,i,o),d(v(f.value))},f.addEventListener(\"input\",t.ref.handleInput),f.addEventListener(\"blur\",t.ref.handleBlur),t.appendChild(f),t.appendChild(g),t.ref.input=f,r.hasFocus=function(){return f===document.activeElement},r.getValue=function(){return v(f.value)},r.setValue=function(e){return f.value=e?m(e,1,999999):null},r.setPlaceholder=function(e){return f.placeholder=e}},destroy:function(e){var t=e.root;t.ref.input.removeEventListener(\"input\",t.ref.handleInput),t.ref.input.removeEventListener(\"blur\",t.ref.handleBlur)}}),checkboxInput=createView({name:\"checkable\",tag:\"span\",mixins:{listeners:!0,apis:[\"id\",\"checked\",\"onChange\",\"onSetValue\",\"setValue\",\"getValue\"]},create:function(e){var t=e.root,r=e.props,n=r.id,i=r.checked,o=r.onChange,a=void 0===o?function(){}:o,c=r.onSetValue,l=void 0===c?function(){}:c,u=\"doka--\".concat(n,\"-\").concat(getUniqueId()),s=createElement(\"input\",{type:\"checkbox\",value:1,id:u});s.checked=i,t.ref.input=s;var d=createElement(\"label\",{for:u});d.innerHTML=r.label,t.appendChild(s),t.appendChild(d),t.ref.handleChange=function(){l(s.checked),a(s.checked)},s.addEventListener(\"change\",t.ref.handleChange),r.getValue=function(){return s.checked},r.setValue=function(e){s.checked=e,l(s.checked)},setTimeout(function(){l(s.checked)},0)},destroy:function(e){var t=e.root;t.ref.input.removeEventListener(\"change\",t.ref.handleChange)}}),testResult$2=null,isAndroid=function(){return null===testResult$2&&(testResult$2=/Android/i.test(navigator.userAgent)),testResult$2},resizeForm=createView({ignoreRect:!0,name:\"resize-form\",tag:\"form\",mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"spring\",mass:15,delay:150}}},create:function(e){var t=e.root;t.element.setAttribute(\"novalidate\",\"novalidate\"),t.element.setAttribute(\"action\",\"#\"),t.ref.shouldBlurKeyboard=isIOS()||isAndroid();var r=t.query(\"GET_SIZE_MAX\"),n=t.query(\"GET_SIZE_MIN\"),i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=e.axisLock,o=void 0===i?\"none\":i,a=e.enforceLimits,c=void 0!==a&&a,l=t.ref,u=l.inputImageWidth,s=l.inputImageHeight,d=l.buttonConfirm,p=t.query(\"GET_SIZE_ASPECT_RATIO_LOCK\"),f=t.query(\"GET_CROP_RECTANGLE_ASPECT_RATIO\"),h={width:u.getValue(),height:s.getValue()},g=limitSize(h,c?n:{width:1,height:1},c?r:{width:999999,height:999999},p?f:null,o);if(p)\"width\"===o?s.setValue(g.width/f):\"height\"===o?u.setValue(g.height*f):(u.setValue(g.width||g.height*f),s.setValue(g.height||g.width/f));else if(g.width&&!g.height){var m=Math.round(g.width/f),v=limitSize({width:g.width,height:m},c?n:{width:1,height:1},c?r:{width:999999,height:999999},f,o);c&&u.setValue(Math.round(v.width)),s.setPlaceholder(Math.round(v.height))}else if(g.height&&!g.width){var y=Math.round(g.height*f);u.setPlaceholder(y)}var E=t.query(\"GET_SIZE_INPUT\"),T=E.width,_=E.height,R=isNumber(T)?Math.round(T):null,w=isNumber(_)?Math.round(_):null,A=u.getValue(),I=s.getValue(),S=A!==R||I!==w;return d.opacity=S?1:0,t.dispatch(\"KICK\"),{width:u.getValue(),height:s.getValue()}},o=t;t.appendChildView(t.createChildView(createFieldGroup(\"Image size\",function(e){var t=e.root,a=t.query(\"GET_SIZE\"),c=t.appendChildView(t.createChildView(sizeInput,{id:\"image-width\",label:t.query(\"GET_LABEL_RESIZE_WIDTH\"),value:isNumber(a.width)?Math.round(a.width):null,min:n.width,max:r.width,placeholder:0,onChange:function(){return i({axisLock:\"width\"})},onBlur:function(){return i({enforceLimits:!1})}})),l=t.appendChildView(t.createChildView(checkboxInput,{id:\"aspect-ratio-lock\",label:createIcon(''),checked:t.query(\"GET_SIZE_ASPECT_RATIO_LOCK\"),onSetValue:function(e){var t=e?0:-3;l.element.querySelector(\".doka--aspect-ratio-lock-ring\").setAttribute(\"transform\",\"translate(0 \".concat(t,\")\"))},onChange:function(e){t.dispatch(\"RESIZE_SET_OUTPUT_SIZE_ASPECT_RATIO_LOCK\",{value:e}),i()}})),u=t.appendChildView(t.createChildView(sizeInput,{id:\"image-height\",label:t.query(\"GET_LABEL_RESIZE_HEIGHT\"),value:isNumber(a.height)?Math.round(a.height):null,min:n.height,max:r.height,placeholder:0,onChange:function(){return i({axisLock:\"height\"})},onBlur:function(){return i({enforceLimits:!1})}}));o.ref.aspectRatioLock=l,o.ref.inputImageWidth=c,o.ref.inputImageHeight=u}))),t.ref.buttonConfirm=t.appendChildView(t.createChildView(button,{name:\"app action-confirm icon-only\",label:t.query(\"GET_LABEL_RESIZE_APPLY_CHANGES\"),action:function(){},opacity:0,icon:createIcon(''),type:\"submit\"})),t.ref.confirmForm=function(e){var r=i({enforceLimits:!0});e.preventDefault();var n=t.ref,o=n.shouldBlurKeyboard,a=n.buttonConfirm;o&&(document.activeElement.blur(),a.element.focus()),a.opacity=0,t.dispatch(\"RESIZE_SET_OUTPUT_SIZE\",r)},t.element.addEventListener(\"submit\",t.ref.confirmForm)},destroy:function(e){var t=e.root;t.element.removeEventListener(\"submit\",t.ref.confirmForm)},write:createRoute({EDIT_RESET:function(e){var t=e.root,r=t.query(\"GET_SIZE\"),n=t.ref,i=n.inputImageWidth,o=n.inputImageHeight,a=n.aspectRatioLock,c=n.buttonConfirm;i.setValue(r.width),o.setValue(r.height),a.setValue(t.query(\"GET_SIZE_ASPECT_RATIO_LOCK\")),c.opacity=0},RESIZE_SET_OUTPUT_SIZE:function(e){var t=e.root,r=e.action,n=t.ref,i=n.inputImageWidth,o=n.inputImageHeight;i.setValue(r.width),o.setValue(r.height)},CROP_SET_ASPECT_RATIO:function(e){var t=e.root,r=e.props,n=e.action,i=e.timestamp,o=t.query(\"GET_CROP\",r.id,i);if(o){var a=o.cropStatus,c=t.ref,l=c.inputImageWidth,u=c.inputImageHeight;null!==n.value?(l.setValue(a.image.width),l.setPlaceholder(a.crop.width),u.setValue(a.image.height),u.setPlaceholder(a.crop.height)):l.getValue()&&u.getValue()&&(u.setValue(null),u.setPlaceholder(a.crop.height))}}},function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.query(\"GET_CROP\",r.id,n);if(i){t.opacity;var o=i.cropStatus,a=t.ref,c=a.inputImageWidth,l=a.inputImageHeight;if(!c.hasFocus()&&!l.hasFocus()){var u=t.query(\"GET_CROP_RECTANGLE_ASPECT_RATIO\");if(null===c.getValue()&&null===l.getValue())c.setPlaceholder(o.crop.width),l.setPlaceholder(o.crop.height);else if(null===c.getValue()&&null!==o.image.height){var s=Math.round(o.image.height*u);c.setPlaceholder(s)}else if(null===l.getValue()&&null!==o.image.width){var d=Math.round(o.image.width/u);l.setPlaceholder(d)}}}})}),createFieldGroup=function(e,t){return createView({tag:\"fieldset\",create:function(r){var n=r.root,i=createElement(\"legend\");i.textContent=e,n.element.appendChild(i),t({root:n})}})},resizeRoot=createView({name:\"resize\",ignoreRect:!0,mixins:{apis:[\"viewId\",\"stagePosition\",\"hidden\"]},create:function(e){var t=e.root,r=e.props;r.viewId=\"resize\",r.hidden=!1,t.ref.isHiding=!1,t.ref.form=t.appendChildView(t.createChildView(resizeForm,{opacity:0,id:r.id}))},read:function(e){var t=e.root,r=e.props;if(!r.hidden){var n=t.rect;if(0!==n.element.width&&0!==n.element.height){var i=t.ref.form.rect;r.stagePosition={x:n.element.left,y:n.element.top+i.element.height,width:n.element.width,height:n.element.height-i.element.height}}}},shouldUpdateChildViews:function(e){var t=e.props,r=e.actions;return!t.hidden||t.hidden&&r&&r.length},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.action,n=e.props;r.id===n.viewId?(t.ref.isHiding=!1,t.ref.form.opacity=1):(t.ref.isHiding=!0,t.ref.form.opacity=0)}},function(e){var t=e.root,r=e.props,n=t.ref,i=n.form,o=n.isHiding,a=r.hidden;o&&0===i.opacity&&!a?r.hidden=!0:r.hidden=!1})}),rangeInput=createView({name:\"range-input\",tag:\"span\",mixins:{listeners:!0,apis:[\"onUpdate\",\"setValue\",\"getValue\",\"setAllowInteraction\"]},create:function(e){var t=e.root,r=e.props,n=r.id,i=r.min,o=r.max,a=r.step,c=r.value,l=r.onUpdate,u=void 0===l?function(){}:l,s=\"doka--\".concat(n,\"-\").concat(getUniqueId()),d=createElement(\"input\",{type:\"range\",id:s,min:i,max:o,step:a});d.value=c,t.ref.input=d;var p=createElement(\"span\");p.className=\"doka--range-input-inner\";var f=createElement(\"label\",{for:s});f.innerHTML=r.label;var h=i+.5*(o-i);t.element.dataset.centered=c===h,t.ref.handleRecenter=function(){r.setValue(h),t.ref.handleChange()};var g=createElement(\"button\",{type:\"button\"});g.textContent=\"center\",g.addEventListener(\"click\",t.ref.handleRecenter),t.ref.recenter=g,p.appendChild(d),p.appendChild(g),t.appendChild(f),t.appendChild(p),t.ref.handleChange=function(){var e=r.getValue();t.element.dataset.centered=e===h,u(e)},d.addEventListener(\"input\",t.ref.handleChange);var m=null;t.ref.dragger=createDragger(p,function(){m=d.getBoundingClientRect()},function(e){var r=(e.pageX-m.left)/m.width;d.value=i+r*(o-i),t.ref.handleChange()},function(){},{stopPropagation:!0}),r.getValue=function(){return parseFloat(d.value)},r.setValue=function(e){return d.value=e},r.setAllowInteraction=function(e){e?t.ref.dragger.enable():t.ref.dragger.disable()}},destroy:function(e){var t=e.root;t.ref.dragger.destroy(),t.ref.recenter.removeEventListener(\"click\",t.ref.handleRecenter),t.ref.input.removeEventListener(\"input\",t.ref.handleChange)}}),COLOR_TOOLS$1={brightness:{icon:createIcon('')},contrast:{icon:createIcon('')},exposure:{icon:createIcon('')},saturation:{icon:createIcon('')}},colorForm=createView({ignoreRect:!0,name:\"color-form\",tag:\"form\",mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"spring\",mass:15}}},create:function(e){var t=e.root;t.element.setAttribute(\"novalidate\",\"novalidate\");var r=t.query(\"GET_COLOR_VALUES\");t.ref.tools=Object.keys(COLOR_TOOLS$1).reduce(function(e,n){var i=n,o=COLOR_TOOLS$1[n].icon,a=t.query(\"GET_LABEL_COLOR_\".concat(n.toUpperCase())),c=t.query(\"GET_COLOR_\".concat(n.toUpperCase(),\"_RANGE\")),l=r[n];return e[i]={view:t.appendChildView(t.createChildView(rangeInput,{id:i,label:\"\".concat(o,\"\").concat(a,\"\"),min:c[0],max:c[1],step:.01,value:l,onUpdate:function(e){return t.dispatch(\"COLOR_SET_COLOR_VALUE\",{key:i,value:e})}}))},e},{})},write:createRoute({COLOR_SET_VALUE:function(e){var t=e.root,r=e.action;t.ref.tools[r.key].view.setValue(r.value)},SHOW_VIEW:function(e){var t=e.root,r=e.action;Object.keys(t.ref.tools).forEach(function(e){t.ref.tools[e].view.setAllowInteraction(\"color\"===r.id)})}})}),tilePreviewWorker=null,tilePreviewWorkerTerminationTimeout=null,updateColors=function(e,t){var r=t.brightness,n=t.exposure,i=t.contrast,o=t.saturation;if(0!==r){var a=r<0,c=a?\"multiply\":\"overlay\",l=a?0:255,u=a?Math.abs(r):1-r;e.ref.imageOverlay.style.cssText=\"mix-blend-mode: \".concat(c,\"; background: rgba(\").concat(l,\",\").concat(l,\",\").concat(l,\",\").concat(u,\")\")}return e.ref.imageOverlay.style.cssText=\"background:transparent\",e.ref.image.style.cssText=\"filter: brightness(\".concat(n,\") contrast(\").concat(i,\") saturate(\").concat(o,\")\"),t},colorKeys=Object.keys(COLOR_TOOLS$1),colorEquals=function(e,t){return colorKeys.findIndex(function(r){return e[r]!==t[r]})<0},createFilterTile=function(e){return createView({ignoreRect:!0,tag:\"li\",name:\"filter-tile\",mixins:{styles:[\"opacity\",\"translateY\"],animations:{translateY:{type:\"spring\",delay:10*e},opacity:{type:\"spring\",delay:30*e}}},create:function(e){var t=e.root,r=e.props,n=\"doka--filter-\".concat(r.style,\"-\").concat(getUniqueId()),i=createElement(\"input\",{id:n,type:\"radio\",name:\"filter\"});t.appendChild(i),i.checked=r.selected,i.value=r.style,i.addEventListener(\"change\",function(){i.checked&&r.onSelect()});var o=createElement(\"label\",{for:n});o.textContent=r.label,t.appendChild(o);var a=r.imageData,c=Math.min(a.width,a.height),l=c,u=createElement(\"canvas\");u.width=c,u.height=l;var s=u.getContext(\"2d\");t.ref.image=u;var d=createElement(\"div\");t.ref.imageOverlay=d;var p={x:.5*c-.5*a.width,y:.5*l-.5*a.height},f=createElement(\"div\");f.appendChild(u),f.appendChild(d),t.appendChild(f),t.ref.imageWrapper=f,r.matrix?(tilePreviewWorker||(tilePreviewWorker=createWorker(TransformWorker)),clearTimeout(tilePreviewWorkerTerminationTimeout),tilePreviewWorker.post({transforms:[{type:\"filter\",data:r.matrix}],imageData:a},function(e){s.putImageData(e,p.x,p.y),clearTimeout(tilePreviewWorkerTerminationTimeout),tilePreviewWorkerTerminationTimeout=setTimeout(function(){tilePreviewWorker.terminate(),tilePreviewWorker=null},1e3)},[a.data.buffer]),t.ref.activeColors=updateColors(t,t.query(\"GET_COLOR_VALUES\"))):s.putImageData(a,p.x,p.y)},write:function(e){var t=e.root;if(!(t.opacity<=0)){var r=t.query(\"GET_COLOR_VALUES\"),n=t.ref.activeColors;(!n&&r||!colorEquals(n,r))&&(t.ref.activeColors=r,updateColors(t,r))}}})},cloneImageData=function(e){var t;try{t=new ImageData(e.width,e.height)}catch(r){t=document.createElement(\"canvas\").getContext(\"2d\").createImageData(e.width,e.height)}return t.data.set(new Uint8ClampedArray(e.data)),t},arrayEqual=function(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every(function(e,r){return e===t[r]})},filterList=createView({ignoreRect:!0,tag:\"ul\",name:\"filter-list\",mixins:{apis:[\"filterOpacity\",\"hidden\"]},create:function(e){var t=e.root,r=e.props;t.element.setAttribute(\"role\",\"list\"),t.ref.tiles=[];var n=t.query(\"GET_THUMB_IMAGE_DATA\"),i=t.query(\"GET_FILTERS\"),o=[];forin(i,function(e,t){o.push(_objectSpread({id:e},t))}),t.ref.activeFilter=t.query(\"GET_FILTER\"),t.ref.tiles=o.map(function(e,i){var o=e.matrix(),a=t.ref.activeFilter===e.id||arrayEqual(t.ref.activeFilter,o)||0===i;return t.appendChildView(t.createChildView(createFilterTile(i),{opacity:0,translateY:-5,id:r.id,style:e.id,label:e.label,matrix:o,imageData:cloneImageData(n),selected:a,onSelect:function(){return t.dispatch(\"FILTER_SET_FILTER\",{value:o?e.id:null})}}))})},write:function(e){var t=e.root,r=e.props;if(!r.hidden){var n=t.query(\"GET_FILTER\");if(n!==t.ref.activeFilter){t.ref.activeFilter=n;var i=t.query(\"GET_FILTERS\"),o=n?isString(n)?n:isColorMatrix(n)?Object.keys(i).find(function(e){return arrayEqual(i[e].matrix(),n)}):null:\"original\";Array.from(t.element.querySelectorAll(\"input\")).forEach(function(e){return e.checked=e.value===o})}t.query(\"IS_ACTIVE_VIEW\",\"filter\")?t.ref.tiles.forEach(function(e){e.opacity=1,e.translateY=0}):t.ref.tiles.forEach(function(e){e.opacity=0,e.translateY=-5}),r.filterOpacity=t.ref.tiles.reduce(function(e,t){return e+t.opacity},0)/t.ref.tiles.length}}}),createScroller=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return createView({name:\"scroller doka--\".concat(e,\"-scroller\"),ignoreRect:!0,ignoreRectUpdate:!0,mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"spring\"}},apis:r},create:function(e){var r,n=e.root,i=e.props;(n.ref.content=n.appendChildView(n.createChildView(t,{id:i.id})),n.element.isScrollContainer=!0,canHover())&&(n.ref.handleMouseWheel=function(e){var t=n.element.scrollLeft,r=n.ref.scrollWidth-n.rect.element.width,i=t+e.deltaX;(i<0||i>r)&&(n.element.scrollLeft=Math.min(Math.max(i,0),r),e.preventDefault())},n.element.addEventListener(\"mousewheel\",n.ref.handleMouseWheel),n.element.dataset.dragState=\"end\",n.ref.dragger=createDragger(n.ref.content.element,function(){n.element.dataset.dragState=\"start\",r=n.element.scrollLeft},function(e,t){n.element.scrollLeft=r-t.x,n.ref.scrollWidth-n.rect.element.width!=0&&vectorDistanceSquared({x:0,y:0},t)>0&&(n.element.dataset.dragState=\"dragging\")},function(){n.element.dataset.dragState=\"end\"},{stopPropagation:!0}))},destroy:function(e){var t=e.root;t.ref.handleMouseWheel&&t.element.removeEventListener(\"mousewheel\",t.ref.handleMouseWheel),t.ref.dragger&&t.ref.dragger.destroy()},read:function(e){var t=e.root;t.ref.scrollWidth=t.element.scrollWidth},write:function(e){var t=e.root,r=e.props;t.ref.content.hidden=r.hidden,r.contentOpacity=t.ref.content.contentOpacity}})},createSelectionView=function(e,t){return createView({name:e,ignoreRect:!0,mixins:{apis:[\"viewId\",\"stagePosition\",\"hidden\"]},create:function(r){var n=r.root,i=r.props;i.viewId=e,i.hidden=!1,n.ref.isHiding=!1,n.ref.content=n.appendChildView(n.createChildView(createScroller(e,t,[\"hidden\",\"contentOpacity\"]),{id:i.id}))},read:function(e){var t=e.root,r=e.props;if(t.ref.content&&!r.hidden){var n=t.rect;if(0!==n.element.width&&0!==n.element.height){var i=t.ref.content.rect,o=0===i.element.top,a=o?n.element.top+i.element.height+i.element.marginBottom:n.element.top,c=o?n.element.height-i.element.height-i.element.marginBottom:n.element.height-i.element.height-n.element.top;r.stagePosition={x:n.element.left,y:a,width:n.element.width,height:c}}}},shouldUpdateChildViews:function(e){var t=e.props,r=e.actions;return!t.hidden||t.hidden&&r&&r.length},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.action,n=e.props;t.ref.content&&(r.id===n.viewId?(t.ref.isHiding=!1,n.hidden=!1,t.ref.content.hidden=!1):t.ref.isHiding=!0)}},function(e){var t=e.root,r=e.props;t.ref.content.opacity=t.ref.isHiding||t.ref.content.hidden?0:1,t.ref.isHiding&&t.ref.content.contentOpacity<=0&&(t.ref.isHiding=!1,r.hidden=!0,t.ref.content.hidden=!0)})})},filterRoot=createSelectionView(\"filter\",filterList),colorRoot=createView({name:\"color\",ignoreRect:!0,mixins:{apis:[\"viewId\",\"stagePosition\",\"hidden\"]},create:function(e){var t=e.root,r=e.props;r.viewId=\"color\",r.hidden=!1,t.ref.isHiding=!1,t.ref.form=t.appendChildView(t.createChildView(colorForm,{opacity:0,id:r.id}))},read:function(e){var t=e.root,r=e.props;if(!r.hidden){var n=t.rect;if(0!==n.element.width&&0!==n.element.height){var i=t.ref.form.rect,o=i.element.height,a=0===i.element.top,c=a?n.element.top+o:n.element.top,l=a?n.element.height-o:n.element.height-o-n.element.top;r.stagePosition={x:n.element.left,y:c,width:n.element.width,height:l}}}},shouldUpdateChildViews:function(e){var t=e.props,r=e.actions;return!t.hidden||t.hidden&&r&&r.length},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.action,n=e.props;r.id===n.viewId?(t.ref.isHiding=!1,t.ref.form.opacity=1,n.hidden=!1):(t.ref.isHiding=!0,t.ref.form.opacity=0)}},function(e){var t=e.root,r=e.props;t.ref.isHiding&&0===t.ref.form.opacity&&(t.ref.isHiding=!1,r.hidden=!0)})}),supportsColorPicker=function(){try{var e=createElement(\"input\",{type:\"color\"}),t=\"color\"===e.type;return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?t:t&&\"number\"!=typeof e.selectionStart}catch(e){return!1}},toHSL=function(e,t,r){var n,i=Math.max(e,t,r),o=Math.min(e,t,r),a=i-o,c=0===i?0:a/i,l=i/255;switch(i){case o:n=0;break;case e:n=t-r+a*(t'.concat(e,\"\")},createShapeStyleIcon=function(e){var t=0===e?\"currentColor\":\"none\",r=e;return createSVG(''))},createLineStyleIcon=function(e){return createSVG(''))},markupTools=createView({name:\"markup-tools\",ignoreRect:!0,mixins:{apis:[\"onUpdate\"],animations:{translateY:\"spring\",opacity:\"spring\"},styles:[\"translateY\",\"opacity\"]},create:function(e){var t=e.root,r=e.props.onUpdate;t.ref.colorSelect=t.appendChildView(t.createChildView(markupColor,{onSelect:function(e){t.ref.colorSelect.selectedValue=e,r(\"color\",e)},name:\"color-select\",colors:t.query(\"GET_MARKUP_COLOR_OPTIONS\")})),t.ref.shapeStyleSelect=t.appendChildView(t.createChildView(dropdown,{onSelect:function(e){t.ref.shapeStyleSelect.selectedValue=e,r(\"shapeStyle\",e.slice(1))},name:\"tool\",label:t.query(\"GET_LABEL_MARKUP_SELECT_SHAPE_STYLE\"),direction:\"up\",options:t.query(\"GET_MARKUP_SHAPE_STYLE_OPTIONS\").map(function(e){return{value:e,label:e[0],icon:createShapeStyleIcon(e[3])}})})),t.ref.lineStyleSelect=t.appendChildView(t.createChildView(dropdown,{onSelect:function(e){t.ref.lineStyleSelect.selectedValue=e,r(\"lineStyle\",e.slice(1))},name:\"tool\",label:t.query(\"GET_LABEL_MARKUP_SELECT_LINE_STYLE\"),direction:\"up\",options:t.query(\"GET_MARKUP_LINE_STYLE_OPTIONS\").map(function(e){return{value:e,label:e[0],icon:createLineStyleIcon(e[3])}})})),t.ref.lineDecorationSelect=t.appendChildView(t.createChildView(dropdown,{onSelect:function(e){t.ref.lineDecorationSelect.selectedValue=e,r(\"lineDecoration\",e)},name:\"tool\",label:t.query(\"GET_LABEL_MARKUP_SELECT_LINE_DECORATION\"),direction:\"up\",options:t.query(\"GET_MARKUP_LINE_DECORATION_OPTIONS\").map(function(e){return{value:e[1],label:e[0]}})})),t.ref.fontFamilySelect=t.appendChildView(t.createChildView(dropdown,{onSelect:function(e){t.ref.fontFamilySelect.selectedValue=e,r(\"fontFamily\",e)},name:\"tool\",label:t.query(\"GET_LABEL_MARKUP_SELECT_FONT_FAMILY\"),direction:\"up\",options:t.query(\"GET_MARKUP_FONT_FAMILY_OPTIONS\").map(function(e){return{value:e[1],label:'').concat(e[0],\"\")}})})),t.ref.fontSizeSelect=t.appendChildView(t.createChildView(dropdown,{onSelect:function(e){t.ref.fontSizeSelect.selectedValue=e,r(\"fontSize\",e)},name:\"tool\",label:t.query(\"GET_LABEL_MARKUP_SELECT_FONT_SIZE\"),direction:\"up\",options:t.query(\"GET_MARKUP_FONT_SIZE_OPTIONS\").map(function(e){return{value:e[1],label:e[0]}})})),\"draw\"===t.query(\"GET_MARKUP_UTIL\")&&showDrawTool(t)},write:createRoute({SWITCH_MARKUP_UTIL:function(e){var t=e.root;\"draw\"===e.action.util&&showDrawTool(t)},MARKUP_SELECT:function(e){var t=e.root,r=e.action,n=t.ref,i=n.colorSelect,o=n.fontFamilySelect,a=n.fontSizeSelect,c=n.shapeStyleSelect,l=n.lineStyleSelect,u=n.lineDecorationSelect,s=r.id?t.query(\"GET_MARKUP_BY_ID\",r.id):null,d=[i,o,a,c,l,u],p=[];if(s){var f=_slicedToArray(s,2),h=f[0],g=f[1],m=Array.isArray(g.allowEdit)?g.allowEdit:!1===g.allowEdit?[]:ALL_SETTINGS,v=ALL_SETTINGS.reduce(function(e,t){return e[t]=-1!==m.indexOf(t),e},{});if(v.color=!!m.find(function(e){return/[a-z]Color/.test(e)}),\"image\"!==h&&v.color&&(i.selectedValue=getColor$2(g),p.push(i)),\"text\"===h&&(v.fontFamily&&(o.selectedValue=g.fontFamily,p.push(o)),v.fontSize&&(a.selectedValue=g.fontSize,p.push(a))),(\"rect\"===h||\"ellipse\"===h)&&v.borderStyle){var y=t.query(\"GET_MARKUP_SHAPE_STYLE_OPTIONS\").find(function(e){var t=g.borderWidth===e[1],r=g.borderStyle===e[2]||arrayEqual(g.borderStyle,e[2]);return t&&r});c.selectedValue=y,p.push(c)}if(\"line\"===h||\"path\"===h){if(v.lineWidth){var E=t.query(\"GET_MARKUP_LINE_STYLE_OPTIONS\").find(function(e){var t=g.lineWidth===e[1],r=g.lineStyle===e[2]||arrayEqual(g.lineStyle,e[2]);return t&&r});l.selectedValue=E,p.push(l)}\"line\"===h&&v.lineDecoration&&(u.selectedValue=g.lineDecoration,p.push(u))}d.forEach(function(e){e.element.dataset.active=\"false\"}),p.forEach(function(e){e.element.dataset.active=\"true\"})}},MARKUP_UPDATE:function(e){var t=e.root,r=e.action,n=r.style,i=r.value;t.ref[n+\"Select\"]&&(t.ref[n+\"Select\"].selectedValue=i)}})}),getColor$2=function(e){var t=e.fontColor,r=e.backgroundColor,n=e.lineColor,i=e.borderColor;return t||r||n||i},markupRoot=createView({name:\"markup\",ignoreRect:!0,mixins:{apis:[\"viewId\",\"stagePosition\",\"hidden\"]},create:function(e){var t=e.root,r=e.props;r.viewId=\"markup\",r.hidden=!1,t.ref.isHiding=!1;var n=[[\"select\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_SELECT\"),icon:createIcon('',26)}],[\"draw\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_DRAW\"),icon:createIcon('',26)}],[\"line\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_LINE\"),icon:createIcon('',26)}],[\"text\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_TEXT\"),icon:createIcon('',26)}],[\"rect\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_RECT\"),icon:createIcon('',26)}],[\"ellipse\",{label:t.query(\"GET_LABEL_MARKUP_TOOL_ELLIPSE\"),icon:createIcon('',26)}]];t.ref.utils=createElement(\"fieldset\"),t.ref.utils.className=\"doka--markup-utils\",t.ref.utilsList=createElement(\"ul\");var i=\"markup-utils-\".concat(getUniqueId());t.ref.inputs=n.map(function(e){var r=e[0],n=e[1],o=\"doka--markup-tool-\"+getUniqueId(),a=createElement(\"li\"),c=createElement(\"input\");c.id=o,c.checked=t.query(\"GET_MARKUP_UTIL\")===r,c.setAttribute(\"type\",\"radio\"),c.setAttribute(\"name\",i),c.value=r;var l=createElement(\"label\");return l.setAttribute(\"for\",o),l.className=\"doka--button-tool\",l.innerHTML=n.icon+\"\"+n.label+\"\",l.title=n.label,a.appendChild(c),a.appendChild(l),t.ref.utilsList.appendChild(a),c}),t.ref.utils.appendChild(t.ref.utilsList),t.ref.utilsList.addEventListener(\"change\",function(e){t.dispatch(\"SET_MARKUP_UTIL\",{value:e.target.value})}),t.query(\"GET_MARKUP_ALLOW_ADD_MARKUP\")&&(t.ref.menu=t.appendChildView(t.createChildView(createGroup(\"toolbar\",[\"opacity\"],{opacity:{type:\"spring\",mass:15,delay:50}}),{opacity:0,element:t.ref.utils})));var o=t.ref.tools=t.appendChildView(t.createChildView(markupTools,{opacity:0,onUpdate:function(e,r){t.dispatch(\"MARKUP_UPDATE\",{style:e,value:r})}}));t.ref.menuItemsRequiredWidth=null,\"draw\"===t.query(\"GET_MARKUP_UTIL\")&&(o.opacity=1,o.translateY=0,o.element.dataset.active=\"true\")},read:function(e){var t=e.root,r=e.props;if(r.hidden)t.ref.menuItemsRequiredWidth=null;else{var n=t.rect;if(0!==n.element.width&&0!==n.element.height){if(t.ref.menu&&null===t.ref.menuItemsRequiredWidth){var i=t.ref.menu.rect.element.width;t.ref.menuItemsRequiredWidth=0===i?null:i}var o=t.ref.menu&&t.ref.menu.rect,a=t.ref.tools.rect.element.height,c=o?o.element.height:a,l=!o||0===o.element.top,u=l?n.element.top+c:n.element.top,s=l?n.element.height-c:n.element.height-c-n.element.top;r.stagePosition={x:n.element.left+20,y:u,width:n.element.width-40,height:s-a}}}},shouldUpdateChildViews:function(e){var t=e.props,r=e.actions;return!t.hidden||t.hidden&&r&&r.length},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.action,n=e.props;r.id===n.viewId?(n.hidden=!1,t.ref.isHiding=!1,t.ref.menu&&(t.ref.menu.opacity=1)):(t.ref.isHiding=!0,t.ref.menu&&(t.ref.menu.opacity=0),t.ref.tools.opacity=0,t.ref.tools.translateY=5,t.dispatch(\"SET_MARKUP_UTIL\",{value:\"select\"}))},MARKUP_SELECT:function(e){var t=e.root,r=e.action;t.ref.tools.opacity=r.id?1:0,t.ref.tools.translateY=r.id?0:5,t.ref.tools.element.dataset.active=r.id?\"true\":\"false\"},DID_SET_MARKUP_UTIL:function(e){var t=e.root,r=e.action,n=t.ref,i=n.inputs,o=n.tools;i.forEach(function(e){e.checked=e.value===r.value}),\"draw\"===r.value&&(o.opacity=1,o.translateY=0,o.element.dataset.active=\"true\")}},function(e){var t=e.root,r=e.props;t.ref.isHiding&&t.ref.menu&&0===t.ref.menu.opacity&&(t.ref.isHiding=!1,r.hidden=!0),r.hidden||(t.ref.menu.element.dataset.layout=t.ref.menuItemsRequiredWidth>t.rect.element.width?\"compact\":\"spacious\")})}),positions=[\"x\",\"y\",\"left\",\"top\",\"right\",\"bottom\"],hasNoPosition=function(e){return positions.every(function(t){return void 0===e[t]})},getRandomRange=function(){return-.5+Math.random()},isEmoji=function(e){return null!==e.match(/(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\u0023-\\u0039]\\ufe0f?\\u20e3|\\u3299|\\u3297|\\u303d|\\u3030|\\u24c2|\\ud83c[\\udd70-\\udd71]|\\ud83c[\\udd7e-\\udd7f]|\\ud83c\\udd8e|\\ud83c[\\udd91-\\udd9a]|\\ud83c[\\udde6-\\uddff]|\\ud83c[\\ude01-\\ude02]|\\ud83c\\ude1a|\\ud83c\\ude2f|\\ud83c[\\ude32-\\ude3a]|\\ud83c[\\ude50-\\ude51]|\\u203c|\\u2049|[\\u25aa-\\u25ab]|\\u25b6|\\u25c0|[\\u25fb-\\u25fe]|\\u00a9|\\u00ae|\\u2122|\\u2139|\\ud83c\\udc04|[\\u2600-\\u26FF]|\\u2b05|\\u2b06|\\u2b07|\\u2b1b|\\u2b1c|\\u2b50|\\u2b55|\\u231a|\\u231b|\\u2328|\\u23cf|[\\u23e9-\\u23f3]|[\\u23f8-\\u23fa]|\\ud83c\\udccf|\\u2934|\\u2935|[\\u2190-\\u21ff])/g)},stickerList=createView({ignoreRect:!0,tag:\"ul\",name:\"sticker-list\",create:function(e){var t=e.root;t.element.setAttribute(\"role\",\"list\");var r=function(e,r){var n=e.markup;\"string\"==typeof e||Array.isArray(e)?n=e:e.markup||(n=e.sticker),Array.isArray(e.sticker)&&(n=[n[0],_objectSpread({},e.sticker[1],n[1])]);var i,o,a=\"string\"==typeof n,c=a&&isEmoji(n),l=a&&!c,u=0,s=0,d=t.query(\"GET_CROP_RECTANGLE_ASPECT_RATIO\");if(l)i=\"image\",u=.5*-(o={src:n,width:.5,height:.5*d,fit:\"contain\"}).width,s=.5*-o.height;else{if(c?(i=\"text\",o={text:n}):(i=n[0],o=_objectSpread({},n[1])),\"text\"===i){o.fontColor=o.fontColor||\"#000000\",o.fontSize=o.fontSize||.125,o.allowInput=void 0!==o.allowInput&&o.allowInput,o.allowEdit=void 0!==o.allowEdit&&o.allowEdit;var p=c?.75*o.fontSize:.35*o.fontSize*o.text.length;u=-.5*p,s=.5*(c?p*d*.5:.5*o.fontSize)}\"string\"==typeof o.width||\"string\"==typeof o.height||\"rect\"!==i&&\"ellipse\"!==i&&\"line\"!==i&&\"image\"!==i||(o.height=o.height*d,u=.5*-o.width,s=.5*-o.height)}r&&(o.x=r.x+u,o.y=r.y+s),hasNoPosition(o)&&(o.x=.5+.5*getRandomRange()+u,o.y=.5+.5*getRandomRange()+s),t.dispatch(\"MARKUP_ADD\",[i,o])};t.element.addEventListener(\"pointerdown\",function(e){var n=e.target.dataset.index||\"\";if(n.length){var i=t.query(\"GET_STICKERS\")[n];if(i){var o={x:e.pageX,y:e.pageY},a=Date.now();document.documentElement.addEventListener(\"pointerup\",function e(n){document.documentElement.removeEventListener(\"pointerup\",e);var c={x:n.pageX,y:n.pageY},l=vectorDistanceSquared(o,c),u=Date.now()-a;if(l<10&&u<300)r(i);else{var s=t.query(\"GET_ROOT\"),d=t.query(\"GET_STAGE\"),p=t.query(\"GET_CROP_RECT\"),f=void 0!==n.offsetX?n.offsetX:n.pageX-s.x-d.x-window.pageXOffset,h=void 0!==n.offsetY?n.offsetY:n.pageY-s.y-d.y-window.pageYOffset,g=d.x+p.x,m=d.y+p.y,v=(f-g)/p.width,y=(h-m)/p.height;v<0||v>1||y<0||y>1||r(i,{x:v,y:y})}})}}});var n=function(){var e=t.query(\"GET_STICKERS\");t.element.innerHTML=\"\",e.forEach(function(e,r){var n,i;\"string\"==typeof e||Array.isArray(e)?(n=\"\",i=e):(n=e.alt||\"\",i=e.sticker);var o,a=createElement(\"button\"),c=\"string\"==typeof i,l=c&&isEmoji(i);if(c&&!l)(o=new Image).src=i;else{var u,s;o=createElement(\"svg\",{viewBox:\"0 0 100 100\",xmlns:\"http://www.w3.org/2000/svg\",\"xmlns:xlink\":\"http://www.w3.org/1999/xlink\"}),l?(u=\"text\",s={text:i}):(u=i[0],s=_objectSpread({},i[1])),\"text\"===u&&(s.fontColor=s.fontColor||\"#000000\",s.fontSize=s.fontSize||.3125);var d=createMarkupByType(u,s);updateMarkupByType(d,u,s,{width:200,height:200}),d.removeAttribute(\"id\");var p=\"text\"===u?6:0;\"ellipse\"===u?(d.setAttribute(\"cx\",\"50\"),d.setAttribute(\"cy\",\"50\")):(d.setAttribute(\"x\",50-.5*d.getAttribute(\"width\")),d.setAttribute(\"y\",50-.5*d.getAttribute(\"height\"))),\"text\"===u&&(d.setAttribute(\"x\",\"50\"),d.setAttribute(\"y\",50+p),d.setAttribute(\"text-anchor\",\"middle\"),d.setAttribute(\"dominant-baseline\",\"middle\")),o.appendChild(d)}n&&(a.innerHTML=\"\".concat(n,\"\")),a.appendChild(o),a.dataset.index=r,a.setAttribute(\"type\",\"button\"),a.className=\"doka--button doka--button-tool\";var f=t.query(\"GET_AFTER_UPDATE_STICKER_ITEM\");f&&f(a,{index:r,sticker:e});var h=createElement(\"li\");h.appendChild(a),t.element.appendChild(h)})};t.ref.updateStickers=n,n()},write:createRoute({DID_SET_STICKERS:function(e){var t=e.root;e.action,e.props;t.ref.updateStickers()}})}),stickerRoot=createSelectionView(\"sticker\",stickerList),hasStagePositionChanged=function(e,t){return!e||!t||!rectEqualsRect(e,t)},VIEW_MAP={crop:cropRoot,resize:resizeRoot,filter:filterRoot,color:colorRoot,markup:markupRoot,sticker:stickerRoot},viewStack=createView({name:\"view-stack\",ignoreRect:!0,mixins:{apis:[\"offsetTop\"]},create:function(e){var t=e.root;t.ref.activeView=null,t.ref.activeStagePosition=null,t.ref.shouldFocus=!1},write:createRoute({SHOW_VIEW:function(e){var t=e.root,r=e.props,n=e.action,i=0===t.childViews.length,o=t.childViews.find(function(e){return e.viewId===n.id});o||(o=t.appendChildView(t.createChildView(VIEW_MAP[n.id],_objectSpread({},r)))),t.ref.activeView=o,t.childViews.map(function(e){return e.element}).forEach(function(e){e.dataset.viewActive=\"false\",e.removeAttribute(\"tabindex\"),isIE()&&(e.style.transform=\"\")});var a=t.ref.activeView.element;a.dataset.viewActive=\"true\",a.setAttribute(\"tabindex\",-1),isIE()&&setTimeout(function(){a.style.transform=\"translateZ(0)\"},32),t.ref.shouldFocus=!i},DID_PRESENT_IMAGE:function(e){var t=e.root;t.dispatch(\"CHANGE_VIEW\",{id:t.query(\"GET_UTIL\")||t.query(\"GET_UTILS\")[0]})},DID_SET_UTILS:function(e){var t=e.root;t.dispatch(\"CHANGE_VIEW\",{id:t.query(\"GET_UTIL\")||t.query(\"GET_UTILS\")[0]})}},function(e){var t=e.root,r=e.props,n=t.ref,i=n.activeView,o=n.previousStagePosition;if(i&&i.stagePosition&&(t.childViews.forEach(function(e){e.offsetTop=r.offsetTop,e.element.viewHidden!==e.hidden&&(e.element.viewHidden=e.hidden,e.element.dataset.viewHidden=e.hidden)}),hasStagePositionChanged(i.stagePosition,o))){var a=i.stagePosition,c=a.x,l=a.y,u=a.width,s=a.height;if(0===u&&0===s)return;t.dispatch(\"DID_RESIZE_STAGE\",{offset:{x:c,y:l},size:{width:u,height:s},animate:!0}),t.ref.previousStagePosition=i.stagePosition}}),didWriteView:function(e){var t=e.root;t.ref.shouldFocus&&(t.ref.activeView.element.focus({preventScroll:!0}),t.ref.shouldFocus=!1)}}),editContent=createView({name:\"content\",ignoreRect:!0,mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"tween\",duration:250}}},create:function(e){var t=e.root,r=e.props;t.opacity=1,t.ref.viewStack=t.appendChildView(t.createChildView(viewStack,{id:r.id})),t.ref.image=null},write:createRoute({DID_LOAD_IMAGE:function(e){var t=e.root,r=e.props;t.ref.image=t.appendChildView(t.createChildView(image,{id:r.id}))}},function(e){var t=e.root,r=t.ref,n=r.image,i=r.viewStack;if(n){var o=t.rect.element.top;i.offsetTop=o,n.offsetTop=o}})}),updateResizeButton=function(e,t){e.element.dataset.scaleDirection=null===t||t>1?\"up\":\"down\"},editUtils=createView({name:\"utils\",create:function(e){var t=e.root,r={crop:{title:t.query(\"GET_LABEL_BUTTON_UTIL_CROP\"),icon:createIcon('')},filter:{title:t.query(\"GET_LABEL_BUTTON_UTIL_FILTER\"),icon:createIcon('')},color:{title:t.query(\"GET_LABEL_BUTTON_UTIL_COLOR\"),icon:createIcon('')},markup:{title:t.query(\"GET_LABEL_BUTTON_UTIL_MARKUP\"),icon:createIcon('')},sticker:{title:t.query(\"GET_LABEL_BUTTON_UTIL_STICKER\"),icon:createIcon('')},resize:{title:t.query(\"GET_LABEL_BUTTON_UTIL_RESIZE\"),icon:createIcon('')}};t.ref.utils=Object.keys(r).map(function(e){return _objectSpread({id:e},r[e])}),t.ref.utilMenuRequiredWidth=null},read:function(e){var t=e.root;if(null===t.ref.utilMenuRequiredWidth){var r=t.childViews.reduce(function(e,t){return e+t.rect.outer.width},0);t.ref.utilMenuRequiredWidth=0===r?null:r}},write:createRoute({DID_SET_UTILS:function(e){var t=e.root,r=_toConsumableArray(t.query(\"GET_UTILS\"));t.childViews.forEach(function(e){return t.removeChildView(e)}),t.element.dataset.utilCount=r.length,1===r.length&&(r.length=0),r.forEach(function(e){var r=t.ref.utils.find(function(t){return t.id===e}),n=t.appendChildView(t.createChildView(button,{name:\"tab\",view:button,label:r.title,opacity:1,icon:r.icon,id:r.id,action:function(){return t.dispatch(\"CHANGE_VIEW\",{id:r.id})}}));t.ref[\"util_button_\".concat(r.id)]=n})},SHOW_VIEW:function(e){var t=e.root,r=e.action;t.childViews.forEach(function(e){e.element.dataset.active=e.id===r.id})}},function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.query(\"GET_CROP\",r.id,n);if(i){var o=i.cropStatus;t.ref.util_button_resize&&updateResizeButton(t.ref.util_button_resize,o.image.width?o.image.width/o.crop.width:null),t.element.dataset.layout=t.ref.utilMenuRequiredWidth>t.rect.element.width?\"compact\":\"spacious\"}})}),HAS_WEBGL=isBrowser()&&function(){try{var e={antialias:!1,alpha:!1},t=document.createElement(\"canvas\");return!!window.WebGLRenderingContext&&(t.getContext(\"webgl\",e)||t.getContext(\"experimental-webgl\",e))}catch(e){return!1}}(),hasWebGL=function(){return HAS_WEBGL},editContainer=createView({name:\"container\",create:function(e){var t=e.root,r=[];t.query(\"GET_ALLOW_BUTTON_RESET\")&&r.push({view:button,opacity:0,label:t.query(\"GET_LABEL_BUTTON_RESET\"),didCreateView:function(e){return t.ref.btnReset=e},name:\"app action-reset icon-only\",icon:createIcon('',26),action:function(){var e=t.query(\"GET_BEFORE_RESET\"),r=!e||e();Promise.resolve(r).then(function(e){e&&t.dispatch(\"EDIT_RESET\")})}}),t.query(\"GET_ALLOW_BUTTON_CANCEL\")&&r.unshift({view:button,label:t.query(\"GET_LABEL_BUTTON_CANCEL\"),name:\"app action-cancel icon-fallback\",opacity:1,icon:createIcon(''),didCreateView:function(e){t.ref.btnCancel=e},action:function(){t.dispatch(\"EDIT_CANCEL\")}}),r.push({view:editUtils}),t.query(\"GET_ALLOW_BUTTON_CONFIRM\")&&r.push({view:button,label:t.query(\"GET_LABEL_BUTTON_CONFIRM\"),name:\"app action-confirm icon-fallback\",opacity:1,icon:createIcon(''),didCreateView:function(e){t.ref.btnConfirm=e},action:function(){t.dispatch(\"EDIT_CONFIRM\")}}),t.ref.menu=t.appendChildView(t.createChildView(createGroup(\"menu\"),{controls:r})),t.ref.menu.opacity=0,t.ref.status=t.appendChildView(t.createChildView(editStatus)),t.ref.hasWebGL=hasWebGL(),t.ref.hasWebGL?t.dispatch(\"AWAIT_IMAGE\"):t.dispatch(\"MISSING_WEBGL\"),t.ref.handleFocusOut=function(e){if(e.relatedTarget&&contains(t.element,e.relatedTarget)){var r=t.ref.status;\"busy\"===r.element.dataset.viewStatus&&r.element.focus()}},t.ref.handleFocusIn=function(e){var r=t.ref,n=r.menu,i=r.content,o=e.target;if(!contains(n.element,o)&&i&&contains(i.element,o)){if(!Array.from(t.element.querySelectorAll(\"[data-view-active=false]\")).reduce(function(e,t){return contains(t,o)&&(e=!0),e},!1))return;n.element.querySelector(\"button,input,[tabindex]\").focus()}},t.element.addEventListener(\"focusin\",t.ref.handleFocusIn),t.element.addEventListener(\"focusout\",t.ref.handleFocusOut),t.ref.previousState=null},destroy:function(e){var t=e.root;t.element.removeEventListener(\"focusin\",t.ref.handleFocusIn),t.element.removeEventListener(\"focusout\",t.ref.handleFocusOut)},write:createRoute({UNLOAD_IMAGE:function(e){var t=e.root;t.ref.content&&(t.ref.content.opacity=0,t.ref.menu.opacity=0)},DID_UNLOAD_IMAGE:function(e){var t=e.root;t.removeChildView(t.ref.content),t.ref.content=null},DID_LOAD_IMAGE:function(e){var t=e.root,r=e.props;t.ref.hasWebGL&&(t.ref.content=t.appendChildView(t.createChildView(editContent,{opacity:null,id:r.id})),t.ref.menu.opacity=1)},SHOW_VIEW:function(e){var t=e.root,r=e.action;t.element.dataset.limitOverflow=\"resize\"===r.id}},function(e){var t=e.root,r=e.props,n=e.timestamp,i=t.query(\"GET_CROP\",r.id,n);if(i){var o=i.cropStatus,a=o.props,c={crop:{center:{x:roundFloat(a.center.x,5),y:roundFloat(a.center.y,5)},rotation:roundFloat(a.rotation,5),zoom:roundFloat(a.zoom,5),aspectRatio:roundFloat(a.aspectRatio,5),flip:{horizontal:a.flip.horizontal,vertical:a.flip.vertical},scaleToFit:a.scaleToFit,width:o.currentWidth,height:o.currentHeight},preview:{scale:i.scale/Math.max(i.cropRect.width/i.previewSize.width,i.cropRect.height/i.previewSize.height)}};hasStateChanged(t.ref.previousState,c)&&(t.dispatch(\"DID_UPDATE\",{state:_objectSpread({},c)}),t.ref.previousState=c);var l=t.ref,u=l.btnReset,s=l.btnCancel,d=l.content,p=i.canReset;if(u&&(u.opacity=p?1:0),s&&u){var f=t.query(\"GET_ROOT_SIZE\");s.opacity=p&&f.width<=600?0:1}d&&0===d.opacity&&t.dispatch(\"DID_UNLOAD_IMAGE\")}})}),hasStateChanged=function(e,t){if(!e)return!0;var r=e.crop,n=t.crop;return r.width!==n.width||r.height!==n.height||r.center.x!==n.center.x||r.center.y!==n.center.y||r.rotation!==n.rotation||r.scaleToFit!==n.scaleToFit||r.zoom!==n.zoom||r.aspectRatio!==n.aspectRatio||r.flip.horizontal!==n.flip.horizontal||r.flip.vertical!==n.flip.vertical},createPointerEvents=function(e){var t={destroy:function(){}};if(\"onpointerdown\"in window||e.pointersPolyfilled)return t;e.pointersPolyfilled=!0;var r=0,n=[],i=function(e,t,r){var n=new UIEvent(t.type,{view:window,bubbles:!r});Object.keys(t).forEach(function(e){Object.defineProperty(n,e,{value:t[e],writable:!1})}),e.dispatchEvent(n)},o=function(e,t,o){return Array.from(t.changedTouches).map(function(a){var c=n[a.identifier],l={type:e,pageX:a.pageX,pageY:a.pageY,pointerId:a.identifier,isPrimary:c?c.isPrimary:0===r,preventDefault:function(){return t.preventDefault()}};return i(a.target,l,o),l})},a=function(e){o(\"pointerdown\",e).forEach(function(e){n[e.pointerId]=e,r++})},c=function(e){o(\"pointermove\",e)},l=function(e){o(\"pointerup\",e).forEach(function(e){delete n[e.pointerId],r--})},u=function(e,t,r){var n={type:e,pageX:t.pageX,pageY:t.pageY,pointerId:0,isPrimary:!0,preventDefault:function(){return t.preventDefault()}};return i(t.target,n,r),n},s=function(e){u(\"pointerdown\",e)},d=function(e){u(\"pointermove\",e)},p=function(e){u(\"pointerup\",e)};return\"ontouchstart\"in window?(e.addEventListener(\"touchstart\",a),e.addEventListener(\"touchmove\",c),e.addEventListener(\"touchend\",l)):\"onmousedown\"in window&&(e.addEventListener(\"mousedown\",s),e.addEventListener(\"mousemove\",d),e.addEventListener(\"mouseup\",p)),t.destroy=function(){n.length=0,e.pointersPolyfilled=!1,e.removeEventListener(\"touchstart\",a),e.removeEventListener(\"touchmove\",c),e.removeEventListener(\"touchend\",l),e.removeEventListener(\"mousedown\",s),e.removeEventListener(\"mousemove\",d),e.removeEventListener(\"mouseup\",p)},t},prevent=function(e){\"gesturestart\"!==e.type?climb(e.target,function(e){return e.isScrollContainer})||e.preventDefault():e.preventDefault()},editor=createView({name:\"editor\",ignoreRect:!0,mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"tween\",duration:350}},apis:[\"markedForRemoval\"]},create:function(e){var t=e.root,r=e.props;r.markedForRemoval=!1,isIOS()&&(t.element.addEventListener(\"touchmove\",prevent,{passive:!1}),t.element.addEventListener(\"gesturestart\",prevent)),t.ref.pointerPolyfill=createPointerEvents(\"root\"===t.query(\"GET_POINTER_EVENTS_POLYFILL_SCOPE\")?t.element:document.documentElement),t.appendChildView(t.createChildView(editContainer,_objectSpread({},r)))},destroy:function(e){var t=e.root;t.ref.pointerPolyfill.destroy(),t.element.removeEventListener(\"touchmove\",prevent,!0),t.element.removeEventListener(\"gesturestart\",prevent)}}),createTouchDetector=function(){function e(){t.fire(\"touch-detected\"),window.removeEventListener(\"touchstart\",e,!1)}var t=_objectSpread({},on(),{destroy:function(){window.removeEventListener(\"touchstart\",e,!1)}});return window.addEventListener(\"touchstart\",e,!1),t},createFileCatcher=function(e){var t,r={browseEnabled:!1},n=function(){t.files.length&&i.fire(\"drop\",Array.from(t.files))},i=_objectSpread({},on(),{enableBrowse:function(){r.browseEnabled||((t=document.createElement(\"input\")).style.display=\"none\",t.setAttribute(\"type\",\"file\"),t.addEventListener(\"change\",n),e.appendChild(t),e.addEventListener(\"click\",o),r.browseEnabled=!0)},disableBrowse:function(){r.browseEnabled&&(t.removeEventListener(\"change\",n),t.parentNode.removeChild(t),e.removeEventListener(\"click\",o),r.browseEnabled=!1)},destroy:function(){e.removeEventListener(\"dragover\",a),e.removeEventListener(\"drop\",c),e.removeEventListener(\"click\",o),t&&t.removeEventListener(\"change\",n)}}),o=function(){return t.click()},a=function(e){return e.preventDefault()},c=function(e){e.preventDefault();var t=Array.from(e.dataTransfer.items||e.dataTransfer.files).map(function(e){return e.getAsFile&&\"file\"===e.kind?e.getAsFile():e});i.fire(\"drop\",t)};return e.addEventListener(\"dragover\",a),e.addEventListener(\"drop\",c),i},createFocusTrap=function(e){var t=function(t){if(9===t.keyCode){var r=Array.from(e.querySelectorAll(\"button,input,[tabindex]\")).filter(function(e){return\"hidden\"!==e.style.visibility&&-1!==e.tabIndex}),n=r[0],i=r[r.length-1];t.shiftKey?document.activeElement===n&&(i.focus(),t.preventDefault()):document.activeElement===i&&(n.focus(),t.preventDefault())}};return e.addEventListener(\"keydown\",t),{destroy:function(){e.removeEventListener(\"keydown\",t)}}},isFullscreen=function(e){return e.ref.isFullscreen},shouldBeFullscreen=function(e){return/fullscreen/.test(e.query(\"GET_STYLE_LAYOUT_MODE\"))},isFloating=function(e){return/fullscreen|preview/.test(e.query(\"GET_STYLE_LAYOUT_MODE\"))},isModal=function(e){return/modal/.test(e.query(\"GET_STYLE_LAYOUT_MODE\"))},mayBeAutoClosed=function(e){return e.query(\"GET_ALLOW_AUTO_CLOSE\")},canBeAutoClosed=isFloating,canBeClosed=isFloating,updateStyleViewport=function(e){var t=e.ref,r=t.environment,n=t.isSingleUtil,i=t.canBeControlled;e.element.dataset.styleViewport=getViewportBySize(e.rect.element.width,e.rect.element.height)+\" \"+r.join(\" \")+(n?\" single-util\":\" multi-util\")+(i?\" flow-controls\":\" no-flow-controls\")},preventNavSwipe=function(e){var t=e.touches?e.touches[0]:e;t.pageX>10&&t.pageX0&&document.body.classList.add(\"doka--parent\"),document.body.appendChild(t);var o=document.querySelector(\"meta[name=viewport]\");e.ref.defaultViewportContent=o?o.getAttribute(\"content\"):null,o||((o=document.createElement(\"meta\")).setAttribute(\"name\",\"viewport\"),document.head.appendChild(o)),o.setAttribute(\"content\",\"width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=0\"),e.opacity=1,contains(e.element,document.activeElement)||t.focus(),e.dispatch(\"INVALIDATE_VIEWPORT\"),e.ref.isFullscreen=!0},cleanFullscreenMode=function(e){var t=e.element,r=e.ref,n=r.handleFullscreenUpdate,i=r.focusTrap,o=r.handleEscapeKey;t.removeAttribute(\"tabindex\"),i.destroy(),t.removeEventListener(\"keydown\",o),isIOS()&&t.removeEventListener(\"touchstart\",preventNavSwipe),window.removeEventListener(\"resize\",n),document.body.classList.remove(\"doka--parent\");var a=document.querySelector(\"meta[name=viewport]\");e.ref.defaultViewportContent?(a.setAttribute(\"content\",e.ref.defaultViewportContent),e.ref.defaultViewportContent=null):a.parentNode.removeChild(a),e.ref.isFullscreen=!1},root=createView({name:\"root\",ignoreRect:!0,mixins:{styles:[\"opacity\"],animations:{opacity:{type:\"tween\",duration:350}}},create:function(e){var t=e.root,r=e.props;t.element.id=t.query(\"GET_ID\")||\"doka-\".concat(r.id);var n=t.query(\"GET_CLASS_NAME\");n&&t.element.classList.add(n),t.ref.environment=[],t.ref.shouldBeDestroyed=!1,t.ref.isClosing=!1,t.ref.isClosed=!1,t.ref.isFullscreen=!1,t.query(\"GET_ALLOW_DROP_FILES\")&&(t.ref.catcher=createFileCatcher(t.element),t.ref.catcher.on(\"drop\",function(e){e.forEach(function(e){t.dispatch(\"REQUEST_LOAD_IMAGE\",{source:e})})})),t.ref.touchDetector=createTouchDetector(),t.ref.touchDetector.onOnce(\"touch-detected\",function(){t.ref.environment.push(\"touch\")}),t.ref.editor=t.appendChildView(t.createChildView(editor,{id:r.id})),t.query(\"GET_STYLES\").filter(function(e){return!isEmpty(e.value)}).map(function(e){var r=e.name,n=e.value;t.element.dataset[r]=n}),t.ref.updateViewport=function(){t.dispatch(\"INVALIDATE_VIEWPORT\")},window.addEventListener(\"resize\",t.ref.updateViewport),window.addEventListener(\"scroll\",t.ref.updateViewport),t.ref.isSingleUtil=1===t.query(\"GET_UTILS\").length,t.ref.canBeControlled=t.query(\"GET_ALLOW_BUTTON_CONFIRM\")||t.query(\"GET_ALLOW_BUTTON_CANCEL\"),updateStyleViewport(t);var i=document.createElement(\"div\");i.style.cssText=\"position:fixed;height:100vh;top:0;\",t.ref.measure=i,document.body.appendChild(i),t.ref.handleEscapeKey=function(e){27===e.keyCode&&t.dispatch(\"EDIT_CANCEL\")},t.ref.initialScreenMeasureHeight=null,t.ref.handleFullscreenUpdate=function(){t.element.dataset.styleFullscreen=window.innerHeight===t.ref.initialScreenMeasureHeight},t.ref.clientRect={left:0,top:0},isModal(t)&&(t.ref.handleModalTap=function(e){e.target===t.element&&t.dispatch(\"EDIT_CANCEL\")},t.element.addEventListener(\"pointerdown\",t.ref.handleModalTap))},read:function(e){var t=e.root,r=t.ref.measure;r&&(t.ref.initialScreenMeasureHeight=r.offsetHeight,r.parentNode.removeChild(r),t.ref.measure=null),t.ref.clientRect=t.element.getBoundingClientRect(),t.ref.clientRect.leftScroll=t.ref.clientRect.left+(window.scrollX||window.pageXOffset),t.ref.clientRect.topScroll=t.ref.clientRect.top+(window.scrollY||window.pageYOffset)},write:createRoute({ENTER_FULLSCREEN:function(e){var t=e.root;setupFullscreenMode(t)},EXIT_FULLSCREEN:function(e){var t=e.root;cleanFullscreenMode(t)},SHOW_VIEW:function(e){var t=e.root,r=e.action;t.element.dataset.view=r.id},DID_SET_STYLE_LAYOUT_MODE:function(e){var t=e.root,r=e.action;t.element.dataset.styleLayoutMode=r.value||\"none\",/fullscreen/.test(r.value)&&!/fullscreen/.test(r.prevValue)&&t.dispatch(\"ENTER_FULLSCREEN\")},AWAITING_IMAGE:function(e){var t=e.root;t.ref.catcher&&t.query(\"GET_ALLOW_BROWSE_FILES\")&&t.ref.catcher.enableBrowse()},DID_REQUEST_LOAD_IMAGE:function(e){var t=e.root;if(t.ref.catcher&&t.query(\"GET_ALLOW_BROWSE_FILES\")&&t.ref.catcher.disableBrowse(),0===t.opacity&&(t.opacity=1),t.ref.isClosing=!1,t.ref.isClosed=!1,!shouldBeFullscreen(t)||isFullscreen(t)){var r=t.query(\"GET_STYLE_LAYOUT_MODE\");null!==r&&\"modal\"!==r||t.element.parentNode||t.dispatch(\"SET_STYLE_LAYOUT_MODE\",{value:(\"fullscreen \"+(r||\"\")).trim()})}else t.dispatch(\"ENTER_FULLSCREEN\")},DID_CANCEL:function(e){var t=e.root;canBeAutoClosed(t)&&mayBeAutoClosed(t)&&t.dispatch(\"EDIT_CLOSE\")},DID_CONFIRM:function(e){var t=e.root;canBeAutoClosed(t)&&mayBeAutoClosed(t)&&t.dispatch(\"EDIT_CLOSE\")},EDIT_CLOSE:function(e){var t=e.root;canBeClosed(t)&&(t.opacity=t.opacity||1,t.opacity=0,t.ref.isClosed=!1,t.ref.isClosing=!0,t.query(\"GET_ALLOW_AUTO_DESTROY\")&&(t.ref.shouldBeDestroyed=!0),isFullscreen(t)&&t.dispatch(\"EXIT_FULLSCREEN\"))},DID_SET_UTILS:function(e){var t=e.root;t.ref.isSingleUtil=1===t.query(\"GET_UTILS\").length}},function(e){var t=e.root;updateStyleViewport(t);var r=t.query(\"GET_ROOT\"),n=t.rect.element;r.width===n.width&&r.height===n.height&&r.y===t.ref.clientRect.top&&r.topScroll===t.ref.clientRect.topScroll||t.dispatch(\"UPDATE_ROOT_RECT\",{rect:{x:t.ref.clientRect.left,y:t.ref.clientRect.top,left:t.ref.editor.rect.element.left,top:t.ref.editor.rect.element.top,leftScroll:t.ref.clientRect.leftScroll,topScroll:t.ref.clientRect.topScroll,width:t.rect.element.width,height:t.rect.element.height}})}),didWriteView:function(e){var t=e.root,r=t.ref,n=r.isClosed,i=r.isClosing,o=r.shouldBeDestroyed;!n&&i&&0===t.opacity&&(t.dispatch(\"DID_CLOSE\"),t.ref.isClosed=!0,t.ref.isClosing=!1,shouldBeFullscreen(t)&&t.element.parentNode&&document.body.removeChild(t.element),o&&t.dispatch(\"EDIT_DESTROY\"))},destroy:function(e){var t=e.root;isFullscreen(t)&&cleanFullscreenMode(t),isModal(t)&&t.element.removeEventListener(\"pointerdown\",t.ref.handleModalTap),shouldBeFullscreen(t)&&t.element.parentNode&&document.body.removeChild(t.element),window.removeEventListener(\"resize\",t.ref.updateViewport),t.ref.touchDetector.destroy(),t.ref.catcher&&t.ref.catcher.destroy()}}),getViewportBySize=function(e,t){var r=\"\";return 0===e&&0===t?\"detached\":(r+=t>e?\"portrait\":\"landscape\",(r+=e<=600?\" x-cramped\":e<=1e3?\" x-comfortable\":\" x-spacious\").trim())},createApp=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=getOptions(),r=createStore(createInitialState(t),[queries,createOptionQueries(t)],[actions,createOptionActions(t)]);r.dispatch(\"SET_OPTIONS\",{options:e});var n=function(){document.hidden||r.dispatch(\"KICK\")};document.addEventListener(\"visibilitychange\",n);var i=getUniqueId();r.dispatch(\"SET_UID\",{id:i});var o=null,a=root(r,{id:i}),c=!1,l={_read:function(){c||a._read()},_write:function(e){var t=r.processActionQueue().filter(function(e){return!/^SET_/.test(e.type)});c&&!t.length||(d(t),(c=a._write(e,t))&&r.processDispatchQueue(),t.find(function(e){return\"EDIT_DESTROY\"===e.type})&&p())}},u=function(e){return function(t){var r={type:e};return t?(t.hasOwnProperty(\"error\")&&(r.error=isObject(t.error)?_objectSpread({},t.error):t.error||null),t.hasOwnProperty(\"output\")&&(r.output=t.output),t.hasOwnProperty(\"image\")&&(r.image=t.image),t.hasOwnProperty(\"source\")&&(r.source=t.source),t.hasOwnProperty(\"state\")&&(r.state=t.state),r):r}},s={DID_CONFIRM:u(\"confirm\"),DID_CANCEL:u(\"cancel\"),DID_REQUEST_LOAD_IMAGE:u(\"loadstart\"),DID_LOAD_IMAGE:u(\"load\"),DID_LOAD_IMAGE_ERROR:u(\"loaderror\"),DID_SHOW_IMAGE:u(\"ready\"),DID_UPDATE:u(\"update\"),DID_CLOSE:u(\"close\"),DID_DESTROY:u(\"destroy\"),DID_INIT:u(\"init\")},d=function(e){e.length&&e.forEach(function(e){if(s[e.type]){var t=s[e.type];(Array.isArray(t)?t:[t]).forEach(function(t){setTimeout(function(){!function(e){var t=_objectSpread({doka:f},e);delete t.type,a&&a.element.dispatchEvent(new CustomEvent(\"Doka:\".concat(e.type),{detail:t,bubbles:!0,cancelable:!0,composed:!0}));var n=[];e.hasOwnProperty(\"error\")&&n.push(e.error);var i=[\"type\",\"error\"];Object.keys(e).filter(function(e){return!i.includes(e)}).forEach(function(t){return n.push(e[t])}),f.fire.apply(f,[e.type].concat(n));var o=r.query(\"GET_ON\".concat(e.type.toUpperCase()));o&&o.apply(void 0,n)}(t(e.data))},0)})}})},p=function(){f.fire(\"destroy\",a.element),document.removeEventListener(\"visibilitychange\",n),a._destroy(),r.dispatch(\"DID_DESTROY\")},f=_objectSpread({},on(),l,createOptionAPI(r,t),{setOptions:function(e){return r.dispatch(\"SET_OPTIONS\",{options:e})},setData:function(e){r.dispatch(\"SET_DATA\",e)},getData:function(e){return new Promise(function(t,n){r.dispatch(\"GET_DATA\",_objectSpread({},e,{success:t,failure:n}))})},open:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(function(n,i){e&&r.dispatch(\"REQUEST_LOAD_IMAGE\",{source:e,options:t,success:n,failure:i,resolveOnConfirm:!!t&&t.resolveOnConfirm})})},edit:function(e,t){return f.open(e,_objectSpread({},t,{resolveOnConfirm:!0}))},save:function(e){return new Promise(function(t,n){r.dispatch(\"GET_DATA\",_objectSpread({},e,{success:t,failure:n}))})},clear:function(){return r.dispatch(\"REQUEST_REMOVE_IMAGE\")},close:function(){return r.dispatch(\"EDIT_CLOSE\")},interact:function(e,t){\"scale\"===e&&r.dispatch(\"CROP_IMAGE_RESIZE_SET\",{value:t})},interactEnd:function(e){\"scale\"===e&&r.dispatch(\"CROP_IMAGE_RESIZE_RELEASE\")},destroy:p,insertBefore:function(e){insertBefore(a.element,e)},insertAfter:function(e){insertAfter(a.element,e)},appendTo:function(e){e.appendChild(a.element)},replaceElement:function(e){insertBefore(a.element,e),e.parentNode.removeChild(e),o=e},restoreElement:function(){o&&(insertAfter(o,a.element),a.element.parentNode.removeChild(a.element),o=null)},isAttachedTo:function(e){return!!a&&(a.element===e||o===e)},element:{get:function(){return a?a.element:null}}});return r.dispatch(\"DID_INIT\"),createObject(f)},createAppObject=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=getOptions(),r={};return forin(t,function(e,t){isString(t)||(r[e]=t[0])}),createApp(_objectSpread({},r,e))},toCamels=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:\"-\";return e.replace(new RegExp(\"\".concat(t,\".\"),\"g\"),function(e){return e.charAt(1).toUpperCase()})},lowerCaseFirstLetter=function(e){return e.charAt(0).toLowerCase()+e.slice(1)},attributeNameToPropertyName=function(e){return toCamels(e.replace(/^data-/,\"\"))},mapObject=function e(t,r){forin(r,function(r,n){forin(t,function(e,i){var o=new RegExp(r);if(o.test(e)&&(delete t[e],!1!==n))if(isString(n))t[n]=i;else{var a=n.group;isObject(n)&&!t[a]&&(t[a]={}),t[a][lowerCaseFirstLetter(e.replace(o,\"\"))]=i}}),n.mapping&&e(t[n.group],n.mapping)})},getAttributesAsObject=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=[];forin(e.attributes,function(t){return r.push(e.attributes[t])});var n=r.filter(function(e){return e.name}).reduce(function(t,r){var n=attr(e,r.name);return t[attributeNameToPropertyName(r.name)]=n===r.name||n,t},{});return mapObject(n,t),n},createAppAtElement=function(e){var t=_objectSpread({},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),r=getAttributesAsObject(e,{\"^class$\":\"className\"});Object.keys(r).forEach(function(e){isObject(r[e])?(isObject(t[e])||(t[e]={}),Object.assign(t[e],r[e])):t[e]=r[e]}),\"CANVAS\"!==e.nodeName&&\"IMG\"!==e.nodeName||(t.src=e.dataset.dokaSrc?e.dataset.dokaSrc:e);var n=createAppObject(t);return n.replaceElement(e),n},createApp$1=function(){for(var e=arguments.length,t=new Array(e),r=0;r=0&&(state.apps.splice(t,1)[0].restoreElement(),!0)},parse=function(e){return Array.from(e.querySelectorAll(\".\".concat(name))).filter(function(e){return!state.apps.find(function(t){return t.isAttachedTo(e)})}).map(function(e){return create$1(e)})},find=function(e){var t=state.apps.find(function(t){return t.isAttachedTo(e)});return t?createAppAPI(t):null},getOptions$1=function(){var e={};return forin(getOptions(),function(t,r){e[t]=r[0]}),e},setOptions$1=function(e){return isObject(e)&&(state.apps.forEach(function(t){t.setOptions(e)}),setOptions(e)),getOptions$1()}}export{supported,OptionTypes,create$1 as create,destroy,parse,find,getOptions$1 as getOptions,setOptions$1 as setOptions};\n","\n \n \n \n
\n\n\n\n\n\n","import mod from \"-!../../node_modules/cache-loader/dist/cjs.js??ref--13-0!../../node_modules/thread-loader/dist/cjs.js!../../node_modules/babel-loader/lib/index.js!../../node_modules/cache-loader/dist/cjs.js??ref--1-0!../../node_modules/vue-loader/lib/index.js??vue-loader-options!./FileUpload.vue?vue&type=script&lang=js&\"; export default mod; export * from \"-!../../node_modules/cache-loader/dist/cjs.js??ref--13-0!../../node_modules/thread-loader/dist/cjs.js!../../node_modules/babel-loader/lib/index.js!../../node_modules/cache-loader/dist/cjs.js??ref--1-0!../../node_modules/vue-loader/lib/index.js??vue-loader-options!./FileUpload.vue?vue&type=script&lang=js&\"","import { render, staticRenderFns } from \"./FileUpload.vue?vue&type=template&id=29a6226e&scoped=true&\"\nimport script from \"./FileUpload.vue?vue&type=script&lang=js&\"\nexport * from \"./FileUpload.vue?vue&type=script&lang=js&\"\nimport style0 from \"./FileUpload.vue?vue&type=style&index=0&id=29a6226e&prod&lang=scss&scoped=true&\"\n\n\n/* normalize component */\nimport normalizer from \"!../../node_modules/vue-loader/lib/runtime/componentNormalizer.js\"\nvar component = normalizer(\n script,\n render,\n staticRenderFns,\n false,\n null,\n \"29a6226e\",\n null\n \n)\n\nexport default component.exports","var $ = require('../internals/export');\nvar log10 = require('../internals/math-log10');\n\n// `Math.log10` method\n// https://tc39.es/ecma262/#sec-math.log10\n$({ target: 'Math', stat: true }, {\n log10: log10\n});\n","var $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names-external').f;\n\n// eslint-disable-next-line es/no-object-getownpropertynames -- required for testing\nvar FAILS_ON_PRIMITIVES = fails(function () { return !Object.getOwnPropertyNames(1); });\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.es/ecma262/#sec-object.getownpropertynames\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {\n getOwnPropertyNames: getOwnPropertyNames\n});\n","'use strict';\nvar exportTypedArrayMethod = require('../internals/array-buffer-view-core').exportTypedArrayMethod;\nvar fails = require('../internals/fails');\nvar global = require('../internals/global');\nvar uncurryThis = require('../internals/function-uncurry-this');\n\nvar Uint8Array = global.Uint8Array;\nvar Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype || {};\nvar arrayToString = [].toString;\nvar join = uncurryThis([].join);\n\nif (fails(function () { arrayToString.call({}); })) {\n arrayToString = function toString() {\n return join(this);\n };\n}\n\nvar IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString;\n\n// `%TypedArray%.prototype.toString` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring\nexportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $fill = require('../internals/array-fill');\nvar toBigInt = require('../internals/to-big-int');\nvar classof = require('../internals/classof');\nvar call = require('../internals/function-call');\nvar uncurryThis = require('../internals/function-uncurry-this');\nvar fails = require('../internals/fails');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar slice = uncurryThis(''.slice);\n\n// V8 ~ Chrome < 59, Safari < 14.1, FF < 55, Edge <=18\nvar CONVERSION_BUG = fails(function () {\n var count = 0;\n // eslint-disable-next-line es/no-typed-arrays -- safe\n new Int8Array(2).fill({ valueOf: function () { return count++; } });\n return count !== 1;\n});\n\n// `%TypedArray%.prototype.fill` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill\nexportTypedArrayMethod('fill', function fill(value /* , start, end */) {\n var length = arguments.length;\n aTypedArray(this);\n var actualValue = slice(classof(this), 0, 3) === 'Big' ? toBigInt(value) : +value;\n return call($fill, this, actualValue, length > 1 ? arguments[1] : undefined, length > 2 ? arguments[2] : undefined);\n}, CONVERSION_BUG);\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar call = require('../internals/function-call');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-array-constructors-require-wrappers');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar ArrayBufferModule = require('../internals/array-buffer');\nvar anInstance = require('../internals/an-instance');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar isIntegralNumber = require('../internals/is-integral-number');\nvar toLength = require('../internals/to-length');\nvar toIndex = require('../internals/to-index');\nvar toOffset = require('../internals/to-offset');\nvar toPropertyKey = require('../internals/to-property-key');\nvar hasOwn = require('../internals/has-own-property');\nvar classof = require('../internals/classof');\nvar isObject = require('../internals/is-object');\nvar isSymbol = require('../internals/is-symbol');\nvar create = require('../internals/object-create');\nvar isPrototypeOf = require('../internals/object-is-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names').f;\nvar typedArrayFrom = require('../internals/typed-array-from');\nvar forEach = require('../internals/array-iteration').forEach;\nvar setSpecies = require('../internals/set-species');\nvar definePropertyModule = require('../internals/object-define-property');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar InternalStateModule = require('../internals/internal-state');\nvar inheritIfRequired = require('../internals/inherit-if-required');\n\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar enforceInternalState = InternalStateModule.enforce;\nvar nativeDefineProperty = definePropertyModule.f;\nvar nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\nvar round = Math.round;\nvar RangeError = global.RangeError;\nvar ArrayBuffer = ArrayBufferModule.ArrayBuffer;\nvar ArrayBufferPrototype = ArrayBuffer.prototype;\nvar DataView = ArrayBufferModule.DataView;\nvar NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;\nvar TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG;\nvar TypedArray = ArrayBufferViewCore.TypedArray;\nvar TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype;\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar isTypedArray = ArrayBufferViewCore.isTypedArray;\nvar BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';\nvar WRONG_LENGTH = 'Wrong length';\n\nvar fromList = function (C, list) {\n aTypedArrayConstructor(C);\n var index = 0;\n var length = list.length;\n var result = new C(length);\n while (length > index) result[index] = list[index++];\n return result;\n};\n\nvar addGetter = function (it, key) {\n nativeDefineProperty(it, key, { get: function () {\n return getInternalState(this)[key];\n } });\n};\n\nvar isArrayBuffer = function (it) {\n var klass;\n return isPrototypeOf(ArrayBufferPrototype, it) || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';\n};\n\nvar isTypedArrayIndex = function (target, key) {\n return isTypedArray(target)\n && !isSymbol(key)\n && key in target\n && isIntegralNumber(+key)\n && key >= 0;\n};\n\nvar wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {\n key = toPropertyKey(key);\n return isTypedArrayIndex(target, key)\n ? createPropertyDescriptor(2, target[key])\n : nativeGetOwnPropertyDescriptor(target, key);\n};\n\nvar wrappedDefineProperty = function defineProperty(target, key, descriptor) {\n key = toPropertyKey(key);\n if (isTypedArrayIndex(target, key)\n && isObject(descriptor)\n && hasOwn(descriptor, 'value')\n && !hasOwn(descriptor, 'get')\n && !hasOwn(descriptor, 'set')\n // TODO: add validation descriptor w/o calling accessors\n && !descriptor.configurable\n && (!hasOwn(descriptor, 'writable') || descriptor.writable)\n && (!hasOwn(descriptor, 'enumerable') || descriptor.enumerable)\n ) {\n target[key] = descriptor.value;\n return target;\n } return nativeDefineProperty(target, key, descriptor);\n};\n\nif (DESCRIPTORS) {\n if (!NATIVE_ARRAY_BUFFER_VIEWS) {\n getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;\n definePropertyModule.f = wrappedDefineProperty;\n addGetter(TypedArrayPrototype, 'buffer');\n addGetter(TypedArrayPrototype, 'byteOffset');\n addGetter(TypedArrayPrototype, 'byteLength');\n addGetter(TypedArrayPrototype, 'length');\n }\n\n $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {\n getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,\n defineProperty: wrappedDefineProperty\n });\n\n module.exports = function (TYPE, wrapper, CLAMPED) {\n var BYTES = TYPE.match(/\\d+$/)[0] / 8;\n var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';\n var GETTER = 'get' + TYPE;\n var SETTER = 'set' + TYPE;\n var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME];\n var TypedArrayConstructor = NativeTypedArrayConstructor;\n var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;\n var exported = {};\n\n var getter = function (that, index) {\n var data = getInternalState(that);\n return data.view[GETTER](index * BYTES + data.byteOffset, true);\n };\n\n var setter = function (that, index, value) {\n var data = getInternalState(that);\n if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;\n data.view[SETTER](index * BYTES + data.byteOffset, value, true);\n };\n\n var addElement = function (that, index) {\n nativeDefineProperty(that, index, {\n get: function () {\n return getter(this, index);\n },\n set: function (value) {\n return setter(this, index, value);\n },\n enumerable: true\n });\n };\n\n if (!NATIVE_ARRAY_BUFFER_VIEWS) {\n TypedArrayConstructor = wrapper(function (that, data, offset, $length) {\n anInstance(that, TypedArrayConstructorPrototype);\n var index = 0;\n var byteOffset = 0;\n var buffer, byteLength, length;\n if (!isObject(data)) {\n length = toIndex(data);\n byteLength = length * BYTES;\n buffer = new ArrayBuffer(byteLength);\n } else if (isArrayBuffer(data)) {\n buffer = data;\n byteOffset = toOffset(offset, BYTES);\n var $len = data.byteLength;\n if ($length === undefined) {\n if ($len % BYTES) throw RangeError(WRONG_LENGTH);\n byteLength = $len - byteOffset;\n if (byteLength < 0) throw RangeError(WRONG_LENGTH);\n } else {\n byteLength = toLength($length) * BYTES;\n if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);\n }\n length = byteLength / BYTES;\n } else if (isTypedArray(data)) {\n return fromList(TypedArrayConstructor, data);\n } else {\n return call(typedArrayFrom, TypedArrayConstructor, data);\n }\n setInternalState(that, {\n buffer: buffer,\n byteOffset: byteOffset,\n byteLength: byteLength,\n length: length,\n view: new DataView(buffer)\n });\n while (index < length) addElement(that, index++);\n });\n\n if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);\n TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype);\n } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {\n TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {\n anInstance(dummy, TypedArrayConstructorPrototype);\n return inheritIfRequired(function () {\n if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data));\n if (isArrayBuffer(data)) return $length !== undefined\n ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length)\n : typedArrayOffset !== undefined\n ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES))\n : new NativeTypedArrayConstructor(data);\n if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);\n return call(typedArrayFrom, TypedArrayConstructor, data);\n }(), dummy, TypedArrayConstructor);\n });\n\n if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);\n forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {\n if (!(key in TypedArrayConstructor)) {\n createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);\n }\n });\n TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;\n }\n\n if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);\n }\n\n enforceInternalState(TypedArrayConstructorPrototype).TypedArrayConstructor = TypedArrayConstructor;\n\n if (TYPED_ARRAY_TAG) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);\n }\n\n var FORCED = TypedArrayConstructor != NativeTypedArrayConstructor;\n\n exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;\n\n $({ global: true, constructor: true, forced: FORCED, sham: !NATIVE_ARRAY_BUFFER_VIEWS }, exported);\n\n if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {\n createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);\n }\n\n if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);\n }\n\n setSpecies(CONSTRUCTOR_NAME);\n };\n} else module.exports = function () { /* empty */ };\n","// IEEE754 conversions based on https://github.com/feross/ieee754\nvar $Array = Array;\nvar abs = Math.abs;\nvar pow = Math.pow;\nvar floor = Math.floor;\nvar log = Math.log;\nvar LN2 = Math.LN2;\n\nvar pack = function (number, mantissaLength, bytes) {\n var buffer = $Array(bytes);\n var exponentLength = bytes * 8 - mantissaLength - 1;\n var eMax = (1 << exponentLength) - 1;\n var eBias = eMax >> 1;\n var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;\n var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;\n var index = 0;\n var exponent, mantissa, c;\n number = abs(number);\n // eslint-disable-next-line no-self-compare -- NaN check\n if (number != number || number === Infinity) {\n // eslint-disable-next-line no-self-compare -- NaN check\n mantissa = number != number ? 1 : 0;\n exponent = eMax;\n } else {\n exponent = floor(log(number) / LN2);\n c = pow(2, -exponent);\n if (number * c < 1) {\n exponent--;\n c *= 2;\n }\n if (exponent + eBias >= 1) {\n number += rt / c;\n } else {\n number += rt * pow(2, 1 - eBias);\n }\n if (number * c >= 2) {\n exponent++;\n c /= 2;\n }\n if (exponent + eBias >= eMax) {\n mantissa = 0;\n exponent = eMax;\n } else if (exponent + eBias >= 1) {\n mantissa = (number * c - 1) * pow(2, mantissaLength);\n exponent = exponent + eBias;\n } else {\n mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);\n exponent = 0;\n }\n }\n while (mantissaLength >= 8) {\n buffer[index++] = mantissa & 255;\n mantissa /= 256;\n mantissaLength -= 8;\n }\n exponent = exponent << mantissaLength | mantissa;\n exponentLength += mantissaLength;\n while (exponentLength > 0) {\n buffer[index++] = exponent & 255;\n exponent /= 256;\n exponentLength -= 8;\n }\n buffer[--index] |= sign * 128;\n return buffer;\n};\n\nvar unpack = function (buffer, mantissaLength) {\n var bytes = buffer.length;\n var exponentLength = bytes * 8 - mantissaLength - 1;\n var eMax = (1 << exponentLength) - 1;\n var eBias = eMax >> 1;\n var nBits = exponentLength - 7;\n var index = bytes - 1;\n var sign = buffer[index--];\n var exponent = sign & 127;\n var mantissa;\n sign >>= 7;\n while (nBits > 0) {\n exponent = exponent * 256 + buffer[index--];\n nBits -= 8;\n }\n mantissa = exponent & (1 << -nBits) - 1;\n exponent >>= -nBits;\n nBits += mantissaLength;\n while (nBits > 0) {\n mantissa = mantissa * 256 + buffer[index--];\n nBits -= 8;\n }\n if (exponent === 0) {\n exponent = 1 - eBias;\n } else if (exponent === eMax) {\n return mantissa ? NaN : sign ? -Infinity : Infinity;\n } else {\n mantissa = mantissa + pow(2, mantissaLength);\n exponent = exponent - eBias;\n } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);\n};\n\nmodule.exports = {\n pack: pack,\n unpack: unpack\n};\n","var IS_NODE = require('../internals/engine-is-node');\n\nmodule.exports = function (name) {\n try {\n // eslint-disable-next-line no-new-func -- safe\n if (IS_NODE) return Function('return require(\"' + name + '\")')();\n } catch (error) { /* empty */ }\n};\n","var $ = require('../internals/export');\nvar getBuiltIn = require('../internals/get-built-in');\nvar uncurryThis = require('../internals/function-uncurry-this');\nvar fails = require('../internals/fails');\nvar toString = require('../internals/to-string');\nvar hasOwn = require('../internals/has-own-property');\nvar validateArgumentsLength = require('../internals/validate-arguments-length');\nvar ctoi = require('../internals/base64-map').ctoi;\n\nvar disallowed = /[^\\d+/a-z]/i;\nvar whitespaces = /[\\t\\n\\f\\r ]+/g;\nvar finalEq = /[=]+$/;\n\nvar $atob = getBuiltIn('atob');\nvar fromCharCode = String.fromCharCode;\nvar charAt = uncurryThis(''.charAt);\nvar replace = uncurryThis(''.replace);\nvar exec = uncurryThis(disallowed.exec);\n\nvar NO_SPACES_IGNORE = fails(function () {\n return $atob(' ') !== '';\n});\n\nvar NO_ENCODING_CHECK = !fails(function () {\n $atob('a');\n});\n\nvar NO_ARG_RECEIVING_CHECK = !NO_SPACES_IGNORE && !NO_ENCODING_CHECK && !fails(function () {\n $atob();\n});\n\nvar WRONG_ARITY = !NO_SPACES_IGNORE && !NO_ENCODING_CHECK && $atob.length !== 1;\n\n// `atob` method\n// https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob\n$({ global: true, enumerable: true, forced: NO_SPACES_IGNORE || NO_ENCODING_CHECK || NO_ARG_RECEIVING_CHECK || WRONG_ARITY }, {\n atob: function atob(data) {\n validateArgumentsLength(arguments.length, 1);\n if (NO_ARG_RECEIVING_CHECK || WRONG_ARITY) return $atob(data);\n var string = replace(toString(data), whitespaces, '');\n var output = '';\n var position = 0;\n var bc = 0;\n var chr, bs;\n if (string.length % 4 == 0) {\n string = replace(string, finalEq, '');\n }\n if (string.length % 4 == 1 || exec(disallowed, string)) {\n throw new (getBuiltIn('DOMException'))('The string is not correctly encoded', 'InvalidCharacterError');\n }\n while (chr = charAt(string, position++)) {\n if (hasOwn(ctoi, chr)) {\n bs = bc % 4 ? bs * 64 + ctoi[chr] : ctoi[chr];\n if (bc++ % 4) output += fromCharCode(255 & bs >> (-2 * bc & 6));\n }\n } return output;\n }\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $includes = require('../internals/array-includes').includes;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.includes` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes\nexportTypedArrayMethod('includes', function includes(searchElement /* , fromIndex */) {\n return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n});\n","var log = Math.log;\nvar LOG10E = Math.LOG10E;\n\n// eslint-disable-next-line es/no-math-log10 -- safe\nmodule.exports = Math.log10 || function log10(x) {\n return log(x) * LOG10E;\n};\n","var createTypedArrayConstructor = require('../internals/typed-array-constructor');\n\n// `Uint8ClampedArray` constructor\n// https://tc39.es/ecma262/#sec-typedarray-objects\ncreateTypedArrayConstructor('Uint8', function (init) {\n return function Uint8ClampedArray(data, byteOffset, length) {\n return init(this, data, byteOffset, length);\n };\n}, true);\n","/* eslint-disable no-new -- required for testing */\nvar global = require('../internals/global');\nvar fails = require('../internals/fails');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar NATIVE_ARRAY_BUFFER_VIEWS = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS;\n\nvar ArrayBuffer = global.ArrayBuffer;\nvar Int8Array = global.Int8Array;\n\nmodule.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {\n Int8Array(1);\n}) || !fails(function () {\n new Int8Array(-1);\n}) || !checkCorrectnessOfIteration(function (iterable) {\n new Int8Array();\n new Int8Array(null);\n new Int8Array(1.5);\n new Int8Array(iterable);\n}, true) || fails(function () {\n // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill\n return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1;\n});\n","var getBuiltIn = require('../internals/get-built-in');\nvar setToStringTag = require('../internals/set-to-string-tag');\n\nvar DOM_EXCEPTION = 'DOMException';\n\nsetToStringTag(getBuiltIn(DOM_EXCEPTION), DOM_EXCEPTION);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar lengthOfArrayLike = require('../internals/length-of-array-like');\nvar toIntegerOrInfinity = require('../internals/to-integer-or-infinity');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.at` method\n// https://github.com/tc39/proposal-relative-indexing-method\nexportTypedArrayMethod('at', function at(index) {\n var O = aTypedArray(this);\n var len = lengthOfArrayLike(O);\n var relativeIndex = toIntegerOrInfinity(index);\n var k = relativeIndex >= 0 ? relativeIndex : len + relativeIndex;\n return (k < 0 || k >= len) ? undefined : O[k];\n});\n","/*!\n * FilePondPluginImageCrop 2.0.6\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? (module.exports = factory())\n : typeof define === 'function' && define.amd\n ? define(factory)\n : ((global = global || self), (global.FilePondPluginImageCrop = factory()));\n})(this, function() {\n 'use strict';\n\n var isImage = function isImage(file) {\n return /^image/.test(file.type);\n };\n\n /**\n * Image Auto Crop Plugin\n */\n var plugin = function plugin(_ref) {\n var addFilter = _ref.addFilter,\n utils = _ref.utils;\n var Type = utils.Type,\n isFile = utils.isFile,\n getNumericAspectRatioFromString = utils.getNumericAspectRatioFromString;\n\n // tests if crop is allowed on this item\n var allowCrop = function allowCrop(item, query) {\n return !(!isImage(item.file) || !query('GET_ALLOW_IMAGE_CROP'));\n };\n\n var isObject = function isObject(value) {\n return typeof value === 'object';\n };\n\n var isNumber = function isNumber(value) {\n return typeof value === 'number';\n };\n\n var updateCrop = function updateCrop(item, obj) {\n return item.setMetadata(\n 'crop',\n Object.assign({}, item.getMetadata('crop'), obj)\n );\n };\n\n // extend item methods\n addFilter('DID_CREATE_ITEM', function(item, _ref2) {\n var query = _ref2.query;\n\n item.extend('setImageCrop', function(crop) {\n if (!allowCrop(item, query) || !isObject(center)) return;\n item.setMetadata('crop', crop);\n return crop;\n });\n\n item.extend('setImageCropCenter', function(center) {\n if (!allowCrop(item, query) || !isObject(center)) return;\n return updateCrop(item, { center: center });\n });\n\n item.extend('setImageCropZoom', function(zoom) {\n if (!allowCrop(item, query) || !isNumber(zoom)) return;\n return updateCrop(item, { zoom: Math.max(1, zoom) });\n });\n\n item.extend('setImageCropRotation', function(rotation) {\n if (!allowCrop(item, query) || !isNumber(rotation)) return;\n return updateCrop(item, { rotation: rotation });\n });\n\n item.extend('setImageCropFlip', function(flip) {\n if (!allowCrop(item, query) || !isObject(flip)) return;\n return updateCrop(item, { flip: flip });\n });\n\n item.extend('setImageCropAspectRatio', function(newAspectRatio) {\n if (!allowCrop(item, query) || typeof newAspectRatio === 'undefined')\n return;\n\n var currentCrop = item.getMetadata('crop');\n\n var aspectRatio = getNumericAspectRatioFromString(newAspectRatio);\n\n var newCrop = {\n center: {\n x: 0.5,\n y: 0.5\n },\n\n flip: currentCrop\n ? Object.assign({}, currentCrop.flip)\n : {\n horizontal: false,\n vertical: false\n },\n\n rotation: 0,\n zoom: 1,\n aspectRatio: aspectRatio\n };\n\n item.setMetadata('crop', newCrop);\n\n return newCrop;\n });\n });\n\n // subscribe to file transformations\n addFilter('DID_LOAD_ITEM', function(item, _ref3) {\n var query = _ref3.query;\n return new Promise(function(resolve, reject) {\n // get file reference\n var file = item.file;\n\n // if this is not an image we do not have any business cropping it and we'll continue with the unaltered dataset\n if (!isFile(file) || !isImage(file) || !query('GET_ALLOW_IMAGE_CROP')) {\n return resolve(item);\n }\n\n // already has crop metadata set?\n var crop = item.getMetadata('crop');\n if (crop) {\n return resolve(item);\n }\n\n // get the required aspect ratio and exit if it's not set\n var humanAspectRatio = query('GET_IMAGE_CROP_ASPECT_RATIO');\n\n // set default crop rectangle\n item.setMetadata('crop', {\n center: {\n x: 0.5,\n y: 0.5\n },\n\n flip: {\n horizontal: false,\n vertical: false\n },\n\n rotation: 0,\n zoom: 1,\n aspectRatio: humanAspectRatio\n ? getNumericAspectRatioFromString(humanAspectRatio)\n : null\n });\n\n // we done!\n resolve(item);\n });\n });\n\n // Expose plugin options\n return {\n options: {\n // enable or disable image cropping\n allowImageCrop: [true, Type.BOOLEAN],\n\n // the aspect ratio of the crop ('1:1', '16:9', etc)\n imageCropAspectRatio: [null, Type.STRING]\n }\n };\n };\n\n // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags\n var isBrowser =\n typeof window !== 'undefined' && typeof window.document !== 'undefined';\n if (isBrowser) {\n document.dispatchEvent(\n new CustomEvent('FilePond:pluginloaded', { detail: plugin })\n );\n }\n\n return plugin;\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $findLast = require('../internals/array-iteration-from-last').findLast;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.findLast` method\n// https://github.com/tc39/proposal-array-find-from-last\nexportTypedArrayMethod('findLast', function findLast(predicate /* , thisArg */) {\n return $findLast(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar uncurryThis = require('../internals/function-uncurry-this');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $ArrayCopyWithin = require('../internals/array-copy-within');\n\nvar u$ArrayCopyWithin = uncurryThis($ArrayCopyWithin);\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.copyWithin` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin\nexportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end */) {\n return u$ArrayCopyWithin(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined);\n});\n","/*!\n * FilePondPluginImageTransform 3.8.7\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? (module.exports = factory())\n : typeof define === 'function' && define.amd\n ? define(factory)\n : ((global = global || self), (global.FilePondPluginImageTransform = factory()));\n})(this, function() {\n 'use strict';\n\n // test if file is of type image\n var isImage = function isImage(file) {\n return /^image/.test(file.type);\n };\n\n var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) {\n return name.substr(0, name.lastIndexOf('.')) || name;\n };\n\n // only handles image/jpg, image/jpeg, image/png, and image/svg+xml for now\n var ExtensionMap = {\n jpeg: 'jpg',\n 'svg+xml': 'svg',\n };\n\n var renameFileToMatchMimeType = function renameFileToMatchMimeType(filename, mimeType) {\n var name = getFilenameWithoutExtension(filename);\n var type = mimeType.split('/')[1];\n var extension = ExtensionMap[type] || type;\n return ''.concat(name, '.').concat(extension);\n };\n\n // returns all the valid output formats we can encode towards\n var getValidOutputMimeType = function getValidOutputMimeType(type) {\n return /jpeg|png|svg\\+xml/.test(type) ? type : 'image/jpeg';\n };\n\n // test if file is of type image\n var isImage$1 = function isImage(file) {\n return /^image/.test(file.type);\n };\n\n var MATRICES = {\n 1: function _() {\n return [1, 0, 0, 1, 0, 0];\n },\n 2: function _(width) {\n return [-1, 0, 0, 1, width, 0];\n },\n 3: function _(width, height) {\n return [-1, 0, 0, -1, width, height];\n },\n 4: function _(width, height) {\n return [1, 0, 0, -1, 0, height];\n },\n 5: function _() {\n return [0, 1, 1, 0, 0, 0];\n },\n 6: function _(width, height) {\n return [0, 1, -1, 0, height, 0];\n },\n 7: function _(width, height) {\n return [0, -1, -1, 0, height, width];\n },\n 8: function _(width) {\n return [0, -1, 1, 0, 0, width];\n },\n };\n\n var getImageOrientationMatrix = function getImageOrientationMatrix(width, height, orientation) {\n if (orientation === -1) {\n orientation = 1;\n }\n return MATRICES[orientation](width, height);\n };\n\n var createVector = function createVector(x, y) {\n return { x: x, y: y };\n };\n\n var vectorDot = function vectorDot(a, b) {\n return a.x * b.x + a.y * b.y;\n };\n\n var vectorSubtract = function vectorSubtract(a, b) {\n return createVector(a.x - b.x, a.y - b.y);\n };\n\n var vectorDistanceSquared = function vectorDistanceSquared(a, b) {\n return vectorDot(vectorSubtract(a, b), vectorSubtract(a, b));\n };\n\n var vectorDistance = function vectorDistance(a, b) {\n return Math.sqrt(vectorDistanceSquared(a, b));\n };\n\n var getOffsetPointOnEdge = function getOffsetPointOnEdge(length, rotation) {\n var a = length;\n\n var A = 1.5707963267948966;\n var B = rotation;\n var C = 1.5707963267948966 - rotation;\n\n var sinA = Math.sin(A);\n var sinB = Math.sin(B);\n var sinC = Math.sin(C);\n var cosC = Math.cos(C);\n var ratio = a / sinA;\n var b = ratio * sinB;\n var c = ratio * sinC;\n\n return createVector(cosC * b, cosC * c);\n };\n\n var getRotatedRectSize = function getRotatedRectSize(rect, rotation) {\n var w = rect.width;\n var h = rect.height;\n\n var hor = getOffsetPointOnEdge(w, rotation);\n var ver = getOffsetPointOnEdge(h, rotation);\n\n var tl = createVector(rect.x + Math.abs(hor.x), rect.y - Math.abs(hor.y));\n\n var tr = createVector(rect.x + rect.width + Math.abs(ver.y), rect.y + Math.abs(ver.x));\n\n var bl = createVector(rect.x - Math.abs(ver.y), rect.y + rect.height - Math.abs(ver.x));\n\n return {\n width: vectorDistance(tl, tr),\n height: vectorDistance(tl, bl),\n };\n };\n\n var getImageRectZoomFactor = function getImageRectZoomFactor(imageRect, cropRect) {\n var rotation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var center =\n arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { x: 0.5, y: 0.5 };\n\n // calculate available space round image center position\n var cx = center.x > 0.5 ? 1 - center.x : center.x;\n var cy = center.y > 0.5 ? 1 - center.y : center.y;\n var imageWidth = cx * 2 * imageRect.width;\n var imageHeight = cy * 2 * imageRect.height;\n\n // calculate rotated crop rectangle size\n var rotatedCropSize = getRotatedRectSize(cropRect, rotation);\n\n return Math.max(rotatedCropSize.width / imageWidth, rotatedCropSize.height / imageHeight);\n };\n\n var getCenteredCropRect = function getCenteredCropRect(container, aspectRatio) {\n var width = container.width;\n var height = width * aspectRatio;\n if (height > container.height) {\n height = container.height;\n width = height / aspectRatio;\n }\n var x = (container.width - width) * 0.5;\n var y = (container.height - height) * 0.5;\n\n return {\n x: x,\n y: y,\n width: width,\n height: height,\n };\n };\n\n var calculateCanvasSize = function calculateCanvasSize(image, canvasAspectRatio) {\n var zoom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n var imageAspectRatio = image.height / image.width;\n\n // determine actual pixels on x and y axis\n var canvasWidth = 1;\n var canvasHeight = canvasAspectRatio;\n var imgWidth = 1;\n var imgHeight = imageAspectRatio;\n if (imgHeight > canvasHeight) {\n imgHeight = canvasHeight;\n imgWidth = imgHeight / imageAspectRatio;\n }\n\n var scalar = Math.max(canvasWidth / imgWidth, canvasHeight / imgHeight);\n var width = image.width / (zoom * scalar * imgWidth);\n var height = width * canvasAspectRatio;\n\n return {\n width: width,\n height: height,\n };\n };\n\n var canvasRelease = function canvasRelease(canvas) {\n canvas.width = 1;\n canvas.height = 1;\n var ctx = canvas.getContext('2d');\n ctx.clearRect(0, 0, 1, 1);\n };\n\n var isFlipped = function isFlipped(flip) {\n return flip && (flip.horizontal || flip.vertical);\n };\n\n var getBitmap = function getBitmap(image, orientation, flip) {\n if (orientation <= 1 && !isFlipped(flip)) {\n image.width = image.naturalWidth;\n image.height = image.naturalHeight;\n return image;\n }\n\n var canvas = document.createElement('canvas');\n var width = image.naturalWidth;\n var height = image.naturalHeight;\n\n // if is rotated incorrectly swap width and height\n var swapped = orientation >= 5 && orientation <= 8;\n if (swapped) {\n canvas.width = height;\n canvas.height = width;\n } else {\n canvas.width = width;\n canvas.height = height;\n }\n\n // draw the image but first fix orientation and set correct flip\n var ctx = canvas.getContext('2d');\n\n // get base transformation matrix\n if (orientation) {\n ctx.transform.apply(ctx, getImageOrientationMatrix(width, height, orientation));\n }\n\n if (isFlipped(flip)) {\n // flip horizontal\n // [-1, 0, 0, 1, width, 0]\n var matrix = [1, 0, 0, 1, 0, 0];\n if ((!swapped && flip.horizontal) || swapped & flip.vertical) {\n matrix[0] = -1;\n matrix[4] = width;\n }\n\n // flip vertical\n // [1, 0, 0, -1, 0, height]\n if ((!swapped && flip.vertical) || (swapped && flip.horizontal)) {\n matrix[3] = -1;\n matrix[5] = height;\n }\n\n ctx.transform.apply(ctx, matrix);\n }\n\n ctx.drawImage(image, 0, 0, width, height);\n\n return canvas;\n };\n\n var imageToImageData = function imageToImageData(imageElement, orientation) {\n var crop = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var canvasMemoryLimit = options.canvasMemoryLimit,\n _options$background = options.background,\n background = _options$background === void 0 ? null : _options$background;\n\n var zoom = crop.zoom || 1;\n\n // fixes possible image orientation problems by drawing the image on the correct canvas\n var bitmap = getBitmap(imageElement, orientation, crop.flip);\n var imageSize = {\n width: bitmap.width,\n height: bitmap.height,\n };\n\n var aspectRatio = crop.aspectRatio || imageSize.height / imageSize.width;\n\n var canvasSize = calculateCanvasSize(imageSize, aspectRatio, zoom);\n\n if (canvasMemoryLimit) {\n var requiredMemory = canvasSize.width * canvasSize.height;\n if (requiredMemory > canvasMemoryLimit) {\n var scalar = Math.sqrt(canvasMemoryLimit) / Math.sqrt(requiredMemory);\n imageSize.width = Math.floor(imageSize.width * scalar);\n imageSize.height = Math.floor(imageSize.height * scalar);\n canvasSize = calculateCanvasSize(imageSize, aspectRatio, zoom);\n }\n }\n\n var canvas = document.createElement('canvas');\n\n var canvasCenter = {\n x: canvasSize.width * 0.5,\n y: canvasSize.height * 0.5,\n };\n\n var stage = {\n x: 0,\n y: 0,\n width: canvasSize.width,\n height: canvasSize.height,\n center: canvasCenter,\n };\n\n var shouldLimit = typeof crop.scaleToFit === 'undefined' || crop.scaleToFit;\n\n var scale =\n zoom *\n getImageRectZoomFactor(\n imageSize,\n getCenteredCropRect(stage, aspectRatio),\n crop.rotation,\n shouldLimit ? crop.center : { x: 0.5, y: 0.5 }\n );\n\n // start drawing\n canvas.width = Math.round(canvasSize.width / scale);\n canvas.height = Math.round(canvasSize.height / scale);\n\n canvasCenter.x /= scale;\n canvasCenter.y /= scale;\n\n var imageOffset = {\n x: canvasCenter.x - imageSize.width * (crop.center ? crop.center.x : 0.5),\n y: canvasCenter.y - imageSize.height * (crop.center ? crop.center.y : 0.5),\n };\n\n var ctx = canvas.getContext('2d');\n if (background) {\n ctx.fillStyle = background;\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n }\n\n // move to draw offset\n ctx.translate(canvasCenter.x, canvasCenter.y);\n ctx.rotate(crop.rotation || 0);\n\n // draw the image\n ctx.drawImage(\n bitmap,\n imageOffset.x - canvasCenter.x,\n imageOffset.y - canvasCenter.y,\n imageSize.width,\n imageSize.height\n );\n\n // get data from canvas\n var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);\n\n // release canvas\n canvasRelease(canvas);\n\n // return data\n return imageData;\n };\n\n /**\n * Polyfill toBlob for Edge\n */\n var IS_BROWSER = (function() {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n })();\n if (IS_BROWSER) {\n if (!HTMLCanvasElement.prototype.toBlob) {\n Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {\n value: function value(callback, type, quality) {\n var dataURL = this.toDataURL(type, quality).split(',')[1];\n setTimeout(function() {\n var binStr = atob(dataURL);\n var len = binStr.length;\n var arr = new Uint8Array(len);\n for (var i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i);\n }\n callback(new Blob([arr], { type: type || 'image/png' }));\n });\n },\n });\n }\n }\n\n var canvasToBlob = function canvasToBlob(canvas, options) {\n var beforeCreateBlob =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n return new Promise(function(resolve) {\n var promisedImage = beforeCreateBlob ? beforeCreateBlob(canvas) : canvas;\n Promise.resolve(promisedImage).then(function(canvas) {\n canvas.toBlob(resolve, options.type, options.quality);\n });\n });\n };\n\n var vectorMultiply = function vectorMultiply(v, amount) {\n return createVector$1(v.x * amount, v.y * amount);\n };\n\n var vectorAdd = function vectorAdd(a, b) {\n return createVector$1(a.x + b.x, a.y + b.y);\n };\n\n var vectorNormalize = function vectorNormalize(v) {\n var l = Math.sqrt(v.x * v.x + v.y * v.y);\n if (l === 0) {\n return {\n x: 0,\n y: 0,\n };\n }\n return createVector$1(v.x / l, v.y / l);\n };\n\n var vectorRotate = function vectorRotate(v, radians, origin) {\n var cos = Math.cos(radians);\n var sin = Math.sin(radians);\n var t = createVector$1(v.x - origin.x, v.y - origin.y);\n return createVector$1(origin.x + cos * t.x - sin * t.y, origin.y + sin * t.x + cos * t.y);\n };\n\n var createVector$1 = function createVector() {\n var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;\n return { x: x, y: y };\n };\n\n var getMarkupValue = function getMarkupValue(value, size) {\n var scalar = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n var axis = arguments.length > 3 ? arguments[3] : undefined;\n if (typeof value === 'string') {\n return parseFloat(value) * scalar;\n }\n if (typeof value === 'number') {\n return value * (axis ? size[axis] : Math.min(size.width, size.height));\n }\n return;\n };\n\n var getMarkupStyles = function getMarkupStyles(markup, size, scale) {\n var lineStyle = markup.borderStyle || markup.lineStyle || 'solid';\n var fill = markup.backgroundColor || markup.fontColor || 'transparent';\n var stroke = markup.borderColor || markup.lineColor || 'transparent';\n var strokeWidth = getMarkupValue(markup.borderWidth || markup.lineWidth, size, scale);\n var lineCap = markup.lineCap || 'round';\n var lineJoin = markup.lineJoin || 'round';\n var dashes =\n typeof lineStyle === 'string'\n ? ''\n : lineStyle\n .map(function(v) {\n return getMarkupValue(v, size, scale);\n })\n .join(',');\n var opacity = markup.opacity || 1;\n return {\n 'stroke-linecap': lineCap,\n 'stroke-linejoin': lineJoin,\n 'stroke-width': strokeWidth || 0,\n 'stroke-dasharray': dashes,\n stroke: stroke,\n fill: fill,\n opacity: opacity,\n };\n };\n\n var isDefined = function isDefined(value) {\n return value != null;\n };\n\n var getMarkupRect = function getMarkupRect(rect, size) {\n var scalar = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;\n\n var left =\n getMarkupValue(rect.x, size, scalar, 'width') ||\n getMarkupValue(rect.left, size, scalar, 'width');\n var top =\n getMarkupValue(rect.y, size, scalar, 'height') ||\n getMarkupValue(rect.top, size, scalar, 'height');\n var width = getMarkupValue(rect.width, size, scalar, 'width');\n var height = getMarkupValue(rect.height, size, scalar, 'height');\n var right = getMarkupValue(rect.right, size, scalar, 'width');\n var bottom = getMarkupValue(rect.bottom, size, scalar, 'height');\n\n if (!isDefined(top)) {\n if (isDefined(height) && isDefined(bottom)) {\n top = size.height - height - bottom;\n } else {\n top = bottom;\n }\n }\n\n if (!isDefined(left)) {\n if (isDefined(width) && isDefined(right)) {\n left = size.width - width - right;\n } else {\n left = right;\n }\n }\n\n if (!isDefined(width)) {\n if (isDefined(left) && isDefined(right)) {\n width = size.width - left - right;\n } else {\n width = 0;\n }\n }\n\n if (!isDefined(height)) {\n if (isDefined(top) && isDefined(bottom)) {\n height = size.height - top - bottom;\n } else {\n height = 0;\n }\n }\n\n return {\n x: left || 0,\n y: top || 0,\n width: width || 0,\n height: height || 0,\n };\n };\n\n var pointsToPathShape = function pointsToPathShape(points) {\n return points\n .map(function(point, index) {\n return ''\n .concat(index === 0 ? 'M' : 'L', ' ')\n .concat(point.x, ' ')\n .concat(point.y);\n })\n .join(' ');\n };\n\n var setAttributes = function setAttributes(element, attr) {\n return Object.keys(attr).forEach(function(key) {\n return element.setAttribute(key, attr[key]);\n });\n };\n\n var ns = 'http://www.w3.org/2000/svg';\n var svg = function svg(tag, attr) {\n var element = document.createElementNS(ns, tag);\n if (attr) {\n setAttributes(element, attr);\n }\n return element;\n };\n\n var updateRect = function updateRect(element) {\n return setAttributes(element, Object.assign({}, element.rect, element.styles));\n };\n\n var updateEllipse = function updateEllipse(element) {\n var cx = element.rect.x + element.rect.width * 0.5;\n var cy = element.rect.y + element.rect.height * 0.5;\n var rx = element.rect.width * 0.5;\n var ry = element.rect.height * 0.5;\n return setAttributes(\n element,\n Object.assign(\n {\n cx: cx,\n cy: cy,\n rx: rx,\n ry: ry,\n },\n element.styles\n )\n );\n };\n\n var IMAGE_FIT_STYLE = {\n contain: 'xMidYMid meet',\n cover: 'xMidYMid slice',\n };\n\n var updateImage = function updateImage(element, markup) {\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n preserveAspectRatio: IMAGE_FIT_STYLE[markup.fit] || 'none',\n })\n );\n };\n\n var TEXT_ANCHOR = {\n left: 'start',\n center: 'middle',\n right: 'end',\n };\n\n var updateText = function updateText(element, markup, size, scale) {\n var fontSize = getMarkupValue(markup.fontSize, size, scale);\n var fontFamily = markup.fontFamily || 'sans-serif';\n var fontWeight = markup.fontWeight || 'normal';\n var textAlign = TEXT_ANCHOR[markup.textAlign] || 'start';\n\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n 'stroke-width': 0,\n 'font-weight': fontWeight,\n 'font-size': fontSize,\n 'font-family': fontFamily,\n 'text-anchor': textAlign,\n })\n );\n\n // update text\n if (element.text !== markup.text) {\n element.text = markup.text;\n element.textContent = markup.text.length ? markup.text : ' ';\n }\n };\n\n var updateLine = function updateLine(element, markup, size, scale) {\n setAttributes(\n element,\n Object.assign({}, element.rect, element.styles, {\n fill: 'none',\n })\n );\n\n var line = element.childNodes[0];\n var begin = element.childNodes[1];\n var end = element.childNodes[2];\n\n var origin = element.rect;\n\n var target = {\n x: element.rect.x + element.rect.width,\n y: element.rect.y + element.rect.height,\n };\n\n setAttributes(line, {\n x1: origin.x,\n y1: origin.y,\n x2: target.x,\n y2: target.y,\n });\n\n if (!markup.lineDecoration) return;\n\n begin.style.display = 'none';\n end.style.display = 'none';\n\n var v = vectorNormalize({\n x: target.x - origin.x,\n y: target.y - origin.y,\n });\n\n var l = getMarkupValue(0.05, size, scale);\n\n if (markup.lineDecoration.indexOf('arrow-begin') !== -1) {\n var arrowBeginRotationPoint = vectorMultiply(v, l);\n var arrowBeginCenter = vectorAdd(origin, arrowBeginRotationPoint);\n var arrowBeginA = vectorRotate(origin, 2, arrowBeginCenter);\n var arrowBeginB = vectorRotate(origin, -2, arrowBeginCenter);\n\n setAttributes(begin, {\n style: 'display:block;',\n d: 'M'\n .concat(arrowBeginA.x, ',')\n .concat(arrowBeginA.y, ' L')\n .concat(origin.x, ',')\n .concat(origin.y, ' L')\n .concat(arrowBeginB.x, ',')\n .concat(arrowBeginB.y),\n });\n }\n\n if (markup.lineDecoration.indexOf('arrow-end') !== -1) {\n var arrowEndRotationPoint = vectorMultiply(v, -l);\n var arrowEndCenter = vectorAdd(target, arrowEndRotationPoint);\n var arrowEndA = vectorRotate(target, 2, arrowEndCenter);\n var arrowEndB = vectorRotate(target, -2, arrowEndCenter);\n\n setAttributes(end, {\n style: 'display:block;',\n d: 'M'\n .concat(arrowEndA.x, ',')\n .concat(arrowEndA.y, ' L')\n .concat(target.x, ',')\n .concat(target.y, ' L')\n .concat(arrowEndB.x, ',')\n .concat(arrowEndB.y),\n });\n }\n };\n\n var updatePath = function updatePath(element, markup, size, scale) {\n setAttributes(\n element,\n Object.assign({}, element.styles, {\n fill: 'none',\n d: pointsToPathShape(\n markup.points.map(function(point) {\n return {\n x: getMarkupValue(point.x, size, scale, 'width'),\n y: getMarkupValue(point.y, size, scale, 'height'),\n };\n })\n ),\n })\n );\n };\n\n var createShape = function createShape(node) {\n return function(markup) {\n return svg(node, { id: markup.id });\n };\n };\n\n var createImage = function createImage(markup) {\n var shape = svg('image', {\n id: markup.id,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n opacity: '0',\n });\n\n shape.onload = function() {\n shape.setAttribute('opacity', markup.opacity || 1);\n };\n shape.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', markup.src);\n return shape;\n };\n\n var createLine = function createLine(markup) {\n var shape = svg('g', {\n id: markup.id,\n 'stroke-linecap': 'round',\n 'stroke-linejoin': 'round',\n });\n\n var line = svg('line');\n shape.appendChild(line);\n\n var begin = svg('path');\n shape.appendChild(begin);\n\n var end = svg('path');\n shape.appendChild(end);\n\n return shape;\n };\n\n var CREATE_TYPE_ROUTES = {\n image: createImage,\n rect: createShape('rect'),\n ellipse: createShape('ellipse'),\n text: createShape('text'),\n path: createShape('path'),\n line: createLine,\n };\n\n var UPDATE_TYPE_ROUTES = {\n rect: updateRect,\n ellipse: updateEllipse,\n image: updateImage,\n text: updateText,\n path: updatePath,\n line: updateLine,\n };\n\n var createMarkupByType = function createMarkupByType(type, markup) {\n return CREATE_TYPE_ROUTES[type](markup);\n };\n\n var updateMarkupByType = function updateMarkupByType(element, type, markup, size, scale) {\n if (type !== 'path') {\n element.rect = getMarkupRect(markup, size, scale);\n }\n element.styles = getMarkupStyles(markup, size, scale);\n UPDATE_TYPE_ROUTES[type](element, markup, size, scale);\n };\n\n var sortMarkupByZIndex = function sortMarkupByZIndex(a, b) {\n if (a[1].zIndex > b[1].zIndex) {\n return 1;\n }\n if (a[1].zIndex < b[1].zIndex) {\n return -1;\n }\n return 0;\n };\n\n var cropSVG = function cropSVG(blob) {\n var crop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var markup = arguments.length > 2 ? arguments[2] : undefined;\n var options = arguments.length > 3 ? arguments[3] : undefined;\n return new Promise(function(resolve) {\n var _options$background = options.background,\n background = _options$background === void 0 ? null : _options$background;\n\n // load blob contents and wrap in crop svg\n var fr = new FileReader();\n fr.onloadend = function() {\n // get svg text\n var text = fr.result;\n\n // create element with svg and get size\n var original = document.createElement('div');\n original.style.cssText =\n 'position:absolute;pointer-events:none;width:0;height:0;visibility:hidden;';\n original.innerHTML = text;\n var originalNode = original.querySelector('svg');\n document.body.appendChild(original);\n\n // request bounding box dimensions\n var bBox = originalNode.getBBox();\n original.parentNode.removeChild(original);\n\n // get title\n var titleNode = original.querySelector('title');\n\n // calculate new heights and widths\n var viewBoxAttribute = originalNode.getAttribute('viewBox') || '';\n var widthAttribute = originalNode.getAttribute('width') || '';\n var heightAttribute = originalNode.getAttribute('height') || '';\n var width = parseFloat(widthAttribute) || null;\n var height = parseFloat(heightAttribute) || null;\n var widthUnits = (widthAttribute.match(/[a-z]+/) || [])[0] || '';\n var heightUnits = (heightAttribute.match(/[a-z]+/) || [])[0] || '';\n\n // create new size\n var viewBoxList = viewBoxAttribute.split(' ').map(parseFloat);\n var viewBox = viewBoxList.length\n ? {\n x: viewBoxList[0],\n y: viewBoxList[1],\n width: viewBoxList[2],\n height: viewBoxList[3],\n }\n : bBox;\n\n var imageWidth = width != null ? width : viewBox.width;\n var imageHeight = height != null ? height : viewBox.height;\n\n originalNode.style.overflow = 'visible';\n originalNode.setAttribute('width', imageWidth);\n originalNode.setAttribute('height', imageHeight);\n\n // markup\n var markupSVG = '';\n if (markup && markup.length) {\n var size = {\n width: imageWidth,\n height: imageHeight,\n };\n\n markupSVG = markup.sort(sortMarkupByZIndex).reduce(function(prev, shape) {\n var el = createMarkupByType(shape[0], shape[1]);\n updateMarkupByType(el, shape[0], shape[1], size);\n el.removeAttribute('id');\n if (el.getAttribute('opacity') === 1) {\n el.removeAttribute('opacity');\n }\n return prev + '\\n' + el.outerHTML + '\\n';\n }, '');\n markupSVG = '\\n\\n'.concat(markupSVG.replace(/ /g, ' '), '\\n\\n');\n }\n\n var aspectRatio = crop.aspectRatio || imageHeight / imageWidth;\n\n var canvasWidth = imageWidth;\n var canvasHeight = canvasWidth * aspectRatio;\n\n var shouldLimit = typeof crop.scaleToFit === 'undefined' || crop.scaleToFit;\n\n var cropCenterX = crop.center ? crop.center.x : 0.5;\n var cropCenterY = crop.center ? crop.center.y : 0.5;\n\n var canvasZoomFactor = getImageRectZoomFactor(\n {\n width: imageWidth,\n height: imageHeight,\n },\n\n getCenteredCropRect(\n {\n width: canvasWidth,\n height: canvasHeight,\n },\n\n aspectRatio\n ),\n\n crop.rotation,\n shouldLimit\n ? { x: cropCenterX, y: cropCenterY }\n : {\n x: 0.5,\n y: 0.5,\n }\n );\n\n var scale = crop.zoom * canvasZoomFactor;\n\n var rotation = crop.rotation * (180 / Math.PI);\n\n var canvasCenter = {\n x: canvasWidth * 0.5,\n y: canvasHeight * 0.5,\n };\n\n var imageOffset = {\n x: canvasCenter.x - imageWidth * cropCenterX,\n y: canvasCenter.y - imageHeight * cropCenterY,\n };\n\n var cropTransforms = [\n // rotate\n 'rotate('\n .concat(rotation, ' ')\n .concat(canvasCenter.x, ' ')\n .concat(canvasCenter.y, ')'),\n\n // scale\n 'translate('.concat(canvasCenter.x, ' ').concat(canvasCenter.y, ')'),\n 'scale('.concat(scale, ')'),\n 'translate('.concat(-canvasCenter.x, ' ').concat(-canvasCenter.y, ')'),\n\n // offset\n 'translate('.concat(imageOffset.x, ' ').concat(imageOffset.y, ')'),\n ];\n\n var cropFlipHorizontal = crop.flip && crop.flip.horizontal;\n var cropFlipVertical = crop.flip && crop.flip.vertical;\n\n var flipTransforms = [\n 'scale('\n .concat(cropFlipHorizontal ? -1 : 1, ' ')\n .concat(cropFlipVertical ? -1 : 1, ')'),\n 'translate('\n .concat(cropFlipHorizontal ? -imageWidth : 0, ' ')\n .concat(cropFlipVertical ? -imageHeight : 0, ')'),\n ];\n\n // crop\n var transformed = '\\n');\n\n // create new svg file\n resolve(transformed);\n };\n\n fr.readAsText(blob);\n });\n };\n\n var objectToImageData = function objectToImageData(obj) {\n var imageData;\n try {\n imageData = new ImageData(obj.width, obj.height);\n } catch (e) {\n // IE + Old EDGE (tested on 12)\n var canvas = document.createElement('canvas');\n imageData = canvas.getContext('2d').createImageData(obj.width, obj.height);\n }\n imageData.data.set(obj.data);\n return imageData;\n };\n\n /* javascript-obfuscator:disable */\n var TransformWorker = function TransformWorker() {\n // maps transform types to transform functions\n var TRANSFORMS = { resize: resize, filter: filter };\n\n // applies all image transforms to the image data array\n var applyTransforms = function applyTransforms(transforms, imageData) {\n transforms.forEach(function(transform) {\n imageData = TRANSFORMS[transform.type](imageData, transform.data);\n });\n return imageData;\n };\n\n // transform image hub\n var transform = function transform(data, cb) {\n var transforms = data.transforms;\n\n // if has filter and has resize, move filter to resize operation\n var filterTransform = null;\n transforms.forEach(function(transform) {\n if (transform.type === 'filter') {\n filterTransform = transform;\n }\n });\n if (filterTransform) {\n // find resize\n var resizeTransform = null;\n transforms.forEach(function(transform) {\n if (transform.type === 'resize') {\n resizeTransform = transform;\n }\n });\n\n if (resizeTransform) {\n // update resize operation\n resizeTransform.data.matrix = filterTransform.data;\n\n // remove filter\n transforms = transforms.filter(function(transform) {\n return transform.type !== 'filter';\n });\n }\n }\n\n cb(applyTransforms(transforms, data.imageData));\n };\n\n // eslint-disable-next-line no-restricted-globals\n self.onmessage = function(e) {\n transform(e.data.message, function(response) {\n // eslint-disable-next-line no-restricted-globals\n self.postMessage({ id: e.data.id, message: response }, [response.data.buffer]);\n });\n };\n\n var br = 1.0;\n var bg = 1.0;\n var bb = 1.0;\n function applyFilterMatrix(index, data, m) {\n var ir = data[index] / 255;\n var ig = data[index + 1] / 255;\n var ib = data[index + 2] / 255;\n var ia = data[index + 3] / 255;\n\n var mr = ir * m[0] + ig * m[1] + ib * m[2] + ia * m[3] + m[4];\n var mg = ir * m[5] + ig * m[6] + ib * m[7] + ia * m[8] + m[9];\n var mb = ir * m[10] + ig * m[11] + ib * m[12] + ia * m[13] + m[14];\n var ma = ir * m[15] + ig * m[16] + ib * m[17] + ia * m[18] + m[19];\n\n var or = Math.max(0, mr * ma) + br * (1.0 - ma);\n var og = Math.max(0, mg * ma) + bg * (1.0 - ma);\n var ob = Math.max(0, mb * ma) + bb * (1.0 - ma);\n\n data[index] = Math.max(0.0, Math.min(1.0, or)) * 255;\n data[index + 1] = Math.max(0.0, Math.min(1.0, og)) * 255;\n data[index + 2] = Math.max(0.0, Math.min(1.0, ob)) * 255;\n }\n\n var identityMatrix = self.JSON.stringify([\n 1,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n ]);\n function isIdentityMatrix(filter) {\n return self.JSON.stringify(filter || []) === identityMatrix;\n }\n\n function filter(imageData, matrix) {\n if (!matrix || isIdentityMatrix(matrix)) return imageData;\n\n var data = imageData.data;\n var l = data.length;\n\n var m11 = matrix[0];\n var m12 = matrix[1];\n var m13 = matrix[2];\n var m14 = matrix[3];\n var m15 = matrix[4];\n\n var m21 = matrix[5];\n var m22 = matrix[6];\n var m23 = matrix[7];\n var m24 = matrix[8];\n var m25 = matrix[9];\n\n var m31 = matrix[10];\n var m32 = matrix[11];\n var m33 = matrix[12];\n var m34 = matrix[13];\n var m35 = matrix[14];\n\n var m41 = matrix[15];\n var m42 = matrix[16];\n var m43 = matrix[17];\n var m44 = matrix[18];\n var m45 = matrix[19];\n\n var index = 0,\n r = 0.0,\n g = 0.0,\n b = 0.0,\n a = 0.0,\n mr = 0.0,\n mg = 0.0,\n mb = 0.0,\n ma = 0.0,\n or = 0.0,\n og = 0.0,\n ob = 0.0;\n\n for (; index < l; index += 4) {\n r = data[index] / 255;\n g = data[index + 1] / 255;\n b = data[index + 2] / 255;\n a = data[index + 3] / 255;\n\n mr = r * m11 + g * m12 + b * m13 + a * m14 + m15;\n mg = r * m21 + g * m22 + b * m23 + a * m24 + m25;\n mb = r * m31 + g * m32 + b * m33 + a * m34 + m35;\n ma = r * m41 + g * m42 + b * m43 + a * m44 + m45;\n\n or = Math.max(0, mr * ma) + br * (1.0 - ma);\n og = Math.max(0, mg * ma) + bg * (1.0 - ma);\n ob = Math.max(0, mb * ma) + bb * (1.0 - ma);\n\n data[index] = Math.max(0.0, Math.min(1.0, or)) * 255;\n data[index + 1] = Math.max(0.0, Math.min(1.0, og)) * 255;\n data[index + 2] = Math.max(0.0, Math.min(1.0, ob)) * 255;\n // don't update alpha value\n }\n\n return imageData;\n }\n\n function resize(imageData, data) {\n var _data$mode = data.mode,\n mode = _data$mode === void 0 ? 'contain' : _data$mode,\n _data$upscale = data.upscale,\n upscale = _data$upscale === void 0 ? false : _data$upscale,\n width = data.width,\n height = data.height,\n matrix = data.matrix;\n\n // test if is identity matrix\n matrix = !matrix || isIdentityMatrix(matrix) ? null : matrix;\n\n // need at least a width or a height\n // also 0 is not a valid width or height\n if (!width && !height) {\n return filter(imageData, matrix);\n }\n\n // make sure all bounds are set\n if (width === null) {\n width = height;\n } else if (height === null) {\n height = width;\n }\n\n if (mode !== 'force') {\n var scalarWidth = width / imageData.width;\n var scalarHeight = height / imageData.height;\n var scalar = 1;\n\n if (mode === 'cover') {\n scalar = Math.max(scalarWidth, scalarHeight);\n } else if (mode === 'contain') {\n scalar = Math.min(scalarWidth, scalarHeight);\n }\n\n // if image is too small, exit here with original image\n if (scalar > 1 && upscale === false) {\n return filter(imageData, matrix);\n }\n\n width = imageData.width * scalar;\n height = imageData.height * scalar;\n }\n\n var originWidth = imageData.width;\n var originHeight = imageData.height;\n var targetWidth = Math.round(width);\n var targetHeight = Math.round(height);\n var inputData = imageData.data;\n var outputData = new Uint8ClampedArray(targetWidth * targetHeight * 4);\n var ratioWidth = originWidth / targetWidth;\n var ratioHeight = originHeight / targetHeight;\n var ratioWidthHalf = Math.ceil(ratioWidth * 0.5);\n var ratioHeightHalf = Math.ceil(ratioHeight * 0.5);\n\n for (var j = 0; j < targetHeight; j++) {\n for (var i = 0; i < targetWidth; i++) {\n var x2 = (i + j * targetWidth) * 4;\n var weight = 0;\n var weights = 0;\n var weightsAlpha = 0;\n var r = 0;\n var g = 0;\n var b = 0;\n var a = 0;\n var centerY = (j + 0.5) * ratioHeight;\n\n for (var yy = Math.floor(j * ratioHeight); yy < (j + 1) * ratioHeight; yy++) {\n var dy = Math.abs(centerY - (yy + 0.5)) / ratioHeightHalf;\n var centerX = (i + 0.5) * ratioWidth;\n var w0 = dy * dy;\n\n for (var xx = Math.floor(i * ratioWidth); xx < (i + 1) * ratioWidth; xx++) {\n var dx = Math.abs(centerX - (xx + 0.5)) / ratioWidthHalf;\n var w = Math.sqrt(w0 + dx * dx);\n\n if (w >= -1 && w <= 1) {\n weight = 2 * w * w * w - 3 * w * w + 1;\n\n if (weight > 0) {\n dx = 4 * (xx + yy * originWidth);\n\n var ref = inputData[dx + 3];\n a += weight * ref;\n weightsAlpha += weight;\n\n if (ref < 255) {\n weight = (weight * ref) / 250;\n }\n\n r += weight * inputData[dx];\n g += weight * inputData[dx + 1];\n b += weight * inputData[dx + 2];\n weights += weight;\n }\n }\n }\n }\n\n outputData[x2] = r / weights;\n outputData[x2 + 1] = g / weights;\n outputData[x2 + 2] = b / weights;\n outputData[x2 + 3] = a / weightsAlpha;\n\n matrix && applyFilterMatrix(x2, outputData, matrix);\n }\n }\n\n return {\n data: outputData,\n width: targetWidth,\n height: targetHeight,\n };\n }\n };\n /* javascript-obfuscator:enable */\n\n var correctOrientation = function correctOrientation(view, offset) {\n // Missing 0x45786966 Marker? No Exif Header, stop here\n if (view.getUint32(offset + 4, false) !== 0x45786966) return;\n\n // next byte!\n offset += 4;\n\n // First 2bytes defines byte align of TIFF data.\n // If it is 0x4949=\"I I\", it means \"Intel\" type byte align\n var intelByteAligned = view.getUint16((offset += 6), false) === 0x4949;\n offset += view.getUint32(offset + 4, intelByteAligned);\n\n var tags = view.getUint16(offset, intelByteAligned);\n offset += 2;\n\n // find Orientation tag\n for (var i = 0; i < tags; i++) {\n if (view.getUint16(offset + i * 12, intelByteAligned) === 0x0112) {\n view.setUint16(offset + i * 12 + 8, 1, intelByteAligned);\n return true;\n }\n }\n return false;\n };\n\n var readData = function readData(data) {\n var view = new DataView(data);\n\n // Every JPEG file starts from binary value '0xFFD8'\n // If it's not present, exit here\n if (view.getUint16(0) !== 0xffd8) return null;\n\n var offset = 2; // Start at 2 as we skipped two bytes (FFD8)\n var marker;\n var markerLength;\n var orientationCorrected = false;\n\n while (offset < view.byteLength) {\n marker = view.getUint16(offset, false);\n markerLength = view.getUint16(offset + 2, false) + 2;\n\n // Test if is APP and COM markers\n var isData = (marker >= 0xffe0 && marker <= 0xffef) || marker === 0xfffe;\n if (!isData) {\n break;\n }\n\n if (!orientationCorrected) {\n orientationCorrected = correctOrientation(view, offset, markerLength);\n }\n\n if (offset + markerLength > view.byteLength) {\n break;\n }\n\n offset += markerLength;\n }\n return data.slice(0, offset);\n };\n\n var getImageHead = function getImageHead(file) {\n return new Promise(function(resolve) {\n var reader = new FileReader();\n reader.onload = function() {\n return resolve(readData(reader.result) || null);\n };\n reader.readAsArrayBuffer(file.slice(0, 256 * 1024));\n });\n };\n\n var getBlobBuilder = function getBlobBuilder() {\n return (window.BlobBuilder =\n window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder);\n };\n\n var createBlob = function createBlob(arrayBuffer, mimeType) {\n var BB = getBlobBuilder();\n\n if (BB) {\n var bb = new BB();\n bb.append(arrayBuffer);\n return bb.getBlob(mimeType);\n }\n\n return new Blob([arrayBuffer], {\n type: mimeType,\n });\n };\n\n var getUniqueId = function getUniqueId() {\n return Math.random()\n .toString(36)\n .substr(2, 9);\n };\n\n var createWorker = function createWorker(fn) {\n var workerBlob = new Blob(['(', fn.toString(), ')()'], { type: 'application/javascript' });\n var workerURL = URL.createObjectURL(workerBlob);\n var worker = new Worker(workerURL);\n\n var trips = [];\n\n return {\n transfer: function transfer() {}, // (message, cb) => {}\n post: function post(message, cb, transferList) {\n var id = getUniqueId();\n trips[id] = cb;\n\n worker.onmessage = function(e) {\n var cb = trips[e.data.id];\n if (!cb) return;\n cb(e.data.message);\n delete trips[e.data.id];\n };\n\n worker.postMessage(\n {\n id: id,\n message: message,\n },\n\n transferList\n );\n },\n terminate: function terminate() {\n worker.terminate();\n URL.revokeObjectURL(workerURL);\n },\n };\n };\n\n var loadImage = function loadImage(url) {\n return new Promise(function(resolve, reject) {\n var img = new Image();\n img.onload = function() {\n resolve(img);\n };\n img.onerror = function(e) {\n reject(e);\n };\n img.src = url;\n });\n };\n\n var chain = function chain(funcs) {\n return funcs.reduce(function(promise, func) {\n return promise.then(function(result) {\n return func().then(Array.prototype.concat.bind(result));\n });\n }, Promise.resolve([]));\n };\n\n var canvasApplyMarkup = function canvasApplyMarkup(canvas, markup) {\n return new Promise(function(resolve) {\n var size = {\n width: canvas.width,\n height: canvas.height,\n };\n\n var ctx = canvas.getContext('2d');\n\n var drawers = markup.sort(sortMarkupByZIndex).map(function(item) {\n return function() {\n return new Promise(function(resolve) {\n var result = TYPE_DRAW_ROUTES[item[0]](ctx, size, item[1], resolve);\n if (result) resolve();\n });\n };\n });\n\n chain(drawers).then(function() {\n return resolve(canvas);\n });\n });\n };\n\n var applyMarkupStyles = function applyMarkupStyles(ctx, styles) {\n ctx.beginPath();\n ctx.lineCap = styles['stroke-linecap'];\n ctx.lineJoin = styles['stroke-linejoin'];\n ctx.lineWidth = styles['stroke-width'];\n if (styles['stroke-dasharray'].length) {\n ctx.setLineDash(styles['stroke-dasharray'].split(','));\n }\n ctx.fillStyle = styles['fill'];\n ctx.strokeStyle = styles['stroke'];\n ctx.globalAlpha = styles.opacity || 1;\n };\n\n var drawMarkupStyles = function drawMarkupStyles(ctx) {\n ctx.fill();\n ctx.stroke();\n ctx.globalAlpha = 1;\n };\n\n var drawRect = function drawRect(ctx, size, markup) {\n var rect = getMarkupRect(markup, size);\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n ctx.rect(rect.x, rect.y, rect.width, rect.height);\n drawMarkupStyles(ctx, styles);\n return true;\n };\n\n var drawEllipse = function drawEllipse(ctx, size, markup) {\n var rect = getMarkupRect(markup, size);\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n\n var x = rect.x,\n y = rect.y,\n w = rect.width,\n h = rect.height,\n kappa = 0.5522848,\n ox = (w / 2) * kappa,\n oy = (h / 2) * kappa,\n xe = x + w,\n ye = y + h,\n xm = x + w / 2,\n ym = y + h / 2;\n\n ctx.moveTo(x, ym);\n ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);\n ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);\n ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);\n ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);\n\n drawMarkupStyles(ctx, styles);\n return true;\n };\n\n var drawImage = function drawImage(ctx, size, markup, done) {\n var rect = getMarkupRect(markup, size);\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n\n var image = new Image();\n\n // if is cross origin image add cross origin attribute\n var isCrossOriginImage =\n new URL(markup.src, window.location.href).origin !== window.location.origin;\n if (isCrossOriginImage) image.crossOrigin = '';\n\n image.onload = function() {\n if (markup.fit === 'cover') {\n var ar = rect.width / rect.height;\n var width = ar > 1 ? image.width : image.height * ar;\n var height = ar > 1 ? image.width / ar : image.height;\n var x = image.width * 0.5 - width * 0.5;\n var y = image.height * 0.5 - height * 0.5;\n ctx.drawImage(image, x, y, width, height, rect.x, rect.y, rect.width, rect.height);\n } else if (markup.fit === 'contain') {\n var scalar = Math.min(rect.width / image.width, rect.height / image.height);\n var _width = scalar * image.width;\n var _height = scalar * image.height;\n var _x = rect.x + rect.width * 0.5 - _width * 0.5;\n var _y = rect.y + rect.height * 0.5 - _height * 0.5;\n ctx.drawImage(image, 0, 0, image.width, image.height, _x, _y, _width, _height);\n } else {\n ctx.drawImage(\n image,\n 0,\n 0,\n image.width,\n image.height,\n rect.x,\n rect.y,\n rect.width,\n rect.height\n );\n }\n\n drawMarkupStyles(ctx, styles);\n done();\n };\n image.src = markup.src;\n };\n\n var drawText = function drawText(ctx, size, markup) {\n var rect = getMarkupRect(markup, size);\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n\n var fontSize = getMarkupValue(markup.fontSize, size);\n var fontFamily = markup.fontFamily || 'sans-serif';\n var fontWeight = markup.fontWeight || 'normal';\n var textAlign = markup.textAlign || 'left';\n\n ctx.font = ''\n .concat(fontWeight, ' ')\n .concat(fontSize, 'px ')\n .concat(fontFamily);\n ctx.textAlign = textAlign;\n ctx.fillText(markup.text, rect.x, rect.y);\n\n drawMarkupStyles(ctx, styles);\n return true;\n };\n\n var drawPath = function drawPath(ctx, size, markup) {\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n ctx.beginPath();\n\n var points = markup.points.map(function(point) {\n return {\n x: getMarkupValue(point.x, size, 1, 'width'),\n y: getMarkupValue(point.y, size, 1, 'height'),\n };\n });\n\n ctx.moveTo(points[0].x, points[0].y);\n var l = points.length;\n for (var i = 1; i < l; i++) {\n ctx.lineTo(points[i].x, points[i].y);\n }\n\n drawMarkupStyles(ctx, styles);\n return true;\n };\n\n var drawLine = function drawLine(ctx, size, markup) {\n var rect = getMarkupRect(markup, size);\n var styles = getMarkupStyles(markup, size);\n applyMarkupStyles(ctx, styles);\n\n ctx.beginPath();\n\n var origin = {\n x: rect.x,\n y: rect.y,\n };\n\n var target = {\n x: rect.x + rect.width,\n y: rect.y + rect.height,\n };\n\n ctx.moveTo(origin.x, origin.y);\n ctx.lineTo(target.x, target.y);\n\n var v = vectorNormalize({\n x: target.x - origin.x,\n y: target.y - origin.y,\n });\n\n var l = 0.04 * Math.min(size.width, size.height);\n\n if (markup.lineDecoration.indexOf('arrow-begin') !== -1) {\n var arrowBeginRotationPoint = vectorMultiply(v, l);\n var arrowBeginCenter = vectorAdd(origin, arrowBeginRotationPoint);\n var arrowBeginA = vectorRotate(origin, 2, arrowBeginCenter);\n var arrowBeginB = vectorRotate(origin, -2, arrowBeginCenter);\n\n ctx.moveTo(arrowBeginA.x, arrowBeginA.y);\n ctx.lineTo(origin.x, origin.y);\n ctx.lineTo(arrowBeginB.x, arrowBeginB.y);\n }\n if (markup.lineDecoration.indexOf('arrow-end') !== -1) {\n var arrowEndRotationPoint = vectorMultiply(v, -l);\n var arrowEndCenter = vectorAdd(target, arrowEndRotationPoint);\n var arrowEndA = vectorRotate(target, 2, arrowEndCenter);\n var arrowEndB = vectorRotate(target, -2, arrowEndCenter);\n\n ctx.moveTo(arrowEndA.x, arrowEndA.y);\n ctx.lineTo(target.x, target.y);\n ctx.lineTo(arrowEndB.x, arrowEndB.y);\n }\n\n drawMarkupStyles(ctx, styles);\n return true;\n };\n\n var TYPE_DRAW_ROUTES = {\n rect: drawRect,\n ellipse: drawEllipse,\n image: drawImage,\n text: drawText,\n line: drawLine,\n path: drawPath,\n };\n\n var imageDataToCanvas = function imageDataToCanvas(imageData) {\n var image = document.createElement('canvas');\n image.width = imageData.width;\n image.height = imageData.height;\n var ctx = image.getContext('2d');\n ctx.putImageData(imageData, 0, 0);\n return image;\n };\n\n var transformImage = function transformImage(file, instructions) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return new Promise(function(resolve, reject) {\n // if the file is not an image we do not have any business transforming it\n if (!file || !isImage$1(file))\n return reject({ status: 'not an image file', file: file });\n\n // get separate options for easier use\n var stripImageHead = options.stripImageHead,\n beforeCreateBlob = options.beforeCreateBlob,\n afterCreateBlob = options.afterCreateBlob,\n canvasMemoryLimit = options.canvasMemoryLimit;\n\n // get crop\n var crop = instructions.crop,\n size = instructions.size,\n filter = instructions.filter,\n markup = instructions.markup,\n output = instructions.output;\n\n // get exif orientation\n var orientation =\n instructions.image && instructions.image.orientation\n ? Math.max(1, Math.min(8, instructions.image.orientation))\n : null;\n\n // compression quality 0 => 100\n var qualityAsPercentage = output && output.quality;\n var quality = qualityAsPercentage === null ? null : qualityAsPercentage / 100;\n\n // output format\n var type = (output && output.type) || null;\n\n // background color\n var background = (output && output.background) || null;\n\n // get transforms\n var transforms = [];\n\n // add resize transforms if set\n if (size && (typeof size.width === 'number' || typeof size.height === 'number')) {\n transforms.push({ type: 'resize', data: size });\n }\n\n // add filters\n if (filter && filter.length === 20) {\n transforms.push({ type: 'filter', data: filter });\n }\n\n // resolves with supplied blob\n var resolveWithBlob = function resolveWithBlob(blob) {\n var promisedBlob = afterCreateBlob ? afterCreateBlob(blob) : blob;\n Promise.resolve(promisedBlob).then(resolve);\n };\n\n // done\n var toBlob = function toBlob(imageData, options) {\n var canvas = imageDataToCanvas(imageData);\n var promisedCanvas = markup.length ? canvasApplyMarkup(canvas, markup) : canvas;\n Promise.resolve(promisedCanvas).then(function(canvas) {\n canvasToBlob(canvas, options, beforeCreateBlob)\n .then(function(blob) {\n // force release of canvas memory\n canvasRelease(canvas);\n\n // remove image head (default)\n if (stripImageHead) return resolveWithBlob(blob);\n\n // try to copy image head from original file to generated blob\n getImageHead(file).then(function(imageHead) {\n // re-inject image head in case of JPEG, as the image head is removed by canvas export\n if (imageHead !== null) {\n blob = new Blob([imageHead, blob.slice(20)], {\n type: blob.type,\n });\n }\n\n // done!\n resolveWithBlob(blob);\n });\n })\n .catch(reject);\n });\n };\n\n // if this is an svg and we want it to stay an svg\n if (/svg/.test(file.type) && type === null) {\n return cropSVG(file, crop, markup, { background: background }).then(function(text) {\n resolve(createBlob(text, 'image/svg+xml'));\n });\n }\n\n // get file url\n var url = URL.createObjectURL(file);\n\n // turn the file into an image\n loadImage(url)\n .then(function(image) {\n // url is no longer needed\n URL.revokeObjectURL(url);\n\n // draw to canvas and start transform chain\n var imageData = imageToImageData(image, orientation, crop, {\n canvasMemoryLimit: canvasMemoryLimit,\n background: background,\n });\n\n // determine the format of the blob that we will output\n var outputFormat = {\n quality: quality,\n type: type || file.type,\n };\n\n // no transforms necessary, we done!\n if (!transforms.length) {\n return toBlob(imageData, outputFormat);\n }\n\n // send to the transform worker to transform the blob on a separate thread\n var worker = createWorker(TransformWorker);\n worker.post(\n {\n transforms: transforms,\n imageData: imageData,\n },\n\n function(response) {\n // finish up\n toBlob(objectToImageData(response), outputFormat);\n\n // stop worker\n worker.terminate();\n },\n [imageData.data.buffer]\n );\n })\n .catch(reject);\n });\n };\n\n function _typeof(obj) {\n if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {\n _typeof = function(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function(obj) {\n return obj &&\n typeof Symbol === 'function' &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? 'symbol'\n : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n var REACT_ELEMENT_TYPE;\n\n function _jsx(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE =\n (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) ||\n 0xeac7;\n }\n\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n props = {\n children: void 0,\n };\n }\n\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n }\n\n function _asyncIterator(iterable) {\n var method;\n\n if (typeof Symbol === 'function') {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator];\n if (method != null) return method.call(iterable);\n }\n }\n\n throw new TypeError('Object is not async iterable');\n }\n\n function _AwaitValue(value) {\n this.wrapped = value;\n }\n\n function _AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function(resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null,\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg);\n var value = result.value;\n var wrappedAwait = value instanceof _AwaitValue;\n Promise.resolve(wrappedAwait ? value.wrapped : value).then(\n function(arg) {\n if (wrappedAwait) {\n resume('next', arg);\n return;\n }\n\n settle(result.done ? 'return' : 'normal', arg);\n },\n function(err) {\n resume('throw', err);\n }\n );\n } catch (err) {\n settle('throw', err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case 'return':\n front.resolve({\n value: value,\n done: true,\n });\n break;\n\n case 'throw':\n front.reject(value);\n break;\n\n default:\n front.resolve({\n value: value,\n done: false,\n });\n break;\n }\n\n front = front.next;\n\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n if (typeof gen.return !== 'function') {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === 'function' && Symbol.asyncIterator) {\n _AsyncGenerator.prototype[Symbol.asyncIterator] = function() {\n return this;\n };\n }\n\n _AsyncGenerator.prototype.next = function(arg) {\n return this._invoke('next', arg);\n };\n\n _AsyncGenerator.prototype.throw = function(arg) {\n return this._invoke('throw', arg);\n };\n\n _AsyncGenerator.prototype.return = function(arg) {\n return this._invoke('return', arg);\n };\n\n function _wrapAsyncGenerator(fn) {\n return function() {\n return new _AsyncGenerator(fn.apply(this, arguments));\n };\n }\n\n function _awaitAsyncGenerator(value) {\n return new _AwaitValue(value);\n }\n\n function _asyncGeneratorDelegate(inner, awaitWrap) {\n var iter = {},\n waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function(resolve) {\n resolve(inner[key](value));\n });\n return {\n done: false,\n value: awaitWrap(value),\n };\n }\n\n if (typeof Symbol === 'function' && Symbol.iterator) {\n iter[Symbol.iterator] = function() {\n return this;\n };\n }\n\n iter.next = function(value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n\n return pump('next', value);\n };\n\n if (typeof inner.throw === 'function') {\n iter.throw = function(value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n\n return pump('throw', value);\n };\n }\n\n if (typeof inner.return === 'function') {\n iter.return = function(value) {\n return pump('return', value);\n };\n }\n\n return iter;\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError('Cannot call a class as a function');\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ('value' in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineEnumerableProperties(obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n\n if (Object.getOwnPropertySymbols) {\n var objectSymbols = Object.getOwnPropertySymbols(descs);\n\n for (var i = 0; i < objectSymbols.length; i++) {\n var sym = objectSymbols[i];\n var desc = descs[sym];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, sym, desc);\n }\n }\n\n return obj;\n }\n\n function _defaults(obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n\n return obj;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _extends() {\n _extends =\n Object.assign ||\n function(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n }\n\n function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n }\n\n function _inherits(subClass, superClass) {\n if (typeof superClass !== 'function' && superClass !== null) {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true,\n },\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n }\n\n function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n }\n\n function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf\n ? Object.getPrototypeOf\n : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n\n function _setPrototypeOf(o, p) {\n _setPrototypeOf =\n Object.setPrototypeOf ||\n function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n }\n\n function isNativeReflectConstruct() {\n if (typeof Reflect === 'undefined' || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === 'function') return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n }\n\n function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf('[native code]') !== -1;\n }\n\n function _wrapNativeSuper(Class) {\n var _cache = typeof Map === 'function' ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n\n if (typeof Class !== 'function') {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n if (typeof _cache !== 'undefined') {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n }\n\n function _instanceof(left, right) {\n if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n }\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule\n ? obj\n : {\n default: obj,\n };\n }\n\n function _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc =\n Object.defineProperty && Object.getOwnPropertyDescriptor\n ? Object.getOwnPropertyDescriptor(obj, key)\n : {};\n\n if (desc.get || desc.set) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n }\n\n newObj.default = obj;\n return newObj;\n }\n }\n\n function _newArrowCheck(innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError('Cannot instantiate an arrow function');\n }\n }\n\n function _objectDestructuringEmpty(obj) {\n if (obj == null) throw new TypeError('Cannot destructure undefined');\n }\n\n function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n }\n\n function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n }\n\n function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n }\n\n function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === 'object' || typeof call === 'function')) {\n return call;\n }\n\n return _assertThisInitialized(self);\n }\n\n function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = _getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n }\n\n function _get(target, property, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = _superPropBase(target, property);\n\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get(target, property, receiver || target);\n }\n\n function set(target, property, value, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.set) {\n set = Reflect.set;\n } else {\n set = function set(target, property, value, receiver) {\n var base = _superPropBase(target, property);\n\n var desc;\n\n if (base) {\n desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.set) {\n desc.set.call(receiver, value);\n return true;\n } else if (!desc.writable) {\n return false;\n }\n }\n\n desc = Object.getOwnPropertyDescriptor(receiver, property);\n\n if (desc) {\n if (!desc.writable) {\n return false;\n }\n\n desc.value = value;\n Object.defineProperty(receiver, property, desc);\n } else {\n _defineProperty(receiver, property, value);\n }\n\n return true;\n };\n }\n\n return set(target, property, value, receiver);\n }\n\n function _set(target, property, value, receiver, isStrict) {\n var s = set(target, property, value, receiver || target);\n\n if (!s && isStrict) {\n throw new Error('failed to set property');\n }\n\n return value;\n }\n\n function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n return Object.freeze(\n Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw),\n },\n })\n );\n }\n\n function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n strings.raw = raw;\n return strings;\n }\n\n function _temporalRef(val, name) {\n if (val === _temporalUndefined) {\n throw new ReferenceError(name + ' is not defined - temporal dead zone');\n } else {\n return val;\n }\n }\n\n function _readOnlyError(name) {\n throw new Error('\"' + name + '\" is read-only');\n }\n\n function _classNameTDZError(name) {\n throw new Error('Class \"' + name + '\" cannot be referenced in computed property keys.');\n }\n\n var _temporalUndefined = {};\n\n function _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n }\n\n function _slicedToArrayLoose(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest();\n }\n\n function _toArray(arr) {\n return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (\n Symbol.iterator in Object(iter) ||\n Object.prototype.toString.call(iter) === '[object Arguments]'\n )\n return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i['return'] != null) _i['return']();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _iterableToArrayLimitLoose(arr, i) {\n var _arr = [];\n\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) {\n _arr.push(_step.value);\n\n if (i && _arr.length === i) break;\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError('Invalid attempt to spread non-iterable instance');\n }\n\n function _nonIterableRest() {\n throw new TypeError('Invalid attempt to destructure non-iterable instance');\n }\n\n function _skipFirstGeneratorNext(fn) {\n return function() {\n var it = fn.apply(this, arguments);\n it.next();\n return it;\n };\n }\n\n function _toPrimitive(input, hint) {\n if (typeof input !== 'object' || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n\n if (prim !== undefined) {\n var res = prim.call(input, hint || 'default');\n if (typeof res !== 'object') return res;\n throw new TypeError('@@toPrimitive must return a primitive value.');\n }\n\n return (hint === 'string' ? String : Number)(input);\n }\n\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, 'string');\n\n return typeof key === 'symbol' ? key : String(key);\n }\n\n function _initializerWarningHelper(descriptor, context) {\n throw new Error(\n 'Decorating class property failed. Please ensure that ' +\n 'proposal-class-properties is enabled and set to use loose mode. ' +\n 'To use proposal-class-properties in spec mode with decorators, wait for ' +\n 'the next major version of decorators in stage 2.'\n );\n }\n\n function _initializerDefineProperty(target, property, descriptor, context) {\n if (!descriptor) return;\n Object.defineProperty(target, property, {\n enumerable: descriptor.enumerable,\n configurable: descriptor.configurable,\n writable: descriptor.writable,\n value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,\n });\n }\n\n function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {\n var desc = {};\n Object.keys(descriptor).forEach(function(key) {\n desc[key] = descriptor[key];\n });\n desc.enumerable = !!desc.enumerable;\n desc.configurable = !!desc.configurable;\n\n if ('value' in desc || desc.initializer) {\n desc.writable = true;\n }\n\n desc = decorators\n .slice()\n .reverse()\n .reduce(function(desc, decorator) {\n return decorator(target, property, desc) || desc;\n }, desc);\n\n if (context && desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(context) : void 0;\n desc.initializer = undefined;\n }\n\n if (desc.initializer === void 0) {\n Object.defineProperty(target, property, desc);\n desc = null;\n }\n\n return desc;\n }\n\n var id = 0;\n\n function _classPrivateFieldLooseKey(name) {\n return '__private_' + id++ + '_' + name;\n }\n\n function _classPrivateFieldLooseBase(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError('attempted to use private field on non-instance');\n }\n\n return receiver;\n }\n\n function _classPrivateFieldGet(receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n }\n\n function _classPrivateFieldSet(receiver, privateMap, value) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n }\n\n return value;\n }\n\n function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return descriptor.value;\n }\n\n function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n return value;\n }\n\n function _classStaticPrivateMethodGet(receiver, classConstructor, method) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return method;\n }\n\n function _classStaticPrivateMethodSet() {\n throw new TypeError('attempted to set read only static private field');\n }\n\n function _decorate(decorators, factory, superClass, mixins) {\n var api = _getDecoratorsApi();\n\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators\n );\n api.initializeClassElements(r.F, decorated.elements);\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [['method'], ['field']],\n initializeInstanceElements: function(O, elements) {\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n if (element.kind === kind && element.placement === 'own') {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n initializeClassElements: function(F, elements) {\n var proto = F.prototype;\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n var placement = element.placement;\n\n if (\n element.kind === kind &&\n (placement === 'static' || placement === 'prototype')\n ) {\n var receiver = placement === 'static' ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n defineClassElement: function(receiver, element) {\n var descriptor = element.descriptor;\n\n if (element.kind === 'field') {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver),\n };\n }\n\n Object.defineProperty(receiver, element.key, descriptor);\n },\n decorateClass: function(elements, decorators) {\n var newElements = [];\n var finishers = [];\n var placements = {\n static: [],\n prototype: [],\n own: [],\n };\n elements.forEach(function(element) {\n this.addElementPlacement(element, placements);\n }, this);\n elements.forEach(function(element) {\n if (!_hasDecorators(element)) return newElements.push(element);\n var elementFinishersExtras = this.decorateElement(element, placements);\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return {\n elements: newElements,\n finishers: finishers,\n };\n }\n\n var result = this.decorateConstructor(newElements, decorators);\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n return result;\n },\n addElementPlacement: function(element, placements, silent) {\n var keys = placements[element.placement];\n\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError('Duplicated element (' + element.key + ')');\n }\n\n keys.push(element.key);\n },\n decorateElement: function(element, placements) {\n var extras = [];\n var finishers = [];\n\n for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n var elementObject = this.fromElementDescriptor(element);\n var elementFinisherExtras = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) || elementObject\n );\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras = elementFinisherExtras.extras;\n\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n\n extras.push.apply(extras, newExtras);\n }\n }\n\n return {\n element: element,\n finishers: finishers,\n extras: extras,\n };\n },\n decorateConstructor: function(elements, decorators) {\n var finishers = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj = this.fromClassDescriptor(elements);\n var elementsAndFinisher = this.toClassDescriptor(\n (0, decorators[i])(obj) || obj\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n 'Duplicated element (' + elements[j].key + ')'\n );\n }\n }\n }\n }\n }\n\n return {\n elements: elements,\n finishers: finishers,\n };\n },\n fromElementDescriptor: function(element) {\n var obj = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor,\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n if (element.kind === 'field') obj.initializer = element.initializer;\n return obj;\n },\n toElementDescriptors: function(elementObjects) {\n if (elementObjects === undefined) return;\n return _toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(elementObject, 'finisher', 'An element descriptor');\n this.disallowProperty(elementObject, 'extras', 'An element descriptor');\n return element;\n }, this);\n },\n toElementDescriptor: function(elementObject) {\n var kind = String(elementObject.kind);\n\n if (kind !== 'method' && kind !== 'field') {\n throw new TypeError(\n 'An element descriptor\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"'\n );\n }\n\n var key = _toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n\n if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') {\n throw new TypeError(\n 'An element descriptor\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"'\n );\n }\n\n var descriptor = elementObject.descriptor;\n this.disallowProperty(elementObject, 'elements', 'An element descriptor');\n var element = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor),\n };\n\n if (kind !== 'field') {\n this.disallowProperty(elementObject, 'initializer', 'A method descriptor');\n } else {\n this.disallowProperty(\n descriptor,\n 'get',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'set',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'value',\n 'The property descriptor of a field descriptor'\n );\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n toElementFinisherExtras: function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n\n var finisher = _optionalCallableProperty(elementObject, 'finisher');\n\n var extras = this.toElementDescriptors(elementObject.extras);\n return {\n element: element,\n finisher: finisher,\n extras: extras,\n };\n },\n fromClassDescriptor: function(elements) {\n var obj = {\n kind: 'class',\n elements: elements.map(this.fromElementDescriptor, this),\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n return obj;\n },\n toClassDescriptor: function(obj) {\n var kind = String(obj.kind);\n\n if (kind !== 'class') {\n throw new TypeError(\n 'A class descriptor\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"'\n );\n }\n\n this.disallowProperty(obj, 'key', 'A class descriptor');\n this.disallowProperty(obj, 'placement', 'A class descriptor');\n this.disallowProperty(obj, 'descriptor', 'A class descriptor');\n this.disallowProperty(obj, 'initializer', 'A class descriptor');\n this.disallowProperty(obj, 'extras', 'A class descriptor');\n\n var finisher = _optionalCallableProperty(obj, 'finisher');\n\n var elements = this.toElementDescriptors(obj.elements);\n return {\n elements: elements,\n finisher: finisher,\n };\n },\n runClassFinishers: function(constructor, finishers) {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor = (0, finishers[i])(constructor);\n\n if (newConstructor !== undefined) {\n if (typeof newConstructor !== 'function') {\n throw new TypeError('Finishers must return a constructor.');\n }\n\n constructor = newConstructor;\n }\n }\n\n return constructor;\n },\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(objectType + \" can't have a .\" + name + ' property.');\n }\n },\n };\n return api;\n }\n\n function _createElementDescriptor(def) {\n var key = _toPropertyKey(def.key);\n\n var descriptor;\n\n if (def.kind === 'method') {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'get') {\n descriptor = {\n get: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'set') {\n descriptor = {\n set: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'field') {\n descriptor = {\n configurable: true,\n writable: true,\n enumerable: true,\n };\n }\n\n var element = {\n kind: def.kind === 'field' ? 'field' : 'method',\n key: key,\n placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype',\n descriptor: descriptor,\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === 'field') element.initializer = def.value;\n return element;\n }\n\n function _coalesceGetterSetter(element, other) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n function _coalesceClassElements(elements) {\n var newElements = [];\n\n var isSameElement = function(other) {\n return (\n other.kind === 'method' &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var other;\n\n if (element.kind === 'method' && (other = newElements.find(isSameElement))) {\n if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n 'Duplicated methods (' + element.key + \") can't be decorated.\"\n );\n }\n\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n 'the same property (' +\n element.key +\n ').'\n );\n }\n\n other.decorators = element.decorators;\n }\n\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element) {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc) {\n return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);\n }\n\n function _optionalCallableProperty(obj, name) {\n var value = obj[name];\n\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n\n return value;\n }\n\n function _classPrivateMethodGet(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n return fn;\n }\n\n function _classPrivateMethodSet() {\n throw new TypeError('attempted to reassign private method');\n }\n\n function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, groups);\n };\n\n var _RegExp = _wrapNativeSuper(RegExp);\n\n var _super = RegExp.prototype;\n\n var _groups = new WeakMap();\n\n function BabelRegExp(re, groups) {\n var _this = _RegExp.call(this, re);\n\n _groups.set(_this, groups);\n\n return _this;\n }\n\n _inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === 'string') {\n var groups = _groups.get(this);\n\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function(_, name) {\n return '$' + groups[name];\n })\n );\n } else if (typeof substitution === 'function') {\n var _this = this;\n\n return _super[Symbol.replace].call(this, str, function() {\n var args = [];\n args.push.apply(args, arguments);\n\n if (typeof args[args.length - 1] !== 'object') {\n args.push(buildGroups(args, _this));\n }\n\n return substitution.apply(this, args);\n });\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n };\n\n function buildGroups(result, re) {\n var g = _groups.get(re);\n\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n\n var MARKUP_RECT = ['x', 'y', 'left', 'top', 'right', 'bottom', 'width', 'height'];\n\n var toOptionalFraction = function toOptionalFraction(value) {\n return typeof value === 'string' && /%/.test(value) ? parseFloat(value) / 100 : value;\n };\n\n // adds default markup properties, clones markup\n var prepareMarkup = function prepareMarkup(markup) {\n var _markup = _slicedToArray(markup, 2),\n type = _markup[0],\n props = _markup[1];\n\n var rect = props.points\n ? {}\n : MARKUP_RECT.reduce(function(prev, curr) {\n prev[curr] = toOptionalFraction(props[curr]);\n return prev;\n }, {});\n\n return [\n type,\n Object.assign(\n {\n zIndex: 0,\n },\n props,\n rect\n ),\n ];\n };\n\n var getImageSize = function getImageSize(file) {\n return new Promise(function(resolve, reject) {\n var imageElement = new Image();\n imageElement.src = URL.createObjectURL(file);\n\n // start testing size\n var measure = function measure() {\n var width = imageElement.naturalWidth;\n var height = imageElement.naturalHeight;\n var hasSize = width && height;\n if (!hasSize) return;\n\n URL.revokeObjectURL(imageElement.src);\n clearInterval(intervalId);\n resolve({ width: width, height: height });\n };\n\n imageElement.onerror = function(err) {\n URL.revokeObjectURL(imageElement.src);\n clearInterval(intervalId);\n reject(err);\n };\n\n var intervalId = setInterval(measure, 1);\n\n measure();\n });\n };\n\n /**\n * Polyfill Edge and IE when in Browser\n */\n if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {\n if (!HTMLCanvasElement.prototype.toBlob) {\n Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {\n value: function value(cb, type, quality) {\n var canvas = this;\n setTimeout(function() {\n var dataURL = canvas.toDataURL(type, quality).split(',')[1];\n var binStr = atob(dataURL);\n var index = binStr.length;\n var data = new Uint8Array(index);\n while (index--) {\n data[index] = binStr.charCodeAt(index);\n }\n cb(new Blob([data], { type: type || 'image/png' }));\n });\n },\n });\n }\n }\n\n var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n var isIOS = isBrowser && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;\n\n /**\n * Image Transform Plugin\n */\n var plugin = function plugin(_ref) {\n var addFilter = _ref.addFilter,\n utils = _ref.utils;\n var Type = utils.Type,\n forin = utils.forin,\n getFileFromBlob = utils.getFileFromBlob,\n isFile = utils.isFile;\n\n /**\n * Helper functions\n */\n\n // valid transforms (in correct order)\n var TRANSFORM_LIST = ['crop', 'resize', 'filter', 'markup', 'output'];\n\n var createVariantCreator = function createVariantCreator(updateMetadata) {\n return function(transform, file, metadata) {\n return transform(file, updateMetadata ? updateMetadata(metadata) : metadata);\n };\n };\n\n var isDefaultCrop = function isDefaultCrop(crop) {\n return (\n crop.aspectRatio === null &&\n crop.rotation === 0 &&\n crop.zoom === 1 &&\n crop.center &&\n crop.center.x === 0.5 &&\n crop.center.y === 0.5 &&\n crop.flip &&\n crop.flip.horizontal === false &&\n crop.flip.vertical === false\n );\n };\n\n /**\n * Filters\n */\n addFilter('SHOULD_PREPARE_OUTPUT', function(shouldPrepareOutput, _ref2) {\n var query = _ref2.query;\n return new Promise(function(resolve) {\n // If is not async should prepare now\n resolve(!query('IS_ASYNC'));\n });\n });\n\n var shouldTransformFile = function shouldTransformFile(query, file, item) {\n return new Promise(function(resolve) {\n if (\n !query('GET_ALLOW_IMAGE_TRANSFORM') ||\n item.archived ||\n !isFile(file) ||\n !isImage(file)\n ) {\n return resolve(false);\n }\n\n // if size can't be read this browser doesn't support image\n getImageSize(file)\n .then(function() {\n var fn = query('GET_IMAGE_TRANSFORM_IMAGE_FILTER');\n if (fn) {\n var filterResult = fn(file);\n if (filterResult == null) {\n // undefined or null\n return handleRevert(true);\n }\n if (typeof filterResult === 'boolean') {\n return resolve(filterResult);\n }\n if (typeof filterResult.then === 'function') {\n return filterResult.then(resolve);\n }\n }\n\n resolve(true);\n })\n .catch(function(err) {\n resolve(false);\n });\n });\n };\n\n addFilter('DID_CREATE_ITEM', function(item, _ref3) {\n var query = _ref3.query,\n dispatch = _ref3.dispatch;\n if (!query('GET_ALLOW_IMAGE_TRANSFORM')) return;\n\n item.extend('requestPrepare', function() {\n return new Promise(function(resolve, reject) {\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: item.id,\n item: item,\n success: resolve,\n failure: reject,\n },\n\n true\n );\n });\n });\n });\n\n // subscribe to file transformations\n addFilter('PREPARE_OUTPUT', function(file, _ref4) {\n var query = _ref4.query,\n item = _ref4.item;\n return new Promise(function(resolve) {\n shouldTransformFile(query, file, item).then(function(shouldTransform) {\n // no need to transform, exit\n if (!shouldTransform) return resolve(file);\n\n // get variants\n var variants = [];\n\n // add original file\n if (query('GET_IMAGE_TRANSFORM_VARIANTS_INCLUDE_ORIGINAL')) {\n variants.push(function() {\n return new Promise(function(resolve) {\n resolve({\n name: query('GET_IMAGE_TRANSFORM_VARIANTS_ORIGINAL_NAME'),\n file: file,\n });\n });\n });\n }\n\n // add default output version if output default set to true or if no variants defined\n if (query('GET_IMAGE_TRANSFORM_VARIANTS_INCLUDE_DEFAULT')) {\n variants.push(function(transform, file, metadata) {\n return new Promise(function(resolve) {\n transform(file, metadata).then(function(file) {\n return resolve({\n name: query('GET_IMAGE_TRANSFORM_VARIANTS_DEFAULT_NAME'),\n\n file: file,\n });\n });\n });\n });\n }\n\n // get other variants\n var variantsDefinition = query('GET_IMAGE_TRANSFORM_VARIANTS') || {};\n forin(variantsDefinition, function(key, fn) {\n var createVariant = createVariantCreator(fn);\n variants.push(function(transform, file, metadata) {\n return new Promise(function(resolve) {\n createVariant(transform, file, metadata).then(function(file) {\n return resolve({ name: key, file: file });\n });\n });\n });\n });\n\n // output format (quality 0 => 100)\n var qualityAsPercentage = query('GET_IMAGE_TRANSFORM_OUTPUT_QUALITY');\n var qualityMode = query('GET_IMAGE_TRANSFORM_OUTPUT_QUALITY_MODE');\n var quality = qualityAsPercentage === null ? null : qualityAsPercentage / 100;\n var type = query('GET_IMAGE_TRANSFORM_OUTPUT_MIME_TYPE');\n var clientTransforms =\n query('GET_IMAGE_TRANSFORM_CLIENT_TRANSFORMS') || TRANSFORM_LIST;\n\n // update transform metadata object\n item.setMetadata(\n 'output',\n {\n type: type,\n quality: quality,\n client: clientTransforms,\n },\n\n true\n );\n\n // the function that is used to apply the file transformations\n var transform = function transform(file, metadata) {\n return new Promise(function(resolve, reject) {\n var filteredMetadata = Object.assign({}, metadata);\n\n Object.keys(filteredMetadata)\n .filter(function(instruction) {\n return instruction !== 'exif';\n })\n .forEach(function(instruction) {\n // if not in list, remove from object, the instruction will be handled by the server\n if (clientTransforms.indexOf(instruction) === -1) {\n delete filteredMetadata[instruction];\n }\n });\n var resize = filteredMetadata.resize,\n exif = filteredMetadata.exif,\n output = filteredMetadata.output,\n crop = filteredMetadata.crop,\n filter = filteredMetadata.filter,\n markup = filteredMetadata.markup;\n\n var instructions = {\n image: {\n orientation: exif ? exif.orientation : null,\n },\n\n output:\n output &&\n (output.type ||\n typeof output.quality === 'number' ||\n output.background)\n ? {\n type: output.type,\n quality:\n typeof output.quality === 'number'\n ? output.quality * 100\n : null,\n background:\n output.background ||\n query(\n 'GET_IMAGE_TRANSFORM_CANVAS_BACKGROUND_COLOR'\n ) ||\n null,\n }\n : undefined,\n size:\n resize && (resize.size.width || resize.size.height)\n ? Object.assign(\n {\n mode: resize.mode,\n upscale: resize.upscale,\n },\n resize.size\n )\n : undefined,\n crop:\n crop && !isDefaultCrop(crop)\n ? Object.assign(\n {},\n\n crop\n )\n : undefined,\n markup: markup && markup.length ? markup.map(prepareMarkup) : [],\n filter: filter,\n };\n\n if (instructions.output) {\n // determine if file type will change\n var willChangeType = output.type\n ? // type set\n output.type !== file.type\n : // type not set\n false;\n\n var canChangeQuality = /\\/jpe?g$/.test(file.type);\n var willChangeQuality =\n output.quality !== null\n ? // quality set\n canChangeQuality && qualityMode === 'always'\n : // quality not set\n false;\n\n // determine if file data will be modified\n var willModifyImageData = !!(\n instructions.size ||\n instructions.crop ||\n instructions.filter ||\n willChangeType ||\n willChangeQuality\n );\n\n // if we're not modifying the image data then we don't have to modify the output\n if (!willModifyImageData) return resolve(file);\n }\n\n var options = {\n beforeCreateBlob: query('GET_IMAGE_TRANSFORM_BEFORE_CREATE_BLOB'),\n afterCreateBlob: query('GET_IMAGE_TRANSFORM_AFTER_CREATE_BLOB'),\n canvasMemoryLimit: query('GET_IMAGE_TRANSFORM_CANVAS_MEMORY_LIMIT'),\n stripImageHead: query(\n 'GET_IMAGE_TRANSFORM_OUTPUT_STRIP_IMAGE_HEAD'\n ),\n };\n\n transformImage(file, instructions, options)\n .then(function(blob) {\n // set file object\n var out = getFileFromBlob(\n blob,\n // rename the original filename to match the mime type of the output image\n renameFileToMatchMimeType(\n file.name,\n getValidOutputMimeType(blob.type)\n )\n );\n\n resolve(out);\n })\n .catch(reject);\n });\n };\n\n // start creating variants\n var variantPromises = variants.map(function(create) {\n return create(transform, file, item.getMetadata());\n });\n\n // wait for results\n Promise.all(variantPromises).then(function(files) {\n // if single file object in array, return the single file object else, return array of\n resolve(\n files.length === 1 && files[0].name === null\n ? // return the File object\n files[0].file\n : // return an array of files { name:'name', file:File }\n files\n );\n });\n });\n });\n });\n\n // Expose plugin options\n return {\n options: {\n allowImageTransform: [true, Type.BOOLEAN],\n\n // filter images to transform\n imageTransformImageFilter: [null, Type.FUNCTION],\n\n // null, 'image/jpeg', 'image/png'\n imageTransformOutputMimeType: [null, Type.STRING],\n\n // null, 0 - 100\n imageTransformOutputQuality: [null, Type.INT],\n\n // set to false to copy image exif data to output\n imageTransformOutputStripImageHead: [true, Type.BOOLEAN],\n\n // only apply transforms in this list\n imageTransformClientTransforms: [null, Type.ARRAY],\n\n // only apply output quality when a transform is required\n imageTransformOutputQualityMode: ['always', Type.STRING],\n // 'always'\n // 'optional'\n // 'mismatch' (future feature, only applied if quality differs from input)\n\n // get image transform variants\n imageTransformVariants: [null, Type.OBJECT],\n\n // should we post the default transformed file\n imageTransformVariantsIncludeDefault: [true, Type.BOOLEAN],\n\n // which name to prefix the default transformed file with\n imageTransformVariantsDefaultName: [null, Type.STRING],\n\n // should we post the original file\n imageTransformVariantsIncludeOriginal: [false, Type.BOOLEAN],\n\n // which name to prefix the original file with\n imageTransformVariantsOriginalName: ['original_', Type.STRING],\n\n // called before creating the blob, receives canvas, expects promise resolve with canvas\n imageTransformBeforeCreateBlob: [null, Type.FUNCTION],\n\n // expects promise resolved with blob\n imageTransformAfterCreateBlob: [null, Type.FUNCTION],\n\n // canvas memory limit\n imageTransformCanvasMemoryLimit: [\n isBrowser && isIOS ? 4096 * 4096 : null,\n Type.INT,\n ],\n\n // background image of the output canvas\n imageTransformCanvasBackgroundColor: [null, Type.STRING],\n },\n };\n };\n\n // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags\n if (isBrowser) {\n document.dispatchEvent(new CustomEvent('FilePond:pluginloaded', { detail: plugin }));\n }\n\n return plugin;\n});\n","var bind = require('../internals/function-bind-context');\nvar call = require('../internals/function-call');\nvar aConstructor = require('../internals/a-constructor');\nvar toObject = require('../internals/to-object');\nvar lengthOfArrayLike = require('../internals/length-of-array-like');\nvar getIterator = require('../internals/get-iterator');\nvar getIteratorMethod = require('../internals/get-iterator-method');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar isBigIntArray = require('../internals/is-big-int-array');\nvar aTypedArrayConstructor = require('../internals/array-buffer-view-core').aTypedArrayConstructor;\nvar toBigInt = require('../internals/to-big-int');\n\nmodule.exports = function from(source /* , mapfn, thisArg */) {\n var C = aConstructor(this);\n var O = toObject(source);\n var argumentsLength = arguments.length;\n var mapfn = argumentsLength > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iteratorMethod = getIteratorMethod(O);\n var i, length, result, thisIsBigIntArray, value, step, iterator, next;\n if (iteratorMethod && !isArrayIteratorMethod(iteratorMethod)) {\n iterator = getIterator(O, iteratorMethod);\n next = iterator.next;\n O = [];\n while (!(step = call(next, iterator)).done) {\n O.push(step.value);\n }\n }\n if (mapping && argumentsLength > 2) {\n mapfn = bind(mapfn, arguments[2]);\n }\n length = lengthOfArrayLike(O);\n result = new (aTypedArrayConstructor(C))(length);\n thisIsBigIntArray = isBigIntArray(result);\n for (i = 0; length > i; i++) {\n value = mapping ? mapfn(O[i], i) : O[i];\n // FF30- typed arrays doesn't properly convert objects to typed array values\n result[i] = thisIsBigIntArray ? toBigInt(value) : +value;\n }\n return result;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar uncurryThis = require('../internals/function-uncurry-this');\nvar IndexedObject = require('../internals/indexed-object');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\n\nvar nativeJoin = uncurryThis([].join);\n\nvar ES3_STRINGS = IndexedObject != Object;\nvar STRICT_METHOD = arrayMethodIsStrict('join', ',');\n\n// `Array.prototype.join` method\n// https://tc39.es/ecma262/#sec-array.prototype.join\n$({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD }, {\n join: function join(separator) {\n return nativeJoin(toIndexedObject(this), separator === undefined ? ',' : separator);\n }\n});\n","var bind = require('../internals/function-bind-context');\nvar IndexedObject = require('../internals/indexed-object');\nvar toObject = require('../internals/to-object');\nvar lengthOfArrayLike = require('../internals/length-of-array-like');\n\n// `Array.prototype.{ findLast, findLastIndex }` methods implementation\nvar createMethod = function (TYPE) {\n var IS_FIND_LAST_INDEX = TYPE == 1;\n return function ($this, callbackfn, that) {\n var O = toObject($this);\n var self = IndexedObject(O);\n var boundFunction = bind(callbackfn, that);\n var index = lengthOfArrayLike(self);\n var value, result;\n while (index-- > 0) {\n value = self[index];\n result = boundFunction(value, index, O);\n if (result) switch (TYPE) {\n case 0: return value; // findLast\n case 1: return index; // findLastIndex\n }\n }\n return IS_FIND_LAST_INDEX ? -1 : undefined;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.findLast` method\n // https://github.com/tc39/proposal-array-find-from-last\n findLast: createMethod(0),\n // `Array.prototype.findLastIndex` method\n // https://github.com/tc39/proposal-array-find-from-last\n findLastIndex: createMethod(1)\n};\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $every = require('../internals/array-iteration').every;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.every` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.every\nexportTypedArrayMethod('every', function every(callbackfn /* , thisArg */) {\n return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar anObject = require('../internals/an-object');\nvar create = require('../internals/object-create');\nvar normalizeStringArgument = require('../internals/normalize-string-argument');\n\nvar nativeErrorToString = Error.prototype.toString;\n\nvar INCORRECT_TO_STRING = fails(function () {\n if (DESCRIPTORS) {\n // Chrome 32- incorrectly call accessor\n // eslint-disable-next-line es/no-object-defineproperty -- safe\n var object = create(Object.defineProperty({}, 'name', { get: function () {\n return this === object;\n } }));\n if (nativeErrorToString.call(object) !== 'true') return true;\n }\n // FF10- does not properly handle non-strings\n return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1'\n // IE8 does not properly handle defaults\n || nativeErrorToString.call({}) !== 'Error';\n});\n\nmodule.exports = INCORRECT_TO_STRING ? function toString() {\n var O = anObject(this);\n var name = normalizeStringArgument(O.name, 'Error');\n var message = normalizeStringArgument(O.message);\n return !name ? message : !message ? name : name + ': ' + message;\n} : nativeErrorToString;\n","'use strict';\nvar $ = require('../internals/export');\nvar uncurryThis = require('../internals/function-uncurry-this');\nvar fails = require('../internals/fails');\nvar ArrayBufferModule = require('../internals/array-buffer');\nvar anObject = require('../internals/an-object');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\nvar speciesConstructor = require('../internals/species-constructor');\n\nvar ArrayBuffer = ArrayBufferModule.ArrayBuffer;\nvar DataView = ArrayBufferModule.DataView;\nvar DataViewPrototype = DataView.prototype;\nvar nativeArrayBufferSlice = uncurryThis(ArrayBuffer.prototype.slice);\nvar getUint8 = uncurryThis(DataViewPrototype.getUint8);\nvar setUint8 = uncurryThis(DataViewPrototype.setUint8);\n\nvar INCORRECT_SLICE = fails(function () {\n return !new ArrayBuffer(2).slice(1, undefined).byteLength;\n});\n\n// `ArrayBuffer.prototype.slice` method\n// https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice\n$({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, {\n slice: function slice(start, end) {\n if (nativeArrayBufferSlice && end === undefined) {\n return nativeArrayBufferSlice(anObject(this), start); // FF fix\n }\n var length = anObject(this).byteLength;\n var first = toAbsoluteIndex(start, length);\n var fin = toAbsoluteIndex(end === undefined ? length : end, length);\n var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first));\n var viewSource = new DataView(this);\n var viewTarget = new DataView(result);\n var index = 0;\n while (first < fin) {\n setUint8(viewTarget, index++, getUint8(viewSource, first++));\n } return result;\n }\n});\n","'use strict';\nvar global = require('../internals/global');\nvar apply = require('../internals/function-apply');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar fails = require('../internals/fails');\nvar arraySlice = require('../internals/array-slice');\n\nvar Int8Array = global.Int8Array;\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar $toLocaleString = [].toLocaleString;\n\n// iOS Safari 6.x fails here\nvar TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {\n $toLocaleString.call(new Int8Array(1));\n});\n\nvar FORCED = fails(function () {\n return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();\n}) || !fails(function () {\n Int8Array.prototype.toLocaleString.call([1, 2]);\n});\n\n// `%TypedArray%.prototype.toLocaleString` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring\nexportTypedArrayMethod('toLocaleString', function toLocaleString() {\n return apply(\n $toLocaleString,\n TO_LOCALE_STRING_BUG ? arraySlice(aTypedArray(this)) : aTypedArray(this),\n arraySlice(arguments)\n );\n}, FORCED);\n","var ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar speciesConstructor = require('../internals/species-constructor');\n\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar getTypedArrayConstructor = ArrayBufferViewCore.getTypedArrayConstructor;\n\n// a part of `TypedArraySpeciesCreate` abstract operation\n// https://tc39.es/ecma262/#typedarray-species-create\nmodule.exports = function (originalArray) {\n return aTypedArrayConstructor(speciesConstructor(originalArray, getTypedArrayConstructor(originalArray)));\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar defineProperty = require('../internals/object-define-property').f;\nvar hasOwn = require('../internals/has-own-property');\nvar anInstance = require('../internals/an-instance');\nvar inheritIfRequired = require('../internals/inherit-if-required');\nvar normalizeStringArgument = require('../internals/normalize-string-argument');\nvar DOMExceptionConstants = require('../internals/dom-exception-constants');\nvar clearErrorStack = require('../internals/error-stack-clear');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar IS_PURE = require('../internals/is-pure');\n\nvar DOM_EXCEPTION = 'DOMException';\nvar Error = getBuiltIn('Error');\nvar NativeDOMException = getBuiltIn(DOM_EXCEPTION);\n\nvar $DOMException = function DOMException() {\n anInstance(this, DOMExceptionPrototype);\n var argumentsLength = arguments.length;\n var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);\n var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');\n var that = new NativeDOMException(message, name);\n var error = Error(message);\n error.name = DOM_EXCEPTION;\n defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));\n inheritIfRequired(that, this, $DOMException);\n return that;\n};\n\nvar DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;\n\nvar ERROR_HAS_STACK = 'stack' in Error(DOM_EXCEPTION);\nvar DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);\n\n// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe\nvar descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(global, DOM_EXCEPTION);\n\n// Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it\n// https://github.com/Jarred-Sumner/bun/issues/399\nvar BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);\n\nvar FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;\n\n// `DOMException` constructor patch for `.stack` where it's required\n// https://webidl.spec.whatwg.org/#es-DOMException-specialness\n$({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic\n DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException\n});\n\nvar PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);\nvar PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;\n\nif (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {\n if (!IS_PURE) {\n defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));\n }\n\n for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {\n var constant = DOMExceptionConstants[key];\n var constantName = constant.s;\n if (!hasOwn(PolyfilledDOMException, constantName)) {\n defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));\n }\n }\n}\n","var itoc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar ctoi = {};\n\nfor (var index = 0; index < 66; index++) ctoi[itoc.charAt(index)] = index;\n\nmodule.exports = {\n itoc: itoc,\n ctoi: ctoi\n};\n","var classof = require('../internals/classof');\nvar uncurryThis = require('../internals/function-uncurry-this');\n\nvar slice = uncurryThis(''.slice);\n\nmodule.exports = function (it) {\n return slice(classof(it), 0, 3) === 'Big';\n};\n","/*!\n * FilePond 4.30.4\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? factory(exports)\n : typeof define === 'function' && define.amd\n ? define(['exports'], factory)\n : ((global = global || self), factory((global.FilePond = {})));\n})(this, function(exports) {\n 'use strict';\n\n var isNode = function isNode(value) {\n return value instanceof HTMLElement;\n };\n\n var createStore = function createStore(initialState) {\n var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var actions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];\n // internal state\n var state = Object.assign({}, initialState);\n\n // contains all actions for next frame, is clear when actions are requested\n var actionQueue = [];\n var dispatchQueue = [];\n\n // returns a duplicate of the current state\n var getState = function getState() {\n return Object.assign({}, state);\n };\n\n // returns a duplicate of the actions array and clears the actions array\n var processActionQueue = function processActionQueue() {\n // create copy of actions queue\n var queue = [].concat(actionQueue);\n\n // clear actions queue (we don't want no double actions)\n actionQueue.length = 0;\n\n return queue;\n };\n\n // processes actions that might block the main UI thread\n var processDispatchQueue = function processDispatchQueue() {\n // create copy of actions queue\n var queue = [].concat(dispatchQueue);\n\n // clear actions queue (we don't want no double actions)\n dispatchQueue.length = 0;\n\n // now dispatch these actions\n queue.forEach(function(_ref) {\n var type = _ref.type,\n data = _ref.data;\n dispatch(type, data);\n });\n };\n\n // adds a new action, calls its handler and\n var dispatch = function dispatch(type, data, isBlocking) {\n // is blocking action (should never block if document is hidden)\n if (isBlocking && !document.hidden) {\n dispatchQueue.push({ type: type, data: data });\n return;\n }\n\n // if this action has a handler, handle the action\n if (actionHandlers[type]) {\n actionHandlers[type](data);\n }\n\n // now add action\n actionQueue.push({\n type: type,\n data: data,\n });\n };\n\n var query = function query(str) {\n var _queryHandles;\n for (\n var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n args[_key - 1] = arguments[_key];\n }\n return queryHandles[str]\n ? (_queryHandles = queryHandles)[str].apply(_queryHandles, args)\n : null;\n };\n\n var api = {\n getState: getState,\n processActionQueue: processActionQueue,\n processDispatchQueue: processDispatchQueue,\n dispatch: dispatch,\n query: query,\n };\n\n var queryHandles = {};\n queries.forEach(function(query) {\n queryHandles = Object.assign({}, query(state), {}, queryHandles);\n });\n\n var actionHandlers = {};\n actions.forEach(function(action) {\n actionHandlers = Object.assign({}, action(dispatch, query, state), {}, actionHandlers);\n });\n\n return api;\n };\n\n var defineProperty = function defineProperty(obj, property, definition) {\n if (typeof definition === 'function') {\n obj[property] = definition;\n return;\n }\n Object.defineProperty(obj, property, Object.assign({}, definition));\n };\n\n var forin = function forin(obj, cb) {\n for (var key in obj) {\n if (!obj.hasOwnProperty(key)) {\n continue;\n }\n\n cb(key, obj[key]);\n }\n };\n\n var createObject = function createObject(definition) {\n var obj = {};\n forin(definition, function(property) {\n defineProperty(obj, property, definition[property]);\n });\n return obj;\n };\n\n var attr = function attr(node, name) {\n var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n if (value === null) {\n return node.getAttribute(name) || node.hasAttribute(name);\n }\n node.setAttribute(name, value);\n };\n\n var ns = 'http://www.w3.org/2000/svg';\n var svgElements = ['svg', 'path']; // only svg elements used\n\n var isSVGElement = function isSVGElement(tag) {\n return svgElements.includes(tag);\n };\n\n var createElement = function createElement(tag, className) {\n var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (typeof className === 'object') {\n attributes = className;\n className = null;\n }\n var element = isSVGElement(tag)\n ? document.createElementNS(ns, tag)\n : document.createElement(tag);\n if (className) {\n if (isSVGElement(tag)) {\n attr(element, 'class', className);\n } else {\n element.className = className;\n }\n }\n forin(attributes, function(name, value) {\n attr(element, name, value);\n });\n return element;\n };\n\n var appendChild = function appendChild(parent) {\n return function(child, index) {\n if (typeof index !== 'undefined' && parent.children[index]) {\n parent.insertBefore(child, parent.children[index]);\n } else {\n parent.appendChild(child);\n }\n };\n };\n\n var appendChildView = function appendChildView(parent, childViews) {\n return function(view, index) {\n if (typeof index !== 'undefined') {\n childViews.splice(index, 0, view);\n } else {\n childViews.push(view);\n }\n\n return view;\n };\n };\n\n var removeChildView = function removeChildView(parent, childViews) {\n return function(view) {\n // remove from child views\n childViews.splice(childViews.indexOf(view), 1);\n\n // remove the element\n if (view.element.parentNode) {\n parent.removeChild(view.element);\n }\n\n return view;\n };\n };\n\n var IS_BROWSER = (function() {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n })();\n var isBrowser = function isBrowser() {\n return IS_BROWSER;\n };\n\n var testElement = isBrowser() ? createElement('svg') : {};\n var getChildCount =\n 'children' in testElement\n ? function(el) {\n return el.children.length;\n }\n : function(el) {\n return el.childNodes.length;\n };\n\n var getViewRect = function getViewRect(elementRect, childViews, offset, scale) {\n var left = offset[0] || elementRect.left;\n var top = offset[1] || elementRect.top;\n var right = left + elementRect.width;\n var bottom = top + elementRect.height * (scale[1] || 1);\n\n var rect = {\n // the rectangle of the element itself\n element: Object.assign({}, elementRect),\n\n // the rectangle of the element expanded to contain its children, does not include any margins\n inner: {\n left: elementRect.left,\n top: elementRect.top,\n right: elementRect.right,\n bottom: elementRect.bottom,\n },\n\n // the rectangle of the element expanded to contain its children including own margin and child margins\n // margins will be added after we've recalculated the size\n outer: {\n left: left,\n top: top,\n right: right,\n bottom: bottom,\n },\n };\n\n // expand rect to fit all child rectangles\n childViews\n .filter(function(childView) {\n return !childView.isRectIgnored();\n })\n .map(function(childView) {\n return childView.rect;\n })\n .forEach(function(childViewRect) {\n expandRect(rect.inner, Object.assign({}, childViewRect.inner));\n expandRect(rect.outer, Object.assign({}, childViewRect.outer));\n });\n\n // calculate inner width and height\n calculateRectSize(rect.inner);\n\n // append additional margin (top and left margins are included in top and left automatically)\n rect.outer.bottom += rect.element.marginBottom;\n rect.outer.right += rect.element.marginRight;\n\n // calculate outer width and height\n calculateRectSize(rect.outer);\n\n return rect;\n };\n\n var expandRect = function expandRect(parent, child) {\n // adjust for parent offset\n child.top += parent.top;\n child.right += parent.left;\n child.bottom += parent.top;\n child.left += parent.left;\n\n if (child.bottom > parent.bottom) {\n parent.bottom = child.bottom;\n }\n\n if (child.right > parent.right) {\n parent.right = child.right;\n }\n };\n\n var calculateRectSize = function calculateRectSize(rect) {\n rect.width = rect.right - rect.left;\n rect.height = rect.bottom - rect.top;\n };\n\n var isNumber = function isNumber(value) {\n return typeof value === 'number';\n };\n\n /**\n * Determines if position is at destination\n * @param position\n * @param destination\n * @param velocity\n * @param errorMargin\n * @returns {boolean}\n */\n var thereYet = function thereYet(position, destination, velocity) {\n var errorMargin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.001;\n return Math.abs(position - destination) < errorMargin && Math.abs(velocity) < errorMargin;\n };\n\n /**\n * Spring animation\n */\n var spring =\n // default options\n function spring() // method definition\n {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$stiffness = _ref.stiffness,\n stiffness = _ref$stiffness === void 0 ? 0.5 : _ref$stiffness,\n _ref$damping = _ref.damping,\n damping = _ref$damping === void 0 ? 0.75 : _ref$damping,\n _ref$mass = _ref.mass,\n mass = _ref$mass === void 0 ? 10 : _ref$mass;\n var target = null;\n var position = null;\n var velocity = 0;\n var resting = false;\n\n // updates spring state\n var interpolate = function interpolate(ts, skipToEndState) {\n // in rest, don't animate\n if (resting) return;\n\n // need at least a target or position to do springy things\n if (!(isNumber(target) && isNumber(position))) {\n resting = true;\n velocity = 0;\n return;\n }\n\n // calculate spring force\n var f = -(position - target) * stiffness;\n\n // update velocity by adding force based on mass\n velocity += f / mass;\n\n // update position by adding velocity\n position += velocity;\n\n // slow down based on amount of damping\n velocity *= damping;\n\n // we've arrived if we're near target and our velocity is near zero\n if (thereYet(position, target, velocity) || skipToEndState) {\n position = target;\n velocity = 0;\n resting = true;\n\n // we done\n api.onupdate(position);\n api.oncomplete(position);\n } else {\n // progress update\n api.onupdate(position);\n }\n };\n\n /**\n * Set new target value\n * @param value\n */\n var setTarget = function setTarget(value) {\n // if currently has no position, set target and position to this value\n if (isNumber(value) && !isNumber(position)) {\n position = value;\n }\n\n // next target value will not be animated to\n if (target === null) {\n target = value;\n position = value;\n }\n\n // let start moving to target\n target = value;\n\n // already at target\n if (position === target || typeof target === 'undefined') {\n // now resting as target is current position, stop moving\n resting = true;\n velocity = 0;\n\n // done!\n api.onupdate(position);\n api.oncomplete(position);\n\n return;\n }\n\n resting = false;\n };\n\n // need 'api' to call onupdate callback\n var api = createObject({\n interpolate: interpolate,\n target: {\n set: setTarget,\n get: function get() {\n return target;\n },\n },\n\n resting: {\n get: function get() {\n return resting;\n },\n },\n\n onupdate: function onupdate(value) {},\n oncomplete: function oncomplete(value) {},\n });\n\n return api;\n };\n\n var easeLinear = function easeLinear(t) {\n return t;\n };\n var easeInOutQuad = function easeInOutQuad(t) {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n };\n\n var tween =\n // default values\n function tween() // method definition\n {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$duration = _ref.duration,\n duration = _ref$duration === void 0 ? 500 : _ref$duration,\n _ref$easing = _ref.easing,\n easing = _ref$easing === void 0 ? easeInOutQuad : _ref$easing,\n _ref$delay = _ref.delay,\n delay = _ref$delay === void 0 ? 0 : _ref$delay;\n var start = null;\n var t;\n var p;\n var resting = true;\n var reverse = false;\n var target = null;\n\n var interpolate = function interpolate(ts, skipToEndState) {\n if (resting || target === null) return;\n\n if (start === null) {\n start = ts;\n }\n\n if (ts - start < delay) return;\n\n t = ts - start - delay;\n\n if (t >= duration || skipToEndState) {\n t = 1;\n p = reverse ? 0 : 1;\n api.onupdate(p * target);\n api.oncomplete(p * target);\n resting = true;\n } else {\n p = t / duration;\n api.onupdate((t >= 0 ? easing(reverse ? 1 - p : p) : 0) * target);\n }\n };\n\n // need 'api' to call onupdate callback\n var api = createObject({\n interpolate: interpolate,\n target: {\n get: function get() {\n return reverse ? 0 : target;\n },\n set: function set(value) {\n // is initial value\n if (target === null) {\n target = value;\n api.onupdate(value);\n api.oncomplete(value);\n return;\n }\n\n // want to tween to a smaller value and have a current value\n if (value < target) {\n target = 1;\n reverse = true;\n } else {\n // not tweening to a smaller value\n reverse = false;\n target = value;\n }\n\n // let's go!\n resting = false;\n start = null;\n },\n },\n\n resting: {\n get: function get() {\n return resting;\n },\n },\n\n onupdate: function onupdate(value) {},\n oncomplete: function oncomplete(value) {},\n });\n\n return api;\n };\n\n var animator = {\n spring: spring,\n tween: tween,\n };\n\n /*\n { type: 'spring', stiffness: .5, damping: .75, mass: 10 };\n { translation: { type: 'spring', ... }, ... }\n { translation: { x: { type: 'spring', ... } } }\n */\n var createAnimator = function createAnimator(definition, category, property) {\n // default is single definition\n // we check if transform is set, if so, we check if property is set\n var def =\n definition[category] && typeof definition[category][property] === 'object'\n ? definition[category][property]\n : definition[category] || definition;\n\n var type = typeof def === 'string' ? def : def.type;\n var props = typeof def === 'object' ? Object.assign({}, def) : {};\n\n return animator[type] ? animator[type](props) : null;\n };\n\n var addGetSet = function addGetSet(keys, obj, props) {\n var overwrite = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;\n obj = Array.isArray(obj) ? obj : [obj];\n obj.forEach(function(o) {\n keys.forEach(function(key) {\n var name = key;\n var getter = function getter() {\n return props[key];\n };\n var setter = function setter(value) {\n return (props[key] = value);\n };\n\n if (typeof key === 'object') {\n name = key.key;\n getter = key.getter || getter;\n setter = key.setter || setter;\n }\n\n if (o[name] && !overwrite) {\n return;\n }\n\n o[name] = {\n get: getter,\n set: setter,\n };\n });\n });\n };\n\n // add to state,\n // add getters and setters to internal and external api (if not set)\n // setup animators\n\n var animations = function animations(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI;\n // initial properties\n var initialProps = Object.assign({}, viewProps);\n\n // list of all active animations\n var animations = [];\n\n // setup animators\n forin(mixinConfig, function(property, animation) {\n var animator = createAnimator(animation);\n if (!animator) {\n return;\n }\n\n // when the animator updates, update the view state value\n animator.onupdate = function(value) {\n viewProps[property] = value;\n };\n\n // set animator target\n animator.target = initialProps[property];\n\n // when value is set, set the animator target value\n var prop = {\n key: property,\n setter: function setter(value) {\n // if already at target, we done!\n if (animator.target === value) {\n return;\n }\n\n animator.target = value;\n },\n getter: function getter() {\n return viewProps[property];\n },\n };\n\n // add getters and setters\n addGetSet([prop], [viewInternalAPI, viewExternalAPI], viewProps, true);\n\n // add it to the list for easy updating from the _write method\n animations.push(animator);\n });\n\n // expose internal write api\n return {\n write: function write(ts) {\n var skipToEndState = document.hidden;\n var resting = true;\n animations.forEach(function(animation) {\n if (!animation.resting) resting = false;\n animation.interpolate(ts, skipToEndState);\n });\n return resting;\n },\n destroy: function destroy() {},\n };\n };\n\n var addEvent = function addEvent(element) {\n return function(type, fn) {\n element.addEventListener(type, fn);\n };\n };\n\n var removeEvent = function removeEvent(element) {\n return function(type, fn) {\n element.removeEventListener(type, fn);\n };\n };\n\n // mixin\n var listeners = function listeners(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI,\n viewState = _ref.viewState,\n view = _ref.view;\n var events = [];\n\n var add = addEvent(view.element);\n var remove = removeEvent(view.element);\n\n viewExternalAPI.on = function(type, fn) {\n events.push({\n type: type,\n fn: fn,\n });\n\n add(type, fn);\n };\n\n viewExternalAPI.off = function(type, fn) {\n events.splice(\n events.findIndex(function(event) {\n return event.type === type && event.fn === fn;\n }),\n 1\n );\n\n remove(type, fn);\n };\n\n return {\n write: function write() {\n // not busy\n return true;\n },\n destroy: function destroy() {\n events.forEach(function(event) {\n remove(event.type, event.fn);\n });\n },\n };\n };\n\n // add to external api and link to props\n\n var apis = function apis(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewExternalAPI = _ref.viewExternalAPI;\n addGetSet(mixinConfig, viewExternalAPI, viewProps);\n };\n\n var isDefined = function isDefined(value) {\n return value != null;\n };\n\n // add to state,\n // add getters and setters to internal and external api (if not set)\n // set initial state based on props in viewProps\n // apply as transforms each frame\n\n var defaults = {\n opacity: 1,\n scaleX: 1,\n scaleY: 1,\n translateX: 0,\n translateY: 0,\n rotateX: 0,\n rotateY: 0,\n rotateZ: 0,\n originX: 0,\n originY: 0,\n };\n\n var styles = function styles(_ref) {\n var mixinConfig = _ref.mixinConfig,\n viewProps = _ref.viewProps,\n viewInternalAPI = _ref.viewInternalAPI,\n viewExternalAPI = _ref.viewExternalAPI,\n view = _ref.view;\n // initial props\n var initialProps = Object.assign({}, viewProps);\n\n // current props\n var currentProps = {};\n\n // we will add those properties to the external API and link them to the viewState\n addGetSet(mixinConfig, [viewInternalAPI, viewExternalAPI], viewProps);\n\n // override rect on internal and external rect getter so it takes in account transforms\n var getOffset = function getOffset() {\n return [viewProps['translateX'] || 0, viewProps['translateY'] || 0];\n };\n\n var getScale = function getScale() {\n return [viewProps['scaleX'] || 0, viewProps['scaleY'] || 0];\n };\n var getRect = function getRect() {\n return view.rect\n ? getViewRect(view.rect, view.childViews, getOffset(), getScale())\n : null;\n };\n viewInternalAPI.rect = { get: getRect };\n viewExternalAPI.rect = { get: getRect };\n\n // apply view props\n mixinConfig.forEach(function(key) {\n viewProps[key] =\n typeof initialProps[key] === 'undefined' ? defaults[key] : initialProps[key];\n });\n\n // expose api\n return {\n write: function write() {\n // see if props have changed\n if (!propsHaveChanged(currentProps, viewProps)) {\n return;\n }\n\n // moves element to correct position on screen\n applyStyles(view.element, viewProps);\n\n // store new transforms\n Object.assign(currentProps, Object.assign({}, viewProps));\n\n // no longer busy\n return true;\n },\n destroy: function destroy() {},\n };\n };\n\n var propsHaveChanged = function propsHaveChanged(currentProps, newProps) {\n // different amount of keys\n if (Object.keys(currentProps).length !== Object.keys(newProps).length) {\n return true;\n }\n\n // lets analyze the individual props\n for (var prop in newProps) {\n if (newProps[prop] !== currentProps[prop]) {\n return true;\n }\n }\n\n return false;\n };\n\n var applyStyles = function applyStyles(element, _ref2) {\n var opacity = _ref2.opacity,\n perspective = _ref2.perspective,\n translateX = _ref2.translateX,\n translateY = _ref2.translateY,\n scaleX = _ref2.scaleX,\n scaleY = _ref2.scaleY,\n rotateX = _ref2.rotateX,\n rotateY = _ref2.rotateY,\n rotateZ = _ref2.rotateZ,\n originX = _ref2.originX,\n originY = _ref2.originY,\n width = _ref2.width,\n height = _ref2.height;\n\n var transforms = '';\n var styles = '';\n\n // handle transform origin\n if (isDefined(originX) || isDefined(originY)) {\n styles += 'transform-origin: ' + (originX || 0) + 'px ' + (originY || 0) + 'px;';\n }\n\n // transform order is relevant\n // 0. perspective\n if (isDefined(perspective)) {\n transforms += 'perspective(' + perspective + 'px) ';\n }\n\n // 1. translate\n if (isDefined(translateX) || isDefined(translateY)) {\n transforms +=\n 'translate3d(' + (translateX || 0) + 'px, ' + (translateY || 0) + 'px, 0) ';\n }\n\n // 2. scale\n if (isDefined(scaleX) || isDefined(scaleY)) {\n transforms +=\n 'scale3d(' +\n (isDefined(scaleX) ? scaleX : 1) +\n ', ' +\n (isDefined(scaleY) ? scaleY : 1) +\n ', 1) ';\n }\n\n // 3. rotate\n if (isDefined(rotateZ)) {\n transforms += 'rotateZ(' + rotateZ + 'rad) ';\n }\n\n if (isDefined(rotateX)) {\n transforms += 'rotateX(' + rotateX + 'rad) ';\n }\n\n if (isDefined(rotateY)) {\n transforms += 'rotateY(' + rotateY + 'rad) ';\n }\n\n // add transforms\n if (transforms.length) {\n styles += 'transform:' + transforms + ';';\n }\n\n // add opacity\n if (isDefined(opacity)) {\n styles += 'opacity:' + opacity + ';';\n\n // if we reach zero, we make the element inaccessible\n if (opacity === 0) {\n styles += 'visibility:hidden;';\n }\n\n // if we're below 100% opacity this element can't be clicked\n if (opacity < 1) {\n styles += 'pointer-events:none;';\n }\n }\n\n // add height\n if (isDefined(height)) {\n styles += 'height:' + height + 'px;';\n }\n\n // add width\n if (isDefined(width)) {\n styles += 'width:' + width + 'px;';\n }\n\n // apply styles\n var elementCurrentStyle = element.elementCurrentStyle || '';\n\n // if new styles does not match current styles, lets update!\n if (styles.length !== elementCurrentStyle.length || styles !== elementCurrentStyle) {\n element.style.cssText = styles;\n // store current styles so we can compare them to new styles later on\n // _not_ getting the style value is faster\n element.elementCurrentStyle = styles;\n }\n };\n\n var Mixins = {\n styles: styles,\n listeners: listeners,\n animations: animations,\n apis: apis,\n };\n\n var updateRect = function updateRect() {\n var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!element.layoutCalculated) {\n rect.paddingTop = parseInt(style.paddingTop, 10) || 0;\n rect.marginTop = parseInt(style.marginTop, 10) || 0;\n rect.marginRight = parseInt(style.marginRight, 10) || 0;\n rect.marginBottom = parseInt(style.marginBottom, 10) || 0;\n rect.marginLeft = parseInt(style.marginLeft, 10) || 0;\n element.layoutCalculated = true;\n }\n\n rect.left = element.offsetLeft || 0;\n rect.top = element.offsetTop || 0;\n rect.width = element.offsetWidth || 0;\n rect.height = element.offsetHeight || 0;\n\n rect.right = rect.left + rect.width;\n rect.bottom = rect.top + rect.height;\n\n rect.scrollTop = element.scrollTop;\n\n rect.hidden = element.offsetParent === null;\n\n return rect;\n };\n\n var createView =\n // default view definition\n function createView() {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n _ref$tag = _ref.tag,\n tag = _ref$tag === void 0 ? 'div' : _ref$tag,\n _ref$name = _ref.name,\n name = _ref$name === void 0 ? null : _ref$name,\n _ref$attributes = _ref.attributes,\n attributes = _ref$attributes === void 0 ? {} : _ref$attributes,\n _ref$read = _ref.read,\n read = _ref$read === void 0 ? function() {} : _ref$read,\n _ref$write = _ref.write,\n write = _ref$write === void 0 ? function() {} : _ref$write,\n _ref$create = _ref.create,\n create = _ref$create === void 0 ? function() {} : _ref$create,\n _ref$destroy = _ref.destroy,\n destroy = _ref$destroy === void 0 ? function() {} : _ref$destroy,\n _ref$filterFrameActio = _ref.filterFrameActionsForChild,\n filterFrameActionsForChild =\n _ref$filterFrameActio === void 0\n ? function(child, actions) {\n return actions;\n }\n : _ref$filterFrameActio,\n _ref$didCreateView = _ref.didCreateView,\n didCreateView = _ref$didCreateView === void 0 ? function() {} : _ref$didCreateView,\n _ref$didWriteView = _ref.didWriteView,\n didWriteView = _ref$didWriteView === void 0 ? function() {} : _ref$didWriteView,\n _ref$ignoreRect = _ref.ignoreRect,\n ignoreRect = _ref$ignoreRect === void 0 ? false : _ref$ignoreRect,\n _ref$ignoreRectUpdate = _ref.ignoreRectUpdate,\n ignoreRectUpdate = _ref$ignoreRectUpdate === void 0 ? false : _ref$ignoreRectUpdate,\n _ref$mixins = _ref.mixins,\n mixins = _ref$mixins === void 0 ? [] : _ref$mixins;\n return function(\n // each view requires reference to store\n store\n ) {\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n // root element should not be changed\n var element = createElement(tag, 'filepond--' + name, attributes);\n\n // style reference should also not be changed\n var style = window.getComputedStyle(element, null);\n\n // element rectangle\n var rect = updateRect();\n var frameRect = null;\n\n // rest state\n var isResting = false;\n\n // pretty self explanatory\n var childViews = [];\n\n // loaded mixins\n var activeMixins = [];\n\n // references to created children\n var ref = {};\n\n // state used for each instance\n var state = {};\n\n // list of writers that will be called to update this view\n var writers = [\n write, // default writer\n ];\n\n var readers = [\n read, // default reader\n ];\n\n var destroyers = [\n destroy, // default destroy\n ];\n\n // core view methods\n var getElement = function getElement() {\n return element;\n };\n var getChildViews = function getChildViews() {\n return childViews.concat();\n };\n var getReference = function getReference() {\n return ref;\n };\n var createChildView = function createChildView(store) {\n return function(view, props) {\n return view(store, props);\n };\n };\n var getRect = function getRect() {\n if (frameRect) {\n return frameRect;\n }\n frameRect = getViewRect(rect, childViews, [0, 0], [1, 1]);\n return frameRect;\n };\n var getStyle = function getStyle() {\n return style;\n };\n\n /**\n * Read data from DOM\n * @private\n */\n var _read = function _read() {\n frameRect = null;\n\n // read child views\n childViews.forEach(function(child) {\n return child._read();\n });\n\n var shouldUpdate = !(ignoreRectUpdate && rect.width && rect.height);\n if (shouldUpdate) {\n updateRect(rect, element, style);\n }\n\n // readers\n var api = { root: internalAPI, props: props, rect: rect };\n readers.forEach(function(reader) {\n return reader(api);\n });\n };\n\n /**\n * Write data to DOM\n * @private\n */\n var _write = function _write(ts, frameActions, shouldOptimize) {\n // if no actions, we assume that the view is resting\n var resting = frameActions.length === 0;\n\n // writers\n writers.forEach(function(writer) {\n var writerResting = writer({\n props: props,\n root: internalAPI,\n actions: frameActions,\n timestamp: ts,\n shouldOptimize: shouldOptimize,\n });\n\n if (writerResting === false) {\n resting = false;\n }\n });\n\n // run mixins\n activeMixins.forEach(function(mixin) {\n // if one of the mixins is still busy after write operation, we are not resting\n var mixinResting = mixin.write(ts);\n if (mixinResting === false) {\n resting = false;\n }\n });\n\n // updates child views that are currently attached to the DOM\n childViews\n .filter(function(child) {\n return !!child.element.parentNode;\n })\n .forEach(function(child) {\n // if a child view is not resting, we are not resting\n var childResting = child._write(\n ts,\n filterFrameActionsForChild(child, frameActions),\n shouldOptimize\n );\n\n if (!childResting) {\n resting = false;\n }\n });\n\n // append new elements to DOM and update those\n childViews\n //.filter(child => !child.element.parentNode)\n .forEach(function(child, index) {\n // skip\n if (child.element.parentNode) {\n return;\n }\n\n // append to DOM\n internalAPI.appendChild(child.element, index);\n\n // call read (need to know the size of these elements)\n child._read();\n\n // re-call write\n child._write(\n ts,\n filterFrameActionsForChild(child, frameActions),\n shouldOptimize\n );\n\n // we just added somthing to the dom, no rest\n resting = false;\n });\n\n // update resting state\n isResting = resting;\n\n didWriteView({\n props: props,\n root: internalAPI,\n actions: frameActions,\n timestamp: ts,\n });\n\n // let parent know if we are resting\n return resting;\n };\n\n var _destroy = function _destroy() {\n activeMixins.forEach(function(mixin) {\n return mixin.destroy();\n });\n destroyers.forEach(function(destroyer) {\n destroyer({ root: internalAPI, props: props });\n });\n childViews.forEach(function(child) {\n return child._destroy();\n });\n };\n\n // sharedAPI\n var sharedAPIDefinition = {\n element: {\n get: getElement,\n },\n\n style: {\n get: getStyle,\n },\n\n childViews: {\n get: getChildViews,\n },\n };\n\n // private API definition\n var internalAPIDefinition = Object.assign({}, sharedAPIDefinition, {\n rect: {\n get: getRect,\n },\n\n // access to custom children references\n ref: {\n get: getReference,\n },\n\n // dom modifiers\n is: function is(needle) {\n return name === needle;\n },\n appendChild: appendChild(element),\n createChildView: createChildView(store),\n linkView: function linkView(view) {\n childViews.push(view);\n return view;\n },\n unlinkView: function unlinkView(view) {\n childViews.splice(childViews.indexOf(view), 1);\n },\n appendChildView: appendChildView(element, childViews),\n removeChildView: removeChildView(element, childViews),\n registerWriter: function registerWriter(writer) {\n return writers.push(writer);\n },\n registerReader: function registerReader(reader) {\n return readers.push(reader);\n },\n registerDestroyer: function registerDestroyer(destroyer) {\n return destroyers.push(destroyer);\n },\n invalidateLayout: function invalidateLayout() {\n return (element.layoutCalculated = false);\n },\n\n // access to data store\n dispatch: store.dispatch,\n query: store.query,\n });\n\n // public view API methods\n var externalAPIDefinition = {\n element: {\n get: getElement,\n },\n\n childViews: {\n get: getChildViews,\n },\n\n rect: {\n get: getRect,\n },\n\n resting: {\n get: function get() {\n return isResting;\n },\n },\n\n isRectIgnored: function isRectIgnored() {\n return ignoreRect;\n },\n _read: _read,\n _write: _write,\n _destroy: _destroy,\n };\n\n // mixin API methods\n var mixinAPIDefinition = Object.assign({}, sharedAPIDefinition, {\n rect: {\n get: function get() {\n return rect;\n },\n },\n });\n\n // add mixin functionality\n Object.keys(mixins)\n .sort(function(a, b) {\n // move styles to the back of the mixin list (so adjustments of other mixins are applied to the props correctly)\n if (a === 'styles') {\n return 1;\n } else if (b === 'styles') {\n return -1;\n }\n return 0;\n })\n .forEach(function(key) {\n var mixinAPI = Mixins[key]({\n mixinConfig: mixins[key],\n viewProps: props,\n viewState: state,\n viewInternalAPI: internalAPIDefinition,\n viewExternalAPI: externalAPIDefinition,\n view: createObject(mixinAPIDefinition),\n });\n\n if (mixinAPI) {\n activeMixins.push(mixinAPI);\n }\n });\n\n // construct private api\n var internalAPI = createObject(internalAPIDefinition);\n\n // create the view\n create({\n root: internalAPI,\n props: props,\n });\n\n // append created child views to root node\n var childCount = getChildCount(element); // need to know the current child count so appending happens in correct order\n childViews.forEach(function(child, index) {\n internalAPI.appendChild(child.element, childCount + index);\n });\n\n // call did create\n didCreateView(internalAPI);\n\n // expose public api\n return createObject(externalAPIDefinition);\n };\n };\n\n var createPainter = function createPainter(read, write) {\n var fps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;\n\n var name = '__framePainter';\n\n // set global painter\n if (window[name]) {\n window[name].readers.push(read);\n window[name].writers.push(write);\n return;\n }\n\n window[name] = {\n readers: [read],\n writers: [write],\n };\n\n var painter = window[name];\n\n var interval = 1000 / fps;\n var last = null;\n var id = null;\n var requestTick = null;\n var cancelTick = null;\n\n var setTimerType = function setTimerType() {\n if (document.hidden) {\n requestTick = function requestTick() {\n return window.setTimeout(function() {\n return tick(performance.now());\n }, interval);\n };\n cancelTick = function cancelTick() {\n return window.clearTimeout(id);\n };\n } else {\n requestTick = function requestTick() {\n return window.requestAnimationFrame(tick);\n };\n cancelTick = function cancelTick() {\n return window.cancelAnimationFrame(id);\n };\n }\n };\n\n document.addEventListener('visibilitychange', function() {\n if (cancelTick) cancelTick();\n setTimerType();\n tick(performance.now());\n });\n\n var tick = function tick(ts) {\n // queue next tick\n id = requestTick(tick);\n\n // limit fps\n if (!last) {\n last = ts;\n }\n\n var delta = ts - last;\n\n if (delta <= interval) {\n // skip frame\n return;\n }\n\n // align next frame\n last = ts - (delta % interval);\n\n // update view\n painter.readers.forEach(function(read) {\n return read();\n });\n painter.writers.forEach(function(write) {\n return write(ts);\n });\n };\n\n setTimerType();\n tick(performance.now());\n\n return {\n pause: function pause() {\n cancelTick(id);\n },\n };\n };\n\n var createRoute = function createRoute(routes, fn) {\n return function(_ref) {\n var root = _ref.root,\n props = _ref.props,\n _ref$actions = _ref.actions,\n actions = _ref$actions === void 0 ? [] : _ref$actions,\n timestamp = _ref.timestamp,\n shouldOptimize = _ref.shouldOptimize;\n actions\n .filter(function(action) {\n return routes[action.type];\n })\n .forEach(function(action) {\n return routes[action.type]({\n root: root,\n props: props,\n action: action.data,\n timestamp: timestamp,\n shouldOptimize: shouldOptimize,\n });\n });\n\n if (fn) {\n fn({\n root: root,\n props: props,\n actions: actions,\n timestamp: timestamp,\n shouldOptimize: shouldOptimize,\n });\n }\n };\n };\n\n var insertBefore = function insertBefore(newNode, referenceNode) {\n return referenceNode.parentNode.insertBefore(newNode, referenceNode);\n };\n\n var insertAfter = function insertAfter(newNode, referenceNode) {\n return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);\n };\n\n var isArray = function isArray(value) {\n return Array.isArray(value);\n };\n\n var isEmpty = function isEmpty(value) {\n return value == null;\n };\n\n var trim = function trim(str) {\n return str.trim();\n };\n\n var toString = function toString(value) {\n return '' + value;\n };\n\n var toArray = function toArray(value) {\n var splitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';\n if (isEmpty(value)) {\n return [];\n }\n if (isArray(value)) {\n return value;\n }\n return toString(value)\n .split(splitter)\n .map(trim)\n .filter(function(str) {\n return str.length;\n });\n };\n\n var isBoolean = function isBoolean(value) {\n return typeof value === 'boolean';\n };\n\n var toBoolean = function toBoolean(value) {\n return isBoolean(value) ? value : value === 'true';\n };\n\n var isString = function isString(value) {\n return typeof value === 'string';\n };\n\n var toNumber = function toNumber(value) {\n return isNumber(value)\n ? value\n : isString(value)\n ? toString(value).replace(/[a-z]+/gi, '')\n : 0;\n };\n\n var toInt = function toInt(value) {\n return parseInt(toNumber(value), 10);\n };\n\n var toFloat = function toFloat(value) {\n return parseFloat(toNumber(value));\n };\n\n var isInt = function isInt(value) {\n return isNumber(value) && isFinite(value) && Math.floor(value) === value;\n };\n\n var toBytes = function toBytes(value) {\n var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;\n // is in bytes\n if (isInt(value)) {\n return value;\n }\n\n // is natural file size\n var naturalFileSize = toString(value).trim();\n\n // if is value in megabytes\n if (/MB$/i.test(naturalFileSize)) {\n naturalFileSize = naturalFileSize.replace(/MB$i/, '').trim();\n return toInt(naturalFileSize) * base * base;\n }\n\n // if is value in kilobytes\n if (/KB/i.test(naturalFileSize)) {\n naturalFileSize = naturalFileSize.replace(/KB$i/, '').trim();\n return toInt(naturalFileSize) * base;\n }\n\n return toInt(naturalFileSize);\n };\n\n var isFunction = function isFunction(value) {\n return typeof value === 'function';\n };\n\n var toFunctionReference = function toFunctionReference(string) {\n var ref = self;\n var levels = string.split('.');\n var level = null;\n while ((level = levels.shift())) {\n ref = ref[level];\n if (!ref) {\n return null;\n }\n }\n return ref;\n };\n\n var methods = {\n process: 'POST',\n patch: 'PATCH',\n revert: 'DELETE',\n fetch: 'GET',\n restore: 'GET',\n load: 'GET',\n };\n\n var createServerAPI = function createServerAPI(outline) {\n var api = {};\n\n api.url = isString(outline) ? outline : outline.url || '';\n api.timeout = outline.timeout ? parseInt(outline.timeout, 10) : 0;\n api.headers = outline.headers ? outline.headers : {};\n\n forin(methods, function(key) {\n api[key] = createAction(key, outline[key], methods[key], api.timeout, api.headers);\n });\n\n // remove process if no url or process on outline\n api.process = outline.process || isString(outline) || outline.url ? api.process : null;\n\n // special treatment for remove\n api.remove = outline.remove || null;\n\n // remove generic headers from api object\n delete api.headers;\n\n return api;\n };\n\n var createAction = function createAction(name, outline, method, timeout, headers) {\n // is explicitely set to null so disable\n if (outline === null) {\n return null;\n }\n\n // if is custom function, done! Dev handles everything.\n if (typeof outline === 'function') {\n return outline;\n }\n\n // build action object\n var action = {\n url: method === 'GET' || method === 'PATCH' ? '?' + name + '=' : '',\n method: method,\n headers: headers,\n withCredentials: false,\n timeout: timeout,\n onload: null,\n ondata: null,\n onerror: null,\n };\n\n // is a single url\n if (isString(outline)) {\n action.url = outline;\n return action;\n }\n\n // overwrite\n Object.assign(action, outline);\n\n // see if should reformat headers;\n if (isString(action.headers)) {\n var parts = action.headers.split(/:(.+)/);\n action.headers = {\n header: parts[0],\n value: parts[1],\n };\n }\n\n // if is bool withCredentials\n action.withCredentials = toBoolean(action.withCredentials);\n\n return action;\n };\n\n var toServerAPI = function toServerAPI(value) {\n return createServerAPI(value);\n };\n\n var isNull = function isNull(value) {\n return value === null;\n };\n\n var isObject = function isObject(value) {\n return typeof value === 'object' && value !== null;\n };\n\n var isAPI = function isAPI(value) {\n return (\n isObject(value) &&\n isString(value.url) &&\n isObject(value.process) &&\n isObject(value.revert) &&\n isObject(value.restore) &&\n isObject(value.fetch)\n );\n };\n\n var getType = function getType(value) {\n if (isArray(value)) {\n return 'array';\n }\n\n if (isNull(value)) {\n return 'null';\n }\n\n if (isInt(value)) {\n return 'int';\n }\n\n if (/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(value)) {\n return 'bytes';\n }\n\n if (isAPI(value)) {\n return 'api';\n }\n\n return typeof value;\n };\n\n var replaceSingleQuotes = function replaceSingleQuotes(str) {\n return str\n .replace(/{\\s*'/g, '{\"')\n .replace(/'\\s*}/g, '\"}')\n .replace(/'\\s*:/g, '\":')\n .replace(/:\\s*'/g, ':\"')\n .replace(/,\\s*'/g, ',\"')\n .replace(/'\\s*,/g, '\",');\n };\n\n var conversionTable = {\n array: toArray,\n boolean: toBoolean,\n int: function int(value) {\n return getType(value) === 'bytes' ? toBytes(value) : toInt(value);\n },\n number: toFloat,\n float: toFloat,\n bytes: toBytes,\n string: function string(value) {\n return isFunction(value) ? value : toString(value);\n },\n function: function _function(value) {\n return toFunctionReference(value);\n },\n serverapi: toServerAPI,\n object: function object(value) {\n try {\n return JSON.parse(replaceSingleQuotes(value));\n } catch (e) {\n return null;\n }\n },\n };\n\n var convertTo = function convertTo(value, type) {\n return conversionTable[type](value);\n };\n\n var getValueByType = function getValueByType(newValue, defaultValue, valueType) {\n // can always assign default value\n if (newValue === defaultValue) {\n return newValue;\n }\n\n // get the type of the new value\n var newValueType = getType(newValue);\n\n // is valid type?\n if (newValueType !== valueType) {\n // is string input, let's attempt to convert\n var convertedValue = convertTo(newValue, valueType);\n\n // what is the type now\n newValueType = getType(convertedValue);\n\n // no valid conversions found\n if (convertedValue === null) {\n throw 'Trying to assign value with incorrect type to \"' +\n option +\n '\", allowed type: \"' +\n valueType +\n '\"';\n } else {\n newValue = convertedValue;\n }\n }\n\n // assign new value\n return newValue;\n };\n\n var createOption = function createOption(defaultValue, valueType) {\n var currentValue = defaultValue;\n return {\n enumerable: true,\n get: function get() {\n return currentValue;\n },\n set: function set(newValue) {\n currentValue = getValueByType(newValue, defaultValue, valueType);\n },\n };\n };\n\n var createOptions = function createOptions(options) {\n var obj = {};\n forin(options, function(prop) {\n var optionDefinition = options[prop];\n obj[prop] = createOption(optionDefinition[0], optionDefinition[1]);\n });\n return createObject(obj);\n };\n\n var createInitialState = function createInitialState(options) {\n return {\n // model\n items: [],\n\n // timeout used for calling update items\n listUpdateTimeout: null,\n\n // timeout used for stacking metadata updates\n itemUpdateTimeout: null,\n\n // queue of items waiting to be processed\n processingQueue: [],\n\n // options\n options: createOptions(options),\n };\n };\n\n var fromCamels = function fromCamels(string) {\n var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';\n return string\n .split(/(?=[A-Z])/)\n .map(function(part) {\n return part.toLowerCase();\n })\n .join(separator);\n };\n\n var createOptionAPI = function createOptionAPI(store, options) {\n var obj = {};\n forin(options, function(key) {\n obj[key] = {\n get: function get() {\n return store.getState().options[key];\n },\n set: function set(value) {\n store.dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {\n value: value,\n });\n },\n };\n });\n return obj;\n };\n\n var createOptionActions = function createOptionActions(options) {\n return function(dispatch, query, state) {\n var obj = {};\n forin(options, function(key) {\n var name = fromCamels(key, '_').toUpperCase();\n\n obj['SET_' + name] = function(action) {\n try {\n state.options[key] = action.value;\n } catch (e) {} // nope, failed\n\n // we successfully set the value of this option\n dispatch('DID_SET_' + name, { value: state.options[key] });\n };\n });\n return obj;\n };\n };\n\n var createOptionQueries = function createOptionQueries(options) {\n return function(state) {\n var obj = {};\n forin(options, function(key) {\n obj['GET_' + fromCamels(key, '_').toUpperCase()] = function(action) {\n return state.options[key];\n };\n });\n return obj;\n };\n };\n\n var InteractionMethod = {\n API: 1,\n DROP: 2,\n BROWSE: 3,\n PASTE: 4,\n NONE: 5,\n };\n\n var getUniqueId = function getUniqueId() {\n return Math.random()\n .toString(36)\n .substring(2, 11);\n };\n\n function _typeof(obj) {\n if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {\n _typeof = function(obj) {\n return typeof obj;\n };\n } else {\n _typeof = function(obj) {\n return obj &&\n typeof Symbol === 'function' &&\n obj.constructor === Symbol &&\n obj !== Symbol.prototype\n ? 'symbol'\n : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n var REACT_ELEMENT_TYPE;\n\n function _jsx(type, props, key, children) {\n if (!REACT_ELEMENT_TYPE) {\n REACT_ELEMENT_TYPE =\n (typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element')) ||\n 0xeac7;\n }\n\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n props = {\n children: void 0,\n };\n }\n\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = new Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n }\n\n function _asyncIterator(iterable) {\n var method;\n\n if (typeof Symbol !== 'undefined') {\n if (Symbol.asyncIterator) {\n method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n\n if (Symbol.iterator) {\n method = iterable[Symbol.iterator];\n if (method != null) return method.call(iterable);\n }\n }\n\n throw new TypeError('Object is not async iterable');\n }\n\n function _AwaitValue(value) {\n this.wrapped = value;\n }\n\n function _AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function(resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null,\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg);\n var value = result.value;\n var wrappedAwait = value instanceof _AwaitValue;\n Promise.resolve(wrappedAwait ? value.wrapped : value).then(\n function(arg) {\n if (wrappedAwait) {\n resume('next', arg);\n return;\n }\n\n settle(result.done ? 'return' : 'normal', arg);\n },\n function(err) {\n resume('throw', err);\n }\n );\n } catch (err) {\n settle('throw', err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case 'return':\n front.resolve({\n value: value,\n done: true,\n });\n break;\n\n case 'throw':\n front.reject(value);\n break;\n\n default:\n front.resolve({\n value: value,\n done: false,\n });\n break;\n }\n\n front = front.next;\n\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n if (typeof gen.return !== 'function') {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === 'function' && Symbol.asyncIterator) {\n _AsyncGenerator.prototype[Symbol.asyncIterator] = function() {\n return this;\n };\n }\n\n _AsyncGenerator.prototype.next = function(arg) {\n return this._invoke('next', arg);\n };\n\n _AsyncGenerator.prototype.throw = function(arg) {\n return this._invoke('throw', arg);\n };\n\n _AsyncGenerator.prototype.return = function(arg) {\n return this._invoke('return', arg);\n };\n\n function _wrapAsyncGenerator(fn) {\n return function() {\n return new _AsyncGenerator(fn.apply(this, arguments));\n };\n }\n\n function _awaitAsyncGenerator(value) {\n return new _AwaitValue(value);\n }\n\n function _asyncGeneratorDelegate(inner, awaitWrap) {\n var iter = {},\n waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function(resolve) {\n resolve(inner[key](value));\n });\n return {\n done: false,\n value: awaitWrap(value),\n };\n }\n\n if (typeof Symbol === 'function' && Symbol.iterator) {\n iter[Symbol.iterator] = function() {\n return this;\n };\n }\n\n iter.next = function(value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n\n return pump('next', value);\n };\n\n if (typeof inner.throw === 'function') {\n iter.throw = function(value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n\n return pump('throw', value);\n };\n }\n\n if (typeof inner.return === 'function') {\n iter.return = function(value) {\n return pump('return', value);\n };\n }\n\n return iter;\n }\n\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n\n function _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);\n }\n\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);\n }\n\n _next(undefined);\n });\n };\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError('Cannot call a class as a function');\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ('value' in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineEnumerableProperties(obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n\n if (Object.getOwnPropertySymbols) {\n var objectSymbols = Object.getOwnPropertySymbols(descs);\n\n for (var i = 0; i < objectSymbols.length; i++) {\n var sym = objectSymbols[i];\n var desc = descs[sym];\n desc.configurable = desc.enumerable = true;\n if ('value' in desc) desc.writable = true;\n Object.defineProperty(obj, sym, desc);\n }\n }\n\n return obj;\n }\n\n function _defaults(obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n\n return obj;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function _extends() {\n _extends =\n Object.assign ||\n function(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n }\n\n function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly)\n symbols = symbols.filter(function(sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(source, true).forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(source).forEach(function(key) {\n Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(source, key)\n );\n });\n }\n }\n\n return target;\n }\n\n function _inherits(subClass, superClass) {\n if (typeof superClass !== 'function' && superClass !== null) {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true,\n },\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n }\n\n function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n }\n\n function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf\n ? Object.getPrototypeOf\n : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n\n function _setPrototypeOf(o, p) {\n _setPrototypeOf =\n Object.setPrototypeOf ||\n function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n\n return _setPrototypeOf(o, p);\n }\n\n function isNativeReflectConstruct() {\n if (typeof Reflect === 'undefined' || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === 'function') return true;\n\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function _construct(Parent, args, Class) {\n if (isNativeReflectConstruct()) {\n _construct = Reflect.construct;\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n\n return _construct.apply(null, arguments);\n }\n\n function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf('[native code]') !== -1;\n }\n\n function _wrapNativeSuper(Class) {\n var _cache = typeof Map === 'function' ? new Map() : undefined;\n\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n\n if (typeof Class !== 'function') {\n throw new TypeError('Super expression must either be null or a function');\n }\n\n if (typeof _cache !== 'undefined') {\n if (_cache.has(Class)) return _cache.get(Class);\n\n _cache.set(Class, Wrapper);\n }\n\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true,\n },\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n\n return _wrapNativeSuper(Class);\n }\n\n function _instanceof(left, right) {\n if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) {\n return !!right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n }\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule\n ? obj\n : {\n default: obj,\n };\n }\n\n function _interopRequireWildcard(obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc =\n Object.defineProperty && Object.getOwnPropertyDescriptor\n ? Object.getOwnPropertyDescriptor(obj, key)\n : {};\n\n if (desc.get || desc.set) {\n Object.defineProperty(newObj, key, desc);\n } else {\n newObj[key] = obj[key];\n }\n }\n }\n }\n\n newObj.default = obj;\n return newObj;\n }\n }\n\n function _newArrowCheck(innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError('Cannot instantiate an arrow function');\n }\n }\n\n function _objectDestructuringEmpty(obj) {\n if (obj == null) throw new TypeError('Cannot destructure undefined');\n }\n\n function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n\n return target;\n }\n\n function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n\n var target = _objectWithoutPropertiesLoose(source, excluded);\n\n var key, i;\n\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n\n return target;\n }\n\n function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n }\n\n function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === 'object' || typeof call === 'function')) {\n return call;\n }\n\n return _assertThisInitialized(self);\n }\n\n function _superPropBase(object, property) {\n while (!Object.prototype.hasOwnProperty.call(object, property)) {\n object = _getPrototypeOf(object);\n if (object === null) break;\n }\n\n return object;\n }\n\n function _get(target, property, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.get) {\n _get = Reflect.get;\n } else {\n _get = function _get(target, property, receiver) {\n var base = _superPropBase(target, property);\n\n if (!base) return;\n var desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.get) {\n return desc.get.call(receiver);\n }\n\n return desc.value;\n };\n }\n\n return _get(target, property, receiver || target);\n }\n\n function set(target, property, value, receiver) {\n if (typeof Reflect !== 'undefined' && Reflect.set) {\n set = Reflect.set;\n } else {\n set = function set(target, property, value, receiver) {\n var base = _superPropBase(target, property);\n\n var desc;\n\n if (base) {\n desc = Object.getOwnPropertyDescriptor(base, property);\n\n if (desc.set) {\n desc.set.call(receiver, value);\n return true;\n } else if (!desc.writable) {\n return false;\n }\n }\n\n desc = Object.getOwnPropertyDescriptor(receiver, property);\n\n if (desc) {\n if (!desc.writable) {\n return false;\n }\n\n desc.value = value;\n Object.defineProperty(receiver, property, desc);\n } else {\n _defineProperty(receiver, property, value);\n }\n\n return true;\n };\n }\n\n return set(target, property, value, receiver);\n }\n\n function _set(target, property, value, receiver, isStrict) {\n var s = set(target, property, value, receiver || target);\n\n if (!s && isStrict) {\n throw new Error('failed to set property');\n }\n\n return value;\n }\n\n function _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n return Object.freeze(\n Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw),\n },\n })\n );\n }\n\n function _taggedTemplateLiteralLoose(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n\n strings.raw = raw;\n return strings;\n }\n\n function _temporalRef(val, name) {\n if (val === _temporalUndefined) {\n throw new ReferenceError(name + ' is not defined - temporal dead zone');\n } else {\n return val;\n }\n }\n\n function _readOnlyError(name) {\n throw new Error('\"' + name + '\" is read-only');\n }\n\n function _classNameTDZError(name) {\n throw new Error('Class \"' + name + '\" cannot be referenced in computed property keys.');\n }\n\n var _temporalUndefined = {};\n\n function _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();\n }\n\n function _slicedToArrayLoose(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest();\n }\n\n function _toArray(arr) {\n return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n }\n\n function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n }\n\n function _iterableToArray(iter) {\n if (\n Symbol.iterator in Object(iter) ||\n Object.prototype.toString.call(iter) === '[object Arguments]'\n )\n return Array.from(iter);\n }\n\n function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i['return'] != null) _i['return']();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n }\n\n function _iterableToArrayLimitLoose(arr, i) {\n var _arr = [];\n\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) {\n _arr.push(_step.value);\n\n if (i && _arr.length === i) break;\n }\n\n return _arr;\n }\n\n function _nonIterableSpread() {\n throw new TypeError('Invalid attempt to spread non-iterable instance');\n }\n\n function _nonIterableRest() {\n throw new TypeError('Invalid attempt to destructure non-iterable instance');\n }\n\n function _skipFirstGeneratorNext(fn) {\n return function() {\n var it = fn.apply(this, arguments);\n it.next();\n return it;\n };\n }\n\n function _toPrimitive(input, hint) {\n if (typeof input !== 'object' || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n\n if (prim !== undefined) {\n var res = prim.call(input, hint || 'default');\n if (typeof res !== 'object') return res;\n throw new TypeError('@@toPrimitive must return a primitive value.');\n }\n\n return (hint === 'string' ? String : Number)(input);\n }\n\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, 'string');\n\n return typeof key === 'symbol' ? key : String(key);\n }\n\n function _initializerWarningHelper(descriptor, context) {\n throw new Error(\n 'Decorating class property failed. Please ensure that ' +\n 'proposal-class-properties is enabled and set to use loose mode. ' +\n 'To use proposal-class-properties in spec mode with decorators, wait for ' +\n 'the next major version of decorators in stage 2.'\n );\n }\n\n function _initializerDefineProperty(target, property, descriptor, context) {\n if (!descriptor) return;\n Object.defineProperty(target, property, {\n enumerable: descriptor.enumerable,\n configurable: descriptor.configurable,\n writable: descriptor.writable,\n value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,\n });\n }\n\n function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {\n var desc = {};\n Object.keys(descriptor).forEach(function(key) {\n desc[key] = descriptor[key];\n });\n desc.enumerable = !!desc.enumerable;\n desc.configurable = !!desc.configurable;\n\n if ('value' in desc || desc.initializer) {\n desc.writable = true;\n }\n\n desc = decorators\n .slice()\n .reverse()\n .reduce(function(desc, decorator) {\n return decorator(target, property, desc) || desc;\n }, desc);\n\n if (context && desc.initializer !== void 0) {\n desc.value = desc.initializer ? desc.initializer.call(context) : void 0;\n desc.initializer = undefined;\n }\n\n if (desc.initializer === void 0) {\n Object.defineProperty(target, property, desc);\n desc = null;\n }\n\n return desc;\n }\n\n var id = 0;\n\n function _classPrivateFieldLooseKey(name) {\n return '__private_' + id++ + '_' + name;\n }\n\n function _classPrivateFieldLooseBase(receiver, privateKey) {\n if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {\n throw new TypeError('attempted to use private field on non-instance');\n }\n\n return receiver;\n }\n\n function _classPrivateFieldGet(receiver, privateMap) {\n var descriptor = privateMap.get(receiver);\n\n if (!descriptor) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n if (descriptor.get) {\n return descriptor.get.call(receiver);\n }\n\n return descriptor.value;\n }\n\n function _classPrivateFieldSet(receiver, privateMap, value) {\n var descriptor = privateMap.get(receiver);\n\n if (!descriptor) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n if (descriptor.set) {\n descriptor.set.call(receiver, value);\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n }\n\n return value;\n }\n\n function _classPrivateFieldDestructureSet(receiver, privateMap) {\n if (!privateMap.has(receiver)) {\n throw new TypeError('attempted to set private field on non-instance');\n }\n\n var descriptor = privateMap.get(receiver);\n\n if (descriptor.set) {\n if (!('__destrObj' in descriptor)) {\n descriptor.__destrObj = {\n set value(v) {\n descriptor.set.call(receiver, v);\n },\n };\n }\n\n return descriptor.__destrObj;\n } else {\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n return descriptor;\n }\n }\n\n function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return descriptor.value;\n }\n\n function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n if (!descriptor.writable) {\n throw new TypeError('attempted to set read only private field');\n }\n\n descriptor.value = value;\n return value;\n }\n\n function _classStaticPrivateMethodGet(receiver, classConstructor, method) {\n if (receiver !== classConstructor) {\n throw new TypeError('Private static access of wrong provenance');\n }\n\n return method;\n }\n\n function _classStaticPrivateMethodSet() {\n throw new TypeError('attempted to set read only static private field');\n }\n\n function _decorate(decorators, factory, superClass, mixins) {\n var api = _getDecoratorsApi();\n\n if (mixins) {\n for (var i = 0; i < mixins.length; i++) {\n api = mixins[i](api);\n }\n }\n\n var r = factory(function initialize(O) {\n api.initializeInstanceElements(O, decorated.elements);\n }, superClass);\n var decorated = api.decorateClass(\n _coalesceClassElements(r.d.map(_createElementDescriptor)),\n decorators\n );\n api.initializeClassElements(r.F, decorated.elements);\n return api.runClassFinishers(r.F, decorated.finishers);\n }\n\n function _getDecoratorsApi() {\n _getDecoratorsApi = function() {\n return api;\n };\n\n var api = {\n elementsDefinitionOrder: [['method'], ['field']],\n initializeInstanceElements: function(O, elements) {\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n if (element.kind === kind && element.placement === 'own') {\n this.defineClassElement(O, element);\n }\n }, this);\n }, this);\n },\n initializeClassElements: function(F, elements) {\n var proto = F.prototype;\n ['method', 'field'].forEach(function(kind) {\n elements.forEach(function(element) {\n var placement = element.placement;\n\n if (\n element.kind === kind &&\n (placement === 'static' || placement === 'prototype')\n ) {\n var receiver = placement === 'static' ? F : proto;\n this.defineClassElement(receiver, element);\n }\n }, this);\n }, this);\n },\n defineClassElement: function(receiver, element) {\n var descriptor = element.descriptor;\n\n if (element.kind === 'field') {\n var initializer = element.initializer;\n descriptor = {\n enumerable: descriptor.enumerable,\n writable: descriptor.writable,\n configurable: descriptor.configurable,\n value: initializer === void 0 ? void 0 : initializer.call(receiver),\n };\n }\n\n Object.defineProperty(receiver, element.key, descriptor);\n },\n decorateClass: function(elements, decorators) {\n var newElements = [];\n var finishers = [];\n var placements = {\n static: [],\n prototype: [],\n own: [],\n };\n elements.forEach(function(element) {\n this.addElementPlacement(element, placements);\n }, this);\n elements.forEach(function(element) {\n if (!_hasDecorators(element)) return newElements.push(element);\n var elementFinishersExtras = this.decorateElement(element, placements);\n newElements.push(elementFinishersExtras.element);\n newElements.push.apply(newElements, elementFinishersExtras.extras);\n finishers.push.apply(finishers, elementFinishersExtras.finishers);\n }, this);\n\n if (!decorators) {\n return {\n elements: newElements,\n finishers: finishers,\n };\n }\n\n var result = this.decorateConstructor(newElements, decorators);\n finishers.push.apply(finishers, result.finishers);\n result.finishers = finishers;\n return result;\n },\n addElementPlacement: function(element, placements, silent) {\n var keys = placements[element.placement];\n\n if (!silent && keys.indexOf(element.key) !== -1) {\n throw new TypeError('Duplicated element (' + element.key + ')');\n }\n\n keys.push(element.key);\n },\n decorateElement: function(element, placements) {\n var extras = [];\n var finishers = [];\n\n for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {\n var keys = placements[element.placement];\n keys.splice(keys.indexOf(element.key), 1);\n var elementObject = this.fromElementDescriptor(element);\n var elementFinisherExtras = this.toElementFinisherExtras(\n (0, decorators[i])(elementObject) || elementObject\n );\n element = elementFinisherExtras.element;\n this.addElementPlacement(element, placements);\n\n if (elementFinisherExtras.finisher) {\n finishers.push(elementFinisherExtras.finisher);\n }\n\n var newExtras = elementFinisherExtras.extras;\n\n if (newExtras) {\n for (var j = 0; j < newExtras.length; j++) {\n this.addElementPlacement(newExtras[j], placements);\n }\n\n extras.push.apply(extras, newExtras);\n }\n }\n\n return {\n element: element,\n finishers: finishers,\n extras: extras,\n };\n },\n decorateConstructor: function(elements, decorators) {\n var finishers = [];\n\n for (var i = decorators.length - 1; i >= 0; i--) {\n var obj = this.fromClassDescriptor(elements);\n var elementsAndFinisher = this.toClassDescriptor(\n (0, decorators[i])(obj) || obj\n );\n\n if (elementsAndFinisher.finisher !== undefined) {\n finishers.push(elementsAndFinisher.finisher);\n }\n\n if (elementsAndFinisher.elements !== undefined) {\n elements = elementsAndFinisher.elements;\n\n for (var j = 0; j < elements.length - 1; j++) {\n for (var k = j + 1; k < elements.length; k++) {\n if (\n elements[j].key === elements[k].key &&\n elements[j].placement === elements[k].placement\n ) {\n throw new TypeError(\n 'Duplicated element (' + elements[j].key + ')'\n );\n }\n }\n }\n }\n }\n\n return {\n elements: elements,\n finishers: finishers,\n };\n },\n fromElementDescriptor: function(element) {\n var obj = {\n kind: element.kind,\n key: element.key,\n placement: element.placement,\n descriptor: element.descriptor,\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n if (element.kind === 'field') obj.initializer = element.initializer;\n return obj;\n },\n toElementDescriptors: function(elementObjects) {\n if (elementObjects === undefined) return;\n return _toArray(elementObjects).map(function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n this.disallowProperty(elementObject, 'finisher', 'An element descriptor');\n this.disallowProperty(elementObject, 'extras', 'An element descriptor');\n return element;\n }, this);\n },\n toElementDescriptor: function(elementObject) {\n var kind = String(elementObject.kind);\n\n if (kind !== 'method' && kind !== 'field') {\n throw new TypeError(\n 'An element descriptor\\'s .kind property must be either \"method\" or' +\n ' \"field\", but a decorator created an element descriptor with' +\n ' .kind \"' +\n kind +\n '\"'\n );\n }\n\n var key = _toPropertyKey(elementObject.key);\n\n var placement = String(elementObject.placement);\n\n if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') {\n throw new TypeError(\n 'An element descriptor\\'s .placement property must be one of \"static\",' +\n ' \"prototype\" or \"own\", but a decorator created an element descriptor' +\n ' with .placement \"' +\n placement +\n '\"'\n );\n }\n\n var descriptor = elementObject.descriptor;\n this.disallowProperty(elementObject, 'elements', 'An element descriptor');\n var element = {\n kind: kind,\n key: key,\n placement: placement,\n descriptor: Object.assign({}, descriptor),\n };\n\n if (kind !== 'field') {\n this.disallowProperty(elementObject, 'initializer', 'A method descriptor');\n } else {\n this.disallowProperty(\n descriptor,\n 'get',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'set',\n 'The property descriptor of a field descriptor'\n );\n this.disallowProperty(\n descriptor,\n 'value',\n 'The property descriptor of a field descriptor'\n );\n element.initializer = elementObject.initializer;\n }\n\n return element;\n },\n toElementFinisherExtras: function(elementObject) {\n var element = this.toElementDescriptor(elementObject);\n\n var finisher = _optionalCallableProperty(elementObject, 'finisher');\n\n var extras = this.toElementDescriptors(elementObject.extras);\n return {\n element: element,\n finisher: finisher,\n extras: extras,\n };\n },\n fromClassDescriptor: function(elements) {\n var obj = {\n kind: 'class',\n elements: elements.map(this.fromElementDescriptor, this),\n };\n var desc = {\n value: 'Descriptor',\n configurable: true,\n };\n Object.defineProperty(obj, Symbol.toStringTag, desc);\n return obj;\n },\n toClassDescriptor: function(obj) {\n var kind = String(obj.kind);\n\n if (kind !== 'class') {\n throw new TypeError(\n 'A class descriptor\\'s .kind property must be \"class\", but a decorator' +\n ' created a class descriptor with .kind \"' +\n kind +\n '\"'\n );\n }\n\n this.disallowProperty(obj, 'key', 'A class descriptor');\n this.disallowProperty(obj, 'placement', 'A class descriptor');\n this.disallowProperty(obj, 'descriptor', 'A class descriptor');\n this.disallowProperty(obj, 'initializer', 'A class descriptor');\n this.disallowProperty(obj, 'extras', 'A class descriptor');\n\n var finisher = _optionalCallableProperty(obj, 'finisher');\n\n var elements = this.toElementDescriptors(obj.elements);\n return {\n elements: elements,\n finisher: finisher,\n };\n },\n runClassFinishers: function(constructor, finishers) {\n for (var i = 0; i < finishers.length; i++) {\n var newConstructor = (0, finishers[i])(constructor);\n\n if (newConstructor !== undefined) {\n if (typeof newConstructor !== 'function') {\n throw new TypeError('Finishers must return a constructor.');\n }\n\n constructor = newConstructor;\n }\n }\n\n return constructor;\n },\n disallowProperty: function(obj, name, objectType) {\n if (obj[name] !== undefined) {\n throw new TypeError(objectType + \" can't have a .\" + name + ' property.');\n }\n },\n };\n return api;\n }\n\n function _createElementDescriptor(def) {\n var key = _toPropertyKey(def.key);\n\n var descriptor;\n\n if (def.kind === 'method') {\n descriptor = {\n value: def.value,\n writable: true,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'get') {\n descriptor = {\n get: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'set') {\n descriptor = {\n set: def.value,\n configurable: true,\n enumerable: false,\n };\n } else if (def.kind === 'field') {\n descriptor = {\n configurable: true,\n writable: true,\n enumerable: true,\n };\n }\n\n var element = {\n kind: def.kind === 'field' ? 'field' : 'method',\n key: key,\n placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype',\n descriptor: descriptor,\n };\n if (def.decorators) element.decorators = def.decorators;\n if (def.kind === 'field') element.initializer = def.value;\n return element;\n }\n\n function _coalesceGetterSetter(element, other) {\n if (element.descriptor.get !== undefined) {\n other.descriptor.get = element.descriptor.get;\n } else {\n other.descriptor.set = element.descriptor.set;\n }\n }\n\n function _coalesceClassElements(elements) {\n var newElements = [];\n\n var isSameElement = function(other) {\n return (\n other.kind === 'method' &&\n other.key === element.key &&\n other.placement === element.placement\n );\n };\n\n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var other;\n\n if (element.kind === 'method' && (other = newElements.find(isSameElement))) {\n if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {\n if (_hasDecorators(element) || _hasDecorators(other)) {\n throw new ReferenceError(\n 'Duplicated methods (' + element.key + \") can't be decorated.\"\n );\n }\n\n other.descriptor = element.descriptor;\n } else {\n if (_hasDecorators(element)) {\n if (_hasDecorators(other)) {\n throw new ReferenceError(\n \"Decorators can't be placed on different accessors with for \" +\n 'the same property (' +\n element.key +\n ').'\n );\n }\n\n other.decorators = element.decorators;\n }\n\n _coalesceGetterSetter(element, other);\n }\n } else {\n newElements.push(element);\n }\n }\n\n return newElements;\n }\n\n function _hasDecorators(element) {\n return element.decorators && element.decorators.length;\n }\n\n function _isDataDescriptor(desc) {\n return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);\n }\n\n function _optionalCallableProperty(obj, name) {\n var value = obj[name];\n\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(\"Expected '\" + name + \"' to be a function\");\n }\n\n return value;\n }\n\n function _classPrivateMethodGet(receiver, privateSet, fn) {\n if (!privateSet.has(receiver)) {\n throw new TypeError('attempted to get private field on non-instance');\n }\n\n return fn;\n }\n\n function _classPrivateMethodSet() {\n throw new TypeError('attempted to reassign private method');\n }\n\n function _wrapRegExp(re, groups) {\n _wrapRegExp = function(re, groups) {\n return new BabelRegExp(re, groups);\n };\n\n var _RegExp = _wrapNativeSuper(RegExp);\n\n var _super = RegExp.prototype;\n\n var _groups = new WeakMap();\n\n function BabelRegExp(re, groups) {\n var _this = _RegExp.call(this, re);\n\n _groups.set(_this, groups);\n\n return _this;\n }\n\n _inherits(BabelRegExp, _RegExp);\n\n BabelRegExp.prototype.exec = function(str) {\n var result = _super.exec.call(this, str);\n\n if (result) result.groups = buildGroups(result, this);\n return result;\n };\n\n BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {\n if (typeof substitution === 'string') {\n var groups = _groups.get(this);\n\n return _super[Symbol.replace].call(\n this,\n str,\n substitution.replace(/\\$<([^>]+)>/g, function(_, name) {\n return '$' + groups[name];\n })\n );\n } else if (typeof substitution === 'function') {\n var _this = this;\n\n return _super[Symbol.replace].call(this, str, function() {\n var args = [];\n args.push.apply(args, arguments);\n\n if (typeof args[args.length - 1] !== 'object') {\n args.push(buildGroups(args, _this));\n }\n\n return substitution.apply(this, args);\n });\n } else {\n return _super[Symbol.replace].call(this, str, substitution);\n }\n };\n\n function buildGroups(result, re) {\n var g = _groups.get(re);\n\n return Object.keys(g).reduce(function(groups, name) {\n groups[name] = result[g[name]];\n return groups;\n }, Object.create(null));\n }\n\n return _wrapRegExp.apply(this, arguments);\n }\n\n var arrayRemove = function arrayRemove(arr, index) {\n return arr.splice(index, 1);\n };\n\n var run = function run(cb, sync) {\n if (sync) {\n cb();\n } else if (document.hidden) {\n Promise.resolve(1).then(cb);\n } else {\n setTimeout(cb, 0);\n }\n };\n\n var on = function on() {\n var listeners = [];\n var off = function off(event, cb) {\n arrayRemove(\n listeners,\n listeners.findIndex(function(listener) {\n return listener.event === event && (listener.cb === cb || !cb);\n })\n );\n };\n var _fire = function fire(event, args, sync) {\n listeners\n .filter(function(listener) {\n return listener.event === event;\n })\n .map(function(listener) {\n return listener.cb;\n })\n .forEach(function(cb) {\n return run(function() {\n return cb.apply(void 0, _toConsumableArray(args));\n }, sync);\n });\n };\n return {\n fireSync: function fireSync(event) {\n for (\n var _len = arguments.length,\n args = new Array(_len > 1 ? _len - 1 : 0),\n _key = 1;\n _key < _len;\n _key++\n ) {\n args[_key - 1] = arguments[_key];\n }\n _fire(event, args, true);\n },\n fire: function fire(event) {\n for (\n var _len2 = arguments.length,\n args = new Array(_len2 > 1 ? _len2 - 1 : 0),\n _key2 = 1;\n _key2 < _len2;\n _key2++\n ) {\n args[_key2 - 1] = arguments[_key2];\n }\n _fire(event, args, false);\n },\n on: function on(event, cb) {\n listeners.push({ event: event, cb: cb });\n },\n onOnce: function onOnce(event, _cb) {\n listeners.push({\n event: event,\n cb: function cb() {\n off(event, _cb);\n _cb.apply(void 0, arguments);\n },\n });\n },\n off: off,\n };\n };\n\n var copyObjectPropertiesToObject = function copyObjectPropertiesToObject(\n src,\n target,\n excluded\n ) {\n Object.getOwnPropertyNames(src)\n .filter(function(property) {\n return !excluded.includes(property);\n })\n .forEach(function(key) {\n return Object.defineProperty(\n target,\n key,\n Object.getOwnPropertyDescriptor(src, key)\n );\n });\n };\n\n var PRIVATE = [\n 'fire',\n 'process',\n 'revert',\n 'load',\n 'on',\n 'off',\n 'onOnce',\n 'retryLoad',\n 'extend',\n 'archive',\n 'archived',\n 'release',\n 'released',\n 'requestProcessing',\n 'freeze',\n ];\n\n var createItemAPI = function createItemAPI(item) {\n var api = {};\n copyObjectPropertiesToObject(item, api, PRIVATE);\n return api;\n };\n\n var removeReleasedItems = function removeReleasedItems(items) {\n items.forEach(function(item, index) {\n if (item.released) {\n arrayRemove(items, index);\n }\n });\n };\n\n var ItemStatus = {\n INIT: 1,\n IDLE: 2,\n PROCESSING_QUEUED: 9,\n PROCESSING: 3,\n PROCESSING_COMPLETE: 5,\n PROCESSING_ERROR: 6,\n PROCESSING_REVERT_ERROR: 10,\n LOADING: 7,\n LOAD_ERROR: 8,\n };\n\n var FileOrigin = {\n INPUT: 1,\n LIMBO: 2,\n LOCAL: 3,\n };\n\n var getNonNumeric = function getNonNumeric(str) {\n return /[^0-9]+/.exec(str);\n };\n\n var getDecimalSeparator = function getDecimalSeparator() {\n return getNonNumeric((1.1).toLocaleString())[0];\n };\n\n var getThousandsSeparator = function getThousandsSeparator() {\n // Added for browsers that do not return the thousands separator (happend on native browser Android 4.4.4)\n // We check against the normal toString output and if they're the same return a comma when decimal separator is a dot\n var decimalSeparator = getDecimalSeparator();\n var thousandsStringWithSeparator = (1000.0).toLocaleString();\n var thousandsStringWithoutSeparator = (1000.0).toString();\n if (thousandsStringWithSeparator !== thousandsStringWithoutSeparator) {\n return getNonNumeric(thousandsStringWithSeparator)[0];\n }\n return decimalSeparator === '.' ? ',' : '.';\n };\n\n var Type = {\n BOOLEAN: 'boolean',\n INT: 'int',\n NUMBER: 'number',\n STRING: 'string',\n ARRAY: 'array',\n OBJECT: 'object',\n FUNCTION: 'function',\n ACTION: 'action',\n SERVER_API: 'serverapi',\n REGEX: 'regex',\n };\n\n // all registered filters\n var filters = [];\n\n // loops over matching filters and passes options to each filter, returning the mapped results\n var applyFilterChain = function applyFilterChain(key, value, utils) {\n return new Promise(function(resolve, reject) {\n // find matching filters for this key\n var matchingFilters = filters\n .filter(function(f) {\n return f.key === key;\n })\n .map(function(f) {\n return f.cb;\n });\n\n // resolve now\n if (matchingFilters.length === 0) {\n resolve(value);\n return;\n }\n\n // first filter to kick things of\n var initialFilter = matchingFilters.shift();\n\n // chain filters\n matchingFilters\n .reduce(\n // loop over promises passing value to next promise\n function(current, next) {\n return current.then(function(value) {\n return next(value, utils);\n });\n },\n\n // call initial filter, will return a promise\n initialFilter(value, utils)\n\n // all executed\n )\n .then(function(value) {\n return resolve(value);\n })\n .catch(function(error) {\n return reject(error);\n });\n });\n };\n\n var applyFilters = function applyFilters(key, value, utils) {\n return filters\n .filter(function(f) {\n return f.key === key;\n })\n .map(function(f) {\n return f.cb(value, utils);\n });\n };\n\n // adds a new filter to the list\n var addFilter = function addFilter(key, cb) {\n return filters.push({ key: key, cb: cb });\n };\n\n var extendDefaultOptions = function extendDefaultOptions(additionalOptions) {\n return Object.assign(defaultOptions, additionalOptions);\n };\n\n var getOptions = function getOptions() {\n return Object.assign({}, defaultOptions);\n };\n\n var setOptions = function setOptions(opts) {\n forin(opts, function(key, value) {\n // key does not exist, so this option cannot be set\n if (!defaultOptions[key]) {\n return;\n }\n defaultOptions[key][0] = getValueByType(\n value,\n defaultOptions[key][0],\n defaultOptions[key][1]\n );\n });\n };\n\n // default options on app\n var defaultOptions = {\n // the id to add to the root element\n id: [null, Type.STRING],\n\n // input field name to use\n name: ['filepond', Type.STRING],\n\n // disable the field\n disabled: [false, Type.BOOLEAN],\n\n // classname to put on wrapper\n className: [null, Type.STRING],\n\n // is the field required\n required: [false, Type.BOOLEAN],\n\n // Allow media capture when value is set\n captureMethod: [null, Type.STRING],\n // - \"camera\", \"microphone\" or \"camcorder\",\n // - Does not work with multiple on apple devices\n // - If set, acceptedFileTypes must be made to match with media wildcard \"image/*\", \"audio/*\" or \"video/*\"\n\n // sync `acceptedFileTypes` property with `accept` attribute\n allowSyncAcceptAttribute: [true, Type.BOOLEAN],\n\n // Feature toggles\n allowDrop: [true, Type.BOOLEAN], // Allow dropping of files\n allowBrowse: [true, Type.BOOLEAN], // Allow browsing the file system\n allowPaste: [true, Type.BOOLEAN], // Allow pasting files\n allowMultiple: [false, Type.BOOLEAN], // Allow multiple files (disabled by default, as multiple attribute is also required on input to allow multiple)\n allowReplace: [true, Type.BOOLEAN], // Allow dropping a file on other file to replace it (only works when multiple is set to false)\n allowRevert: [true, Type.BOOLEAN], // Allows user to revert file upload\n allowRemove: [true, Type.BOOLEAN], // Allow user to remove a file\n allowProcess: [true, Type.BOOLEAN], // Allows user to process a file, when set to false, this removes the file upload button\n allowReorder: [false, Type.BOOLEAN], // Allow reordering of files\n allowDirectoriesOnly: [false, Type.BOOLEAN], // Allow only selecting directories with browse (no support for filtering dnd at this point)\n\n // Try store file if `server` not set\n storeAsFile: [false, Type.BOOLEAN],\n\n // Revert mode\n forceRevert: [false, Type.BOOLEAN], // Set to 'force' to require the file to be reverted before removal\n\n // Input requirements\n maxFiles: [null, Type.INT], // Max number of files\n checkValidity: [false, Type.BOOLEAN], // Enables custom validity messages\n\n // Where to put file\n itemInsertLocationFreedom: [true, Type.BOOLEAN], // Set to false to always add items to begin or end of list\n itemInsertLocation: ['before', Type.STRING], // Default index in list to add items that have been dropped at the top of the list\n itemInsertInterval: [75, Type.INT],\n\n // Drag 'n Drop related\n dropOnPage: [false, Type.BOOLEAN], // Allow dropping of files anywhere on page (prevents browser from opening file if dropped outside of Up)\n dropOnElement: [true, Type.BOOLEAN], // Drop needs to happen on element (set to false to also load drops outside of Up)\n dropValidation: [false, Type.BOOLEAN], // Enable or disable validating files on drop\n ignoredFiles: [['.ds_store', 'thumbs.db', 'desktop.ini'], Type.ARRAY],\n\n // Upload related\n instantUpload: [true, Type.BOOLEAN], // Should upload files immediately on drop\n maxParallelUploads: [2, Type.INT], // Maximum files to upload in parallel\n allowMinimumUploadDuration: [true, Type.BOOLEAN], // if true uploads take at least 750 ms, this ensures the user sees the upload progress giving trust the upload actually happened\n\n // Chunks\n chunkUploads: [false, Type.BOOLEAN], // Enable chunked uploads\n chunkForce: [false, Type.BOOLEAN], // Force use of chunk uploads even for files smaller than chunk size\n chunkSize: [5000000, Type.INT], // Size of chunks (5MB default)\n chunkRetryDelays: [[500, 1000, 3000], Type.ARRAY], // Amount of times to retry upload of a chunk when it fails\n\n // The server api end points to use for uploading (see docs)\n server: [null, Type.SERVER_API],\n\n // File size calculations, can set to 1024, this is only used for display, properties use file size base 1000\n fileSizeBase: [1000, Type.INT],\n\n // Labels and status messages\n labelFileSizeBytes: ['bytes', Type.STRING],\n labelFileSizeKilobytes: ['KB', Type.STRING],\n labelFileSizeMegabytes: ['MB', Type.STRING],\n labelFileSizeGigabytes: ['GB', Type.STRING],\n\n labelDecimalSeparator: [getDecimalSeparator(), Type.STRING], // Default is locale separator\n labelThousandsSeparator: [getThousandsSeparator(), Type.STRING], // Default is locale separator\n\n labelIdle: [\n 'Drag & Drop your files or Browse',\n Type.STRING,\n ],\n\n labelInvalidField: ['Field contains invalid files', Type.STRING],\n labelFileWaitingForSize: ['Waiting for size', Type.STRING],\n labelFileSizeNotAvailable: ['Size not available', Type.STRING],\n labelFileCountSingular: ['file in list', Type.STRING],\n labelFileCountPlural: ['files in list', Type.STRING],\n labelFileLoading: ['Loading', Type.STRING],\n labelFileAdded: ['Added', Type.STRING], // assistive only\n labelFileLoadError: ['Error during load', Type.STRING],\n labelFileRemoved: ['Removed', Type.STRING], // assistive only\n labelFileRemoveError: ['Error during remove', Type.STRING],\n labelFileProcessing: ['Uploading', Type.STRING],\n labelFileProcessingComplete: ['Upload complete', Type.STRING],\n labelFileProcessingAborted: ['Upload cancelled', Type.STRING],\n labelFileProcessingError: ['Error during upload', Type.STRING],\n labelFileProcessingRevertError: ['Error during revert', Type.STRING],\n\n labelTapToCancel: ['tap to cancel', Type.STRING],\n labelTapToRetry: ['tap to retry', Type.STRING],\n labelTapToUndo: ['tap to undo', Type.STRING],\n\n labelButtonRemoveItem: ['Remove', Type.STRING],\n labelButtonAbortItemLoad: ['Abort', Type.STRING],\n labelButtonRetryItemLoad: ['Retry', Type.STRING],\n labelButtonAbortItemProcessing: ['Cancel', Type.STRING],\n labelButtonUndoItemProcessing: ['Undo', Type.STRING],\n labelButtonRetryItemProcessing: ['Retry', Type.STRING],\n labelButtonProcessItem: ['Upload', Type.STRING],\n\n // make sure width and height plus viewpox are even numbers so icons are nicely centered\n iconRemove: [\n '',\n Type.STRING,\n ],\n\n iconProcess: [\n '',\n Type.STRING,\n ],\n\n iconRetry: [\n '',\n Type.STRING,\n ],\n\n iconUndo: [\n '',\n Type.STRING,\n ],\n\n iconDone: [\n '',\n Type.STRING,\n ],\n\n // event handlers\n oninit: [null, Type.FUNCTION],\n onwarning: [null, Type.FUNCTION],\n onerror: [null, Type.FUNCTION],\n onactivatefile: [null, Type.FUNCTION],\n oninitfile: [null, Type.FUNCTION],\n onaddfilestart: [null, Type.FUNCTION],\n onaddfileprogress: [null, Type.FUNCTION],\n onaddfile: [null, Type.FUNCTION],\n onprocessfilestart: [null, Type.FUNCTION],\n onprocessfileprogress: [null, Type.FUNCTION],\n onprocessfileabort: [null, Type.FUNCTION],\n onprocessfilerevert: [null, Type.FUNCTION],\n onprocessfile: [null, Type.FUNCTION],\n onprocessfiles: [null, Type.FUNCTION],\n onremovefile: [null, Type.FUNCTION],\n onpreparefile: [null, Type.FUNCTION],\n onupdatefiles: [null, Type.FUNCTION],\n onreorderfiles: [null, Type.FUNCTION],\n\n // hooks\n beforeDropFile: [null, Type.FUNCTION],\n beforeAddFile: [null, Type.FUNCTION],\n beforeRemoveFile: [null, Type.FUNCTION],\n beforePrepareFile: [null, Type.FUNCTION],\n\n // styles\n stylePanelLayout: [null, Type.STRING], // null 'integrated', 'compact', 'circle'\n stylePanelAspectRatio: [null, Type.STRING], // null or '3:2' or 1\n styleItemPanelAspectRatio: [null, Type.STRING],\n styleButtonRemoveItemPosition: ['left', Type.STRING],\n styleButtonProcessItemPosition: ['right', Type.STRING],\n styleLoadIndicatorPosition: ['right', Type.STRING],\n styleProgressIndicatorPosition: ['right', Type.STRING],\n styleButtonRemoveItemAlign: [false, Type.BOOLEAN],\n\n // custom initial files array\n files: [[], Type.ARRAY],\n\n // show support by displaying credits\n credits: [['https://pqina.nl/', 'Powered by PQINA'], Type.ARRAY],\n };\n\n var getItemByQuery = function getItemByQuery(items, query) {\n // just return first index\n if (isEmpty(query)) {\n return items[0] || null;\n }\n\n // query is index\n if (isInt(query)) {\n return items[query] || null;\n }\n\n // if query is item, get the id\n if (typeof query === 'object') {\n query = query.id;\n }\n\n // assume query is a string and return item by id\n return (\n items.find(function(item) {\n return item.id === query;\n }) || null\n );\n };\n\n var getNumericAspectRatioFromString = function getNumericAspectRatioFromString(aspectRatio) {\n if (isEmpty(aspectRatio)) {\n return aspectRatio;\n }\n if (/:/.test(aspectRatio)) {\n var parts = aspectRatio.split(':');\n return parts[1] / parts[0];\n }\n return parseFloat(aspectRatio);\n };\n\n var getActiveItems = function getActiveItems(items) {\n return items.filter(function(item) {\n return !item.archived;\n });\n };\n\n var Status = {\n EMPTY: 0,\n IDLE: 1, // waiting\n ERROR: 2, // a file is in error state\n BUSY: 3, // busy processing or loading\n READY: 4, // all files uploaded\n };\n\n var res = null;\n var canUpdateFileInput = function canUpdateFileInput() {\n if (res === null) {\n try {\n var dataTransfer = new DataTransfer();\n dataTransfer.items.add(new File(['hello world'], 'This_Works.txt'));\n var el = document.createElement('input');\n el.setAttribute('type', 'file');\n el.files = dataTransfer.files;\n res = el.files.length === 1;\n } catch (err) {\n res = false;\n }\n }\n return res;\n };\n\n var ITEM_ERROR = [\n ItemStatus.LOAD_ERROR,\n ItemStatus.PROCESSING_ERROR,\n ItemStatus.PROCESSING_REVERT_ERROR,\n ];\n\n var ITEM_BUSY = [\n ItemStatus.LOADING,\n ItemStatus.PROCESSING,\n ItemStatus.PROCESSING_QUEUED,\n ItemStatus.INIT,\n ];\n\n var ITEM_READY = [ItemStatus.PROCESSING_COMPLETE];\n\n var isItemInErrorState = function isItemInErrorState(item) {\n return ITEM_ERROR.includes(item.status);\n };\n var isItemInBusyState = function isItemInBusyState(item) {\n return ITEM_BUSY.includes(item.status);\n };\n var isItemInReadyState = function isItemInReadyState(item) {\n return ITEM_READY.includes(item.status);\n };\n\n var isAsync = function isAsync(state) {\n return (\n isObject(state.options.server) &&\n (isObject(state.options.server.process) || isFunction(state.options.server.process))\n );\n };\n\n var queries = function queries(state) {\n return {\n GET_STATUS: function GET_STATUS() {\n var items = getActiveItems(state.items);\n var EMPTY = Status.EMPTY,\n ERROR = Status.ERROR,\n BUSY = Status.BUSY,\n IDLE = Status.IDLE,\n READY = Status.READY;\n\n if (items.length === 0) return EMPTY;\n\n if (items.some(isItemInErrorState)) return ERROR;\n\n if (items.some(isItemInBusyState)) return BUSY;\n\n if (items.some(isItemInReadyState)) return READY;\n\n return IDLE;\n },\n\n GET_ITEM: function GET_ITEM(query) {\n return getItemByQuery(state.items, query);\n },\n\n GET_ACTIVE_ITEM: function GET_ACTIVE_ITEM(query) {\n return getItemByQuery(getActiveItems(state.items), query);\n },\n\n GET_ACTIVE_ITEMS: function GET_ACTIVE_ITEMS() {\n return getActiveItems(state.items);\n },\n\n GET_ITEMS: function GET_ITEMS() {\n return state.items;\n },\n\n GET_ITEM_NAME: function GET_ITEM_NAME(query) {\n var item = getItemByQuery(state.items, query);\n return item ? item.filename : null;\n },\n\n GET_ITEM_SIZE: function GET_ITEM_SIZE(query) {\n var item = getItemByQuery(state.items, query);\n return item ? item.fileSize : null;\n },\n\n GET_STYLES: function GET_STYLES() {\n return Object.keys(state.options)\n .filter(function(key) {\n return /^style/.test(key);\n })\n .map(function(option) {\n return {\n name: option,\n value: state.options[option],\n };\n });\n },\n\n GET_PANEL_ASPECT_RATIO: function GET_PANEL_ASPECT_RATIO() {\n var isShapeCircle = /circle/.test(state.options.stylePanelLayout);\n var aspectRatio = isShapeCircle\n ? 1\n : getNumericAspectRatioFromString(state.options.stylePanelAspectRatio);\n return aspectRatio;\n },\n\n GET_ITEM_PANEL_ASPECT_RATIO: function GET_ITEM_PANEL_ASPECT_RATIO() {\n return state.options.styleItemPanelAspectRatio;\n },\n\n GET_ITEMS_BY_STATUS: function GET_ITEMS_BY_STATUS(status) {\n return getActiveItems(state.items).filter(function(item) {\n return item.status === status;\n });\n },\n\n GET_TOTAL_ITEMS: function GET_TOTAL_ITEMS() {\n return getActiveItems(state.items).length;\n },\n\n SHOULD_UPDATE_FILE_INPUT: function SHOULD_UPDATE_FILE_INPUT() {\n return state.options.storeAsFile && canUpdateFileInput() && !isAsync(state);\n },\n\n IS_ASYNC: function IS_ASYNC() {\n return isAsync(state);\n },\n\n GET_FILE_SIZE_LABELS: function GET_FILE_SIZE_LABELS(query) {\n return {\n labelBytes: query('GET_LABEL_FILE_SIZE_BYTES') || undefined,\n labelKilobytes: query('GET_LABEL_FILE_SIZE_KILOBYTES') || undefined,\n labelMegabytes: query('GET_LABEL_FILE_SIZE_MEGABYTES') || undefined,\n labelGigabytes: query('GET_LABEL_FILE_SIZE_GIGABYTES') || undefined,\n };\n },\n };\n };\n\n var hasRoomForItem = function hasRoomForItem(state) {\n var count = getActiveItems(state.items).length;\n\n // if cannot have multiple items, to add one item it should currently not contain items\n if (!state.options.allowMultiple) {\n return count === 0;\n }\n\n // if allows multiple items, we check if a max item count has been set, if not, there's no limit\n var maxFileCount = state.options.maxFiles;\n if (maxFileCount === null) {\n return true;\n }\n\n // we check if the current count is smaller than the max count, if so, another file can still be added\n if (count < maxFileCount) {\n return true;\n }\n\n // no more room for another file\n return false;\n };\n\n var limit = function limit(value, min, max) {\n return Math.max(Math.min(max, value), min);\n };\n\n var arrayInsert = function arrayInsert(arr, index, item) {\n return arr.splice(index, 0, item);\n };\n\n var insertItem = function insertItem(items, item, index) {\n if (isEmpty(item)) {\n return null;\n }\n\n // if index is undefined, append\n if (typeof index === 'undefined') {\n items.push(item);\n return item;\n }\n\n // limit the index to the size of the items array\n index = limit(index, 0, items.length);\n\n // add item to array\n arrayInsert(items, index, item);\n\n // expose\n return item;\n };\n\n var isBase64DataURI = function isBase64DataURI(str) {\n return /^\\s*data:([a-z]+\\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\\-._~:@\\/?%\\s]*)\\s*$/i.test(\n str\n );\n };\n\n var getFilenameFromURL = function getFilenameFromURL(url) {\n return url\n .split('/')\n .pop()\n .split('?')\n .shift();\n };\n\n var getExtensionFromFilename = function getExtensionFromFilename(name) {\n return name.split('.').pop();\n };\n\n var guesstimateExtension = function guesstimateExtension(type) {\n // if no extension supplied, exit here\n if (typeof type !== 'string') {\n return '';\n }\n\n // get subtype\n var subtype = type.split('/').pop();\n\n // is svg subtype\n if (/svg/.test(subtype)) {\n return 'svg';\n }\n\n if (/zip|compressed/.test(subtype)) {\n return 'zip';\n }\n\n if (/plain/.test(subtype)) {\n return 'txt';\n }\n\n if (/msword/.test(subtype)) {\n return 'doc';\n }\n\n // if is valid subtype\n if (/[a-z]+/.test(subtype)) {\n // always use jpg extension\n if (subtype === 'jpeg') {\n return 'jpg';\n }\n\n // return subtype\n return subtype;\n }\n\n return '';\n };\n\n var leftPad = function leftPad(value) {\n var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return (padding + value).slice(-padding.length);\n };\n\n var getDateString = function getDateString() {\n var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();\n return (\n date.getFullYear() +\n '-' +\n leftPad(date.getMonth() + 1, '00') +\n '-' +\n leftPad(date.getDate(), '00') +\n '_' +\n leftPad(date.getHours(), '00') +\n '-' +\n leftPad(date.getMinutes(), '00') +\n '-' +\n leftPad(date.getSeconds(), '00')\n );\n };\n\n var getFileFromBlob = function getFileFromBlob(blob, filename) {\n var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n var extension = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n var file =\n typeof type === 'string'\n ? blob.slice(0, blob.size, type)\n : blob.slice(0, blob.size, blob.type);\n file.lastModifiedDate = new Date();\n\n // copy relative path\n if (blob._relativePath) file._relativePath = blob._relativePath;\n\n // if blob has name property, use as filename if no filename supplied\n if (!isString(filename)) {\n filename = getDateString();\n }\n\n // if filename supplied but no extension and filename has extension\n if (filename && extension === null && getExtensionFromFilename(filename)) {\n file.name = filename;\n } else {\n extension = extension || guesstimateExtension(file.type);\n file.name = filename + (extension ? '.' + extension : '');\n }\n\n return file;\n };\n\n var getBlobBuilder = function getBlobBuilder() {\n return (window.BlobBuilder =\n window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder);\n };\n\n var createBlob = function createBlob(arrayBuffer, mimeType) {\n var BB = getBlobBuilder();\n\n if (BB) {\n var bb = new BB();\n bb.append(arrayBuffer);\n return bb.getBlob(mimeType);\n }\n\n return new Blob([arrayBuffer], {\n type: mimeType,\n });\n };\n\n var getBlobFromByteStringWithMimeType = function getBlobFromByteStringWithMimeType(\n byteString,\n mimeType\n ) {\n var ab = new ArrayBuffer(byteString.length);\n var ia = new Uint8Array(ab);\n\n for (var i = 0; i < byteString.length; i++) {\n ia[i] = byteString.charCodeAt(i);\n }\n\n return createBlob(ab, mimeType);\n };\n\n var getMimeTypeFromBase64DataURI = function getMimeTypeFromBase64DataURI(dataURI) {\n return (/^data:(.+);/.exec(dataURI) || [])[1] || null;\n };\n\n var getBase64DataFromBase64DataURI = function getBase64DataFromBase64DataURI(dataURI) {\n // get data part of string (remove data:image/jpeg...,)\n var data = dataURI.split(',')[1];\n\n // remove any whitespace as that causes InvalidCharacterError in IE\n return data.replace(/\\s/g, '');\n };\n\n var getByteStringFromBase64DataURI = function getByteStringFromBase64DataURI(dataURI) {\n return atob(getBase64DataFromBase64DataURI(dataURI));\n };\n\n var getBlobFromBase64DataURI = function getBlobFromBase64DataURI(dataURI) {\n var mimeType = getMimeTypeFromBase64DataURI(dataURI);\n var byteString = getByteStringFromBase64DataURI(dataURI);\n\n return getBlobFromByteStringWithMimeType(byteString, mimeType);\n };\n\n var getFileFromBase64DataURI = function getFileFromBase64DataURI(dataURI, filename, extension) {\n return getFileFromBlob(getBlobFromBase64DataURI(dataURI), filename, null, extension);\n };\n\n var getFileNameFromHeader = function getFileNameFromHeader(header) {\n // test if is content disposition header, if not exit\n if (!/^content-disposition:/i.test(header)) return null;\n\n // get filename parts\n var matches = header\n .split(/filename=|filename\\*=.+''/)\n .splice(1)\n .map(function(name) {\n return name.trim().replace(/^[\"']|[;\"']{0,2}$/g, '');\n })\n .filter(function(name) {\n return name.length;\n });\n\n return matches.length ? decodeURI(matches[matches.length - 1]) : null;\n };\n\n var getFileSizeFromHeader = function getFileSizeFromHeader(header) {\n if (/content-length:/i.test(header)) {\n var size = header.match(/[0-9]+/)[0];\n return size ? parseInt(size, 10) : null;\n }\n return null;\n };\n\n var getTranfserIdFromHeader = function getTranfserIdFromHeader(header) {\n if (/x-content-transfer-id:/i.test(header)) {\n var id = (header.split(':')[1] || '').trim();\n return id || null;\n }\n return null;\n };\n\n var getFileInfoFromHeaders = function getFileInfoFromHeaders(headers) {\n var info = {\n source: null,\n name: null,\n size: null,\n };\n\n var rows = headers.split('\\n');\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n try {\n for (\n var _iterator = rows[Symbol.iterator](), _step;\n !(_iteratorNormalCompletion = (_step = _iterator.next()).done);\n _iteratorNormalCompletion = true\n ) {\n var header = _step.value;\n\n var name = getFileNameFromHeader(header);\n if (name) {\n info.name = name;\n continue;\n }\n\n var size = getFileSizeFromHeader(header);\n if (size) {\n info.size = size;\n continue;\n }\n\n var source = getTranfserIdFromHeader(header);\n if (source) {\n info.source = source;\n continue;\n }\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return != null) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return info;\n };\n\n var createFileLoader = function createFileLoader(fetchFn) {\n var state = {\n source: null,\n complete: false,\n progress: 0,\n size: null,\n timestamp: null,\n duration: 0,\n request: null,\n };\n\n var getProgress = function getProgress() {\n return state.progress;\n };\n var abort = function abort() {\n if (state.request && state.request.abort) {\n state.request.abort();\n }\n };\n\n // load source\n var load = function load() {\n // get quick reference\n var source = state.source;\n\n api.fire('init', source);\n\n // Load Files\n if (source instanceof File) {\n api.fire('load', source);\n } else if (source instanceof Blob) {\n // Load blobs, set default name to current date\n api.fire('load', getFileFromBlob(source, source.name));\n } else if (isBase64DataURI(source)) {\n // Load base 64, set default name to current date\n api.fire('load', getFileFromBase64DataURI(source));\n } else {\n // Deal as if is external URL, let's load it!\n loadURL(source);\n }\n };\n\n // loads a url\n var loadURL = function loadURL(url) {\n // is remote url and no fetch method supplied\n if (!fetchFn) {\n api.fire('error', {\n type: 'error',\n body: \"Can't load URL\",\n code: 400,\n });\n\n return;\n }\n\n // set request start\n state.timestamp = Date.now();\n\n // load file\n state.request = fetchFn(\n url,\n function(response) {\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // done!\n state.complete = true;\n\n // turn blob response into a file\n if (response instanceof Blob) {\n response = getFileFromBlob(\n response,\n response.name || getFilenameFromURL(url)\n );\n }\n\n api.fire(\n 'load',\n // if has received blob, we go with blob, if no response, we return null\n response instanceof Blob ? response : response ? response.body : null\n );\n },\n function(error) {\n api.fire(\n 'error',\n typeof error === 'string'\n ? {\n type: 'error',\n code: 0,\n body: error,\n }\n : error\n );\n },\n function(computable, current, total) {\n // collected some meta data already\n if (total) {\n state.size = total;\n }\n\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // if we can't compute progress, we're not going to fire progress events\n if (!computable) {\n state.progress = null;\n return;\n }\n\n // update progress percentage\n state.progress = current / total;\n\n // expose\n api.fire('progress', state.progress);\n },\n function() {\n api.fire('abort');\n },\n function(response) {\n var fileinfo = getFileInfoFromHeaders(\n typeof response === 'string' ? response : response.headers\n );\n api.fire('meta', {\n size: state.size || fileinfo.size,\n filename: fileinfo.name,\n source: fileinfo.source,\n });\n }\n );\n };\n\n var api = Object.assign({}, on(), {\n setSource: function setSource(source) {\n return (state.source = source);\n },\n getProgress: getProgress, // file load progress\n abort: abort, // abort file load\n load: load, // start load\n });\n\n return api;\n };\n\n var isGet = function isGet(method) {\n return /GET|HEAD/.test(method);\n };\n\n var sendRequest = function sendRequest(data, url, options) {\n var api = {\n onheaders: function onheaders() {},\n onprogress: function onprogress() {},\n onload: function onload() {},\n ontimeout: function ontimeout() {},\n onerror: function onerror() {},\n onabort: function onabort() {},\n abort: function abort() {\n aborted = true;\n xhr.abort();\n },\n };\n\n // timeout identifier, only used when timeout is defined\n var aborted = false;\n var headersReceived = false;\n\n // set default options\n options = Object.assign(\n {\n method: 'POST',\n headers: {},\n withCredentials: false,\n },\n options\n );\n\n // encode url\n url = encodeURI(url);\n\n // if method is GET, add any received data to url\n\n if (isGet(options.method) && data) {\n url =\n '' +\n url +\n encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data));\n }\n\n // create request\n var xhr = new XMLHttpRequest();\n\n // progress of load\n var process = isGet(options.method) ? xhr : xhr.upload;\n process.onprogress = function(e) {\n // no progress event when aborted ( onprogress is called once after abort() )\n if (aborted) {\n return;\n }\n\n api.onprogress(e.lengthComputable, e.loaded, e.total);\n };\n\n // tries to get header info to the app as fast as possible\n xhr.onreadystatechange = function() {\n // not interesting in these states ('unsent' and 'openend' as they don't give us any additional info)\n if (xhr.readyState < 2) {\n return;\n }\n\n // no server response\n if (xhr.readyState === 4 && xhr.status === 0) {\n return;\n }\n\n if (headersReceived) {\n return;\n }\n\n headersReceived = true;\n\n // we've probably received some useful data in response headers\n api.onheaders(xhr);\n };\n\n // load successful\n xhr.onload = function() {\n // is classified as valid response\n if (xhr.status >= 200 && xhr.status < 300) {\n api.onload(xhr);\n } else {\n api.onerror(xhr);\n }\n };\n\n // error during load\n xhr.onerror = function() {\n return api.onerror(xhr);\n };\n\n // request aborted\n xhr.onabort = function() {\n aborted = true;\n api.onabort();\n };\n\n // request timeout\n xhr.ontimeout = function() {\n return api.ontimeout(xhr);\n };\n\n // open up open up!\n xhr.open(options.method, url, true);\n\n // set timeout if defined (do it after open so IE11 plays ball)\n if (isInt(options.timeout)) {\n xhr.timeout = options.timeout;\n }\n\n // add headers\n Object.keys(options.headers).forEach(function(key) {\n var value = unescape(encodeURIComponent(options.headers[key]));\n xhr.setRequestHeader(key, value);\n });\n\n // set type of response\n if (options.responseType) {\n xhr.responseType = options.responseType;\n }\n\n // set credentials\n if (options.withCredentials) {\n xhr.withCredentials = true;\n }\n\n // let's send our data\n xhr.send(data);\n\n return api;\n };\n\n var createResponse = function createResponse(type, code, body, headers) {\n return {\n type: type,\n code: code,\n body: body,\n headers: headers,\n };\n };\n\n var createTimeoutResponse = function createTimeoutResponse(cb) {\n return function(xhr) {\n cb(createResponse('error', 0, 'Timeout', xhr.getAllResponseHeaders()));\n };\n };\n\n var hasQS = function hasQS(str) {\n return /\\?/.test(str);\n };\n var buildURL = function buildURL() {\n var url = '';\n for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) {\n parts[_key] = arguments[_key];\n }\n parts.forEach(function(part) {\n url += hasQS(url) && hasQS(part) ? part.replace(/\\?/, '&') : part;\n });\n return url;\n };\n\n var createFetchFunction = function createFetchFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n // custom handler (should also handle file, load, error, progress and abort)\n if (typeof action === 'function') {\n return action;\n }\n\n // no action supplied\n if (!action || !isString(action.url)) {\n return null;\n }\n\n // set onload hanlder\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // internal handler\n return function(url, load, error, progress, abort, headers) {\n // do local or remote request based on if the url is external\n var request = sendRequest(\n url,\n buildURL(apiUrl, action.url),\n Object.assign({}, action, {\n responseType: 'blob',\n })\n );\n\n request.onload = function(xhr) {\n // get headers\n var headers = xhr.getAllResponseHeaders();\n\n // get filename\n var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);\n\n // create response\n load(\n createResponse(\n 'load',\n xhr.status,\n action.method === 'HEAD'\n ? null\n : getFileFromBlob(onload(xhr.response), filename),\n headers\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onheaders = function(xhr) {\n headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n };\n\n var ChunkStatus = {\n QUEUED: 0,\n COMPLETE: 1,\n PROCESSING: 2,\n ERROR: 3,\n WAITING: 4,\n };\n\n /*\n function signature:\n (file, metadata, load, error, progress, abort, transfer, options) => {\n return {\n abort:() => {}\n }\n }\n */\n\n // apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options\n var processFileChunked = function processFileChunked(\n apiUrl,\n action,\n name,\n file,\n metadata,\n load,\n error,\n progress,\n abort,\n transfer,\n options\n ) {\n // all chunks\n var chunks = [];\n var chunkTransferId = options.chunkTransferId,\n chunkServer = options.chunkServer,\n chunkSize = options.chunkSize,\n chunkRetryDelays = options.chunkRetryDelays;\n\n // default state\n var state = {\n serverId: chunkTransferId,\n aborted: false,\n };\n\n // set onload handlers\n var ondata =\n action.ondata ||\n function(fd) {\n return fd;\n };\n var onload =\n action.onload ||\n function(xhr, method) {\n return method === 'HEAD' ? xhr.getResponseHeader('Upload-Offset') : xhr.response;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // create server hook\n var requestTransferId = function requestTransferId(cb) {\n var formData = new FormData();\n\n // add metadata under same name\n if (isObject(metadata)) formData.append(name, JSON.stringify(metadata));\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(file, metadata)\n : Object.assign({}, action.headers, {\n 'Upload-Length': file.size,\n });\n\n var requestParams = Object.assign({}, action, {\n headers: headers,\n });\n\n // send request object\n var request = sendRequest(\n ondata(formData),\n buildURL(apiUrl, action.url),\n requestParams\n );\n\n request.onload = function(xhr) {\n return cb(onload(xhr, requestParams.method));\n };\n\n request.onerror = function(xhr) {\n return error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n };\n\n var requestTransferOffset = function requestTransferOffset(cb) {\n var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(state.serverId)\n : Object.assign({}, action.headers);\n\n var requestParams = {\n headers: headers,\n method: 'HEAD',\n };\n\n var request = sendRequest(null, requestUrl, requestParams);\n\n request.onload = function(xhr) {\n return cb(onload(xhr, requestParams.method));\n };\n\n request.onerror = function(xhr) {\n return error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n };\n\n // create chunks\n var lastChunkIndex = Math.floor(file.size / chunkSize);\n for (var i = 0; i <= lastChunkIndex; i++) {\n var offset = i * chunkSize;\n var data = file.slice(offset, offset + chunkSize, 'application/offset+octet-stream');\n chunks[i] = {\n index: i,\n size: data.size,\n offset: offset,\n data: data,\n file: file,\n progress: 0,\n retries: _toConsumableArray(chunkRetryDelays),\n status: ChunkStatus.QUEUED,\n error: null,\n request: null,\n timeout: null,\n };\n }\n\n var completeProcessingChunks = function completeProcessingChunks() {\n return load(state.serverId);\n };\n\n var canProcessChunk = function canProcessChunk(chunk) {\n return chunk.status === ChunkStatus.QUEUED || chunk.status === ChunkStatus.ERROR;\n };\n\n var processChunk = function processChunk(chunk) {\n // processing is paused, wait here\n if (state.aborted) return;\n\n // get next chunk to process\n chunk = chunk || chunks.find(canProcessChunk);\n\n // no more chunks to process\n if (!chunk) {\n // all done?\n if (\n chunks.every(function(chunk) {\n return chunk.status === ChunkStatus.COMPLETE;\n })\n ) {\n completeProcessingChunks();\n }\n\n // no chunk to handle\n return;\n }\n\n // now processing this chunk\n chunk.status = ChunkStatus.PROCESSING;\n chunk.progress = null;\n\n // allow parsing of formdata\n var ondata =\n chunkServer.ondata ||\n function(fd) {\n return fd;\n };\n var onerror =\n chunkServer.onerror ||\n function(res) {\n return null;\n };\n\n // send request object\n var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);\n\n var headers =\n typeof chunkServer.headers === 'function'\n ? chunkServer.headers(chunk)\n : Object.assign({}, chunkServer.headers, {\n 'Content-Type': 'application/offset+octet-stream',\n 'Upload-Offset': chunk.offset,\n 'Upload-Length': file.size,\n 'Upload-Name': file.name,\n });\n\n var request = (chunk.request = sendRequest(\n ondata(chunk.data),\n requestUrl,\n Object.assign({}, chunkServer, {\n headers: headers,\n })\n ));\n\n request.onload = function() {\n // done!\n chunk.status = ChunkStatus.COMPLETE;\n\n // remove request reference\n chunk.request = null;\n\n // start processing more chunks\n processChunks();\n };\n\n request.onprogress = function(lengthComputable, loaded, total) {\n chunk.progress = lengthComputable ? loaded : null;\n updateTotalProgress();\n };\n\n request.onerror = function(xhr) {\n chunk.status = ChunkStatus.ERROR;\n chunk.request = null;\n chunk.error = onerror(xhr.response) || xhr.statusText;\n if (!retryProcessChunk(chunk)) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n }\n };\n\n request.ontimeout = function(xhr) {\n chunk.status = ChunkStatus.ERROR;\n chunk.request = null;\n if (!retryProcessChunk(chunk)) {\n createTimeoutResponse(error)(xhr);\n }\n };\n\n request.onabort = function() {\n chunk.status = ChunkStatus.QUEUED;\n chunk.request = null;\n abort();\n };\n };\n\n var retryProcessChunk = function retryProcessChunk(chunk) {\n // no more retries left\n if (chunk.retries.length === 0) return false;\n\n // new retry\n chunk.status = ChunkStatus.WAITING;\n clearTimeout(chunk.timeout);\n chunk.timeout = setTimeout(function() {\n processChunk(chunk);\n }, chunk.retries.shift());\n\n // we're going to retry\n return true;\n };\n\n var updateTotalProgress = function updateTotalProgress() {\n // calculate total progress fraction\n var totalBytesTransfered = chunks.reduce(function(p, chunk) {\n if (p === null || chunk.progress === null) return null;\n return p + chunk.progress;\n }, 0);\n\n // can't compute progress\n if (totalBytesTransfered === null) return progress(false, 0, 0);\n\n // calculate progress values\n var totalSize = chunks.reduce(function(total, chunk) {\n return total + chunk.size;\n }, 0);\n\n // can update progress indicator\n progress(true, totalBytesTransfered, totalSize);\n };\n\n // process new chunks\n var processChunks = function processChunks() {\n var totalProcessing = chunks.filter(function(chunk) {\n return chunk.status === ChunkStatus.PROCESSING;\n }).length;\n if (totalProcessing >= 1) return;\n processChunk();\n };\n\n var abortChunks = function abortChunks() {\n chunks.forEach(function(chunk) {\n clearTimeout(chunk.timeout);\n if (chunk.request) {\n chunk.request.abort();\n }\n });\n };\n\n // let's go!\n if (!state.serverId) {\n requestTransferId(function(serverId) {\n // stop here if aborted, might have happened in between request and callback\n if (state.aborted) return;\n\n // pass back to item so we can use it if something goes wrong\n transfer(serverId);\n\n // store internally\n state.serverId = serverId;\n processChunks();\n });\n } else {\n requestTransferOffset(function(offset) {\n // stop here if aborted, might have happened in between request and callback\n if (state.aborted) return;\n\n // mark chunks with lower offset as complete\n chunks\n .filter(function(chunk) {\n return chunk.offset < offset;\n })\n .forEach(function(chunk) {\n chunk.status = ChunkStatus.COMPLETE;\n chunk.progress = chunk.size;\n });\n\n // continue processing\n processChunks();\n });\n }\n\n return {\n abort: function abort() {\n state.aborted = true;\n abortChunks();\n },\n };\n };\n\n /*\n function signature:\n (file, metadata, load, error, progress, abort) => {\n return {\n abort:() => {}\n }\n }\n */\n var createFileProcessorFunction = function createFileProcessorFunction(\n apiUrl,\n action,\n name,\n options\n ) {\n return function(file, metadata, load, error, progress, abort, transfer) {\n // no file received\n if (!file) return;\n\n // if was passed a file, and we can chunk it, exit here\n var canChunkUpload = options.chunkUploads;\n var shouldChunkUpload = canChunkUpload && file.size > options.chunkSize;\n var willChunkUpload = canChunkUpload && (shouldChunkUpload || options.chunkForce);\n if (file instanceof Blob && willChunkUpload)\n return processFileChunked(\n apiUrl,\n action,\n name,\n file,\n metadata,\n load,\n error,\n progress,\n abort,\n transfer,\n options\n );\n\n // set handlers\n var ondata =\n action.ondata ||\n function(fd) {\n return fd;\n };\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n var headers =\n typeof action.headers === 'function'\n ? action.headers(file, metadata) || {}\n : Object.assign(\n {},\n\n action.headers\n );\n\n var requestParams = Object.assign({}, action, {\n headers: headers,\n });\n\n // create formdata object\n var formData = new FormData();\n\n // add metadata under same name\n if (isObject(metadata)) {\n formData.append(name, JSON.stringify(metadata));\n }\n\n // Turn into an array of objects so no matter what the input, we can handle it the same way\n (file instanceof Blob ? [{ name: null, file: file }] : file).forEach(function(item) {\n formData.append(\n name,\n item.file,\n item.name === null ? item.file.name : '' + item.name + item.file.name\n );\n });\n\n // send request object\n var request = sendRequest(\n ondata(formData),\n buildURL(apiUrl, action.url),\n requestParams\n );\n request.onload = function(xhr) {\n load(\n createResponse(\n 'load',\n xhr.status,\n onload(xhr.response),\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n };\n\n var createProcessorFunction = function createProcessorFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n var name = arguments.length > 2 ? arguments[2] : undefined;\n var options = arguments.length > 3 ? arguments[3] : undefined;\n\n // custom handler (should also handle file, load, error, progress and abort)\n if (typeof action === 'function')\n return function() {\n for (\n var _len = arguments.length, params = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n params[_key] = arguments[_key];\n }\n return action.apply(void 0, [name].concat(params, [options]));\n };\n\n // no action supplied\n if (!action || !isString(action.url)) return null;\n\n // internal handler\n return createFileProcessorFunction(apiUrl, action, name, options);\n };\n\n /*\n function signature:\n (uniqueFileId, load, error) => { }\n */\n var createRevertFunction = function createRevertFunction() {\n var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n var action = arguments.length > 1 ? arguments[1] : undefined;\n // is custom implementation\n if (typeof action === 'function') {\n return action;\n }\n\n // no action supplied, return stub function, interface will work, but file won't be removed\n if (!action || !isString(action.url)) {\n return function(uniqueFileId, load) {\n return load();\n };\n }\n\n // set onload hanlder\n var onload =\n action.onload ||\n function(res) {\n return res;\n };\n var onerror =\n action.onerror ||\n function(res) {\n return null;\n };\n\n // internal implementation\n return function(uniqueFileId, load, error) {\n var request = sendRequest(\n uniqueFileId,\n apiUrl + action.url,\n action // contains method, headers and withCredentials properties\n );\n request.onload = function(xhr) {\n load(\n createResponse(\n 'load',\n xhr.status,\n onload(xhr.response),\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.onerror = function(xhr) {\n error(\n createResponse(\n 'error',\n xhr.status,\n onerror(xhr.response) || xhr.statusText,\n xhr.getAllResponseHeaders()\n )\n );\n };\n\n request.ontimeout = createTimeoutResponse(error);\n\n return request;\n };\n };\n\n var getRandomNumber = function getRandomNumber() {\n var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;\n var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;\n return min + Math.random() * (max - min);\n };\n\n var createPerceivedPerformanceUpdater = function createPerceivedPerformanceUpdater(cb) {\n var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;\n var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var tickMin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 25;\n var tickMax = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250;\n var timeout = null;\n var start = Date.now();\n\n var tick = function tick() {\n var runtime = Date.now() - start;\n var delay = getRandomNumber(tickMin, tickMax);\n\n if (runtime + delay > duration) {\n delay = runtime + delay - duration;\n }\n\n var progress = runtime / duration;\n if (progress >= 1 || document.hidden) {\n cb(1);\n return;\n }\n\n cb(progress);\n\n timeout = setTimeout(tick, delay);\n };\n\n if (duration > 0) tick();\n\n return {\n clear: function clear() {\n clearTimeout(timeout);\n },\n };\n };\n\n var createFileProcessor = function createFileProcessor(processFn, options) {\n var state = {\n complete: false,\n perceivedProgress: 0,\n perceivedPerformanceUpdater: null,\n progress: null,\n timestamp: null,\n perceivedDuration: 0,\n duration: 0,\n request: null,\n response: null,\n };\n var allowMinimumUploadDuration = options.allowMinimumUploadDuration;\n\n var process = function process(file, metadata) {\n var progressFn = function progressFn() {\n // we've not yet started the real download, stop here\n // the request might not go through, for instance, there might be some server trouble\n // if state.progress is null, the server does not allow computing progress and we show the spinner instead\n if (state.duration === 0 || state.progress === null) return;\n\n // as we're now processing, fire the progress event\n api.fire('progress', api.getProgress());\n };\n\n var completeFn = function completeFn() {\n state.complete = true;\n api.fire('load-perceived', state.response.body);\n };\n\n // let's start processing\n api.fire('start');\n\n // set request start\n state.timestamp = Date.now();\n\n // create perceived performance progress indicator\n state.perceivedPerformanceUpdater = createPerceivedPerformanceUpdater(\n function(progress) {\n state.perceivedProgress = progress;\n state.perceivedDuration = Date.now() - state.timestamp;\n\n progressFn();\n\n // if fake progress is done, and a response has been received,\n // and we've not yet called the complete method\n if (state.response && state.perceivedProgress === 1 && !state.complete) {\n // we done!\n completeFn();\n }\n },\n // random delay as in a list of files you start noticing\n // files uploading at the exact same speed\n allowMinimumUploadDuration ? getRandomNumber(750, 1500) : 0\n );\n\n // remember request so we can abort it later\n state.request = processFn(\n // the file to process\n file,\n\n // the metadata to send along\n metadata,\n\n // callbacks (load, error, progress, abort, transfer)\n // load expects the body to be a server id if\n // you want to make use of revert\n function(response) {\n // we put the response in state so we can access\n // it outside of this method\n state.response = isObject(response)\n ? response\n : {\n type: 'load',\n code: 200,\n body: '' + response,\n headers: {},\n };\n\n // update duration\n state.duration = Date.now() - state.timestamp;\n\n // force progress to 1 as we're now done\n state.progress = 1;\n\n // actual load is done let's share results\n api.fire('load', state.response.body);\n\n // we are really done\n // if perceived progress is 1 ( wait for perceived progress to complete )\n // or if server does not support progress ( null )\n if (\n !allowMinimumUploadDuration ||\n (allowMinimumUploadDuration && state.perceivedProgress === 1)\n ) {\n completeFn();\n }\n },\n\n // error is expected to be an object with type, code, body\n function(error) {\n // cancel updater\n state.perceivedPerformanceUpdater.clear();\n\n // update others about this error\n api.fire(\n 'error',\n isObject(error)\n ? error\n : {\n type: 'error',\n code: 0,\n body: '' + error,\n }\n );\n },\n\n // actual processing progress\n function(computable, current, total) {\n // update actual duration\n state.duration = Date.now() - state.timestamp;\n\n // update actual progress\n state.progress = computable ? current / total : null;\n\n progressFn();\n },\n\n // abort does not expect a value\n function() {\n // stop updater\n state.perceivedPerformanceUpdater.clear();\n\n // fire the abort event so we can switch visuals\n api.fire('abort', state.response ? state.response.body : null);\n },\n\n // register the id for this transfer\n function(transferId) {\n api.fire('transfer', transferId);\n }\n );\n };\n\n var abort = function abort() {\n // no request running, can't abort\n if (!state.request) return;\n\n // stop updater\n state.perceivedPerformanceUpdater.clear();\n\n // abort actual request\n if (state.request.abort) state.request.abort();\n\n // if has response object, we've completed the request\n state.complete = true;\n };\n\n var reset = function reset() {\n abort();\n state.complete = false;\n state.perceivedProgress = 0;\n state.progress = 0;\n state.timestamp = null;\n state.perceivedDuration = 0;\n state.duration = 0;\n state.request = null;\n state.response = null;\n };\n\n var getProgress = allowMinimumUploadDuration\n ? function() {\n return state.progress ? Math.min(state.progress, state.perceivedProgress) : null;\n }\n : function() {\n return state.progress || null;\n };\n\n var getDuration = allowMinimumUploadDuration\n ? function() {\n return Math.min(state.duration, state.perceivedDuration);\n }\n : function() {\n return state.duration;\n };\n\n var api = Object.assign({}, on(), {\n process: process, // start processing file\n abort: abort, // abort active process request\n getProgress: getProgress,\n getDuration: getDuration,\n reset: reset,\n });\n\n return api;\n };\n\n var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) {\n return name.substring(0, name.lastIndexOf('.')) || name;\n };\n\n var createFileStub = function createFileStub(source) {\n var data = [source.name, source.size, source.type];\n\n // is blob or base64, then we need to set the name\n if (source instanceof Blob || isBase64DataURI(source)) {\n data[0] = source.name || getDateString();\n } else if (isBase64DataURI(source)) {\n // if is base64 data uri we need to determine the average size and type\n data[1] = source.length;\n data[2] = getMimeTypeFromBase64DataURI(source);\n } else if (isString(source)) {\n // url\n data[0] = getFilenameFromURL(source);\n data[1] = 0;\n data[2] = 'application/octet-stream';\n }\n\n return {\n name: data[0],\n size: data[1],\n type: data[2],\n };\n };\n\n var isFile = function isFile(value) {\n return !!(value instanceof File || (value instanceof Blob && value.name));\n };\n\n var deepCloneObject = function deepCloneObject(src) {\n if (!isObject(src)) return src;\n var target = isArray(src) ? [] : {};\n for (var key in src) {\n if (!src.hasOwnProperty(key)) continue;\n var v = src[key];\n target[key] = v && isObject(v) ? deepCloneObject(v) : v;\n }\n return target;\n };\n\n var createItem = function createItem() {\n var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var serverFileReference =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n // unique id for this item, is used to identify the item across views\n var id = getUniqueId();\n\n /**\n * Internal item state\n */\n var state = {\n // is archived\n archived: false,\n\n // if is frozen, no longer fires events\n frozen: false,\n\n // removed from view\n released: false,\n\n // original source\n source: null,\n\n // file model reference\n file: file,\n\n // id of file on server\n serverFileReference: serverFileReference,\n\n // id of file transfer on server\n transferId: null,\n\n // is aborted\n processingAborted: false,\n\n // current item status\n status: serverFileReference ? ItemStatus.PROCESSING_COMPLETE : ItemStatus.INIT,\n\n // active processes\n activeLoader: null,\n activeProcessor: null,\n };\n\n // callback used when abort processing is called to link back to the resolve method\n var abortProcessingRequestComplete = null;\n\n /**\n * Externally added item metadata\n */\n var metadata = {};\n\n // item data\n var setStatus = function setStatus(status) {\n return (state.status = status);\n };\n\n // fire event unless the item has been archived\n var fire = function fire(event) {\n if (state.released || state.frozen) return;\n for (\n var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n params[_key - 1] = arguments[_key];\n }\n api.fire.apply(api, [event].concat(params));\n };\n\n // file data\n var getFileExtension = function getFileExtension() {\n return getExtensionFromFilename(state.file.name);\n };\n var getFileType = function getFileType() {\n return state.file.type;\n };\n var getFileSize = function getFileSize() {\n return state.file.size;\n };\n var getFile = function getFile() {\n return state.file;\n };\n\n //\n // logic to load a file\n //\n var load = function load(source, loader, onload) {\n // remember the original item source\n state.source = source;\n\n // source is known\n api.fireSync('init');\n\n // file stub is already there\n if (state.file) {\n api.fireSync('load-skip');\n return;\n }\n\n // set a stub file object while loading the actual data\n state.file = createFileStub(source);\n\n // starts loading\n loader.on('init', function() {\n fire('load-init');\n });\n\n // we'eve received a size indication, let's update the stub\n loader.on('meta', function(meta) {\n // set size of file stub\n state.file.size = meta.size;\n\n // set name of file stub\n state.file.filename = meta.filename;\n\n // if has received source, we done\n if (meta.source) {\n origin = FileOrigin.LIMBO;\n state.serverFileReference = meta.source;\n state.status = ItemStatus.PROCESSING_COMPLETE;\n }\n\n // size has been updated\n fire('load-meta');\n });\n\n // the file is now loading we need to update the progress indicators\n loader.on('progress', function(progress) {\n setStatus(ItemStatus.LOADING);\n\n fire('load-progress', progress);\n });\n\n // an error was thrown while loading the file, we need to switch to error state\n loader.on('error', function(error) {\n setStatus(ItemStatus.LOAD_ERROR);\n\n fire('load-request-error', error);\n });\n\n // user or another process aborted the file load (cannot retry)\n loader.on('abort', function() {\n setStatus(ItemStatus.INIT);\n fire('load-abort');\n });\n\n // done loading\n loader.on('load', function(file) {\n // as we've now loaded the file the loader is no longer required\n state.activeLoader = null;\n\n // called when file has loaded succesfully\n var success = function success(result) {\n // set (possibly) transformed file\n state.file = isFile(result) ? result : state.file;\n\n // file received\n if (origin === FileOrigin.LIMBO && state.serverFileReference) {\n setStatus(ItemStatus.PROCESSING_COMPLETE);\n } else {\n setStatus(ItemStatus.IDLE);\n }\n\n fire('load');\n };\n\n var error = function error(result) {\n // set original file\n state.file = file;\n fire('load-meta');\n\n setStatus(ItemStatus.LOAD_ERROR);\n fire('load-file-error', result);\n };\n\n // if we already have a server file reference, we don't need to call the onload method\n if (state.serverFileReference) {\n success(file);\n return;\n }\n\n // no server id, let's give this file the full treatment\n onload(file, success, error);\n });\n\n // set loader source data\n loader.setSource(source);\n\n // set as active loader\n state.activeLoader = loader;\n\n // load the source data\n loader.load();\n };\n\n var retryLoad = function retryLoad() {\n if (!state.activeLoader) {\n return;\n }\n state.activeLoader.load();\n };\n\n var abortLoad = function abortLoad() {\n if (state.activeLoader) {\n state.activeLoader.abort();\n return;\n }\n setStatus(ItemStatus.INIT);\n fire('load-abort');\n };\n\n //\n // logic to process a file\n //\n var process = function process(processor, onprocess) {\n // processing was aborted\n if (state.processingAborted) {\n state.processingAborted = false;\n return;\n }\n\n // now processing\n setStatus(ItemStatus.PROCESSING);\n\n // reset abort callback\n abortProcessingRequestComplete = null;\n\n // if no file loaded we'll wait for the load event\n if (!(state.file instanceof Blob)) {\n api.on('load', function() {\n process(processor, onprocess);\n });\n return;\n }\n\n // setup processor\n processor.on('load', function(serverFileReference) {\n // need this id to be able to revert the upload\n state.transferId = null;\n state.serverFileReference = serverFileReference;\n });\n\n // register transfer id\n processor.on('transfer', function(transferId) {\n // need this id to be able to revert the upload\n state.transferId = transferId;\n });\n\n processor.on('load-perceived', function(serverFileReference) {\n // no longer required\n state.activeProcessor = null;\n\n // need this id to be able to rever the upload\n state.transferId = null;\n state.serverFileReference = serverFileReference;\n\n setStatus(ItemStatus.PROCESSING_COMPLETE);\n fire('process-complete', serverFileReference);\n });\n\n processor.on('start', function() {\n fire('process-start');\n });\n\n processor.on('error', function(error) {\n state.activeProcessor = null;\n setStatus(ItemStatus.PROCESSING_ERROR);\n fire('process-error', error);\n });\n\n processor.on('abort', function(serverFileReference) {\n state.activeProcessor = null;\n\n // if file was uploaded but processing was cancelled during perceived processor time store file reference\n state.serverFileReference = serverFileReference;\n\n setStatus(ItemStatus.IDLE);\n fire('process-abort');\n\n // has timeout so doesn't interfere with remove action\n if (abortProcessingRequestComplete) {\n abortProcessingRequestComplete();\n }\n });\n\n processor.on('progress', function(progress) {\n fire('process-progress', progress);\n });\n\n // when successfully transformed\n var success = function success(file) {\n // if was archived in the mean time, don't process\n if (state.archived) return;\n\n // process file!\n processor.process(file, Object.assign({}, metadata));\n };\n\n // something went wrong during transform phase\n var error = console.error;\n\n // start processing the file\n onprocess(state.file, success, error);\n\n // set as active processor\n state.activeProcessor = processor;\n };\n\n var requestProcessing = function requestProcessing() {\n state.processingAborted = false;\n setStatus(ItemStatus.PROCESSING_QUEUED);\n };\n\n var abortProcessing = function abortProcessing() {\n return new Promise(function(resolve) {\n if (!state.activeProcessor) {\n state.processingAborted = true;\n\n setStatus(ItemStatus.IDLE);\n fire('process-abort');\n\n resolve();\n return;\n }\n\n abortProcessingRequestComplete = function abortProcessingRequestComplete() {\n resolve();\n };\n\n state.activeProcessor.abort();\n });\n };\n\n //\n // logic to revert a processed file\n //\n var revert = function revert(revertFileUpload, forceRevert) {\n return new Promise(function(resolve, reject) {\n // a completed upload will have a serverFileReference, a failed chunked upload where\n // getting a serverId succeeded but >=0 chunks have been uploaded will have transferId set\n var serverTransferId =\n state.serverFileReference !== null\n ? state.serverFileReference\n : state.transferId;\n\n // cannot revert without a server id for this process\n if (serverTransferId === null) {\n resolve();\n return;\n }\n\n // revert the upload (fire and forget)\n revertFileUpload(\n serverTransferId,\n function() {\n // reset file server id and transfer id as now it's not available on the server\n state.serverFileReference = null;\n state.transferId = null;\n resolve();\n },\n function(error) {\n // don't set error state when reverting is optional, it will always resolve\n if (!forceRevert) {\n resolve();\n return;\n }\n\n // oh no errors\n setStatus(ItemStatus.PROCESSING_REVERT_ERROR);\n fire('process-revert-error');\n reject(error);\n }\n );\n\n // fire event\n setStatus(ItemStatus.IDLE);\n fire('process-revert');\n });\n };\n\n // exposed methods\n var _setMetadata = function setMetadata(key, value, silent) {\n var keys = key.split('.');\n var root = keys[0];\n var last = keys.pop();\n var data = metadata;\n keys.forEach(function(key) {\n return (data = data[key]);\n });\n\n // compare old value against new value, if they're the same, we're not updating\n if (JSON.stringify(data[last]) === JSON.stringify(value)) return;\n\n // update value\n data[last] = value;\n\n // fire update\n fire('metadata-update', {\n key: root,\n value: metadata[root],\n silent: silent,\n });\n };\n\n var getMetadata = function getMetadata(key) {\n return deepCloneObject(key ? metadata[key] : metadata);\n };\n\n var api = Object.assign(\n {\n id: {\n get: function get() {\n return id;\n },\n },\n origin: {\n get: function get() {\n return origin;\n },\n set: function set(value) {\n return (origin = value);\n },\n },\n serverId: {\n get: function get() {\n return state.serverFileReference;\n },\n },\n transferId: {\n get: function get() {\n return state.transferId;\n },\n },\n status: {\n get: function get() {\n return state.status;\n },\n },\n filename: {\n get: function get() {\n return state.file.name;\n },\n },\n filenameWithoutExtension: {\n get: function get() {\n return getFilenameWithoutExtension(state.file.name);\n },\n },\n fileExtension: { get: getFileExtension },\n fileType: { get: getFileType },\n fileSize: { get: getFileSize },\n file: { get: getFile },\n relativePath: {\n get: function get() {\n return state.file._relativePath;\n },\n },\n\n source: {\n get: function get() {\n return state.source;\n },\n },\n\n getMetadata: getMetadata,\n setMetadata: function setMetadata(key, value, silent) {\n if (isObject(key)) {\n var data = key;\n Object.keys(data).forEach(function(key) {\n _setMetadata(key, data[key], value);\n });\n return key;\n }\n _setMetadata(key, value, silent);\n return value;\n },\n\n extend: function extend(name, handler) {\n return (itemAPI[name] = handler);\n },\n\n abortLoad: abortLoad,\n retryLoad: retryLoad,\n requestProcessing: requestProcessing,\n abortProcessing: abortProcessing,\n\n load: load,\n process: process,\n revert: revert,\n },\n\n on(),\n {\n freeze: function freeze() {\n return (state.frozen = true);\n },\n\n release: function release() {\n return (state.released = true);\n },\n released: {\n get: function get() {\n return state.released;\n },\n },\n\n archive: function archive() {\n return (state.archived = true);\n },\n archived: {\n get: function get() {\n return state.archived;\n },\n },\n }\n );\n\n // create it here instead of returning it instantly so we can extend it later\n var itemAPI = createObject(api);\n\n return itemAPI;\n };\n\n var getItemIndexByQuery = function getItemIndexByQuery(items, query) {\n // just return first index\n if (isEmpty(query)) {\n return 0;\n }\n\n // invalid queries\n if (!isString(query)) {\n return -1;\n }\n\n // return item by id (or -1 if not found)\n return items.findIndex(function(item) {\n return item.id === query;\n });\n };\n\n var getItemById = function getItemById(items, itemId) {\n var index = getItemIndexByQuery(items, itemId);\n if (index < 0) {\n return;\n }\n return items[index] || null;\n };\n\n var fetchBlob = function fetchBlob(url, load, error, progress, abort, headers) {\n var request = sendRequest(null, url, {\n method: 'GET',\n responseType: 'blob',\n });\n\n request.onload = function(xhr) {\n // get headers\n var headers = xhr.getAllResponseHeaders();\n\n // get filename\n var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);\n\n // create response\n load(\n createResponse('load', xhr.status, getFileFromBlob(xhr.response, filename), headers)\n );\n };\n\n request.onerror = function(xhr) {\n error(createResponse('error', xhr.status, xhr.statusText, xhr.getAllResponseHeaders()));\n };\n\n request.onheaders = function(xhr) {\n headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));\n };\n\n request.ontimeout = createTimeoutResponse(error);\n request.onprogress = progress;\n request.onabort = abort;\n\n // should return request\n return request;\n };\n\n var getDomainFromURL = function getDomainFromURL(url) {\n if (url.indexOf('//') === 0) {\n url = location.protocol + url;\n }\n return url\n .toLowerCase()\n .replace('blob:', '')\n .replace(/([a-z])?:\\/\\//, '$1')\n .split('/')[0];\n };\n\n var isExternalURL = function isExternalURL(url) {\n return (\n (url.indexOf(':') > -1 || url.indexOf('//') > -1) &&\n getDomainFromURL(location.href) !== getDomainFromURL(url)\n );\n };\n\n var dynamicLabel = function dynamicLabel(label) {\n return function() {\n return isFunction(label) ? label.apply(void 0, arguments) : label;\n };\n };\n\n var isMockItem = function isMockItem(item) {\n return !isFile(item.file);\n };\n\n var listUpdated = function listUpdated(dispatch, state) {\n clearTimeout(state.listUpdateTimeout);\n state.listUpdateTimeout = setTimeout(function() {\n dispatch('DID_UPDATE_ITEMS', { items: getActiveItems(state.items) });\n }, 0);\n };\n\n var optionalPromise = function optionalPromise(fn) {\n for (\n var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;\n _key < _len;\n _key++\n ) {\n params[_key - 1] = arguments[_key];\n }\n return new Promise(function(resolve) {\n if (!fn) {\n return resolve(true);\n }\n\n var result = fn.apply(void 0, params);\n\n if (result == null) {\n return resolve(true);\n }\n\n if (typeof result === 'boolean') {\n return resolve(result);\n }\n\n if (typeof result.then === 'function') {\n result.then(resolve);\n }\n });\n };\n\n var sortItems = function sortItems(state, compare) {\n state.items.sort(function(a, b) {\n return compare(createItemAPI(a), createItemAPI(b));\n });\n };\n\n // returns item based on state\n var getItemByQueryFromState = function getItemByQueryFromState(state, itemHandler) {\n return function() {\n var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var query = _ref.query,\n _ref$success = _ref.success,\n success = _ref$success === void 0 ? function() {} : _ref$success,\n _ref$failure = _ref.failure,\n failure = _ref$failure === void 0 ? function() {} : _ref$failure,\n options = _objectWithoutProperties(_ref, ['query', 'success', 'failure']);\n var item = getItemByQuery(state.items, query);\n if (!item) {\n failure({\n error: createResponse('error', 0, 'Item not found'),\n file: null,\n });\n\n return;\n }\n itemHandler(item, success, failure, options || {});\n };\n };\n\n var actions = function actions(dispatch, query, state) {\n return {\n /**\n * Aborts all ongoing processes\n */\n ABORT_ALL: function ABORT_ALL() {\n getActiveItems(state.items).forEach(function(item) {\n item.freeze();\n item.abortLoad();\n item.abortProcessing();\n });\n },\n\n /**\n * Sets initial files\n */\n DID_SET_FILES: function DID_SET_FILES(_ref2) {\n var _ref2$value = _ref2.value,\n value = _ref2$value === void 0 ? [] : _ref2$value;\n // map values to file objects\n var files = value.map(function(file) {\n return {\n source: file.source ? file.source : file,\n options: file.options,\n };\n });\n\n // loop over files, if file is in list, leave it be, if not, remove\n // test if items should be moved\n var activeItems = getActiveItems(state.items);\n\n activeItems.forEach(function(item) {\n // if item not is in new value, remove\n if (\n !files.find(function(file) {\n return file.source === item.source || file.source === item.file;\n })\n ) {\n dispatch('REMOVE_ITEM', { query: item, remove: false });\n }\n });\n\n // add new files\n activeItems = getActiveItems(state.items);\n files.forEach(function(file, index) {\n // if file is already in list\n if (\n activeItems.find(function(item) {\n return item.source === file.source || item.file === file.source;\n })\n )\n return;\n\n // not in list, add\n dispatch(\n 'ADD_ITEM',\n Object.assign({}, file, {\n interactionMethod: InteractionMethod.NONE,\n index: index,\n })\n );\n });\n },\n\n DID_UPDATE_ITEM_METADATA: function DID_UPDATE_ITEM_METADATA(_ref3) {\n var id = _ref3.id,\n action = _ref3.action,\n change = _ref3.change;\n // don't do anything\n if (change.silent) return;\n\n // if is called multiple times in close succession we combined all calls together to save resources\n clearTimeout(state.itemUpdateTimeout);\n state.itemUpdateTimeout = setTimeout(function() {\n var item = getItemById(state.items, id);\n\n // only revert and attempt to upload when we're uploading to a server\n if (!query('IS_ASYNC')) {\n // should we update the output data\n applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {\n item: item,\n query: query,\n action: action,\n change: change,\n }).then(function(shouldPrepareOutput) {\n // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook\n var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');\n if (beforePrepareFile)\n shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);\n\n if (!shouldPrepareOutput) return;\n\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });\n },\n },\n\n true\n );\n });\n\n return;\n }\n\n // if is local item we need to enable upload button so change can be propagated to server\n if (item.origin === FileOrigin.LOCAL) {\n dispatch('DID_LOAD_ITEM', {\n id: item.id,\n error: null,\n serverFileReference: item.source,\n });\n }\n\n // for async scenarios\n var upload = function upload() {\n // we push this forward a bit so the interface is updated correctly\n setTimeout(function() {\n dispatch('REQUEST_ITEM_PROCESSING', { query: id });\n }, 32);\n };\n\n var revert = function revert(doUpload) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n )\n .then(doUpload ? upload : function() {})\n .catch(function() {});\n };\n\n var abort = function abort(doUpload) {\n item.abortProcessing().then(doUpload ? upload : function() {});\n };\n\n // if we should re-upload the file immediately\n if (item.status === ItemStatus.PROCESSING_COMPLETE) {\n return revert(state.options.instantUpload);\n }\n\n // if currently uploading, cancel upload\n if (item.status === ItemStatus.PROCESSING) {\n return abort(state.options.instantUpload);\n }\n\n if (state.options.instantUpload) {\n upload();\n }\n }, 0);\n },\n\n MOVE_ITEM: function MOVE_ITEM(_ref4) {\n var query = _ref4.query,\n index = _ref4.index;\n var item = getItemByQuery(state.items, query);\n if (!item) return;\n var currentIndex = state.items.indexOf(item);\n index = limit(index, 0, state.items.length - 1);\n if (currentIndex === index) return;\n state.items.splice(index, 0, state.items.splice(currentIndex, 1)[0]);\n },\n\n SORT: function SORT(_ref5) {\n var compare = _ref5.compare;\n sortItems(state, compare);\n dispatch('DID_SORT_ITEMS', {\n items: query('GET_ACTIVE_ITEMS'),\n });\n },\n\n ADD_ITEMS: function ADD_ITEMS(_ref6) {\n var items = _ref6.items,\n index = _ref6.index,\n interactionMethod = _ref6.interactionMethod,\n _ref6$success = _ref6.success,\n success = _ref6$success === void 0 ? function() {} : _ref6$success,\n _ref6$failure = _ref6.failure,\n failure = _ref6$failure === void 0 ? function() {} : _ref6$failure;\n var currentIndex = index;\n\n if (index === -1 || typeof index === 'undefined') {\n var insertLocation = query('GET_ITEM_INSERT_LOCATION');\n var totalItems = query('GET_TOTAL_ITEMS');\n currentIndex = insertLocation === 'before' ? 0 : totalItems;\n }\n\n var ignoredFiles = query('GET_IGNORED_FILES');\n var isValidFile = function isValidFile(source) {\n return isFile(source)\n ? !ignoredFiles.includes(source.name.toLowerCase())\n : !isEmpty(source);\n };\n var validItems = items.filter(isValidFile);\n\n var promises = validItems.map(function(source) {\n return new Promise(function(resolve, reject) {\n dispatch('ADD_ITEM', {\n interactionMethod: interactionMethod,\n source: source.source || source,\n success: resolve,\n failure: reject,\n index: currentIndex++,\n options: source.options || {},\n });\n });\n });\n\n Promise.all(promises)\n .then(success)\n .catch(failure);\n },\n\n /**\n * @param source\n * @param index\n * @param interactionMethod\n */\n ADD_ITEM: function ADD_ITEM(_ref7) {\n var source = _ref7.source,\n _ref7$index = _ref7.index,\n index = _ref7$index === void 0 ? -1 : _ref7$index,\n interactionMethod = _ref7.interactionMethod,\n _ref7$success = _ref7.success,\n success = _ref7$success === void 0 ? function() {} : _ref7$success,\n _ref7$failure = _ref7.failure,\n failure = _ref7$failure === void 0 ? function() {} : _ref7$failure,\n _ref7$options = _ref7.options,\n options = _ref7$options === void 0 ? {} : _ref7$options;\n // if no source supplied\n if (isEmpty(source)) {\n failure({\n error: createResponse('error', 0, 'No source'),\n file: null,\n });\n\n return;\n }\n\n // filter out invalid file items, used to filter dropped directory contents\n if (\n isFile(source) &&\n state.options.ignoredFiles.includes(source.name.toLowerCase())\n ) {\n // fail silently\n return;\n }\n\n // test if there's still room in the list of files\n if (!hasRoomForItem(state)) {\n // if multiple allowed, we can't replace\n // or if only a single item is allowed but we're not allowed to replace it we exit\n if (\n state.options.allowMultiple ||\n (!state.options.allowMultiple && !state.options.allowReplace)\n ) {\n var error = createResponse('warning', 0, 'Max files');\n\n dispatch('DID_THROW_MAX_FILES', {\n source: source,\n error: error,\n });\n\n failure({ error: error, file: null });\n\n return;\n }\n\n // let's replace the item\n // id of first item we're about to remove\n var _item = getActiveItems(state.items)[0];\n\n // if has been processed remove it from the server as well\n if (\n _item.status === ItemStatus.PROCESSING_COMPLETE ||\n _item.status === ItemStatus.PROCESSING_REVERT_ERROR\n ) {\n var forceRevert = query('GET_FORCE_REVERT');\n _item\n .revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n forceRevert\n )\n .then(function() {\n if (!forceRevert) return;\n\n // try to add now\n dispatch('ADD_ITEM', {\n source: source,\n index: index,\n interactionMethod: interactionMethod,\n success: success,\n failure: failure,\n options: options,\n });\n })\n .catch(function() {}); // no need to handle this catch state for now\n\n if (forceRevert) return;\n }\n\n // remove first item as it will be replaced by this item\n dispatch('REMOVE_ITEM', { query: _item.id });\n }\n\n // where did the file originate\n var origin =\n options.type === 'local'\n ? FileOrigin.LOCAL\n : options.type === 'limbo'\n ? FileOrigin.LIMBO\n : FileOrigin.INPUT;\n\n // create a new blank item\n var item = createItem(\n // where did this file come from\n origin,\n\n // an input file never has a server file reference\n origin === FileOrigin.INPUT ? null : source,\n\n // file mock data, if defined\n options.file\n );\n\n // set initial meta data\n Object.keys(options.metadata || {}).forEach(function(key) {\n item.setMetadata(key, options.metadata[key]);\n });\n\n // created the item, let plugins add methods\n applyFilters('DID_CREATE_ITEM', item, { query: query, dispatch: dispatch });\n\n // where to insert new items\n var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');\n\n // adjust index if is not allowed to pick location\n if (!state.options.itemInsertLocationFreedom) {\n index = itemInsertLocation === 'before' ? -1 : state.items.length;\n }\n\n // add item to list\n insertItem(state.items, item, index);\n\n // sort items in list\n if (isFunction(itemInsertLocation) && source) {\n sortItems(state, itemInsertLocation);\n }\n\n // get a quick reference to the item id\n var id = item.id;\n\n // observe item events\n item.on('init', function() {\n dispatch('DID_INIT_ITEM', { id: id });\n });\n\n item.on('load-init', function() {\n dispatch('DID_START_ITEM_LOAD', { id: id });\n });\n\n item.on('load-meta', function() {\n dispatch('DID_UPDATE_ITEM_META', { id: id });\n });\n\n item.on('load-progress', function(progress) {\n dispatch('DID_UPDATE_ITEM_LOAD_PROGRESS', { id: id, progress: progress });\n });\n\n item.on('load-request-error', function(error) {\n var mainStatus = dynamicLabel(state.options.labelFileLoadError)(error);\n\n // is client error, no way to recover\n if (error.code >= 400 && error.code < 500) {\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: error,\n status: {\n main: mainStatus,\n sub: error.code + ' (' + error.body + ')',\n },\n });\n\n // reject the file so can be dealt with through API\n failure({ error: error, file: createItemAPI(item) });\n return;\n }\n\n // is possible server error, so might be possible to retry\n dispatch('DID_THROW_ITEM_LOAD_ERROR', {\n id: id,\n error: error,\n status: {\n main: mainStatus,\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('load-file-error', function(error) {\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: error.status,\n status: error.status,\n });\n\n failure({ error: error.status, file: createItemAPI(item) });\n });\n\n item.on('load-abort', function() {\n dispatch('REMOVE_ITEM', { query: id });\n });\n\n item.on('load-skip', function() {\n dispatch('COMPLETE_LOAD_ITEM', {\n query: id,\n item: item,\n data: {\n source: source,\n success: success,\n },\n });\n });\n\n item.on('load', function() {\n var handleAdd = function handleAdd(shouldAdd) {\n // no should not add this file\n if (!shouldAdd) {\n dispatch('REMOVE_ITEM', {\n query: id,\n });\n\n return;\n }\n\n // now interested in metadata updates\n item.on('metadata-update', function(change) {\n dispatch('DID_UPDATE_ITEM_METADATA', { id: id, change: change });\n });\n\n // let plugins decide if the output data should be prepared at this point\n // means we'll do this and wait for idle state\n applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {\n item: item,\n query: query,\n }).then(function(shouldPrepareOutput) {\n // plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook\n var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');\n if (beforePrepareFile)\n shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);\n\n var loadComplete = function loadComplete() {\n dispatch('COMPLETE_LOAD_ITEM', {\n query: id,\n item: item,\n data: {\n source: source,\n success: success,\n },\n });\n\n listUpdated(dispatch, state);\n };\n\n // exit\n if (shouldPrepareOutput) {\n // wait for idle state and then run PREPARE_OUTPUT\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });\n loadComplete();\n },\n },\n\n true\n );\n\n return;\n }\n\n loadComplete();\n });\n };\n\n // item loaded, allow plugins to\n // - read data (quickly)\n // - add metadata\n applyFilterChain('DID_LOAD_ITEM', item, { query: query, dispatch: dispatch })\n .then(function() {\n optionalPromise(query('GET_BEFORE_ADD_FILE'), createItemAPI(item)).then(\n handleAdd\n );\n })\n .catch(function(e) {\n if (!e || !e.error || !e.status) return handleAdd(false);\n dispatch('DID_THROW_ITEM_INVALID', {\n id: id,\n error: e.error,\n status: e.status,\n });\n });\n });\n\n item.on('process-start', function() {\n dispatch('DID_START_ITEM_PROCESSING', { id: id });\n });\n\n item.on('process-progress', function(progress) {\n dispatch('DID_UPDATE_ITEM_PROCESS_PROGRESS', { id: id, progress: progress });\n });\n\n item.on('process-error', function(error) {\n dispatch('DID_THROW_ITEM_PROCESSING_ERROR', {\n id: id,\n error: error,\n status: {\n main: dynamicLabel(state.options.labelFileProcessingError)(error),\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('process-revert-error', function(error) {\n dispatch('DID_THROW_ITEM_PROCESSING_REVERT_ERROR', {\n id: id,\n error: error,\n status: {\n main: dynamicLabel(state.options.labelFileProcessingRevertError)(error),\n sub: state.options.labelTapToRetry,\n },\n });\n });\n\n item.on('process-complete', function(serverFileReference) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING', {\n id: id,\n error: null,\n serverFileReference: serverFileReference,\n });\n\n dispatch('DID_DEFINE_VALUE', { id: id, value: serverFileReference });\n });\n\n item.on('process-abort', function() {\n dispatch('DID_ABORT_ITEM_PROCESSING', { id: id });\n });\n\n item.on('process-revert', function() {\n dispatch('DID_REVERT_ITEM_PROCESSING', { id: id });\n dispatch('DID_DEFINE_VALUE', { id: id, value: null });\n });\n\n // let view know the item has been inserted\n dispatch('DID_ADD_ITEM', {\n id: id,\n index: index,\n interactionMethod: interactionMethod,\n });\n\n listUpdated(dispatch, state);\n\n // start loading the source\n var _ref8 = state.options.server || {},\n url = _ref8.url,\n load = _ref8.load,\n restore = _ref8.restore,\n fetch = _ref8.fetch;\n\n item.load(\n source,\n\n // this creates a function that loads the file based on the type of file (string, base64, blob, file) and location of file (local, remote, limbo)\n createFileLoader(\n origin === FileOrigin.INPUT\n ? // input, if is remote, see if should use custom fetch, else use default fetchBlob\n isString(source) && isExternalURL(source)\n ? fetch\n ? createFetchFunction(url, fetch)\n : fetchBlob // remote url\n : fetchBlob // try to fetch url\n : // limbo or local\n origin === FileOrigin.LIMBO\n ? createFetchFunction(url, restore) // limbo\n : createFetchFunction(url, load) // local\n ),\n\n // called when the file is loaded so it can be piped through the filters\n function(file, success, error) {\n // let's process the file\n applyFilterChain('LOAD_FILE', file, { query: query })\n .then(success)\n .catch(error);\n }\n );\n },\n\n REQUEST_PREPARE_OUTPUT: function REQUEST_PREPARE_OUTPUT(_ref9) {\n var item = _ref9.item,\n success = _ref9.success,\n _ref9$failure = _ref9.failure,\n failure = _ref9$failure === void 0 ? function() {} : _ref9$failure;\n // error response if item archived\n var err = {\n error: createResponse('error', 0, 'Item not found'),\n file: null,\n };\n\n // don't handle archived items, an item could have been archived (load aborted) while waiting to be prepared\n if (item.archived) return failure(err);\n\n // allow plugins to alter the file data\n applyFilterChain('PREPARE_OUTPUT', item.file, { query: query, item: item }).then(\n function(result) {\n applyFilterChain('COMPLETE_PREPARE_OUTPUT', result, {\n query: query,\n item: item,\n }).then(function(result) {\n // don't handle archived items, an item could have been archived (load aborted) while being prepared\n if (item.archived) return failure(err);\n\n // we done!\n success(result);\n });\n }\n );\n },\n\n COMPLETE_LOAD_ITEM: function COMPLETE_LOAD_ITEM(_ref10) {\n var item = _ref10.item,\n data = _ref10.data;\n var success = data.success,\n source = data.source;\n\n // sort items in list\n var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');\n if (isFunction(itemInsertLocation) && source) {\n sortItems(state, itemInsertLocation);\n }\n\n // let interface know the item has loaded\n dispatch('DID_LOAD_ITEM', {\n id: item.id,\n error: null,\n serverFileReference: item.origin === FileOrigin.INPUT ? null : source,\n });\n\n // item has been successfully loaded and added to the\n // list of items so can now be safely returned for use\n success(createItemAPI(item));\n\n // if this is a local server file we need to show a different state\n if (item.origin === FileOrigin.LOCAL) {\n dispatch('DID_LOAD_LOCAL_ITEM', { id: item.id });\n return;\n }\n\n // if is a temp server file we prevent async upload call here (as the file is already on the server)\n if (item.origin === FileOrigin.LIMBO) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING', {\n id: item.id,\n error: null,\n serverFileReference: source,\n });\n\n dispatch('DID_DEFINE_VALUE', {\n id: item.id,\n value: item.serverId || source,\n });\n\n return;\n }\n\n // id we are allowed to upload the file immediately, lets do it\n if (query('IS_ASYNC') && state.options.instantUpload) {\n dispatch('REQUEST_ITEM_PROCESSING', { query: item.id });\n }\n },\n\n RETRY_ITEM_LOAD: getItemByQueryFromState(state, function(item) {\n // try loading the source one more time\n item.retryLoad();\n }),\n\n REQUEST_ITEM_PREPARE: getItemByQueryFromState(state, function(item, _success, failure) {\n dispatch(\n 'REQUEST_PREPARE_OUTPUT',\n {\n query: item.id,\n item: item,\n success: function success(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });\n _success({\n file: item,\n output: file,\n });\n },\n failure: failure,\n },\n\n true\n );\n }),\n\n REQUEST_ITEM_PROCESSING: getItemByQueryFromState(state, function(\n item,\n success,\n failure\n ) {\n // cannot be queued (or is already queued)\n var itemCanBeQueuedForProcessing =\n // waiting for something\n item.status === ItemStatus.IDLE ||\n // processing went wrong earlier\n item.status === ItemStatus.PROCESSING_ERROR;\n\n // not ready to be processed\n if (!itemCanBeQueuedForProcessing) {\n var processNow = function processNow() {\n return dispatch('REQUEST_ITEM_PROCESSING', {\n query: item,\n success: success,\n failure: failure,\n });\n };\n\n var process = function process() {\n return document.hidden ? processNow() : setTimeout(processNow, 32);\n };\n\n // if already done processing or tried to revert but didn't work, try again\n if (\n item.status === ItemStatus.PROCESSING_COMPLETE ||\n item.status === ItemStatus.PROCESSING_REVERT_ERROR\n ) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n )\n .then(process)\n .catch(function() {}); // don't continue with processing if something went wrong\n } else if (item.status === ItemStatus.PROCESSING) {\n item.abortProcessing().then(process);\n }\n\n return;\n }\n\n // already queued for processing\n if (item.status === ItemStatus.PROCESSING_QUEUED) return;\n\n item.requestProcessing();\n\n dispatch('DID_REQUEST_ITEM_PROCESSING', { id: item.id });\n\n dispatch('PROCESS_ITEM', { query: item, success: success, failure: failure }, true);\n }),\n\n PROCESS_ITEM: getItemByQueryFromState(state, function(item, success, failure) {\n var maxParallelUploads = query('GET_MAX_PARALLEL_UPLOADS');\n var totalCurrentUploads = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING)\n .length;\n\n // queue and wait till queue is freed up\n if (totalCurrentUploads === maxParallelUploads) {\n // queue for later processing\n state.processingQueue.push({\n id: item.id,\n success: success,\n failure: failure,\n });\n\n // stop it!\n return;\n }\n\n // if was not queued or is already processing exit here\n if (item.status === ItemStatus.PROCESSING) return;\n\n var processNext = function processNext() {\n // process queueud items\n var queueEntry = state.processingQueue.shift();\n\n // no items left\n if (!queueEntry) return;\n\n // get item reference\n var id = queueEntry.id,\n success = queueEntry.success,\n failure = queueEntry.failure;\n var itemReference = getItemByQuery(state.items, id);\n\n // if item was archived while in queue, jump to next\n if (!itemReference || itemReference.archived) {\n processNext();\n return;\n }\n\n // process queued item\n dispatch(\n 'PROCESS_ITEM',\n { query: id, success: success, failure: failure },\n true\n );\n };\n\n // we done function\n item.onOnce('process-complete', function() {\n success(createItemAPI(item));\n processNext();\n\n // if origin is local, and we're instant uploading, trigger remove of original\n // as revert will remove file from list\n var server = state.options.server;\n var instantUpload = state.options.instantUpload;\n if (\n instantUpload &&\n item.origin === FileOrigin.LOCAL &&\n isFunction(server.remove)\n ) {\n var noop = function noop() {};\n item.origin = FileOrigin.LIMBO;\n state.options.server.remove(item.source, noop, noop);\n }\n\n // All items processed? No errors?\n var allItemsProcessed =\n query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING_COMPLETE).length ===\n state.items.length;\n if (allItemsProcessed) {\n dispatch('DID_COMPLETE_ITEM_PROCESSING_ALL');\n }\n });\n\n // we error function\n item.onOnce('process-error', function(error) {\n failure({ error: error, file: createItemAPI(item) });\n processNext();\n });\n\n // start file processing\n var options = state.options;\n item.process(\n createFileProcessor(\n createProcessorFunction(\n options.server.url,\n options.server.process,\n options.name,\n {\n chunkTransferId: item.transferId,\n chunkServer: options.server.patch,\n chunkUploads: options.chunkUploads,\n chunkForce: options.chunkForce,\n chunkSize: options.chunkSize,\n chunkRetryDelays: options.chunkRetryDelays,\n }\n ),\n\n {\n allowMinimumUploadDuration: query('GET_ALLOW_MINIMUM_UPLOAD_DURATION'),\n }\n ),\n\n // called when the file is about to be processed so it can be piped through the transform filters\n function(file, success, error) {\n // allow plugins to alter the file data\n applyFilterChain('PREPARE_OUTPUT', file, { query: query, item: item })\n .then(function(file) {\n dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });\n\n success(file);\n })\n .catch(error);\n }\n );\n }),\n\n RETRY_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n dispatch('REQUEST_ITEM_PROCESSING', { query: item });\n }),\n\n REQUEST_REMOVE_ITEM: getItemByQueryFromState(state, function(item) {\n optionalPromise(query('GET_BEFORE_REMOVE_FILE'), createItemAPI(item)).then(function(\n shouldRemove\n ) {\n if (!shouldRemove) {\n return;\n }\n dispatch('REMOVE_ITEM', { query: item });\n });\n }),\n\n RELEASE_ITEM: getItemByQueryFromState(state, function(item) {\n item.release();\n }),\n\n REMOVE_ITEM: getItemByQueryFromState(state, function(item, success, failure, options) {\n var removeFromView = function removeFromView() {\n // get id reference\n var id = item.id;\n\n // archive the item, this does not remove it from the list\n getItemById(state.items, id).archive();\n\n // tell the view the item has been removed\n dispatch('DID_REMOVE_ITEM', { error: null, id: id, item: item });\n\n // now the list has been modified\n listUpdated(dispatch, state);\n\n // correctly removed\n success(createItemAPI(item));\n };\n\n // if this is a local file and the `server.remove` function has been configured,\n // send source there so dev can remove file from server\n var server = state.options.server;\n if (\n item.origin === FileOrigin.LOCAL &&\n server &&\n isFunction(server.remove) &&\n options.remove !== false\n ) {\n dispatch('DID_START_ITEM_REMOVE', { id: item.id });\n\n server.remove(\n item.source,\n function() {\n return removeFromView();\n },\n function(status) {\n dispatch('DID_THROW_ITEM_REMOVE_ERROR', {\n id: item.id,\n error: createResponse('error', 0, status, null),\n status: {\n main: dynamicLabel(state.options.labelFileRemoveError)(status),\n sub: state.options.labelTapToRetry,\n },\n });\n }\n );\n } else {\n // if is requesting revert and can revert need to call revert handler (not calling request_ because that would also trigger beforeRemoveHook)\n if (\n (options.revert &&\n item.origin !== FileOrigin.LOCAL &&\n item.serverId !== null) ||\n // if chunked uploads are enabled and we're uploading in chunks for this specific file\n // or if the file isn't big enough for chunked uploads but chunkForce is set then call\n // revert before removing from the view...\n (state.options.chunkUploads && item.file.size > state.options.chunkSize) ||\n (state.options.chunkUploads && state.options.chunkForce)\n ) {\n item.revert(\n createRevertFunction(\n state.options.server.url,\n state.options.server.revert\n ),\n query('GET_FORCE_REVERT')\n );\n }\n\n // can now safely remove from view\n removeFromView();\n }\n }),\n\n ABORT_ITEM_LOAD: getItemByQueryFromState(state, function(item) {\n item.abortLoad();\n }),\n\n ABORT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n // test if is already processed\n if (item.serverId) {\n dispatch('REVERT_ITEM_PROCESSING', { id: item.id });\n return;\n }\n\n // abort\n item.abortProcessing().then(function() {\n var shouldRemove = state.options.instantUpload;\n if (shouldRemove) {\n dispatch('REMOVE_ITEM', { query: item.id });\n }\n });\n }),\n\n REQUEST_REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n // not instant uploading, revert immediately\n if (!state.options.instantUpload) {\n dispatch('REVERT_ITEM_PROCESSING', { query: item });\n return;\n }\n\n // if we're instant uploading the file will also be removed if we revert,\n // so if a before remove file hook is defined we need to run it now\n var handleRevert = function handleRevert(shouldRevert) {\n if (!shouldRevert) return;\n dispatch('REVERT_ITEM_PROCESSING', { query: item });\n };\n\n var fn = query('GET_BEFORE_REMOVE_FILE');\n if (!fn) {\n return handleRevert(true);\n }\n\n var requestRemoveResult = fn(createItemAPI(item));\n if (requestRemoveResult == null) {\n // undefined or null\n return handleRevert(true);\n }\n\n if (typeof requestRemoveResult === 'boolean') {\n return handleRevert(requestRemoveResult);\n }\n\n if (typeof requestRemoveResult.then === 'function') {\n requestRemoveResult.then(handleRevert);\n }\n }),\n\n REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {\n item.revert(\n createRevertFunction(state.options.server.url, state.options.server.revert),\n query('GET_FORCE_REVERT')\n )\n .then(function() {\n var shouldRemove = state.options.instantUpload || isMockItem(item);\n if (shouldRemove) {\n dispatch('REMOVE_ITEM', { query: item.id });\n }\n })\n .catch(function() {});\n }),\n\n SET_OPTIONS: function SET_OPTIONS(_ref11) {\n var options = _ref11.options;\n // get all keys passed\n var optionKeys = Object.keys(options);\n\n // get prioritized keyed to include (remove once not in options object)\n var prioritizedOptionKeys = PrioritizedOptions.filter(function(key) {\n return optionKeys.includes(key);\n });\n\n // order the keys, prioritized first, then rest\n var orderedOptionKeys = [].concat(\n _toConsumableArray(prioritizedOptionKeys),\n _toConsumableArray(\n Object.keys(options).filter(function(key) {\n return !prioritizedOptionKeys.includes(key);\n })\n )\n );\n\n // dispatch set event for each option\n orderedOptionKeys.forEach(function(key) {\n dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {\n value: options[key],\n });\n });\n },\n };\n };\n\n var PrioritizedOptions = ['server'];\n\n var formatFilename = function formatFilename(name) {\n return name;\n };\n\n var createElement$1 = function createElement(tagName) {\n return document.createElement(tagName);\n };\n\n var text = function text(node, value) {\n var textNode = node.childNodes[0];\n if (!textNode) {\n textNode = document.createTextNode(value);\n node.appendChild(textNode);\n } else if (value !== textNode.nodeValue) {\n textNode.nodeValue = value;\n }\n };\n\n var polarToCartesian = function polarToCartesian(centerX, centerY, radius, angleInDegrees) {\n var angleInRadians = (((angleInDegrees % 360) - 90) * Math.PI) / 180.0;\n return {\n x: centerX + radius * Math.cos(angleInRadians),\n y: centerY + radius * Math.sin(angleInRadians),\n };\n };\n\n var describeArc = function describeArc(x, y, radius, startAngle, endAngle, arcSweep) {\n var start = polarToCartesian(x, y, radius, endAngle);\n var end = polarToCartesian(x, y, radius, startAngle);\n return ['M', start.x, start.y, 'A', radius, radius, 0, arcSweep, 0, end.x, end.y].join(' ');\n };\n\n var percentageArc = function percentageArc(x, y, radius, from, to) {\n var arcSweep = 1;\n if (to > from && to - from <= 0.5) {\n arcSweep = 0;\n }\n if (from > to && from - to >= 0.5) {\n arcSweep = 0;\n }\n return describeArc(\n x,\n y,\n radius,\n Math.min(0.9999, from) * 360,\n Math.min(0.9999, to) * 360,\n arcSweep\n );\n };\n\n var create = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // start at 0\n props.spin = false;\n props.progress = 0;\n props.opacity = 0;\n\n // svg\n var svg = createElement('svg');\n root.ref.path = createElement('path', {\n 'stroke-width': 2,\n 'stroke-linecap': 'round',\n });\n\n svg.appendChild(root.ref.path);\n\n root.ref.svg = svg;\n\n root.appendChild(svg);\n };\n\n var write = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n if (props.opacity === 0) {\n return;\n }\n\n if (props.align) {\n root.element.dataset.align = props.align;\n }\n\n // get width of stroke\n var ringStrokeWidth = parseInt(attr(root.ref.path, 'stroke-width'), 10);\n\n // calculate size of ring\n var size = root.rect.element.width * 0.5;\n\n // ring state\n var ringFrom = 0;\n var ringTo = 0;\n\n // now in busy mode\n if (props.spin) {\n ringFrom = 0;\n ringTo = 0.5;\n } else {\n ringFrom = 0;\n ringTo = props.progress;\n }\n\n // get arc path\n var coordinates = percentageArc(size, size, size - ringStrokeWidth, ringFrom, ringTo);\n\n // update progress bar\n attr(root.ref.path, 'd', coordinates);\n\n // hide while contains 0 value\n attr(root.ref.path, 'stroke-opacity', props.spin || props.progress > 0 ? 1 : 0);\n };\n\n var progressIndicator = createView({\n tag: 'div',\n name: 'progress-indicator',\n ignoreRectUpdate: true,\n ignoreRect: true,\n create: create,\n write: write,\n mixins: {\n apis: ['progress', 'spin', 'align'],\n styles: ['opacity'],\n animations: {\n opacity: { type: 'tween', duration: 500 },\n progress: {\n type: 'spring',\n stiffness: 0.95,\n damping: 0.65,\n mass: 10,\n },\n },\n },\n });\n\n var create$1 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.element.innerHTML = (props.icon || '') + ('' + props.label + '');\n\n props.isDisabled = false;\n };\n\n var write$1 = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n var isDisabled = props.isDisabled;\n var shouldDisable = root.query('GET_DISABLED') || props.opacity === 0;\n\n if (shouldDisable && !isDisabled) {\n props.isDisabled = true;\n attr(root.element, 'disabled', 'disabled');\n } else if (!shouldDisable && isDisabled) {\n props.isDisabled = false;\n root.element.removeAttribute('disabled');\n }\n };\n\n var fileActionButton = createView({\n tag: 'button',\n attributes: {\n type: 'button',\n },\n\n ignoreRect: true,\n ignoreRectUpdate: true,\n name: 'file-action-button',\n mixins: {\n apis: ['label'],\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n translateX: 'spring',\n translateY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n\n listeners: true,\n },\n\n create: create$1,\n write: write$1,\n });\n\n var toNaturalFileSize = function toNaturalFileSize(bytes) {\n var decimalSeparator =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';\n var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var _options$labelBytes = options.labelBytes,\n labelBytes = _options$labelBytes === void 0 ? 'bytes' : _options$labelBytes,\n _options$labelKilobyt = options.labelKilobytes,\n labelKilobytes = _options$labelKilobyt === void 0 ? 'KB' : _options$labelKilobyt,\n _options$labelMegabyt = options.labelMegabytes,\n labelMegabytes = _options$labelMegabyt === void 0 ? 'MB' : _options$labelMegabyt,\n _options$labelGigabyt = options.labelGigabytes,\n labelGigabytes = _options$labelGigabyt === void 0 ? 'GB' : _options$labelGigabyt;\n\n // no negative byte sizes\n bytes = Math.round(Math.abs(bytes));\n\n var KB = base;\n var MB = base * base;\n var GB = base * base * base;\n\n // just bytes\n if (bytes < KB) {\n return bytes + ' ' + labelBytes;\n }\n\n // kilobytes\n if (bytes < MB) {\n return Math.floor(bytes / KB) + ' ' + labelKilobytes;\n }\n\n // megabytes\n if (bytes < GB) {\n return removeDecimalsWhenZero(bytes / MB, 1, decimalSeparator) + ' ' + labelMegabytes;\n }\n\n // gigabytes\n return removeDecimalsWhenZero(bytes / GB, 2, decimalSeparator) + ' ' + labelGigabytes;\n };\n\n var removeDecimalsWhenZero = function removeDecimalsWhenZero(value, decimalCount, separator) {\n return value\n .toFixed(decimalCount)\n .split('.')\n .filter(function(part) {\n return part !== '0';\n })\n .join(separator);\n };\n\n var create$2 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // filename\n var fileName = createElement$1('span');\n fileName.className = 'filepond--file-info-main';\n // hide for screenreaders\n // the file is contained in a fieldset with legend that contains the filename\n // no need to read it twice\n attr(fileName, 'aria-hidden', 'true');\n root.appendChild(fileName);\n root.ref.fileName = fileName;\n\n // filesize\n var fileSize = createElement$1('span');\n fileSize.className = 'filepond--file-info-sub';\n root.appendChild(fileSize);\n root.ref.fileSize = fileSize;\n\n // set initial values\n text(fileSize, root.query('GET_LABEL_FILE_WAITING_FOR_SIZE'));\n text(fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var updateFile = function updateFile(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n text(\n root.ref.fileSize,\n toNaturalFileSize(\n root.query('GET_ITEM_SIZE', props.id),\n '.',\n root.query('GET_FILE_SIZE_BASE'),\n root.query('GET_FILE_SIZE_LABELS', root.query)\n )\n );\n\n text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var updateFileSizeOnError = function updateFileSizeOnError(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n // if size is available don't fallback to unknown size message\n if (isInt(root.query('GET_ITEM_SIZE', props.id))) {\n updateFile({ root: root, props: props });\n return;\n }\n\n text(root.ref.fileSize, root.query('GET_LABEL_FILE_SIZE_NOT_AVAILABLE'));\n };\n\n var fileInfo = createView({\n name: 'file-info',\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: updateFile,\n DID_UPDATE_ITEM_META: updateFile,\n DID_THROW_ITEM_LOAD_ERROR: updateFileSizeOnError,\n DID_THROW_ITEM_INVALID: updateFileSizeOnError,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n create: create$2,\n mixins: {\n styles: ['translateX', 'translateY'],\n animations: {\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n var toPercentage = function toPercentage(value) {\n return Math.round(value * 100);\n };\n\n var create$3 = function create(_ref) {\n var root = _ref.root;\n\n // main status\n var main = createElement$1('span');\n main.className = 'filepond--file-status-main';\n root.appendChild(main);\n root.ref.main = main;\n\n // sub status\n var sub = createElement$1('span');\n sub.className = 'filepond--file-status-sub';\n root.appendChild(sub);\n root.ref.sub = sub;\n\n didSetItemLoadProgress({ root: root, action: { progress: null } });\n };\n\n var didSetItemLoadProgress = function didSetItemLoadProgress(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n var title =\n action.progress === null\n ? root.query('GET_LABEL_FILE_LOADING')\n : root.query('GET_LABEL_FILE_LOADING') + ' ' + toPercentage(action.progress) + '%';\n\n text(root.ref.main, title);\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didSetItemProcessProgress = function didSetItemProcessProgress(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var title =\n action.progress === null\n ? root.query('GET_LABEL_FILE_PROCESSING')\n : root.query('GET_LABEL_FILE_PROCESSING') +\n ' ' +\n toPercentage(action.progress) +\n '%';\n\n text(root.ref.main, title);\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didRequestItemProcessing = function didRequestItemProcessing(_ref4) {\n var root = _ref4.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));\n };\n\n var didAbortItemProcessing = function didAbortItemProcessing(_ref5) {\n var root = _ref5.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_ABORTED'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_RETRY'));\n };\n\n var didCompleteItemProcessing = function didCompleteItemProcessing(_ref6) {\n var root = _ref6.root;\n text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_COMPLETE'));\n text(root.ref.sub, root.query('GET_LABEL_TAP_TO_UNDO'));\n };\n\n var clear = function clear(_ref7) {\n var root = _ref7.root;\n text(root.ref.main, '');\n text(root.ref.sub, '');\n };\n\n var error = function error(_ref8) {\n var root = _ref8.root,\n action = _ref8.action;\n text(root.ref.main, action.status.main);\n text(root.ref.sub, action.status.sub);\n };\n\n var fileStatus = createView({\n name: 'file-status',\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: clear,\n DID_REVERT_ITEM_PROCESSING: clear,\n DID_REQUEST_ITEM_PROCESSING: didRequestItemProcessing,\n DID_ABORT_ITEM_PROCESSING: didAbortItemProcessing,\n DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing,\n DID_UPDATE_ITEM_PROCESS_PROGRESS: didSetItemProcessProgress,\n DID_UPDATE_ITEM_LOAD_PROGRESS: didSetItemLoadProgress,\n DID_THROW_ITEM_LOAD_ERROR: error,\n DID_THROW_ITEM_INVALID: error,\n DID_THROW_ITEM_PROCESSING_ERROR: error,\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: error,\n DID_THROW_ITEM_REMOVE_ERROR: error,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n create: create$3,\n mixins: {\n styles: ['translateX', 'translateY', 'opacity'],\n animations: {\n opacity: { type: 'tween', duration: 250 },\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n /**\n * Button definitions for the file view\n */\n\n var Buttons = {\n AbortItemLoad: {\n label: 'GET_LABEL_BUTTON_ABORT_ITEM_LOAD',\n action: 'ABORT_ITEM_LOAD',\n className: 'filepond--action-abort-item-load',\n align: 'LOAD_INDICATOR_POSITION', // right\n },\n RetryItemLoad: {\n label: 'GET_LABEL_BUTTON_RETRY_ITEM_LOAD',\n action: 'RETRY_ITEM_LOAD',\n icon: 'GET_ICON_RETRY',\n className: 'filepond--action-retry-item-load',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RemoveItem: {\n label: 'GET_LABEL_BUTTON_REMOVE_ITEM',\n action: 'REQUEST_REMOVE_ITEM',\n icon: 'GET_ICON_REMOVE',\n className: 'filepond--action-remove-item',\n align: 'BUTTON_REMOVE_ITEM_POSITION', // left\n },\n ProcessItem: {\n label: 'GET_LABEL_BUTTON_PROCESS_ITEM',\n action: 'REQUEST_ITEM_PROCESSING',\n icon: 'GET_ICON_PROCESS',\n className: 'filepond--action-process-item',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n AbortItemProcessing: {\n label: 'GET_LABEL_BUTTON_ABORT_ITEM_PROCESSING',\n action: 'ABORT_ITEM_PROCESSING',\n className: 'filepond--action-abort-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RetryItemProcessing: {\n label: 'GET_LABEL_BUTTON_RETRY_ITEM_PROCESSING',\n action: 'RETRY_ITEM_PROCESSING',\n icon: 'GET_ICON_RETRY',\n className: 'filepond--action-retry-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n RevertItemProcessing: {\n label: 'GET_LABEL_BUTTON_UNDO_ITEM_PROCESSING',\n action: 'REQUEST_REVERT_ITEM_PROCESSING',\n icon: 'GET_ICON_UNDO',\n className: 'filepond--action-revert-item-processing',\n align: 'BUTTON_PROCESS_ITEM_POSITION', // right\n },\n };\n\n // make a list of buttons, we can then remove buttons from this list if they're disabled\n var ButtonKeys = [];\n forin(Buttons, function(key) {\n ButtonKeys.push(key);\n });\n\n var calculateFileInfoOffset = function calculateFileInfoOffset(root) {\n if (getRemoveIndicatorAligment(root) === 'right') return 0;\n var buttonRect = root.ref.buttonRemoveItem.rect.element;\n return buttonRect.hidden ? null : buttonRect.width + buttonRect.left;\n };\n\n var calculateButtonWidth = function calculateButtonWidth(root) {\n var buttonRect = root.ref.buttonAbortItemLoad.rect.element;\n return buttonRect.width;\n };\n\n // Force on full pixels so text stays crips\n var calculateFileVerticalCenterOffset = function calculateFileVerticalCenterOffset(root) {\n return Math.floor(root.ref.buttonRemoveItem.rect.element.height / 4);\n };\n var calculateFileHorizontalCenterOffset = function calculateFileHorizontalCenterOffset(root) {\n return Math.floor(root.ref.buttonRemoveItem.rect.element.left / 2);\n };\n\n var getLoadIndicatorAlignment = function getLoadIndicatorAlignment(root) {\n return root.query('GET_STYLE_LOAD_INDICATOR_POSITION');\n };\n var getProcessIndicatorAlignment = function getProcessIndicatorAlignment(root) {\n return root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION');\n };\n var getRemoveIndicatorAligment = function getRemoveIndicatorAligment(root) {\n return root.query('GET_STYLE_BUTTON_REMOVE_ITEM_POSITION');\n };\n\n var DefaultStyle = {\n buttonAbortItemLoad: { opacity: 0 },\n buttonRetryItemLoad: { opacity: 0 },\n buttonRemoveItem: { opacity: 0 },\n buttonProcessItem: { opacity: 0 },\n buttonAbortItemProcessing: { opacity: 0 },\n buttonRetryItemProcessing: { opacity: 0 },\n buttonRevertItemProcessing: { opacity: 0 },\n loadProgressIndicator: { opacity: 0, align: getLoadIndicatorAlignment },\n processProgressIndicator: { opacity: 0, align: getProcessIndicatorAlignment },\n processingCompleteIndicator: { opacity: 0, scaleX: 0.75, scaleY: 0.75 },\n info: { translateX: 0, translateY: 0, opacity: 0 },\n status: { translateX: 0, translateY: 0, opacity: 0 },\n };\n\n var IdleStyle = {\n buttonRemoveItem: { opacity: 1 },\n buttonProcessItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset },\n };\n\n var ProcessingStyle = {\n buttonAbortItemProcessing: { opacity: 1 },\n processProgressIndicator: { opacity: 1 },\n status: { opacity: 1 },\n };\n\n var StyleMap = {\n DID_THROW_ITEM_INVALID: {\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset, opacity: 1 },\n },\n\n DID_START_ITEM_LOAD: {\n buttonAbortItemLoad: { opacity: 1 },\n loadProgressIndicator: { opacity: 1 },\n status: { opacity: 1 },\n },\n\n DID_THROW_ITEM_LOAD_ERROR: {\n buttonRetryItemLoad: { opacity: 1 },\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1 },\n },\n\n DID_START_ITEM_REMOVE: {\n processProgressIndicator: { opacity: 1, align: getRemoveIndicatorAligment },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 0 },\n },\n\n DID_THROW_ITEM_REMOVE_ERROR: {\n processProgressIndicator: { opacity: 0, align: getRemoveIndicatorAligment },\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1, translateX: calculateFileInfoOffset },\n },\n\n DID_LOAD_ITEM: IdleStyle,\n DID_LOAD_LOCAL_ITEM: {\n buttonRemoveItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { translateX: calculateFileInfoOffset },\n },\n\n DID_START_ITEM_PROCESSING: ProcessingStyle,\n DID_REQUEST_ITEM_PROCESSING: ProcessingStyle,\n DID_UPDATE_ITEM_PROCESS_PROGRESS: ProcessingStyle,\n DID_COMPLETE_ITEM_PROCESSING: {\n buttonRevertItemProcessing: { opacity: 1 },\n info: { opacity: 1 },\n status: { opacity: 1 },\n },\n\n DID_THROW_ITEM_PROCESSING_ERROR: {\n buttonRemoveItem: { opacity: 1 },\n buttonRetryItemProcessing: { opacity: 1 },\n status: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n },\n\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: {\n buttonRevertItemProcessing: { opacity: 1 },\n status: { opacity: 1 },\n info: { opacity: 1 },\n },\n\n DID_ABORT_ITEM_PROCESSING: {\n buttonRemoveItem: { opacity: 1 },\n buttonProcessItem: { opacity: 1 },\n info: { translateX: calculateFileInfoOffset },\n status: { opacity: 1 },\n },\n\n DID_REVERT_ITEM_PROCESSING: IdleStyle,\n };\n\n // complete indicator view\n var processingCompleteIndicatorView = createView({\n create: function create(_ref) {\n var root = _ref.root;\n root.element.innerHTML = root.query('GET_ICON_DONE');\n },\n name: 'processing-complete-indicator',\n ignoreRect: true,\n mixins: {\n styles: ['scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n },\n });\n\n /**\n * Creates the file view\n */\n var create$4 = function create(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n // copy Buttons object\n var LocalButtons = Object.keys(Buttons).reduce(function(prev, curr) {\n prev[curr] = Object.assign({}, Buttons[curr]);\n return prev;\n }, {});\n var id = props.id;\n\n // allow reverting upload\n var allowRevert = root.query('GET_ALLOW_REVERT');\n\n // allow remove file\n var allowRemove = root.query('GET_ALLOW_REMOVE');\n\n // allow processing upload\n var allowProcess = root.query('GET_ALLOW_PROCESS');\n\n // is instant uploading, need this to determine the icon of the undo button\n var instantUpload = root.query('GET_INSTANT_UPLOAD');\n\n // is async set up\n var isAsync = root.query('IS_ASYNC');\n\n // should align remove item buttons\n var alignRemoveItemButton = root.query('GET_STYLE_BUTTON_REMOVE_ITEM_ALIGN');\n\n // enabled buttons array\n var buttonFilter;\n if (isAsync) {\n if (allowProcess && !allowRevert) {\n // only remove revert button\n buttonFilter = function buttonFilter(key) {\n return !/RevertItemProcessing/.test(key);\n };\n } else if (!allowProcess && allowRevert) {\n // only remove process button\n buttonFilter = function buttonFilter(key) {\n return !/ProcessItem|RetryItemProcessing|AbortItemProcessing/.test(key);\n };\n } else if (!allowProcess && !allowRevert) {\n // remove all process buttons\n buttonFilter = function buttonFilter(key) {\n return !/Process/.test(key);\n };\n }\n } else {\n // no process controls available\n buttonFilter = function buttonFilter(key) {\n return !/Process/.test(key);\n };\n }\n\n var enabledButtons = buttonFilter ? ButtonKeys.filter(buttonFilter) : ButtonKeys.concat();\n\n // update icon and label for revert button when instant uploading\n if (instantUpload && allowRevert) {\n LocalButtons['RevertItemProcessing'].label = 'GET_LABEL_BUTTON_REMOVE_ITEM';\n LocalButtons['RevertItemProcessing'].icon = 'GET_ICON_REMOVE';\n }\n\n // remove last button (revert) if not allowed\n if (isAsync && !allowRevert) {\n var map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];\n map.info.translateX = calculateFileHorizontalCenterOffset;\n map.info.translateY = calculateFileVerticalCenterOffset;\n map.status.translateY = calculateFileVerticalCenterOffset;\n map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };\n }\n\n // should align center\n if (isAsync && !allowProcess) {\n [\n 'DID_START_ITEM_PROCESSING',\n 'DID_REQUEST_ITEM_PROCESSING',\n 'DID_UPDATE_ITEM_PROCESS_PROGRESS',\n 'DID_THROW_ITEM_PROCESSING_ERROR',\n ].forEach(function(key) {\n StyleMap[key].status.translateY = calculateFileVerticalCenterOffset;\n });\n StyleMap['DID_THROW_ITEM_PROCESSING_ERROR'].status.translateX = calculateButtonWidth;\n }\n\n // move remove button to right\n if (alignRemoveItemButton && allowRevert) {\n LocalButtons['RevertItemProcessing'].align = 'BUTTON_REMOVE_ITEM_POSITION';\n var _map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];\n _map.info.translateX = calculateFileInfoOffset;\n _map.status.translateY = calculateFileVerticalCenterOffset;\n _map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };\n }\n\n // show/hide RemoveItem button\n if (!allowRemove) {\n LocalButtons['RemoveItem'].disabled = true;\n }\n\n // create the button views\n forin(LocalButtons, function(key, definition) {\n // create button\n var buttonView = root.createChildView(fileActionButton, {\n label: root.query(definition.label),\n icon: root.query(definition.icon),\n opacity: 0,\n });\n\n // should be appended?\n if (enabledButtons.includes(key)) {\n root.appendChildView(buttonView);\n }\n\n // toggle\n if (definition.disabled) {\n buttonView.element.setAttribute('disabled', 'disabled');\n buttonView.element.setAttribute('hidden', 'hidden');\n }\n\n // add position attribute\n buttonView.element.dataset.align = root.query('GET_STYLE_' + definition.align);\n\n // add class\n buttonView.element.classList.add(definition.className);\n\n // handle interactions\n buttonView.on('click', function(e) {\n e.stopPropagation();\n if (definition.disabled) return;\n root.dispatch(definition.action, { query: id });\n });\n\n // set reference\n root.ref['button' + key] = buttonView;\n });\n\n // checkmark\n root.ref.processingCompleteIndicator = root.appendChildView(\n root.createChildView(processingCompleteIndicatorView)\n );\n\n root.ref.processingCompleteIndicator.element.dataset.align = root.query(\n 'GET_STYLE_BUTTON_PROCESS_ITEM_POSITION'\n );\n\n // create file info view\n root.ref.info = root.appendChildView(root.createChildView(fileInfo, { id: id }));\n\n // create file status view\n root.ref.status = root.appendChildView(root.createChildView(fileStatus, { id: id }));\n\n // add progress indicators\n var loadIndicatorView = root.appendChildView(\n root.createChildView(progressIndicator, {\n opacity: 0,\n align: root.query('GET_STYLE_LOAD_INDICATOR_POSITION'),\n })\n );\n\n loadIndicatorView.element.classList.add('filepond--load-indicator');\n root.ref.loadProgressIndicator = loadIndicatorView;\n\n var progressIndicatorView = root.appendChildView(\n root.createChildView(progressIndicator, {\n opacity: 0,\n align: root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'),\n })\n );\n\n progressIndicatorView.element.classList.add('filepond--process-indicator');\n root.ref.processProgressIndicator = progressIndicatorView;\n\n // current active styles\n root.ref.activeStyles = [];\n };\n\n var write$2 = function write(_ref3) {\n var root = _ref3.root,\n actions = _ref3.actions,\n props = _ref3.props;\n // route actions\n route({ root: root, actions: actions, props: props });\n\n // select last state change action\n var action = actions\n .concat()\n .filter(function(action) {\n return /^DID_/.test(action.type);\n })\n .reverse()\n .find(function(action) {\n return StyleMap[action.type];\n });\n\n // a new action happened, let's get the matching styles\n if (action) {\n // define new active styles\n root.ref.activeStyles = [];\n\n var stylesToApply = StyleMap[action.type];\n forin(DefaultStyle, function(name, defaultStyles) {\n // get reference to control\n var control = root.ref[name];\n\n // loop over all styles for this control\n forin(defaultStyles, function(key, defaultValue) {\n var value =\n stylesToApply[name] && typeof stylesToApply[name][key] !== 'undefined'\n ? stylesToApply[name][key]\n : defaultValue;\n root.ref.activeStyles.push({ control: control, key: key, value: value });\n });\n });\n }\n\n // apply active styles to element\n root.ref.activeStyles.forEach(function(_ref4) {\n var control = _ref4.control,\n key = _ref4.key,\n value = _ref4.value;\n control[key] = typeof value === 'function' ? value(root) : value;\n });\n };\n\n var route = createRoute({\n DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING: function DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING(\n _ref5\n ) {\n var root = _ref5.root,\n action = _ref5.action;\n root.ref.buttonAbortItemProcessing.label = action.value;\n },\n DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD: function DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n root.ref.buttonAbortItemLoad.label = action.value;\n },\n DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL: function DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL(\n _ref7\n ) {\n var root = _ref7.root,\n action = _ref7.action;\n root.ref.buttonAbortItemRemoval.label = action.value;\n },\n DID_REQUEST_ITEM_PROCESSING: function DID_REQUEST_ITEM_PROCESSING(_ref8) {\n var root = _ref8.root;\n root.ref.processProgressIndicator.spin = true;\n root.ref.processProgressIndicator.progress = 0;\n },\n DID_START_ITEM_LOAD: function DID_START_ITEM_LOAD(_ref9) {\n var root = _ref9.root;\n root.ref.loadProgressIndicator.spin = true;\n root.ref.loadProgressIndicator.progress = 0;\n },\n DID_START_ITEM_REMOVE: function DID_START_ITEM_REMOVE(_ref10) {\n var root = _ref10.root;\n root.ref.processProgressIndicator.spin = true;\n root.ref.processProgressIndicator.progress = 0;\n },\n DID_UPDATE_ITEM_LOAD_PROGRESS: function DID_UPDATE_ITEM_LOAD_PROGRESS(_ref11) {\n var root = _ref11.root,\n action = _ref11.action;\n root.ref.loadProgressIndicator.spin = false;\n root.ref.loadProgressIndicator.progress = action.progress;\n },\n DID_UPDATE_ITEM_PROCESS_PROGRESS: function DID_UPDATE_ITEM_PROCESS_PROGRESS(_ref12) {\n var root = _ref12.root,\n action = _ref12.action;\n root.ref.processProgressIndicator.spin = false;\n root.ref.processProgressIndicator.progress = action.progress;\n },\n });\n\n var file = createView({\n create: create$4,\n write: write$2,\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n name: 'file',\n });\n\n /**\n * Creates the file view\n */\n var create$5 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // filename\n root.ref.fileName = createElement$1('legend');\n root.appendChild(root.ref.fileName);\n\n // file appended\n root.ref.file = root.appendChildView(root.createChildView(file, { id: props.id }));\n\n // data has moved to data.js\n root.ref.data = false;\n };\n\n /**\n * Data storage\n */\n var didLoadItem = function didLoadItem(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n // updates the legend of the fieldset so screenreaders can better group buttons\n text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));\n };\n\n var fileWrapper = createView({\n create: create$5,\n ignoreRect: true,\n write: createRoute({\n DID_LOAD_ITEM: didLoadItem,\n }),\n\n didCreateView: function didCreateView(root) {\n applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));\n },\n tag: 'fieldset',\n name: 'file-wrapper',\n });\n\n var PANEL_SPRING_PROPS = { type: 'spring', damping: 0.6, mass: 7 };\n\n var create$6 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n [\n {\n name: 'top',\n },\n\n {\n name: 'center',\n props: {\n translateY: null,\n scaleY: null,\n },\n\n mixins: {\n animations: {\n scaleY: PANEL_SPRING_PROPS,\n },\n\n styles: ['translateY', 'scaleY'],\n },\n },\n\n {\n name: 'bottom',\n props: {\n translateY: null,\n },\n\n mixins: {\n animations: {\n translateY: PANEL_SPRING_PROPS,\n },\n\n styles: ['translateY'],\n },\n },\n ].forEach(function(section) {\n createSection(root, section, props.name);\n });\n\n root.element.classList.add('filepond--' + props.name);\n\n root.ref.scalable = null;\n };\n\n var createSection = function createSection(root, section, className) {\n var viewConstructor = createView({\n name: 'panel-' + section.name + ' filepond--' + className,\n mixins: section.mixins,\n ignoreRectUpdate: true,\n });\n\n var view = root.createChildView(viewConstructor, section.props);\n\n root.ref[section.name] = root.appendChildView(view);\n };\n\n var write$3 = function write(_ref2) {\n var root = _ref2.root,\n props = _ref2.props;\n\n // update scalable state\n if (root.ref.scalable === null || props.scalable !== root.ref.scalable) {\n root.ref.scalable = isBoolean(props.scalable) ? props.scalable : true;\n root.element.dataset.scalable = root.ref.scalable;\n }\n\n // no height, can't set\n if (!props.height) return;\n\n // get child rects\n var topRect = root.ref.top.rect.element;\n var bottomRect = root.ref.bottom.rect.element;\n\n // make sure height never is smaller than bottom and top seciton heights combined (will probably never happen, but who knows)\n var height = Math.max(topRect.height + bottomRect.height, props.height);\n\n // offset center part\n root.ref.center.translateY = topRect.height;\n\n // scale center part\n // use math ceil to prevent transparent lines because of rounding errors\n root.ref.center.scaleY = (height - topRect.height - bottomRect.height) / 100;\n\n // offset bottom part\n root.ref.bottom.translateY = height - bottomRect.height;\n };\n\n var panel = createView({\n name: 'panel',\n read: function read(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n return (props.heightCurrent = root.ref.bottom.translateY);\n },\n write: write$3,\n create: create$6,\n ignoreRect: true,\n mixins: {\n apis: ['height', 'heightCurrent', 'scalable'],\n },\n });\n\n var createDragHelper = function createDragHelper(items) {\n var itemIds = items.map(function(item) {\n return item.id;\n });\n var prevIndex = undefined;\n return {\n setIndex: function setIndex(index) {\n prevIndex = index;\n },\n getIndex: function getIndex() {\n return prevIndex;\n },\n getItemIndex: function getItemIndex(item) {\n return itemIds.indexOf(item.id);\n },\n };\n };\n\n var ITEM_TRANSLATE_SPRING = {\n type: 'spring',\n stiffness: 0.75,\n damping: 0.45,\n mass: 10,\n };\n\n var ITEM_SCALE_SPRING = 'spring';\n\n var StateMap = {\n DID_START_ITEM_LOAD: 'busy',\n DID_UPDATE_ITEM_LOAD_PROGRESS: 'loading',\n DID_THROW_ITEM_INVALID: 'load-invalid',\n DID_THROW_ITEM_LOAD_ERROR: 'load-error',\n DID_LOAD_ITEM: 'idle',\n DID_THROW_ITEM_REMOVE_ERROR: 'remove-error',\n DID_START_ITEM_REMOVE: 'busy',\n DID_START_ITEM_PROCESSING: 'busy processing',\n DID_REQUEST_ITEM_PROCESSING: 'busy processing',\n DID_UPDATE_ITEM_PROCESS_PROGRESS: 'processing',\n DID_COMPLETE_ITEM_PROCESSING: 'processing-complete',\n DID_THROW_ITEM_PROCESSING_ERROR: 'processing-error',\n DID_THROW_ITEM_PROCESSING_REVERT_ERROR: 'processing-revert-error',\n DID_ABORT_ITEM_PROCESSING: 'cancelled',\n DID_REVERT_ITEM_PROCESSING: 'idle',\n };\n\n /**\n * Creates the file view\n */\n var create$7 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // select\n root.ref.handleClick = function(e) {\n return root.dispatch('DID_ACTIVATE_ITEM', { id: props.id });\n };\n\n // set id\n root.element.id = 'filepond--item-' + props.id;\n root.element.addEventListener('click', root.ref.handleClick);\n\n // file view\n root.ref.container = root.appendChildView(\n root.createChildView(fileWrapper, { id: props.id })\n );\n\n // file panel\n root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'item-panel' }));\n\n // default start height\n root.ref.panel.height = null;\n\n // by default not marked for removal\n props.markedForRemoval = false;\n\n // if not allowed to reorder file items, exit here\n if (!root.query('GET_ALLOW_REORDER')) return;\n\n // set to idle so shows grab cursor\n root.element.dataset.dragState = 'idle';\n\n var grab = function grab(e) {\n if (!e.isPrimary) return;\n\n var removedActivateListener = false;\n\n var origin = {\n x: e.pageX,\n y: e.pageY,\n };\n\n props.dragOrigin = {\n x: root.translateX,\n y: root.translateY,\n };\n\n props.dragCenter = {\n x: e.offsetX,\n y: e.offsetY,\n };\n\n var dragState = createDragHelper(root.query('GET_ACTIVE_ITEMS'));\n\n root.dispatch('DID_GRAB_ITEM', { id: props.id, dragState: dragState });\n\n var drag = function drag(e) {\n if (!e.isPrimary) return;\n\n e.stopPropagation();\n e.preventDefault();\n\n props.dragOffset = {\n x: e.pageX - origin.x,\n y: e.pageY - origin.y,\n };\n\n // if dragged stop listening to clicks, will re-add when done dragging\n var dist =\n props.dragOffset.x * props.dragOffset.x +\n props.dragOffset.y * props.dragOffset.y;\n if (dist > 16 && !removedActivateListener) {\n removedActivateListener = true;\n root.element.removeEventListener('click', root.ref.handleClick);\n }\n\n root.dispatch('DID_DRAG_ITEM', { id: props.id, dragState: dragState });\n };\n\n var drop = function drop(e) {\n if (!e.isPrimary) return;\n\n document.removeEventListener('pointermove', drag);\n document.removeEventListener('pointerup', drop);\n\n props.dragOffset = {\n x: e.pageX - origin.x,\n y: e.pageY - origin.y,\n };\n\n root.dispatch('DID_DROP_ITEM', { id: props.id, dragState: dragState });\n\n // start listening to clicks again\n if (removedActivateListener) {\n setTimeout(function() {\n return root.element.addEventListener('click', root.ref.handleClick);\n }, 0);\n }\n };\n\n document.addEventListener('pointermove', drag);\n document.addEventListener('pointerup', drop);\n };\n\n root.element.addEventListener('pointerdown', grab);\n };\n\n var route$1 = createRoute({\n DID_UPDATE_PANEL_HEIGHT: function DID_UPDATE_PANEL_HEIGHT(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n root.height = action.height;\n },\n });\n\n var write$4 = createRoute(\n {\n DID_GRAB_ITEM: function DID_GRAB_ITEM(_ref3) {\n var root = _ref3.root,\n props = _ref3.props;\n props.dragOrigin = {\n x: root.translateX,\n y: root.translateY,\n };\n },\n DID_DRAG_ITEM: function DID_DRAG_ITEM(_ref4) {\n var root = _ref4.root;\n root.element.dataset.dragState = 'drag';\n },\n DID_DROP_ITEM: function DID_DROP_ITEM(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n props.dragOffset = null;\n props.dragOrigin = null;\n root.element.dataset.dragState = 'drop';\n },\n },\n function(_ref6) {\n var root = _ref6.root,\n actions = _ref6.actions,\n props = _ref6.props,\n shouldOptimize = _ref6.shouldOptimize;\n\n if (root.element.dataset.dragState === 'drop') {\n if (root.scaleX <= 1) {\n root.element.dataset.dragState = 'idle';\n }\n }\n\n // select last state change action\n var action = actions\n .concat()\n .filter(function(action) {\n return /^DID_/.test(action.type);\n })\n .reverse()\n .find(function(action) {\n return StateMap[action.type];\n });\n\n // no need to set same state twice\n if (action && action.type !== props.currentState) {\n // set current state\n props.currentState = action.type;\n\n // set state\n root.element.dataset.filepondItemState = StateMap[props.currentState] || '';\n }\n\n // route actions\n var aspectRatio =\n root.query('GET_ITEM_PANEL_ASPECT_RATIO') || root.query('GET_PANEL_ASPECT_RATIO');\n if (!aspectRatio) {\n route$1({ root: root, actions: actions, props: props });\n if (!root.height && root.ref.container.rect.element.height > 0) {\n root.height = root.ref.container.rect.element.height;\n }\n } else if (!shouldOptimize) {\n root.height = root.rect.element.width * aspectRatio;\n }\n\n // sync panel height with item height\n if (shouldOptimize) {\n root.ref.panel.height = null;\n }\n\n root.ref.panel.height = root.height;\n }\n );\n\n var item = createView({\n create: create$7,\n write: write$4,\n destroy: function destroy(_ref7) {\n var root = _ref7.root,\n props = _ref7.props;\n root.element.removeEventListener('click', root.ref.handleClick);\n root.dispatch('RELEASE_ITEM', { query: props.id });\n },\n tag: 'li',\n name: 'item',\n mixins: {\n apis: [\n 'id',\n 'interactionMethod',\n 'markedForRemoval',\n 'spawnDate',\n 'dragCenter',\n 'dragOrigin',\n 'dragOffset',\n ],\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity', 'height'],\n\n animations: {\n scaleX: ITEM_SCALE_SPRING,\n scaleY: ITEM_SCALE_SPRING,\n translateX: ITEM_TRANSLATE_SPRING,\n translateY: ITEM_TRANSLATE_SPRING,\n opacity: { type: 'tween', duration: 150 },\n },\n },\n });\n\n var getItemsPerRow = function(horizontalSpace, itemWidth) {\n // add one pixel leeway, when using percentages for item width total items can be 1.99 per row\n\n return Math.max(1, Math.floor((horizontalSpace + 1) / itemWidth));\n };\n\n var getItemIndexByPosition = function getItemIndexByPosition(view, children, positionInView) {\n if (!positionInView) return;\n\n var horizontalSpace = view.rect.element.width;\n // const children = view.childViews;\n var l = children.length;\n var last = null;\n\n // -1, don't move items to accomodate (either add to top or bottom)\n if (l === 0 || positionInView.top < children[0].rect.element.top) return -1;\n\n // let's get the item width\n var item = children[0];\n var itemRect = item.rect.element;\n var itemHorizontalMargin = itemRect.marginLeft + itemRect.marginRight;\n var itemWidth = itemRect.width + itemHorizontalMargin;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n for (var index = 0; index < l; index++) {\n var child = children[index];\n var childMid = child.rect.outer.top + child.rect.element.height * 0.5;\n if (positionInView.top < childMid) {\n return index;\n }\n }\n return l;\n }\n\n // grid\n var itemVerticalMargin = itemRect.marginTop + itemRect.marginBottom;\n var itemHeight = itemRect.height + itemVerticalMargin;\n for (var _index = 0; _index < l; _index++) {\n var indexX = _index % itemsPerRow;\n var indexY = Math.floor(_index / itemsPerRow);\n\n var offsetX = indexX * itemWidth;\n var offsetY = indexY * itemHeight;\n\n var itemTop = offsetY - itemRect.marginTop;\n var itemRight = offsetX + itemWidth;\n var itemBottom = offsetY + itemHeight + itemRect.marginBottom;\n\n if (positionInView.top < itemBottom && positionInView.top > itemTop) {\n if (positionInView.left < itemRight) {\n return _index;\n } else if (_index !== l - 1) {\n last = _index;\n } else {\n last = null;\n }\n }\n }\n\n if (last !== null) {\n return last;\n }\n\n return l;\n };\n\n var dropAreaDimensions = {\n height: 0,\n width: 0,\n get getHeight() {\n return this.height;\n },\n set setHeight(val) {\n if (this.height === 0 || val === 0) this.height = val;\n },\n get getWidth() {\n return this.width;\n },\n set setWidth(val) {\n if (this.width === 0 || val === 0) this.width = val;\n },\n setDimensions: function setDimensions(height, width) {\n if (this.height === 0 || height === 0) this.height = height;\n if (this.width === 0 || width === 0) this.width = width;\n },\n };\n\n var create$8 = function create(_ref) {\n var root = _ref.root;\n // need to set role to list as otherwise it won't be read as a list by VoiceOver\n attr(root.element, 'role', 'list');\n\n root.ref.lastItemSpanwDate = Date.now();\n };\n\n /**\n * Inserts a new item\n * @param root\n * @param action\n */\n var addItemView = function addItemView(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n var id = action.id,\n index = action.index,\n interactionMethod = action.interactionMethod;\n\n root.ref.addIndex = index;\n\n var now = Date.now();\n var spawnDate = now;\n var opacity = 1;\n\n if (interactionMethod !== InteractionMethod.NONE) {\n opacity = 0;\n var cooldown = root.query('GET_ITEM_INSERT_INTERVAL');\n var dist = now - root.ref.lastItemSpanwDate;\n spawnDate = dist < cooldown ? now + (cooldown - dist) : now;\n }\n\n root.ref.lastItemSpanwDate = spawnDate;\n\n root.appendChildView(\n root.createChildView(\n // view type\n item,\n\n // props\n {\n spawnDate: spawnDate,\n id: id,\n opacity: opacity,\n interactionMethod: interactionMethod,\n }\n ),\n\n index\n );\n };\n\n var moveItem = function moveItem(item, x, y) {\n var vx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var vy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;\n // set to null to remove animation while dragging\n if (item.dragOffset) {\n item.translateX = null;\n item.translateY = null;\n item.translateX = item.dragOrigin.x + item.dragOffset.x;\n item.translateY = item.dragOrigin.y + item.dragOffset.y;\n item.scaleX = 1.025;\n item.scaleY = 1.025;\n } else {\n item.translateX = x;\n item.translateY = y;\n\n if (Date.now() > item.spawnDate) {\n // reveal element\n if (item.opacity === 0) {\n introItemView(item, x, y, vx, vy);\n }\n\n // make sure is default scale every frame\n item.scaleX = 1;\n item.scaleY = 1;\n item.opacity = 1;\n }\n }\n };\n\n var introItemView = function introItemView(item, x, y, vx, vy) {\n if (item.interactionMethod === InteractionMethod.NONE) {\n item.translateX = null;\n item.translateX = x;\n item.translateY = null;\n item.translateY = y;\n } else if (item.interactionMethod === InteractionMethod.DROP) {\n item.translateX = null;\n item.translateX = x - vx * 20;\n\n item.translateY = null;\n item.translateY = y - vy * 10;\n\n item.scaleX = 0.8;\n item.scaleY = 0.8;\n } else if (item.interactionMethod === InteractionMethod.BROWSE) {\n item.translateY = null;\n item.translateY = y - 30;\n } else if (item.interactionMethod === InteractionMethod.API) {\n item.translateX = null;\n item.translateX = x - 30;\n item.translateY = null;\n }\n };\n\n /**\n * Removes an existing item\n * @param root\n * @param action\n */\n var removeItemView = function removeItemView(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var id = action.id;\n\n // get the view matching the given id\n var view = root.childViews.find(function(child) {\n return child.id === id;\n });\n\n // if no view found, exit\n if (!view) {\n return;\n }\n\n // animate view out of view\n view.scaleX = 0.9;\n view.scaleY = 0.9;\n view.opacity = 0;\n\n // mark for removal\n view.markedForRemoval = true;\n };\n\n var getItemHeight = function getItemHeight(child) {\n return (\n child.rect.element.height +\n child.rect.element.marginBottom * 0.5 +\n child.rect.element.marginTop * 0.5\n );\n };\n var getItemWidth = function getItemWidth(child) {\n return (\n child.rect.element.width +\n child.rect.element.marginLeft * 0.5 +\n child.rect.element.marginRight * 0.5\n );\n };\n\n var dragItem = function dragItem(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n var id = action.id,\n dragState = action.dragState;\n\n // reference to item\n var item = root.query('GET_ITEM', { id: id });\n\n // get the view matching the given id\n var view = root.childViews.find(function(child) {\n return child.id === id;\n });\n\n var numItems = root.childViews.length;\n var oldIndex = dragState.getItemIndex(item);\n\n // if no view found, exit\n if (!view) return;\n\n var dragPosition = {\n x: view.dragOrigin.x + view.dragOffset.x + view.dragCenter.x,\n y: view.dragOrigin.y + view.dragOffset.y + view.dragCenter.y,\n };\n\n // get drag area dimensions\n var dragHeight = getItemHeight(view);\n var dragWidth = getItemWidth(view);\n\n // get rows and columns (There will always be at least one row and one column if a file is present)\n var cols = Math.floor(root.rect.outer.width / dragWidth);\n if (cols > numItems) cols = numItems;\n\n // rows are used to find when we have left the preview area bounding box\n var rows = Math.floor(numItems / cols + 1);\n\n dropAreaDimensions.setHeight = dragHeight * rows;\n dropAreaDimensions.setWidth = dragWidth * cols;\n\n // get new index of dragged item\n var location = {\n y: Math.floor(dragPosition.y / dragHeight),\n x: Math.floor(dragPosition.x / dragWidth),\n getGridIndex: function getGridIndex() {\n if (\n dragPosition.y > dropAreaDimensions.getHeight ||\n dragPosition.y < 0 ||\n dragPosition.x > dropAreaDimensions.getWidth ||\n dragPosition.x < 0\n )\n return oldIndex;\n return this.y * cols + this.x;\n },\n getColIndex: function getColIndex() {\n var items = root.query('GET_ACTIVE_ITEMS');\n var visibleChildren = root.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = items.map(function(item) {\n return visibleChildren.find(function(childView) {\n return childView.id === item.id;\n });\n });\n\n var currentIndex = children.findIndex(function(child) {\n return child === view;\n });\n var dragHeight = getItemHeight(view);\n var l = children.length;\n var idx = l;\n var childHeight = 0;\n var childBottom = 0;\n var childTop = 0;\n for (var i = 0; i < l; i++) {\n childHeight = getItemHeight(children[i]);\n childTop = childBottom;\n childBottom = childTop + childHeight;\n if (dragPosition.y < childBottom) {\n if (currentIndex > i) {\n if (dragPosition.y < childTop + dragHeight) {\n idx = i;\n break;\n }\n continue;\n }\n idx = i;\n break;\n }\n }\n return idx;\n },\n };\n\n // get new index\n var index = cols > 1 ? location.getGridIndex() : location.getColIndex();\n root.dispatch('MOVE_ITEM', { query: view, index: index });\n\n // if the index of the item changed, dispatch reorder action\n var currentIndex = dragState.getIndex();\n\n if (currentIndex === undefined || currentIndex !== index) {\n dragState.setIndex(index);\n\n if (currentIndex === undefined) return;\n\n root.dispatch('DID_REORDER_ITEMS', {\n items: root.query('GET_ACTIVE_ITEMS'),\n origin: oldIndex,\n target: index,\n });\n }\n };\n\n /**\n * Setup action routes\n */\n var route$2 = createRoute({\n DID_ADD_ITEM: addItemView,\n DID_REMOVE_ITEM: removeItemView,\n DID_DRAG_ITEM: dragItem,\n });\n\n /**\n * Write to view\n * @param root\n * @param actions\n * @param props\n */\n var write$5 = function write(_ref5) {\n var root = _ref5.root,\n props = _ref5.props,\n actions = _ref5.actions,\n shouldOptimize = _ref5.shouldOptimize;\n // route actions\n route$2({ root: root, props: props, actions: actions });\n var dragCoordinates = props.dragCoordinates;\n\n // available space on horizontal axis\n var horizontalSpace = root.rect.element.width;\n\n // only draw children that have dimensions\n var visibleChildren = root.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n\n // sort based on current active items\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n // get index\n var dragIndex = dragCoordinates\n ? getItemIndexByPosition(root, children, dragCoordinates)\n : null;\n\n // add index is used to reserve the dropped/added item index till the actual item is rendered\n var addIndex = root.ref.addIndex || null;\n\n // add index no longer needed till possibly next draw\n root.ref.addIndex = null;\n\n var dragIndexOffset = 0;\n var removeIndexOffset = 0;\n var addIndexOffset = 0;\n\n if (children.length === 0) return;\n\n var childRect = children[0].rect.element;\n var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;\n var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;\n var itemWidth = childRect.width + itemHorizontalMargin;\n var itemHeight = childRect.height + itemVerticalMargin;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n var offsetY = 0;\n var dragOffset = 0;\n\n children.forEach(function(child, index) {\n if (dragIndex) {\n var dist = index - dragIndex;\n if (dist === -2) {\n dragOffset = -itemVerticalMargin * 0.25;\n } else if (dist === -1) {\n dragOffset = -itemVerticalMargin * 0.75;\n } else if (dist === 0) {\n dragOffset = itemVerticalMargin * 0.75;\n } else if (dist === 1) {\n dragOffset = itemVerticalMargin * 0.25;\n } else {\n dragOffset = 0;\n }\n }\n\n if (shouldOptimize) {\n child.translateX = null;\n child.translateY = null;\n }\n\n if (!child.markedForRemoval) {\n moveItem(child, 0, offsetY + dragOffset);\n }\n\n var itemHeight = child.rect.element.height + itemVerticalMargin;\n\n var visualHeight = itemHeight * (child.markedForRemoval ? child.opacity : 1);\n\n offsetY += visualHeight;\n });\n }\n // grid\n else {\n var prevX = 0;\n var prevY = 0;\n\n children.forEach(function(child, index) {\n if (index === dragIndex) {\n dragIndexOffset = 1;\n }\n\n if (index === addIndex) {\n addIndexOffset += 1;\n }\n\n if (child.markedForRemoval && child.opacity < 0.5) {\n removeIndexOffset -= 1;\n }\n\n var visualIndex = index + addIndexOffset + dragIndexOffset + removeIndexOffset;\n\n var indexX = visualIndex % itemsPerRow;\n var indexY = Math.floor(visualIndex / itemsPerRow);\n\n var offsetX = indexX * itemWidth;\n var offsetY = indexY * itemHeight;\n\n var vectorX = Math.sign(offsetX - prevX);\n var vectorY = Math.sign(offsetY - prevY);\n\n prevX = offsetX;\n prevY = offsetY;\n\n if (child.markedForRemoval) return;\n\n if (shouldOptimize) {\n child.translateX = null;\n child.translateY = null;\n }\n\n moveItem(child, offsetX, offsetY, vectorX, vectorY);\n });\n }\n };\n\n /**\n * Filters actions that are meant specifically for a certain child of the list\n * @param child\n * @param actions\n */\n var filterSetItemActions = function filterSetItemActions(child, actions) {\n return actions.filter(function(action) {\n // if action has an id, filter out actions that don't have this child id\n if (action.data && action.data.id) {\n return child.id === action.data.id;\n }\n\n // allow all other actions\n return true;\n });\n };\n\n var list = createView({\n create: create$8,\n write: write$5,\n tag: 'ul',\n name: 'list',\n didWriteView: function didWriteView(_ref6) {\n var root = _ref6.root;\n root.childViews\n .filter(function(view) {\n return view.markedForRemoval && view.opacity === 0 && view.resting;\n })\n .forEach(function(view) {\n view._destroy();\n root.removeChildView(view);\n });\n },\n filterFrameActionsForChild: filterSetItemActions,\n mixins: {\n apis: ['dragCoordinates'],\n },\n });\n\n var create$9 = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.ref.list = root.appendChildView(root.createChildView(list));\n props.dragCoordinates = null;\n props.overflowing = false;\n };\n\n var storeDragCoordinates = function storeDragCoordinates(_ref2) {\n var root = _ref2.root,\n props = _ref2.props,\n action = _ref2.action;\n if (!root.query('GET_ITEM_INSERT_LOCATION_FREEDOM')) return;\n props.dragCoordinates = {\n left: action.position.scopeLeft - root.ref.list.rect.element.left,\n top:\n action.position.scopeTop -\n (root.rect.outer.top + root.rect.element.marginTop + root.rect.element.scrollTop),\n };\n };\n\n var clearDragCoordinates = function clearDragCoordinates(_ref3) {\n var props = _ref3.props;\n props.dragCoordinates = null;\n };\n\n var route$3 = createRoute({\n DID_DRAG: storeDragCoordinates,\n DID_END_DRAG: clearDragCoordinates,\n });\n\n var write$6 = function write(_ref4) {\n var root = _ref4.root,\n props = _ref4.props,\n actions = _ref4.actions;\n\n // route actions\n route$3({ root: root, props: props, actions: actions });\n\n // current drag position\n root.ref.list.dragCoordinates = props.dragCoordinates;\n\n // if currently overflowing but no longer received overflow\n if (props.overflowing && !props.overflow) {\n props.overflowing = false;\n\n // reset overflow state\n root.element.dataset.state = '';\n root.height = null;\n }\n\n // if is not overflowing currently but does receive overflow value\n if (props.overflow) {\n var newHeight = Math.round(props.overflow);\n if (newHeight !== root.height) {\n props.overflowing = true;\n root.element.dataset.state = 'overflow';\n root.height = newHeight;\n }\n }\n };\n\n var listScroller = createView({\n create: create$9,\n write: write$6,\n name: 'list-scroller',\n mixins: {\n apis: ['overflow', 'dragCoordinates'],\n styles: ['height', 'translateY'],\n animations: {\n translateY: 'spring',\n },\n },\n });\n\n var attrToggle = function attrToggle(element, name, state) {\n var enabledValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';\n if (state) {\n attr(element, name, enabledValue);\n } else {\n element.removeAttribute(name);\n }\n };\n\n var resetFileInput = function resetFileInput(input) {\n // no value, no need to reset\n if (!input || input.value === '') {\n return;\n }\n\n try {\n // for modern browsers\n input.value = '';\n } catch (err) {}\n\n // for IE10\n if (input.value) {\n // quickly append input to temp form and reset form\n var form = createElement$1('form');\n var parentNode = input.parentNode;\n var ref = input.nextSibling;\n form.appendChild(input);\n form.reset();\n\n // re-inject input where it originally was\n if (ref) {\n parentNode.insertBefore(input, ref);\n } else {\n parentNode.appendChild(input);\n }\n }\n };\n\n var create$a = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // set id so can be referenced from outside labels\n root.element.id = 'filepond--browser-' + props.id;\n\n // set name of element (is removed when a value is set)\n attr(root.element, 'name', root.query('GET_NAME'));\n\n // we have to link this element to the status element\n attr(root.element, 'aria-controls', 'filepond--assistant-' + props.id);\n\n // set label, we use labelled by as otherwise the screenreader does not read the \"browse\" text in the label (as it has tabindex: 0)\n attr(root.element, 'aria-labelledby', 'filepond--drop-label-' + props.id);\n\n // set configurable props\n setAcceptedFileTypes({\n root: root,\n action: { value: root.query('GET_ACCEPTED_FILE_TYPES') },\n });\n toggleAllowMultiple({ root: root, action: { value: root.query('GET_ALLOW_MULTIPLE') } });\n toggleDirectoryFilter({\n root: root,\n action: { value: root.query('GET_ALLOW_DIRECTORIES_ONLY') },\n });\n toggleDisabled({ root: root });\n toggleRequired({ root: root, action: { value: root.query('GET_REQUIRED') } });\n setCaptureMethod({ root: root, action: { value: root.query('GET_CAPTURE_METHOD') } });\n\n // handle changes to the input field\n root.ref.handleChange = function(e) {\n if (!root.element.value) {\n return;\n }\n\n // extract files and move value of webkitRelativePath path to _relativePath\n var files = Array.from(root.element.files).map(function(file) {\n file._relativePath = file.webkitRelativePath;\n return file;\n });\n\n // we add a little delay so the OS file select window can move out of the way before we add our file\n setTimeout(function() {\n // load files\n props.onload(files);\n\n // reset input, it's just for exposing a method to drop files, should not retain any state\n resetFileInput(root.element);\n }, 250);\n };\n\n root.element.addEventListener('change', root.ref.handleChange);\n };\n\n var setAcceptedFileTypes = function setAcceptedFileTypes(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!root.query('GET_ALLOW_SYNC_ACCEPT_ATTRIBUTE')) return;\n attrToggle(\n root.element,\n 'accept',\n !!action.value,\n action.value ? action.value.join(',') : ''\n );\n };\n\n var toggleAllowMultiple = function toggleAllowMultiple(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n attrToggle(root.element, 'multiple', action.value);\n };\n\n var toggleDirectoryFilter = function toggleDirectoryFilter(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n attrToggle(root.element, 'webkitdirectory', action.value);\n };\n\n var toggleDisabled = function toggleDisabled(_ref5) {\n var root = _ref5.root;\n var isDisabled = root.query('GET_DISABLED');\n var doesAllowBrowse = root.query('GET_ALLOW_BROWSE');\n var disableField = isDisabled || !doesAllowBrowse;\n attrToggle(root.element, 'disabled', disableField);\n };\n\n var toggleRequired = function toggleRequired(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n // want to remove required, always possible\n if (!action.value) {\n attrToggle(root.element, 'required', false);\n }\n // if want to make required, only possible when zero items\n else if (root.query('GET_TOTAL_ITEMS') === 0) {\n attrToggle(root.element, 'required', true);\n }\n };\n\n var setCaptureMethod = function setCaptureMethod(_ref7) {\n var root = _ref7.root,\n action = _ref7.action;\n attrToggle(\n root.element,\n 'capture',\n !!action.value,\n action.value === true ? '' : action.value\n );\n };\n\n var updateRequiredStatus = function updateRequiredStatus(_ref8) {\n var root = _ref8.root;\n var element = root.element;\n // always remove the required attribute when more than zero items\n if (root.query('GET_TOTAL_ITEMS') > 0) {\n attrToggle(element, 'required', false);\n attrToggle(element, 'name', false);\n } else {\n // add name attribute\n attrToggle(element, 'name', true, root.query('GET_NAME'));\n\n // remove any validation messages\n var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');\n if (shouldCheckValidity) {\n element.setCustomValidity('');\n }\n\n // we only add required if the field has been deemed required\n if (root.query('GET_REQUIRED')) {\n attrToggle(element, 'required', true);\n }\n }\n };\n\n var updateFieldValidityStatus = function updateFieldValidityStatus(_ref9) {\n var root = _ref9.root;\n var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');\n if (!shouldCheckValidity) return;\n root.element.setCustomValidity(root.query('GET_LABEL_INVALID_FIELD'));\n };\n\n var browser = createView({\n tag: 'input',\n name: 'browser',\n ignoreRect: true,\n ignoreRectUpdate: true,\n attributes: {\n type: 'file',\n },\n\n create: create$a,\n destroy: function destroy(_ref10) {\n var root = _ref10.root;\n root.element.removeEventListener('change', root.ref.handleChange);\n },\n write: createRoute({\n DID_LOAD_ITEM: updateRequiredStatus,\n DID_REMOVE_ITEM: updateRequiredStatus,\n DID_THROW_ITEM_INVALID: updateFieldValidityStatus,\n\n DID_SET_DISABLED: toggleDisabled,\n DID_SET_ALLOW_BROWSE: toggleDisabled,\n DID_SET_ALLOW_DIRECTORIES_ONLY: toggleDirectoryFilter,\n DID_SET_ALLOW_MULTIPLE: toggleAllowMultiple,\n DID_SET_ACCEPTED_FILE_TYPES: setAcceptedFileTypes,\n DID_SET_CAPTURE_METHOD: setCaptureMethod,\n DID_SET_REQUIRED: toggleRequired,\n }),\n });\n\n var Key = {\n ENTER: 13,\n SPACE: 32,\n };\n\n var create$b = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n\n // create the label and link it to the file browser\n var label = createElement$1('label');\n attr(label, 'for', 'filepond--browser-' + props.id);\n\n // use for labeling file input (aria-labelledby on file input)\n attr(label, 'id', 'filepond--drop-label-' + props.id);\n\n // hide the label for screenreaders, the input element will read the contents of the label when it's focussed. If we don't set aria-hidden the screenreader will also navigate the contents of the label separately from the input.\n attr(label, 'aria-hidden', 'true');\n\n // handle keys\n root.ref.handleKeyDown = function(e) {\n var isActivationKey = e.keyCode === Key.ENTER || e.keyCode === Key.SPACE;\n if (!isActivationKey) return;\n // stops from triggering the element a second time\n e.preventDefault();\n\n // click link (will then in turn activate file input)\n root.ref.label.click();\n };\n\n root.ref.handleClick = function(e) {\n var isLabelClick = e.target === label || label.contains(e.target);\n\n // don't want to click twice\n if (isLabelClick) return;\n\n // click link (will then in turn activate file input)\n root.ref.label.click();\n };\n\n // attach events\n label.addEventListener('keydown', root.ref.handleKeyDown);\n root.element.addEventListener('click', root.ref.handleClick);\n\n // update\n updateLabelValue(label, props.caption);\n\n // add!\n root.appendChild(label);\n root.ref.label = label;\n };\n\n var updateLabelValue = function updateLabelValue(label, value) {\n label.innerHTML = value;\n var clickable = label.querySelector('.filepond--label-action');\n if (clickable) {\n attr(clickable, 'tabindex', '0');\n }\n return value;\n };\n\n var dropLabel = createView({\n name: 'drop-label',\n ignoreRect: true,\n create: create$b,\n destroy: function destroy(_ref2) {\n var root = _ref2.root;\n root.ref.label.addEventListener('keydown', root.ref.handleKeyDown);\n root.element.removeEventListener('click', root.ref.handleClick);\n },\n write: createRoute({\n DID_SET_LABEL_IDLE: function DID_SET_LABEL_IDLE(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n updateLabelValue(root.ref.label, action.value);\n },\n }),\n\n mixins: {\n styles: ['opacity', 'translateX', 'translateY'],\n animations: {\n opacity: { type: 'tween', duration: 150 },\n translateX: 'spring',\n translateY: 'spring',\n },\n },\n });\n\n var blob = createView({\n name: 'drip-blob',\n ignoreRect: true,\n mixins: {\n styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],\n animations: {\n scaleX: 'spring',\n scaleY: 'spring',\n translateX: 'spring',\n translateY: 'spring',\n opacity: { type: 'tween', duration: 250 },\n },\n },\n });\n\n var addBlob = function addBlob(_ref) {\n var root = _ref.root;\n var centerX = root.rect.element.width * 0.5;\n var centerY = root.rect.element.height * 0.5;\n\n root.ref.blob = root.appendChildView(\n root.createChildView(blob, {\n opacity: 0,\n scaleX: 2.5,\n scaleY: 2.5,\n translateX: centerX,\n translateY: centerY,\n })\n );\n };\n\n var moveBlob = function moveBlob(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!root.ref.blob) {\n addBlob({ root: root });\n return;\n }\n\n root.ref.blob.translateX = action.position.scopeLeft;\n root.ref.blob.translateY = action.position.scopeTop;\n root.ref.blob.scaleX = 1;\n root.ref.blob.scaleY = 1;\n root.ref.blob.opacity = 1;\n };\n\n var hideBlob = function hideBlob(_ref3) {\n var root = _ref3.root;\n if (!root.ref.blob) {\n return;\n }\n root.ref.blob.opacity = 0;\n };\n\n var explodeBlob = function explodeBlob(_ref4) {\n var root = _ref4.root;\n if (!root.ref.blob) {\n return;\n }\n root.ref.blob.scaleX = 2.5;\n root.ref.blob.scaleY = 2.5;\n root.ref.blob.opacity = 0;\n };\n\n var write$7 = function write(_ref5) {\n var root = _ref5.root,\n props = _ref5.props,\n actions = _ref5.actions;\n route$4({ root: root, props: props, actions: actions });\n var blob = root.ref.blob;\n\n if (actions.length === 0 && blob && blob.opacity === 0) {\n root.removeChildView(blob);\n root.ref.blob = null;\n }\n };\n\n var route$4 = createRoute({\n DID_DRAG: moveBlob,\n DID_DROP: explodeBlob,\n DID_END_DRAG: hideBlob,\n });\n\n var drip = createView({\n ignoreRect: true,\n ignoreRectUpdate: true,\n name: 'drip',\n write: write$7,\n });\n\n var setInputFiles = function setInputFiles(element, files) {\n try {\n // Create a DataTransfer instance and add a newly created file\n var dataTransfer = new DataTransfer();\n files.forEach(function(file) {\n if (file instanceof File) {\n dataTransfer.items.add(file);\n } else {\n dataTransfer.items.add(\n new File([file], file.name, {\n type: file.type,\n })\n );\n }\n });\n\n // Assign the DataTransfer files list to the file input\n element.files = dataTransfer.files;\n } catch (err) {\n return false;\n }\n return true;\n };\n\n var create$c = function create(_ref) {\n var root = _ref.root;\n return (root.ref.fields = {});\n };\n\n var getField = function getField(root, id) {\n return root.ref.fields[id];\n };\n\n var syncFieldPositionsWithItems = function syncFieldPositionsWithItems(root) {\n root.query('GET_ACTIVE_ITEMS').forEach(function(item) {\n if (!root.ref.fields[item.id]) return;\n root.element.appendChild(root.ref.fields[item.id]);\n });\n };\n\n var didReorderItems = function didReorderItems(_ref2) {\n var root = _ref2.root;\n return syncFieldPositionsWithItems(root);\n };\n\n var didAddItem = function didAddItem(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n var fileItem = root.query('GET_ITEM', action.id);\n var isLocalFile = fileItem.origin === FileOrigin.LOCAL;\n var shouldUseFileInput = !isLocalFile && root.query('SHOULD_UPDATE_FILE_INPUT');\n var dataContainer = createElement$1('input');\n dataContainer.type = shouldUseFileInput ? 'file' : 'hidden';\n dataContainer.name = root.query('GET_NAME');\n dataContainer.disabled = root.query('GET_DISABLED');\n root.ref.fields[action.id] = dataContainer;\n syncFieldPositionsWithItems(root);\n };\n\n var didLoadItem$1 = function didLoadItem(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n var field = getField(root, action.id);\n if (!field) return;\n\n // store server ref in hidden input\n if (action.serverFileReference !== null) field.value = action.serverFileReference;\n\n // store file item in file input\n if (!root.query('SHOULD_UPDATE_FILE_INPUT')) return;\n\n var fileItem = root.query('GET_ITEM', action.id);\n setInputFiles(field, [fileItem.file]);\n };\n\n var didPrepareOutput = function didPrepareOutput(_ref5) {\n var root = _ref5.root,\n action = _ref5.action;\n // this timeout pushes the handler after 'load'\n if (!root.query('SHOULD_UPDATE_FILE_INPUT')) return;\n setTimeout(function() {\n var field = getField(root, action.id);\n if (!field) return;\n setInputFiles(field, [action.file]);\n }, 0);\n };\n\n var didSetDisabled = function didSetDisabled(_ref6) {\n var root = _ref6.root;\n root.element.disabled = root.query('GET_DISABLED');\n };\n\n var didRemoveItem = function didRemoveItem(_ref7) {\n var root = _ref7.root,\n action = _ref7.action;\n var field = getField(root, action.id);\n if (!field) return;\n if (field.parentNode) field.parentNode.removeChild(field);\n delete root.ref.fields[action.id];\n };\n\n // only runs for server files (so doesn't deal with file input)\n var didDefineValue = function didDefineValue(_ref8) {\n var root = _ref8.root,\n action = _ref8.action;\n var field = getField(root, action.id);\n if (!field) return;\n if (action.value === null) {\n // clear field value\n field.removeAttribute('value');\n } else {\n // set field value\n field.value = action.value;\n }\n syncFieldPositionsWithItems(root);\n };\n\n var write$8 = createRoute({\n DID_SET_DISABLED: didSetDisabled,\n DID_ADD_ITEM: didAddItem,\n DID_LOAD_ITEM: didLoadItem$1,\n DID_REMOVE_ITEM: didRemoveItem,\n DID_DEFINE_VALUE: didDefineValue,\n DID_PREPARE_OUTPUT: didPrepareOutput,\n DID_REORDER_ITEMS: didReorderItems,\n DID_SORT_ITEMS: didReorderItems,\n });\n\n var data = createView({\n tag: 'fieldset',\n name: 'data',\n create: create$c,\n write: write$8,\n ignoreRect: true,\n });\n\n var getRootNode = function getRootNode(element) {\n return 'getRootNode' in element ? element.getRootNode() : document;\n };\n\n var images = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff'];\n var text$1 = ['css', 'csv', 'html', 'txt'];\n var map = {\n zip: 'zip|compressed',\n epub: 'application/epub+zip',\n };\n\n var guesstimateMimeType = function guesstimateMimeType() {\n var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';\n extension = extension.toLowerCase();\n if (images.includes(extension)) {\n return (\n 'image/' +\n (extension === 'jpg' ? 'jpeg' : extension === 'svg' ? 'svg+xml' : extension)\n );\n }\n if (text$1.includes(extension)) {\n return 'text/' + extension;\n }\n\n return map[extension] || '';\n };\n\n var requestDataTransferItems = function requestDataTransferItems(dataTransfer) {\n return new Promise(function(resolve, reject) {\n // try to get links from transfer, if found we'll exit immediately (unless a file is in the dataTransfer as well, this is because Firefox could represent the file as a URL and a file object at the same time)\n var links = getLinks(dataTransfer);\n if (links.length && !hasFiles(dataTransfer)) {\n return resolve(links);\n }\n // try to get files from the transfer\n getFiles(dataTransfer).then(resolve);\n });\n };\n\n /**\n * Test if datatransfer has files\n */\n var hasFiles = function hasFiles(dataTransfer) {\n if (dataTransfer.files) return dataTransfer.files.length > 0;\n return false;\n };\n\n /**\n * Extracts files from a DataTransfer object\n */\n var getFiles = function getFiles(dataTransfer) {\n return new Promise(function(resolve, reject) {\n // get the transfer items as promises\n var promisedFiles = (dataTransfer.items ? Array.from(dataTransfer.items) : [])\n // only keep file system items (files and directories)\n .filter(function(item) {\n return isFileSystemItem(item);\n })\n\n // map each item to promise\n .map(function(item) {\n return getFilesFromItem(item);\n });\n\n // if is empty, see if we can extract some info from the files property as a fallback\n if (!promisedFiles.length) {\n // TODO: test for directories (should not be allowed)\n // Use FileReader, problem is that the files property gets lost in the process\n resolve(dataTransfer.files ? Array.from(dataTransfer.files) : []);\n return;\n }\n\n // done!\n Promise.all(promisedFiles)\n .then(function(returnedFileGroups) {\n // flatten groups\n var files = [];\n returnedFileGroups.forEach(function(group) {\n files.push.apply(files, group);\n });\n\n // done (filter out empty files)!\n resolve(\n files\n .filter(function(file) {\n return file;\n })\n .map(function(file) {\n if (!file._relativePath)\n file._relativePath = file.webkitRelativePath;\n return file;\n })\n );\n })\n .catch(console.error);\n });\n };\n\n var isFileSystemItem = function isFileSystemItem(item) {\n if (isEntry(item)) {\n var entry = getAsEntry(item);\n if (entry) {\n return entry.isFile || entry.isDirectory;\n }\n }\n return item.kind === 'file';\n };\n\n var getFilesFromItem = function getFilesFromItem(item) {\n return new Promise(function(resolve, reject) {\n if (isDirectoryEntry(item)) {\n getFilesInDirectory(getAsEntry(item))\n .then(resolve)\n .catch(reject);\n return;\n }\n\n resolve([item.getAsFile()]);\n });\n };\n\n var getFilesInDirectory = function getFilesInDirectory(entry) {\n return new Promise(function(resolve, reject) {\n var files = [];\n\n // the total entries to read\n var dirCounter = 0;\n var fileCounter = 0;\n\n var resolveIfDone = function resolveIfDone() {\n if (fileCounter === 0 && dirCounter === 0) {\n resolve(files);\n }\n };\n\n // the recursive function\n var readEntries = function readEntries(dirEntry) {\n dirCounter++;\n\n var directoryReader = dirEntry.createReader();\n\n // directories are returned in batches, we need to process all batches before we're done\n var readBatch = function readBatch() {\n directoryReader.readEntries(function(entries) {\n if (entries.length === 0) {\n dirCounter--;\n resolveIfDone();\n return;\n }\n\n entries.forEach(function(entry) {\n // recursively read more directories\n if (entry.isDirectory) {\n readEntries(entry);\n } else {\n // read as file\n fileCounter++;\n\n entry.file(function(file) {\n var correctedFile = correctMissingFileType(file);\n if (entry.fullPath)\n correctedFile._relativePath = entry.fullPath;\n files.push(correctedFile);\n fileCounter--;\n resolveIfDone();\n });\n }\n });\n\n // try to get next batch of files\n readBatch();\n }, reject);\n };\n\n // read first batch of files\n readBatch();\n };\n\n // go!\n readEntries(entry);\n });\n };\n\n var correctMissingFileType = function correctMissingFileType(file) {\n if (file.type.length) return file;\n var date = file.lastModifiedDate;\n var name = file.name;\n var type = guesstimateMimeType(getExtensionFromFilename(file.name));\n if (!type.length) return file;\n file = file.slice(0, file.size, type);\n file.name = name;\n file.lastModifiedDate = date;\n return file;\n };\n\n var isDirectoryEntry = function isDirectoryEntry(item) {\n return isEntry(item) && (getAsEntry(item) || {}).isDirectory;\n };\n\n var isEntry = function isEntry(item) {\n return 'webkitGetAsEntry' in item;\n };\n\n var getAsEntry = function getAsEntry(item) {\n return item.webkitGetAsEntry();\n };\n\n /**\n * Extracts links from a DataTransfer object\n */\n var getLinks = function getLinks(dataTransfer) {\n var links = [];\n try {\n // look in meta data property\n links = getLinksFromTransferMetaData(dataTransfer);\n if (links.length) {\n return links;\n }\n links = getLinksFromTransferURLData(dataTransfer);\n } catch (e) {\n // nope nope nope (probably IE trouble)\n }\n return links;\n };\n\n var getLinksFromTransferURLData = function getLinksFromTransferURLData(dataTransfer) {\n var data = dataTransfer.getData('url');\n if (typeof data === 'string' && data.length) {\n return [data];\n }\n return [];\n };\n\n var getLinksFromTransferMetaData = function getLinksFromTransferMetaData(dataTransfer) {\n var data = dataTransfer.getData('text/html');\n if (typeof data === 'string' && data.length) {\n var matches = data.match(/src\\s*=\\s*\"(.+?)\"/);\n if (matches) {\n return [matches[1]];\n }\n }\n return [];\n };\n\n var dragNDropObservers = [];\n\n var eventPosition = function eventPosition(e) {\n return {\n pageLeft: e.pageX,\n pageTop: e.pageY,\n scopeLeft: e.offsetX || e.layerX,\n scopeTop: e.offsetY || e.layerY,\n };\n };\n\n var createDragNDropClient = function createDragNDropClient(\n element,\n scopeToObserve,\n filterElement\n ) {\n var observer = getDragNDropObserver(scopeToObserve);\n\n var client = {\n element: element,\n filterElement: filterElement,\n state: null,\n ondrop: function ondrop() {},\n onenter: function onenter() {},\n ondrag: function ondrag() {},\n onexit: function onexit() {},\n onload: function onload() {},\n allowdrop: function allowdrop() {},\n };\n\n client.destroy = observer.addListener(client);\n\n return client;\n };\n\n var getDragNDropObserver = function getDragNDropObserver(element) {\n // see if already exists, if so, return\n var observer = dragNDropObservers.find(function(item) {\n return item.element === element;\n });\n if (observer) {\n return observer;\n }\n\n // create new observer, does not yet exist for this element\n var newObserver = createDragNDropObserver(element);\n dragNDropObservers.push(newObserver);\n return newObserver;\n };\n\n var createDragNDropObserver = function createDragNDropObserver(element) {\n var clients = [];\n\n var routes = {\n dragenter: dragenter,\n dragover: dragover,\n dragleave: dragleave,\n drop: drop,\n };\n\n var handlers = {};\n\n forin(routes, function(event, createHandler) {\n handlers[event] = createHandler(element, clients);\n element.addEventListener(event, handlers[event], false);\n });\n\n var observer = {\n element: element,\n addListener: function addListener(client) {\n // add as client\n clients.push(client);\n\n // return removeListener function\n return function() {\n // remove client\n clients.splice(clients.indexOf(client), 1);\n\n // if no more clients, clean up observer\n if (clients.length === 0) {\n dragNDropObservers.splice(dragNDropObservers.indexOf(observer), 1);\n\n forin(routes, function(event) {\n element.removeEventListener(event, handlers[event], false);\n });\n }\n };\n },\n };\n\n return observer;\n };\n\n var elementFromPoint = function elementFromPoint(root, point) {\n if (!('elementFromPoint' in root)) {\n root = document;\n }\n return root.elementFromPoint(point.x, point.y);\n };\n\n var isEventTarget = function isEventTarget(e, target) {\n // get root\n var root = getRootNode(target);\n\n // get element at position\n // if root is not actual shadow DOM and does not have elementFromPoint method, use the one on document\n var elementAtPosition = elementFromPoint(root, {\n x: e.pageX - window.pageXOffset,\n y: e.pageY - window.pageYOffset,\n });\n\n // test if target is the element or if one of its children is\n return elementAtPosition === target || target.contains(elementAtPosition);\n };\n\n var initialTarget = null;\n\n var setDropEffect = function setDropEffect(dataTransfer, effect) {\n // is in try catch as IE11 will throw error if not\n try {\n dataTransfer.dropEffect = effect;\n } catch (e) {}\n };\n\n var dragenter = function dragenter(root, clients) {\n return function(e) {\n e.preventDefault();\n\n initialTarget = e.target;\n\n clients.forEach(function(client) {\n var element = client.element,\n onenter = client.onenter;\n\n if (isEventTarget(e, element)) {\n client.state = 'enter';\n\n // fire enter event\n onenter(eventPosition(e));\n }\n });\n };\n };\n\n var dragover = function dragover(root, clients) {\n return function(e) {\n e.preventDefault();\n\n var dataTransfer = e.dataTransfer;\n\n requestDataTransferItems(dataTransfer).then(function(items) {\n var overDropTarget = false;\n\n clients.some(function(client) {\n var filterElement = client.filterElement,\n element = client.element,\n onenter = client.onenter,\n onexit = client.onexit,\n ondrag = client.ondrag,\n allowdrop = client.allowdrop;\n\n // by default we can drop\n setDropEffect(dataTransfer, 'copy');\n\n // allow transfer of these items\n var allowsTransfer = allowdrop(items);\n\n // only used when can be dropped on page\n if (!allowsTransfer) {\n setDropEffect(dataTransfer, 'none');\n return;\n }\n\n // targetting this client\n if (isEventTarget(e, element)) {\n overDropTarget = true;\n\n // had no previous state, means we are entering this client\n if (client.state === null) {\n client.state = 'enter';\n onenter(eventPosition(e));\n return;\n }\n\n // now over element (no matter if it allows the drop or not)\n client.state = 'over';\n\n // needs to allow transfer\n if (filterElement && !allowsTransfer) {\n setDropEffect(dataTransfer, 'none');\n return;\n }\n\n // dragging\n ondrag(eventPosition(e));\n } else {\n // should be over an element to drop\n if (filterElement && !overDropTarget) {\n setDropEffect(dataTransfer, 'none');\n }\n\n // might have just left this client?\n if (client.state) {\n client.state = null;\n onexit(eventPosition(e));\n }\n }\n });\n });\n };\n };\n\n var drop = function drop(root, clients) {\n return function(e) {\n e.preventDefault();\n\n var dataTransfer = e.dataTransfer;\n\n requestDataTransferItems(dataTransfer).then(function(items) {\n clients.forEach(function(client) {\n var filterElement = client.filterElement,\n element = client.element,\n ondrop = client.ondrop,\n onexit = client.onexit,\n allowdrop = client.allowdrop;\n\n client.state = null;\n\n // if we're filtering on element we need to be over the element to drop\n if (filterElement && !isEventTarget(e, element)) return;\n\n // no transfer for this client\n if (!allowdrop(items)) return onexit(eventPosition(e));\n\n // we can drop these items on this client\n ondrop(eventPosition(e), items);\n });\n });\n };\n };\n\n var dragleave = function dragleave(root, clients) {\n return function(e) {\n if (initialTarget !== e.target) {\n return;\n }\n\n clients.forEach(function(client) {\n var onexit = client.onexit;\n\n client.state = null;\n\n onexit(eventPosition(e));\n });\n };\n };\n\n var createHopper = function createHopper(scope, validateItems, options) {\n // is now hopper scope\n scope.classList.add('filepond--hopper');\n\n // shortcuts\n var catchesDropsOnPage = options.catchesDropsOnPage,\n requiresDropOnElement = options.requiresDropOnElement,\n _options$filterItems = options.filterItems,\n filterItems =\n _options$filterItems === void 0\n ? function(items) {\n return items;\n }\n : _options$filterItems;\n\n // create a dnd client\n var client = createDragNDropClient(\n scope,\n catchesDropsOnPage ? document.documentElement : scope,\n requiresDropOnElement\n );\n\n // current client state\n var lastState = '';\n var currentState = '';\n\n // determines if a file may be dropped\n client.allowdrop = function(items) {\n // TODO: if we can, throw error to indicate the items cannot by dropped\n\n return validateItems(filterItems(items));\n };\n\n client.ondrop = function(position, items) {\n var filteredItems = filterItems(items);\n\n if (!validateItems(filteredItems)) {\n api.ondragend(position);\n return;\n }\n\n currentState = 'drag-drop';\n\n api.onload(filteredItems, position);\n };\n\n client.ondrag = function(position) {\n api.ondrag(position);\n };\n\n client.onenter = function(position) {\n currentState = 'drag-over';\n\n api.ondragstart(position);\n };\n\n client.onexit = function(position) {\n currentState = 'drag-exit';\n\n api.ondragend(position);\n };\n\n var api = {\n updateHopperState: function updateHopperState() {\n if (lastState !== currentState) {\n scope.dataset.hopperState = currentState;\n lastState = currentState;\n }\n },\n onload: function onload() {},\n ondragstart: function ondragstart() {},\n ondrag: function ondrag() {},\n ondragend: function ondragend() {},\n destroy: function destroy() {\n // destroy client\n client.destroy();\n },\n };\n\n return api;\n };\n\n var listening = false;\n var listeners$1 = [];\n\n var handlePaste = function handlePaste(e) {\n // if is pasting in input or textarea and the target is outside of a filepond scope, ignore\n var activeEl = document.activeElement;\n if (activeEl && /textarea|input/i.test(activeEl.nodeName)) {\n // test textarea or input is contained in filepond root\n var inScope = false;\n var element = activeEl;\n while (element !== document.body) {\n if (element.classList.contains('filepond--root')) {\n inScope = true;\n break;\n }\n element = element.parentNode;\n }\n\n if (!inScope) return;\n }\n\n requestDataTransferItems(e.clipboardData).then(function(files) {\n // no files received\n if (!files.length) {\n return;\n }\n\n // notify listeners of received files\n listeners$1.forEach(function(listener) {\n return listener(files);\n });\n });\n };\n\n var listen = function listen(cb) {\n // can't add twice\n if (listeners$1.includes(cb)) {\n return;\n }\n\n // add initial listener\n listeners$1.push(cb);\n\n // setup paste listener for entire page\n if (listening) {\n return;\n }\n\n listening = true;\n document.addEventListener('paste', handlePaste);\n };\n\n var unlisten = function unlisten(listener) {\n arrayRemove(listeners$1, listeners$1.indexOf(listener));\n\n // clean up\n if (listeners$1.length === 0) {\n document.removeEventListener('paste', handlePaste);\n listening = false;\n }\n };\n\n var createPaster = function createPaster() {\n var cb = function cb(files) {\n api.onload(files);\n };\n\n var api = {\n destroy: function destroy() {\n unlisten(cb);\n },\n onload: function onload() {},\n };\n\n listen(cb);\n\n return api;\n };\n\n /**\n * Creates the file view\n */\n var create$d = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n root.element.id = 'filepond--assistant-' + props.id;\n attr(root.element, 'role', 'status');\n attr(root.element, 'aria-live', 'polite');\n attr(root.element, 'aria-relevant', 'additions');\n };\n\n var addFilesNotificationTimeout = null;\n var notificationClearTimeout = null;\n\n var filenames = [];\n\n var assist = function assist(root, message) {\n root.element.textContent = message;\n };\n\n var clear$1 = function clear(root) {\n root.element.textContent = '';\n };\n\n var listModified = function listModified(root, filename, label) {\n var total = root.query('GET_TOTAL_ITEMS');\n assist(\n root,\n label +\n ' ' +\n filename +\n ', ' +\n total +\n ' ' +\n (total === 1\n ? root.query('GET_LABEL_FILE_COUNT_SINGULAR')\n : root.query('GET_LABEL_FILE_COUNT_PLURAL'))\n );\n\n // clear group after set amount of time so the status is not read twice\n clearTimeout(notificationClearTimeout);\n notificationClearTimeout = setTimeout(function() {\n clear$1(root);\n }, 1500);\n };\n\n var isUsingFilePond = function isUsingFilePond(root) {\n return root.element.parentNode.contains(document.activeElement);\n };\n\n var itemAdded = function itemAdded(_ref2) {\n var root = _ref2.root,\n action = _ref2.action;\n if (!isUsingFilePond(root)) {\n return;\n }\n\n root.element.textContent = '';\n var item = root.query('GET_ITEM', action.id);\n filenames.push(item.filename);\n\n clearTimeout(addFilesNotificationTimeout);\n addFilesNotificationTimeout = setTimeout(function() {\n listModified(root, filenames.join(', '), root.query('GET_LABEL_FILE_ADDED'));\n\n filenames.length = 0;\n }, 750);\n };\n\n var itemRemoved = function itemRemoved(_ref3) {\n var root = _ref3.root,\n action = _ref3.action;\n if (!isUsingFilePond(root)) {\n return;\n }\n\n var item = action.item;\n listModified(root, item.filename, root.query('GET_LABEL_FILE_REMOVED'));\n };\n\n var itemProcessed = function itemProcessed(_ref4) {\n var root = _ref4.root,\n action = _ref4.action;\n // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file\n\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n var label = root.query('GET_LABEL_FILE_PROCESSING_COMPLETE');\n\n assist(root, filename + ' ' + label);\n };\n\n var itemProcessedUndo = function itemProcessedUndo(_ref5) {\n var root = _ref5.root,\n action = _ref5.action;\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n var label = root.query('GET_LABEL_FILE_PROCESSING_ABORTED');\n\n assist(root, filename + ' ' + label);\n };\n\n var itemError = function itemError(_ref6) {\n var root = _ref6.root,\n action = _ref6.action;\n var item = root.query('GET_ITEM', action.id);\n var filename = item.filename;\n\n // will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file\n\n assist(root, action.status.main + ' ' + filename + ' ' + action.status.sub);\n };\n\n var assistant = createView({\n create: create$d,\n ignoreRect: true,\n ignoreRectUpdate: true,\n write: createRoute({\n DID_LOAD_ITEM: itemAdded,\n DID_REMOVE_ITEM: itemRemoved,\n DID_COMPLETE_ITEM_PROCESSING: itemProcessed,\n\n DID_ABORT_ITEM_PROCESSING: itemProcessedUndo,\n DID_REVERT_ITEM_PROCESSING: itemProcessedUndo,\n\n DID_THROW_ITEM_REMOVE_ERROR: itemError,\n DID_THROW_ITEM_LOAD_ERROR: itemError,\n DID_THROW_ITEM_INVALID: itemError,\n DID_THROW_ITEM_PROCESSING_ERROR: itemError,\n }),\n\n tag: 'span',\n name: 'assistant',\n });\n\n var toCamels = function toCamels(string) {\n var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';\n return string.replace(new RegExp(separator + '.', 'g'), function(sub) {\n return sub.charAt(1).toUpperCase();\n });\n };\n\n var debounce = function debounce(func) {\n var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;\n var immidiateOnly =\n arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var last = Date.now();\n var timeout = null;\n\n return function() {\n for (\n var _len = arguments.length, args = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n args[_key] = arguments[_key];\n }\n clearTimeout(timeout);\n\n var dist = Date.now() - last;\n\n var fn = function fn() {\n last = Date.now();\n func.apply(void 0, args);\n };\n\n if (dist < interval) {\n // we need to delay by the difference between interval and dist\n // for example: if distance is 10 ms and interval is 16 ms,\n // we need to wait an additional 6ms before calling the function)\n if (!immidiateOnly) {\n timeout = setTimeout(fn, interval - dist);\n }\n } else {\n // go!\n fn();\n }\n };\n };\n\n var MAX_FILES_LIMIT = 1000000;\n\n var prevent = function prevent(e) {\n return e.preventDefault();\n };\n\n var create$e = function create(_ref) {\n var root = _ref.root,\n props = _ref.props;\n // Add id\n var id = root.query('GET_ID');\n if (id) {\n root.element.id = id;\n }\n\n // Add className\n var className = root.query('GET_CLASS_NAME');\n if (className) {\n className\n .split(' ')\n .filter(function(name) {\n return name.length;\n })\n .forEach(function(name) {\n root.element.classList.add(name);\n });\n }\n\n // Field label\n root.ref.label = root.appendChildView(\n root.createChildView(\n dropLabel,\n Object.assign({}, props, {\n translateY: null,\n caption: root.query('GET_LABEL_IDLE'),\n })\n )\n );\n\n // List of items\n root.ref.list = root.appendChildView(\n root.createChildView(listScroller, { translateY: null })\n );\n\n // Background panel\n root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'panel-root' }));\n\n // Assistant notifies assistive tech when content changes\n root.ref.assistant = root.appendChildView(\n root.createChildView(assistant, Object.assign({}, props))\n );\n\n // Data\n root.ref.data = root.appendChildView(root.createChildView(data, Object.assign({}, props)));\n\n // Measure (tests if fixed height was set)\n // DOCTYPE needs to be set for this to work\n root.ref.measure = createElement$1('div');\n root.ref.measure.style.height = '100%';\n root.element.appendChild(root.ref.measure);\n\n // information on the root height or fixed height status\n root.ref.bounds = null;\n\n // apply initial style properties\n root.query('GET_STYLES')\n .filter(function(style) {\n return !isEmpty(style.value);\n })\n .map(function(_ref2) {\n var name = _ref2.name,\n value = _ref2.value;\n root.element.dataset[name] = value;\n });\n\n // determine if width changed\n root.ref.widthPrevious = null;\n root.ref.widthUpdated = debounce(function() {\n root.ref.updateHistory = [];\n root.dispatch('DID_RESIZE_ROOT');\n }, 250);\n\n // history of updates\n root.ref.previousAspectRatio = null;\n root.ref.updateHistory = [];\n\n // prevent scrolling and zooming on iOS (only if supports pointer events, for then we can enable reorder)\n var canHover = window.matchMedia('(pointer: fine) and (hover: hover)').matches;\n var hasPointerEvents = 'PointerEvent' in window;\n if (root.query('GET_ALLOW_REORDER') && hasPointerEvents && !canHover) {\n root.element.addEventListener('touchmove', prevent, { passive: false });\n root.element.addEventListener('gesturestart', prevent);\n }\n\n // add credits\n var credits = root.query('GET_CREDITS');\n var hasCredits = credits.length === 2;\n if (hasCredits) {\n var frag = document.createElement('a');\n frag.className = 'filepond--credits';\n frag.setAttribute('aria-hidden', 'true');\n frag.href = credits[0];\n frag.tabindex = -1;\n frag.target = '_blank';\n frag.rel = 'noopener noreferrer';\n frag.textContent = credits[1];\n root.element.appendChild(frag);\n root.ref.credits = frag;\n }\n };\n\n var write$9 = function write(_ref3) {\n var root = _ref3.root,\n props = _ref3.props,\n actions = _ref3.actions;\n // route actions\n route$5({ root: root, props: props, actions: actions });\n\n // apply style properties\n actions\n .filter(function(action) {\n return /^DID_SET_STYLE_/.test(action.type);\n })\n .filter(function(action) {\n return !isEmpty(action.data.value);\n })\n .map(function(_ref4) {\n var type = _ref4.type,\n data = _ref4.data;\n var name = toCamels(type.substring(8).toLowerCase(), '_');\n root.element.dataset[name] = data.value;\n root.invalidateLayout();\n });\n\n if (root.rect.element.hidden) return;\n\n if (root.rect.element.width !== root.ref.widthPrevious) {\n root.ref.widthPrevious = root.rect.element.width;\n root.ref.widthUpdated();\n }\n\n // get box bounds, we do this only once\n var bounds = root.ref.bounds;\n if (!bounds) {\n bounds = root.ref.bounds = calculateRootBoundingBoxHeight(root);\n\n // destroy measure element\n root.element.removeChild(root.ref.measure);\n root.ref.measure = null;\n }\n\n // get quick references to various high level parts of the upload tool\n var _root$ref = root.ref,\n hopper = _root$ref.hopper,\n label = _root$ref.label,\n list = _root$ref.list,\n panel = _root$ref.panel;\n\n // sets correct state to hopper scope\n if (hopper) {\n hopper.updateHopperState();\n }\n\n // bool to indicate if we're full or not\n var aspectRatio = root.query('GET_PANEL_ASPECT_RATIO');\n var isMultiItem = root.query('GET_ALLOW_MULTIPLE');\n var totalItems = root.query('GET_TOTAL_ITEMS');\n var maxItems = isMultiItem ? root.query('GET_MAX_FILES') || MAX_FILES_LIMIT : 1;\n var atMaxCapacity = totalItems === maxItems;\n\n // action used to add item\n var addAction = actions.find(function(action) {\n return action.type === 'DID_ADD_ITEM';\n });\n\n // if reached max capacity and we've just reached it\n if (atMaxCapacity && addAction) {\n // get interaction type\n var interactionMethod = addAction.data.interactionMethod;\n\n // hide label\n label.opacity = 0;\n\n if (isMultiItem) {\n label.translateY = -40;\n } else {\n if (interactionMethod === InteractionMethod.API) {\n label.translateX = 40;\n } else if (interactionMethod === InteractionMethod.BROWSE) {\n label.translateY = 40;\n } else {\n label.translateY = 30;\n }\n }\n } else if (!atMaxCapacity) {\n label.opacity = 1;\n label.translateX = 0;\n label.translateY = 0;\n }\n\n var listItemMargin = calculateListItemMargin(root);\n\n var listHeight = calculateListHeight(root);\n\n var labelHeight = label.rect.element.height;\n var currentLabelHeight = !isMultiItem || atMaxCapacity ? 0 : labelHeight;\n\n var listMarginTop = atMaxCapacity ? list.rect.element.marginTop : 0;\n var listMarginBottom = totalItems === 0 ? 0 : list.rect.element.marginBottom;\n\n var visualHeight =\n currentLabelHeight + listMarginTop + listHeight.visual + listMarginBottom;\n var boundsHeight =\n currentLabelHeight + listMarginTop + listHeight.bounds + listMarginBottom;\n\n // link list to label bottom position\n list.translateY =\n Math.max(0, currentLabelHeight - list.rect.element.marginTop) - listItemMargin.top;\n\n if (aspectRatio) {\n // fixed aspect ratio\n\n // calculate height based on width\n var width = root.rect.element.width;\n var height = width * aspectRatio;\n\n // clear history if aspect ratio has changed\n if (aspectRatio !== root.ref.previousAspectRatio) {\n root.ref.previousAspectRatio = aspectRatio;\n root.ref.updateHistory = [];\n }\n\n // remember this width\n var history = root.ref.updateHistory;\n history.push(width);\n\n var MAX_BOUNCES = 2;\n if (history.length > MAX_BOUNCES * 2) {\n var l = history.length;\n var bottom = l - 10;\n var bounces = 0;\n for (var i = l; i >= bottom; i--) {\n if (history[i] === history[i - 2]) {\n bounces++;\n }\n\n if (bounces >= MAX_BOUNCES) {\n // dont adjust height\n return;\n }\n }\n }\n\n // fix height of panel so it adheres to aspect ratio\n panel.scalable = false;\n panel.height = height;\n\n // available height for list\n var listAvailableHeight =\n // the height of the panel minus the label height\n height -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n if (listHeight.visual > listAvailableHeight) {\n list.overflow = listAvailableHeight;\n } else {\n list.overflow = null;\n }\n\n // set container bounds (so pushes siblings downwards)\n root.height = height;\n } else if (bounds.fixedHeight) {\n // fixed height\n\n // fix height of panel\n panel.scalable = false;\n\n // available height for list\n var _listAvailableHeight =\n // the height of the panel minus the label height\n bounds.fixedHeight -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n // set list height\n if (listHeight.visual > _listAvailableHeight) {\n list.overflow = _listAvailableHeight;\n } else {\n list.overflow = null;\n }\n\n // no need to set container bounds as these are handles by CSS fixed height\n } else if (bounds.cappedHeight) {\n // max-height\n\n // not a fixed height panel\n var isCappedHeight = visualHeight >= bounds.cappedHeight;\n var panelHeight = Math.min(bounds.cappedHeight, visualHeight);\n panel.scalable = true;\n panel.height = isCappedHeight\n ? panelHeight\n : panelHeight - listItemMargin.top - listItemMargin.bottom;\n\n // available height for list\n var _listAvailableHeight2 =\n // the height of the panel minus the label height\n panelHeight -\n currentLabelHeight -\n // the room we leave open between the end of the list and the panel bottom\n (listMarginBottom - listItemMargin.bottom) -\n // if we're full we need to leave some room between the top of the panel and the list\n (atMaxCapacity ? listMarginTop : 0);\n\n // set list height (if is overflowing)\n if (visualHeight > bounds.cappedHeight && listHeight.visual > _listAvailableHeight2) {\n list.overflow = _listAvailableHeight2;\n } else {\n list.overflow = null;\n }\n\n // set container bounds (so pushes siblings downwards)\n root.height = Math.min(\n bounds.cappedHeight,\n boundsHeight - listItemMargin.top - listItemMargin.bottom\n );\n } else {\n // flexible height\n\n // not a fixed height panel\n var itemMargin = totalItems > 0 ? listItemMargin.top + listItemMargin.bottom : 0;\n panel.scalable = true;\n panel.height = Math.max(labelHeight, visualHeight - itemMargin);\n\n // set container bounds (so pushes siblings downwards)\n root.height = Math.max(labelHeight, boundsHeight - itemMargin);\n }\n\n // move credits to bottom\n if (root.ref.credits && panel.heightCurrent)\n root.ref.credits.style.transform = 'translateY(' + panel.heightCurrent + 'px)';\n };\n\n var calculateListItemMargin = function calculateListItemMargin(root) {\n var item = root.ref.list.childViews[0].childViews[0];\n return item\n ? {\n top: item.rect.element.marginTop,\n bottom: item.rect.element.marginBottom,\n }\n : {\n top: 0,\n bottom: 0,\n };\n };\n\n var calculateListHeight = function calculateListHeight(root) {\n var visual = 0;\n var bounds = 0;\n\n // get file list reference\n var scrollList = root.ref.list;\n var itemList = scrollList.childViews[0];\n var visibleChildren = itemList.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n // no children, done!\n if (children.length === 0) return { visual: visual, bounds: bounds };\n\n var horizontalSpace = itemList.rect.element.width;\n var dragIndex = getItemIndexByPosition(itemList, children, scrollList.dragCoordinates);\n\n var childRect = children[0].rect.element;\n\n var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;\n var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;\n\n var itemWidth = childRect.width + itemHorizontalMargin;\n var itemHeight = childRect.height + itemVerticalMargin;\n\n var newItem = typeof dragIndex !== 'undefined' && dragIndex >= 0 ? 1 : 0;\n var removedItem = children.find(function(child) {\n return child.markedForRemoval && child.opacity < 0.45;\n })\n ? -1\n : 0;\n var verticalItemCount = children.length + newItem + removedItem;\n var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);\n\n // stack\n if (itemsPerRow === 1) {\n children.forEach(function(item) {\n var height = item.rect.element.height + itemVerticalMargin;\n bounds += height;\n visual += height * item.opacity;\n });\n }\n // grid\n else {\n bounds = Math.ceil(verticalItemCount / itemsPerRow) * itemHeight;\n visual = bounds;\n }\n\n return { visual: visual, bounds: bounds };\n };\n\n var calculateRootBoundingBoxHeight = function calculateRootBoundingBoxHeight(root) {\n var height = root.ref.measureHeight || null;\n var cappedHeight = parseInt(root.style.maxHeight, 10) || null;\n var fixedHeight = height === 0 ? null : height;\n\n return {\n cappedHeight: cappedHeight,\n fixedHeight: fixedHeight,\n };\n };\n\n var exceedsMaxFiles = function exceedsMaxFiles(root, items) {\n var allowReplace = root.query('GET_ALLOW_REPLACE');\n var allowMultiple = root.query('GET_ALLOW_MULTIPLE');\n var totalItems = root.query('GET_TOTAL_ITEMS');\n var maxItems = root.query('GET_MAX_FILES');\n\n // total amount of items being dragged\n var totalBrowseItems = items.length;\n\n // if does not allow multiple items and dragging more than one item\n if (!allowMultiple && totalBrowseItems > 1) {\n root.dispatch('DID_THROW_MAX_FILES', {\n source: items,\n error: createResponse('warning', 0, 'Max files'),\n });\n\n return true;\n }\n\n // limit max items to one if not allowed to drop multiple items\n maxItems = allowMultiple ? maxItems : 1;\n\n if (!allowMultiple && allowReplace) {\n // There is only one item, so there is room to replace or add an item\n return false;\n }\n\n // no more room?\n var hasMaxItems = isInt(maxItems);\n if (hasMaxItems && totalItems + totalBrowseItems > maxItems) {\n root.dispatch('DID_THROW_MAX_FILES', {\n source: items,\n error: createResponse('warning', 0, 'Max files'),\n });\n\n return true;\n }\n\n return false;\n };\n\n var getDragIndex = function getDragIndex(list, children, position) {\n var itemList = list.childViews[0];\n return getItemIndexByPosition(itemList, children, {\n left: position.scopeLeft - itemList.rect.element.left,\n top:\n position.scopeTop -\n (list.rect.outer.top + list.rect.element.marginTop + list.rect.element.scrollTop),\n });\n };\n\n /**\n * Enable or disable file drop functionality\n */\n var toggleDrop = function toggleDrop(root) {\n var isAllowed = root.query('GET_ALLOW_DROP');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.hopper) {\n var hopper = createHopper(\n root.element,\n function(items) {\n // allow quick validation of dropped items\n var beforeDropFile =\n root.query('GET_BEFORE_DROP_FILE') ||\n function() {\n return true;\n };\n\n // all items should be validated by all filters as valid\n var dropValidation = root.query('GET_DROP_VALIDATION');\n return dropValidation\n ? items.every(function(item) {\n return (\n applyFilters('ALLOW_HOPPER_ITEM', item, {\n query: root.query,\n }).every(function(result) {\n return result === true;\n }) && beforeDropFile(item)\n );\n })\n : true;\n },\n {\n filterItems: function filterItems(items) {\n var ignoredFiles = root.query('GET_IGNORED_FILES');\n return items.filter(function(item) {\n if (isFile(item)) {\n return !ignoredFiles.includes(item.name.toLowerCase());\n }\n return true;\n });\n },\n catchesDropsOnPage: root.query('GET_DROP_ON_PAGE'),\n requiresDropOnElement: root.query('GET_DROP_ON_ELEMENT'),\n }\n );\n\n hopper.onload = function(items, position) {\n // get item children elements and sort based on list sort\n var list = root.ref.list.childViews[0];\n var visibleChildren = list.childViews.filter(function(child) {\n return child.rect.element.height;\n });\n var children = root\n .query('GET_ACTIVE_ITEMS')\n .map(function(item) {\n return visibleChildren.find(function(child) {\n return child.id === item.id;\n });\n })\n .filter(function(item) {\n return item;\n });\n\n applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(\n queue\n ) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // go\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: getDragIndex(root.ref.list, children, position),\n interactionMethod: InteractionMethod.DROP,\n });\n });\n\n root.dispatch('DID_DROP', { position: position });\n\n root.dispatch('DID_END_DRAG', { position: position });\n };\n\n hopper.ondragstart = function(position) {\n root.dispatch('DID_START_DRAG', { position: position });\n };\n\n hopper.ondrag = debounce(function(position) {\n root.dispatch('DID_DRAG', { position: position });\n });\n\n hopper.ondragend = function(position) {\n root.dispatch('DID_END_DRAG', { position: position });\n };\n\n root.ref.hopper = hopper;\n\n root.ref.drip = root.appendChildView(root.createChildView(drip));\n } else if (!enabled && root.ref.hopper) {\n root.ref.hopper.destroy();\n root.ref.hopper = null;\n root.removeChildView(root.ref.drip);\n }\n };\n\n /**\n * Enable or disable browse functionality\n */\n var toggleBrowse = function toggleBrowse(root, props) {\n var isAllowed = root.query('GET_ALLOW_BROWSE');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.browser) {\n root.ref.browser = root.appendChildView(\n root.createChildView(\n browser,\n Object.assign({}, props, {\n onload: function onload(items) {\n applyFilterChain('ADD_ITEMS', items, {\n dispatch: root.dispatch,\n }).then(function(queue) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // add items!\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: -1,\n interactionMethod: InteractionMethod.BROWSE,\n });\n });\n },\n })\n ),\n\n 0\n );\n } else if (!enabled && root.ref.browser) {\n root.removeChildView(root.ref.browser);\n root.ref.browser = null;\n }\n };\n\n /**\n * Enable or disable paste functionality\n */\n var togglePaste = function togglePaste(root) {\n var isAllowed = root.query('GET_ALLOW_PASTE');\n var isDisabled = root.query('GET_DISABLED');\n var enabled = isAllowed && !isDisabled;\n if (enabled && !root.ref.paster) {\n root.ref.paster = createPaster();\n root.ref.paster.onload = function(items) {\n applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(\n queue\n ) {\n // these files don't fit so stop here\n if (exceedsMaxFiles(root, queue)) return false;\n\n // add items!\n root.dispatch('ADD_ITEMS', {\n items: queue,\n index: -1,\n interactionMethod: InteractionMethod.PASTE,\n });\n });\n };\n } else if (!enabled && root.ref.paster) {\n root.ref.paster.destroy();\n root.ref.paster = null;\n }\n };\n\n /**\n * Route actions\n */\n var route$5 = createRoute({\n DID_SET_ALLOW_BROWSE: function DID_SET_ALLOW_BROWSE(_ref5) {\n var root = _ref5.root,\n props = _ref5.props;\n toggleBrowse(root, props);\n },\n DID_SET_ALLOW_DROP: function DID_SET_ALLOW_DROP(_ref6) {\n var root = _ref6.root;\n toggleDrop(root);\n },\n DID_SET_ALLOW_PASTE: function DID_SET_ALLOW_PASTE(_ref7) {\n var root = _ref7.root;\n togglePaste(root);\n },\n DID_SET_DISABLED: function DID_SET_DISABLED(_ref8) {\n var root = _ref8.root,\n props = _ref8.props;\n toggleDrop(root);\n togglePaste(root);\n toggleBrowse(root, props);\n var isDisabled = root.query('GET_DISABLED');\n if (isDisabled) {\n root.element.dataset.disabled = 'disabled';\n } else {\n // delete root.element.dataset.disabled; <= this does not work on iOS 10\n root.element.removeAttribute('data-disabled');\n }\n },\n });\n\n var root = createView({\n name: 'root',\n read: function read(_ref9) {\n var root = _ref9.root;\n if (root.ref.measure) {\n root.ref.measureHeight = root.ref.measure.offsetHeight;\n }\n },\n create: create$e,\n write: write$9,\n destroy: function destroy(_ref10) {\n var root = _ref10.root;\n if (root.ref.paster) {\n root.ref.paster.destroy();\n }\n if (root.ref.hopper) {\n root.ref.hopper.destroy();\n }\n root.element.removeEventListener('touchmove', prevent);\n root.element.removeEventListener('gesturestart', prevent);\n },\n mixins: {\n styles: ['height'],\n },\n });\n\n // creates the app\n var createApp = function createApp() {\n var initialOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // let element\n var originalElement = null;\n\n // get default options\n var defaultOptions = getOptions();\n\n // create the data store, this will contain all our app info\n var store = createStore(\n // initial state (should be serializable)\n createInitialState(defaultOptions),\n\n // queries\n [queries, createOptionQueries(defaultOptions)],\n\n // action handlers\n [actions, createOptionActions(defaultOptions)]\n );\n\n // set initial options\n store.dispatch('SET_OPTIONS', { options: initialOptions });\n\n // kick thread if visibility changes\n var visibilityHandler = function visibilityHandler() {\n if (document.hidden) return;\n store.dispatch('KICK');\n };\n document.addEventListener('visibilitychange', visibilityHandler);\n\n // re-render on window resize start and finish\n var resizeDoneTimer = null;\n var isResizing = false;\n var isResizingHorizontally = false;\n var initialWindowWidth = null;\n var currentWindowWidth = null;\n var resizeHandler = function resizeHandler() {\n if (!isResizing) {\n isResizing = true;\n }\n clearTimeout(resizeDoneTimer);\n resizeDoneTimer = setTimeout(function() {\n isResizing = false;\n initialWindowWidth = null;\n currentWindowWidth = null;\n if (isResizingHorizontally) {\n isResizingHorizontally = false;\n store.dispatch('DID_STOP_RESIZE');\n }\n }, 500);\n };\n window.addEventListener('resize', resizeHandler);\n\n // render initial view\n var view = root(store, { id: getUniqueId() });\n\n //\n // PRIVATE API -------------------------------------------------------------------------------------\n //\n var isResting = false;\n var isHidden = false;\n\n var readWriteApi = {\n // necessary for update loop\n\n /**\n * Reads from dom (never call manually)\n * @private\n */\n _read: function _read() {\n // test if we're resizing horizontally\n // TODO: see if we can optimize this by measuring root rect\n if (isResizing) {\n currentWindowWidth = window.innerWidth;\n if (!initialWindowWidth) {\n initialWindowWidth = currentWindowWidth;\n }\n\n if (!isResizingHorizontally && currentWindowWidth !== initialWindowWidth) {\n store.dispatch('DID_START_RESIZE');\n isResizingHorizontally = true;\n }\n }\n\n if (isHidden && isResting) {\n // test if is no longer hidden\n isResting = view.element.offsetParent === null;\n }\n\n // if resting, no need to read as numbers will still all be correct\n if (isResting) return;\n\n // read view data\n view._read();\n\n // if is hidden we need to know so we exit rest mode when revealed\n isHidden = view.rect.element.hidden;\n },\n\n /**\n * Writes to dom (never call manually)\n * @private\n */\n _write: function _write(ts) {\n // get all actions from store\n var actions = store\n .processActionQueue()\n\n // filter out set actions (these will automatically trigger DID_SET)\n .filter(function(action) {\n return !/^SET_/.test(action.type);\n });\n\n // if was idling and no actions stop here\n if (isResting && !actions.length) return;\n\n // some actions might trigger events\n routeActionsToEvents(actions);\n\n // update the view\n isResting = view._write(ts, actions, isResizingHorizontally);\n\n // will clean up all archived items\n removeReleasedItems(store.query('GET_ITEMS'));\n\n // now idling\n if (isResting) {\n store.processDispatchQueue();\n }\n },\n };\n\n //\n // EXPOSE EVENTS -------------------------------------------------------------------------------------\n //\n var createEvent = function createEvent(name) {\n return function(data) {\n // create default event\n var event = {\n type: name,\n };\n\n // no data to add\n if (!data) {\n return event;\n }\n\n // copy relevant props\n if (data.hasOwnProperty('error')) {\n event.error = data.error ? Object.assign({}, data.error) : null;\n }\n\n if (data.status) {\n event.status = Object.assign({}, data.status);\n }\n\n if (data.file) {\n event.output = data.file;\n }\n\n // only source is available, else add item if possible\n if (data.source) {\n event.file = data.source;\n } else if (data.item || data.id) {\n var item = data.item ? data.item : store.query('GET_ITEM', data.id);\n event.file = item ? createItemAPI(item) : null;\n }\n\n // map all items in a possible items array\n if (data.items) {\n event.items = data.items.map(createItemAPI);\n }\n\n // if this is a progress event add the progress amount\n if (/progress/.test(name)) {\n event.progress = data.progress;\n }\n\n // copy relevant props\n if (data.hasOwnProperty('origin') && data.hasOwnProperty('target')) {\n event.origin = data.origin;\n event.target = data.target;\n }\n\n return event;\n };\n };\n\n var eventRoutes = {\n DID_DESTROY: createEvent('destroy'),\n\n DID_INIT: createEvent('init'),\n\n DID_THROW_MAX_FILES: createEvent('warning'),\n\n DID_INIT_ITEM: createEvent('initfile'),\n DID_START_ITEM_LOAD: createEvent('addfilestart'),\n DID_UPDATE_ITEM_LOAD_PROGRESS: createEvent('addfileprogress'),\n DID_LOAD_ITEM: createEvent('addfile'),\n\n DID_THROW_ITEM_INVALID: [createEvent('error'), createEvent('addfile')],\n\n DID_THROW_ITEM_LOAD_ERROR: [createEvent('error'), createEvent('addfile')],\n\n DID_THROW_ITEM_REMOVE_ERROR: [createEvent('error'), createEvent('removefile')],\n\n DID_PREPARE_OUTPUT: createEvent('preparefile'),\n\n DID_START_ITEM_PROCESSING: createEvent('processfilestart'),\n DID_UPDATE_ITEM_PROCESS_PROGRESS: createEvent('processfileprogress'),\n DID_ABORT_ITEM_PROCESSING: createEvent('processfileabort'),\n DID_COMPLETE_ITEM_PROCESSING: createEvent('processfile'),\n DID_COMPLETE_ITEM_PROCESSING_ALL: createEvent('processfiles'),\n DID_REVERT_ITEM_PROCESSING: createEvent('processfilerevert'),\n\n DID_THROW_ITEM_PROCESSING_ERROR: [createEvent('error'), createEvent('processfile')],\n\n DID_REMOVE_ITEM: createEvent('removefile'),\n\n DID_UPDATE_ITEMS: createEvent('updatefiles'),\n\n DID_ACTIVATE_ITEM: createEvent('activatefile'),\n\n DID_REORDER_ITEMS: createEvent('reorderfiles'),\n };\n\n var exposeEvent = function exposeEvent(event) {\n // create event object to be dispatched\n var detail = Object.assign({ pond: exports }, event);\n delete detail.type;\n view.element.dispatchEvent(\n new CustomEvent('FilePond:' + event.type, {\n // event info\n detail: detail,\n\n // event behaviour\n bubbles: true,\n cancelable: true,\n composed: true, // triggers listeners outside of shadow root\n })\n );\n\n // event object to params used for `on()` event handlers and callbacks `oninit()`\n var params = [];\n\n // if is possible error event, make it the first param\n if (event.hasOwnProperty('error')) {\n params.push(event.error);\n }\n\n // file is always section\n if (event.hasOwnProperty('file')) {\n params.push(event.file);\n }\n\n // append other props\n var filtered = ['type', 'error', 'file'];\n Object.keys(event)\n .filter(function(key) {\n return !filtered.includes(key);\n })\n .forEach(function(key) {\n return params.push(event[key]);\n });\n\n // on(type, () => { })\n exports.fire.apply(exports, [event.type].concat(params));\n\n // oninit = () => {}\n var handler = store.query('GET_ON' + event.type.toUpperCase());\n if (handler) {\n handler.apply(void 0, params);\n }\n };\n\n var routeActionsToEvents = function routeActionsToEvents(actions) {\n if (!actions.length) return;\n actions\n .filter(function(action) {\n return eventRoutes[action.type];\n })\n .forEach(function(action) {\n var routes = eventRoutes[action.type];\n (Array.isArray(routes) ? routes : [routes]).forEach(function(route) {\n // this isn't fantastic, but because of the stacking of settimeouts plugins can handle the did_load before the did_init\n if (action.type === 'DID_INIT_ITEM') {\n exposeEvent(route(action.data));\n } else {\n setTimeout(function() {\n exposeEvent(route(action.data));\n }, 0);\n }\n });\n });\n };\n\n //\n // PUBLIC API -------------------------------------------------------------------------------------\n //\n var setOptions = function setOptions(options) {\n return store.dispatch('SET_OPTIONS', { options: options });\n };\n\n var getFile = function getFile(query) {\n return store.query('GET_ACTIVE_ITEM', query);\n };\n\n var prepareFile = function prepareFile(query) {\n return new Promise(function(resolve, reject) {\n store.dispatch('REQUEST_ITEM_PREPARE', {\n query: query,\n success: function success(item) {\n resolve(item);\n },\n failure: function failure(error) {\n reject(error);\n },\n });\n });\n };\n\n var addFile = function addFile(source) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return new Promise(function(resolve, reject) {\n addFiles([{ source: source, options: options }], { index: options.index })\n .then(function(items) {\n return resolve(items && items[0]);\n })\n .catch(reject);\n });\n };\n\n var isFilePondFile = function isFilePondFile(obj) {\n return obj.file && obj.id;\n };\n\n var removeFile = function removeFile(query, options) {\n // if only passed options\n if (typeof query === 'object' && !isFilePondFile(query) && !options) {\n options = query;\n query = undefined;\n }\n\n // request item removal\n store.dispatch('REMOVE_ITEM', Object.assign({}, options, { query: query }));\n\n // see if item has been removed\n return store.query('GET_ACTIVE_ITEM', query) === null;\n };\n\n var addFiles = function addFiles() {\n for (\n var _len = arguments.length, args = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n args[_key] = arguments[_key];\n }\n return new Promise(function(resolve, reject) {\n var sources = [];\n var options = {};\n\n // user passed a sources array\n if (isArray(args[0])) {\n sources.push.apply(sources, args[0]);\n Object.assign(options, args[1] || {});\n } else {\n // user passed sources as arguments, last one might be options object\n var lastArgument = args[args.length - 1];\n if (typeof lastArgument === 'object' && !(lastArgument instanceof Blob)) {\n Object.assign(options, args.pop());\n }\n\n // add rest to sources\n sources.push.apply(sources, args);\n }\n\n store.dispatch('ADD_ITEMS', {\n items: sources,\n index: options.index,\n interactionMethod: InteractionMethod.API,\n success: resolve,\n failure: reject,\n });\n });\n };\n\n var getFiles = function getFiles() {\n return store.query('GET_ACTIVE_ITEMS');\n };\n\n var processFile = function processFile(query) {\n return new Promise(function(resolve, reject) {\n store.dispatch('REQUEST_ITEM_PROCESSING', {\n query: query,\n success: function success(item) {\n resolve(item);\n },\n failure: function failure(error) {\n reject(error);\n },\n });\n });\n };\n\n var prepareFiles = function prepareFiles() {\n for (\n var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;\n _key2 < _len2;\n _key2++\n ) {\n args[_key2] = arguments[_key2];\n }\n var queries = Array.isArray(args[0]) ? args[0] : args;\n var items = queries.length ? queries : getFiles();\n return Promise.all(items.map(prepareFile));\n };\n\n var processFiles = function processFiles() {\n for (\n var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;\n _key3 < _len3;\n _key3++\n ) {\n args[_key3] = arguments[_key3];\n }\n var queries = Array.isArray(args[0]) ? args[0] : args;\n if (!queries.length) {\n var files = getFiles().filter(function(item) {\n return (\n !(item.status === ItemStatus.IDLE && item.origin === FileOrigin.LOCAL) &&\n item.status !== ItemStatus.PROCESSING &&\n item.status !== ItemStatus.PROCESSING_COMPLETE &&\n item.status !== ItemStatus.PROCESSING_REVERT_ERROR\n );\n });\n\n return Promise.all(files.map(processFile));\n }\n return Promise.all(queries.map(processFile));\n };\n\n var removeFiles = function removeFiles() {\n for (\n var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;\n _key4 < _len4;\n _key4++\n ) {\n args[_key4] = arguments[_key4];\n }\n\n var queries = Array.isArray(args[0]) ? args[0] : args;\n\n var options;\n if (typeof queries[queries.length - 1] === 'object') {\n options = queries.pop();\n } else if (Array.isArray(args[0])) {\n options = args[1];\n }\n\n var files = getFiles();\n\n if (!queries.length)\n return Promise.all(\n files.map(function(file) {\n return removeFile(file, options);\n })\n );\n\n // when removing by index the indexes shift after each file removal so we need to convert indexes to ids\n var mappedQueries = queries\n .map(function(query) {\n return isNumber(query) ? (files[query] ? files[query].id : null) : query;\n })\n .filter(function(query) {\n return query;\n });\n\n return mappedQueries.map(function(q) {\n return removeFile(q, options);\n });\n };\n\n var exports = Object.assign(\n {},\n\n on(),\n {},\n\n readWriteApi,\n {},\n\n createOptionAPI(store, defaultOptions),\n {\n /**\n * Override options defined in options object\n * @param options\n */\n setOptions: setOptions,\n\n /**\n * Load the given file\n * @param source - the source of the file (either a File, base64 data uri or url)\n * @param options - object, { index: 0 }\n */\n addFile: addFile,\n\n /**\n * Load the given files\n * @param sources - the sources of the files to load\n * @param options - object, { index: 0 }\n */\n addFiles: addFiles,\n\n /**\n * Returns the file objects matching the given query\n * @param query { string, number, null }\n */\n getFile: getFile,\n\n /**\n * Upload file with given name\n * @param query { string, number, null }\n */\n processFile: processFile,\n\n /**\n * Request prepare output for file with given name\n * @param query { string, number, null }\n */\n prepareFile: prepareFile,\n\n /**\n * Removes a file by its name\n * @param query { string, number, null }\n */\n removeFile: removeFile,\n\n /**\n * Moves a file to a new location in the files list\n */\n moveFile: function moveFile(query, index) {\n return store.dispatch('MOVE_ITEM', { query: query, index: index });\n },\n\n /**\n * Returns all files (wrapped in public api)\n */\n getFiles: getFiles,\n\n /**\n * Starts uploading all files\n */\n processFiles: processFiles,\n\n /**\n * Clears all files from the files list\n */\n removeFiles: removeFiles,\n\n /**\n * Starts preparing output of all files\n */\n prepareFiles: prepareFiles,\n\n /**\n * Sort list of files\n */\n sort: function sort(compare) {\n return store.dispatch('SORT', { compare: compare });\n },\n\n /**\n * Browse the file system for a file\n */\n browse: function browse() {\n // needs to be trigger directly as user action needs to be traceable (is not traceable in requestAnimationFrame)\n var input = view.element.querySelector('input[type=file]');\n if (input) {\n input.click();\n }\n },\n\n /**\n * Destroys the app\n */\n destroy: function destroy() {\n // request destruction\n exports.fire('destroy', view.element);\n\n // stop active processes (file uploads, fetches, stuff like that)\n // loop over items and depending on states call abort for ongoing processes\n store.dispatch('ABORT_ALL');\n\n // destroy view\n view._destroy();\n\n // stop listening to resize\n window.removeEventListener('resize', resizeHandler);\n\n // stop listening to the visiblitychange event\n document.removeEventListener('visibilitychange', visibilityHandler);\n\n // dispatch destroy\n store.dispatch('DID_DESTROY');\n },\n\n /**\n * Inserts the plugin before the target element\n */\n insertBefore: function insertBefore$1(element) {\n return insertBefore(view.element, element);\n },\n\n /**\n * Inserts the plugin after the target element\n */\n insertAfter: function insertAfter$1(element) {\n return insertAfter(view.element, element);\n },\n\n /**\n * Appends the plugin to the target element\n */\n appendTo: function appendTo(element) {\n return element.appendChild(view.element);\n },\n\n /**\n * Replaces an element with the app\n */\n replaceElement: function replaceElement(element) {\n // insert the app before the element\n insertBefore(view.element, element);\n\n // remove the original element\n element.parentNode.removeChild(element);\n\n // remember original element\n originalElement = element;\n },\n\n /**\n * Restores the original element\n */\n restoreElement: function restoreElement() {\n if (!originalElement) {\n return; // no element to restore\n }\n\n // restore original element\n insertAfter(originalElement, view.element);\n\n // remove our element\n view.element.parentNode.removeChild(view.element);\n\n // remove reference\n originalElement = null;\n },\n\n /**\n * Returns true if the app root is attached to given element\n * @param element\n */\n isAttachedTo: function isAttachedTo(element) {\n return view.element === element || originalElement === element;\n },\n\n /**\n * Returns the root element\n */\n element: {\n get: function get() {\n return view.element;\n },\n },\n\n /**\n * Returns the current pond status\n */\n status: {\n get: function get() {\n return store.query('GET_STATUS');\n },\n },\n }\n );\n\n // Done!\n store.dispatch('DID_INIT');\n\n // create actual api object\n return createObject(exports);\n };\n\n var createAppObject = function createAppObject() {\n var customOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // default options\n var defaultOptions = {};\n forin(getOptions(), function(key, value) {\n defaultOptions[key] = value[0];\n });\n\n // set app options\n var app = createApp(\n Object.assign(\n {},\n\n defaultOptions,\n {},\n\n customOptions\n )\n );\n\n // return the plugin instance\n return app;\n };\n\n var lowerCaseFirstLetter = function lowerCaseFirstLetter(string) {\n return string.charAt(0).toLowerCase() + string.slice(1);\n };\n\n var attributeNameToPropertyName = function attributeNameToPropertyName(attributeName) {\n return toCamels(attributeName.replace(/^data-/, ''));\n };\n\n var mapObject = function mapObject(object, propertyMap) {\n // remove unwanted\n forin(propertyMap, function(selector, mapping) {\n forin(object, function(property, value) {\n // create regexp shortcut\n var selectorRegExp = new RegExp(selector);\n\n // tests if\n var matches = selectorRegExp.test(property);\n\n // no match, skip\n if (!matches) {\n return;\n }\n\n // if there's a mapping, the original property is always removed\n delete object[property];\n\n // should only remove, we done!\n if (mapping === false) {\n return;\n }\n\n // move value to new property\n if (isString(mapping)) {\n object[mapping] = value;\n return;\n }\n\n // move to group\n var group = mapping.group;\n if (isObject(mapping) && !object[group]) {\n object[group] = {};\n }\n\n object[group][lowerCaseFirstLetter(property.replace(selectorRegExp, ''))] = value;\n });\n\n // do submapping\n if (mapping.mapping) {\n mapObject(object[mapping.group], mapping.mapping);\n }\n });\n };\n\n var getAttributesAsObject = function getAttributesAsObject(node) {\n var attributeMapping =\n arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n // turn attributes into object\n var attributes = [];\n forin(node.attributes, function(index) {\n attributes.push(node.attributes[index]);\n });\n\n var output = attributes\n .filter(function(attribute) {\n return attribute.name;\n })\n .reduce(function(obj, attribute) {\n var value = attr(node, attribute.name);\n\n obj[attributeNameToPropertyName(attribute.name)] =\n value === attribute.name ? true : value;\n return obj;\n }, {});\n\n // do mapping of object properties\n mapObject(output, attributeMapping);\n\n return output;\n };\n\n var createAppAtElement = function createAppAtElement(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n // how attributes of the input element are mapped to the options for the plugin\n var attributeMapping = {\n // translate to other name\n '^class$': 'className',\n '^multiple$': 'allowMultiple',\n '^capture$': 'captureMethod',\n '^webkitdirectory$': 'allowDirectoriesOnly',\n\n // group under single property\n '^server': {\n group: 'server',\n mapping: {\n '^process': {\n group: 'process',\n },\n\n '^revert': {\n group: 'revert',\n },\n\n '^fetch': {\n group: 'fetch',\n },\n\n '^restore': {\n group: 'restore',\n },\n\n '^load': {\n group: 'load',\n },\n },\n },\n\n // don't include in object\n '^type$': false,\n '^files$': false,\n };\n\n // add additional option translators\n applyFilters('SET_ATTRIBUTE_TO_OPTION_MAP', attributeMapping);\n\n // create final options object by setting options object and then overriding options supplied on element\n var mergedOptions = Object.assign({}, options);\n\n var attributeOptions = getAttributesAsObject(\n element.nodeName === 'FIELDSET' ? element.querySelector('input[type=file]') : element,\n attributeMapping\n );\n\n // merge with options object\n Object.keys(attributeOptions).forEach(function(key) {\n if (isObject(attributeOptions[key])) {\n if (!isObject(mergedOptions[key])) {\n mergedOptions[key] = {};\n }\n Object.assign(mergedOptions[key], attributeOptions[key]);\n } else {\n mergedOptions[key] = attributeOptions[key];\n }\n });\n\n // if parent is a fieldset, get files from parent by selecting all input fields that are not file upload fields\n // these will then be automatically set to the initial files\n mergedOptions.files = (options.files || []).concat(\n Array.from(element.querySelectorAll('input:not([type=file])')).map(function(input) {\n return {\n source: input.value,\n options: {\n type: input.dataset.type,\n },\n };\n })\n );\n\n // build plugin\n var app = createAppObject(mergedOptions);\n\n // add already selected files\n if (element.files) {\n Array.from(element.files).forEach(function(file) {\n app.addFile(file);\n });\n }\n\n // replace the target element\n app.replaceElement(element);\n\n // expose\n return app;\n };\n\n // if an element is passed, we create the instance at that element, if not, we just create an up object\n var createApp$1 = function createApp() {\n return isNode(arguments.length <= 0 ? undefined : arguments[0])\n ? createAppAtElement.apply(void 0, arguments)\n : createAppObject.apply(void 0, arguments);\n };\n\n var PRIVATE_METHODS = ['fire', '_read', '_write'];\n\n var createAppAPI = function createAppAPI(app) {\n var api = {};\n\n copyObjectPropertiesToObject(app, api, PRIVATE_METHODS);\n\n return api;\n };\n\n /**\n * Replaces placeholders in given string with replacements\n * @param string - \"Foo {bar}\"\"\n * @param replacements - { \"bar\": 10 }\n */\n var replaceInString = function replaceInString(string, replacements) {\n return string.replace(/(?:{([a-zA-Z]+)})/g, function(match, group) {\n return replacements[group];\n });\n };\n\n var createWorker = function createWorker(fn) {\n var workerBlob = new Blob(['(', fn.toString(), ')()'], {\n type: 'application/javascript',\n });\n\n var workerURL = URL.createObjectURL(workerBlob);\n var worker = new Worker(workerURL);\n\n return {\n transfer: function transfer(message, cb) {},\n post: function post(message, cb, transferList) {\n var id = getUniqueId();\n\n worker.onmessage = function(e) {\n if (e.data.id === id) {\n cb(e.data.message);\n }\n };\n\n worker.postMessage(\n {\n id: id,\n message: message,\n },\n\n transferList\n );\n },\n terminate: function terminate() {\n worker.terminate();\n URL.revokeObjectURL(workerURL);\n },\n };\n };\n\n var loadImage = function loadImage(url) {\n return new Promise(function(resolve, reject) {\n var img = new Image();\n img.onload = function() {\n resolve(img);\n };\n img.onerror = function(e) {\n reject(e);\n };\n img.src = url;\n });\n };\n\n var renameFile = function renameFile(file, name) {\n var renamedFile = file.slice(0, file.size, file.type);\n renamedFile.lastModifiedDate = file.lastModifiedDate;\n renamedFile.name = name;\n return renamedFile;\n };\n\n var copyFile = function copyFile(file) {\n return renameFile(file, file.name);\n };\n\n // already registered plugins (can't register twice)\n var registeredPlugins = [];\n\n // pass utils to plugin\n var createAppPlugin = function createAppPlugin(plugin) {\n // already registered\n if (registeredPlugins.includes(plugin)) {\n return;\n }\n\n // remember this plugin\n registeredPlugins.push(plugin);\n\n // setup!\n var pluginOutline = plugin({\n addFilter: addFilter,\n utils: {\n Type: Type,\n forin: forin,\n isString: isString,\n isFile: isFile,\n toNaturalFileSize: toNaturalFileSize,\n replaceInString: replaceInString,\n getExtensionFromFilename: getExtensionFromFilename,\n getFilenameWithoutExtension: getFilenameWithoutExtension,\n guesstimateMimeType: guesstimateMimeType,\n getFileFromBlob: getFileFromBlob,\n getFilenameFromURL: getFilenameFromURL,\n createRoute: createRoute,\n createWorker: createWorker,\n createView: createView,\n createItemAPI: createItemAPI,\n loadImage: loadImage,\n copyFile: copyFile,\n renameFile: renameFile,\n createBlob: createBlob,\n applyFilterChain: applyFilterChain,\n text: text,\n getNumericAspectRatioFromString: getNumericAspectRatioFromString,\n },\n\n views: {\n fileActionButton: fileActionButton,\n },\n });\n\n // add plugin options to default options\n extendDefaultOptions(pluginOutline.options);\n };\n\n // feature detection used by supported() method\n var isOperaMini = function isOperaMini() {\n return Object.prototype.toString.call(window.operamini) === '[object OperaMini]';\n };\n var hasPromises = function hasPromises() {\n return 'Promise' in window;\n };\n var hasBlobSlice = function hasBlobSlice() {\n return 'slice' in Blob.prototype;\n };\n var hasCreateObjectURL = function hasCreateObjectURL() {\n return 'URL' in window && 'createObjectURL' in window.URL;\n };\n var hasVisibility = function hasVisibility() {\n return 'visibilityState' in document;\n };\n var hasTiming = function hasTiming() {\n return 'performance' in window;\n }; // iOS 8.x\n var hasCSSSupports = function hasCSSSupports() {\n return 'supports' in (window.CSS || {});\n }; // use to detect Safari 9+\n var isIE11 = function isIE11() {\n return /MSIE|Trident/.test(window.navigator.userAgent);\n };\n\n var supported = (function() {\n // Runs immediately and then remembers result for subsequent calls\n var isSupported =\n // Has to be a browser\n isBrowser() &&\n // Can't run on Opera Mini due to lack of everything\n !isOperaMini() &&\n // Require these APIs to feature detect a modern browser\n hasVisibility() &&\n hasPromises() &&\n hasBlobSlice() &&\n hasCreateObjectURL() &&\n hasTiming() &&\n // doesn't need CSSSupports but is a good way to detect Safari 9+ (we do want to support IE11 though)\n (hasCSSSupports() || isIE11());\n\n return function() {\n return isSupported;\n };\n })();\n\n /**\n * Plugin internal state (over all instances)\n */\n var state = {\n // active app instances, used to redraw the apps and to find the later\n apps: [],\n };\n\n // plugin name\n var name = 'filepond';\n\n /**\n * Public Plugin methods\n */\n var fn = function fn() {};\n exports.Status = {};\n exports.FileStatus = {};\n exports.FileOrigin = {};\n exports.OptionTypes = {};\n exports.create = fn;\n exports.destroy = fn;\n exports.parse = fn;\n exports.find = fn;\n exports.registerPlugin = fn;\n exports.getOptions = fn;\n exports.setOptions = fn;\n\n // if not supported, no API\n if (supported()) {\n // start painter and fire load event\n createPainter(\n function() {\n state.apps.forEach(function(app) {\n return app._read();\n });\n },\n function(ts) {\n state.apps.forEach(function(app) {\n return app._write(ts);\n });\n }\n );\n\n // fire loaded event so we know when FilePond is available\n var dispatch = function dispatch() {\n // let others know we have area ready\n document.dispatchEvent(\n new CustomEvent('FilePond:loaded', {\n detail: {\n supported: supported,\n create: exports.create,\n destroy: exports.destroy,\n parse: exports.parse,\n find: exports.find,\n registerPlugin: exports.registerPlugin,\n setOptions: exports.setOptions,\n },\n })\n );\n\n // clean up event\n document.removeEventListener('DOMContentLoaded', dispatch);\n };\n\n if (document.readyState !== 'loading') {\n // move to back of execution queue, FilePond should have been exported by then\n setTimeout(function() {\n return dispatch();\n }, 0);\n } else {\n document.addEventListener('DOMContentLoaded', dispatch);\n }\n\n // updates the OptionTypes object based on the current options\n var updateOptionTypes = function updateOptionTypes() {\n return forin(getOptions(), function(key, value) {\n exports.OptionTypes[key] = value[1];\n });\n };\n\n exports.Status = Object.assign({}, Status);\n exports.FileOrigin = Object.assign({}, FileOrigin);\n exports.FileStatus = Object.assign({}, ItemStatus);\n\n exports.OptionTypes = {};\n updateOptionTypes();\n\n // create method, creates apps and adds them to the app array\n exports.create = function create() {\n var app = createApp$1.apply(void 0, arguments);\n app.on('destroy', exports.destroy);\n state.apps.push(app);\n return createAppAPI(app);\n };\n\n // destroys apps and removes them from the app array\n exports.destroy = function destroy(hook) {\n // returns true if the app was destroyed successfully\n var indexToRemove = state.apps.findIndex(function(app) {\n return app.isAttachedTo(hook);\n });\n if (indexToRemove >= 0) {\n // remove from apps\n var app = state.apps.splice(indexToRemove, 1)[0];\n\n // restore original dom element\n app.restoreElement();\n\n return true;\n }\n\n return false;\n };\n\n // parses the given context for plugins (does not include the context element itself)\n exports.parse = function parse(context) {\n // get all possible hooks\n var matchedHooks = Array.from(context.querySelectorAll('.' + name));\n\n // filter out already active hooks\n var newHooks = matchedHooks.filter(function(newHook) {\n return !state.apps.find(function(app) {\n return app.isAttachedTo(newHook);\n });\n });\n\n // create new instance for each hook\n return newHooks.map(function(hook) {\n return exports.create(hook);\n });\n };\n\n // returns an app based on the given element hook\n exports.find = function find(hook) {\n var app = state.apps.find(function(app) {\n return app.isAttachedTo(hook);\n });\n if (!app) {\n return null;\n }\n return createAppAPI(app);\n };\n\n // adds a plugin extension\n exports.registerPlugin = function registerPlugin() {\n for (\n var _len = arguments.length, plugins = new Array(_len), _key = 0;\n _key < _len;\n _key++\n ) {\n plugins[_key] = arguments[_key];\n }\n\n // register plugins\n plugins.forEach(createAppPlugin);\n\n // update OptionTypes, each plugin might have extended the default options\n updateOptionTypes();\n };\n\n exports.getOptions = function getOptions$1() {\n var opts = {};\n forin(getOptions(), function(key, value) {\n opts[key] = value[0];\n });\n return opts;\n };\n\n exports.setOptions = function setOptions$1(opts) {\n if (isObject(opts)) {\n // update existing plugins\n state.apps.forEach(function(app) {\n app.setOptions(opts);\n });\n\n // override defaults\n setOptions(opts);\n }\n\n // return new options\n return exports.getOptions();\n };\n }\n\n exports.supported = supported;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar arrayBufferModule = require('../internals/array-buffer');\nvar setSpecies = require('../internals/set-species');\n\nvar ARRAY_BUFFER = 'ArrayBuffer';\nvar ArrayBuffer = arrayBufferModule[ARRAY_BUFFER];\nvar NativeArrayBuffer = global[ARRAY_BUFFER];\n\n// `ArrayBuffer` constructor\n// https://tc39.es/ecma262/#sec-arraybuffer-constructor\n$({ global: true, constructor: true, forced: NativeArrayBuffer !== ArrayBuffer }, {\n ArrayBuffer: ArrayBuffer\n});\n\nsetSpecies(ARRAY_BUFFER);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $filter = require('../internals/array-iteration').filter;\nvar fromSpeciesAndList = require('../internals/typed-array-from-species-and-list');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.filter` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter\nexportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */) {\n var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n return fromSpeciesAndList(this, list);\n});\n","var PROPER_FUNCTION_NAME = require('../internals/function-name').PROPER;\nvar fails = require('../internals/fails');\nvar whitespaces = require('../internals/whitespaces');\n\nvar non = '\\u200B\\u0085\\u180E';\n\n// check that a method works with the correct list\n// of whitespaces and has a correct name\nmodule.exports = function (METHOD_NAME) {\n return fails(function () {\n return !!whitespaces[METHOD_NAME]()\n || non[METHOD_NAME]() !== non\n || (PROPER_FUNCTION_NAME && whitespaces[METHOD_NAME].name !== METHOD_NAME);\n });\n};\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $reduce = require('../internals/array-reduce').left;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.reduce` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce\nexportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */) {\n var length = arguments.length;\n return $reduce(aTypedArray(this), callbackfn, length, length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar floor = Math.floor;\n\n// `%TypedArray%.prototype.reverse` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse\nexportTypedArrayMethod('reverse', function reverse() {\n var that = this;\n var length = aTypedArray(that).length;\n var middle = floor(length / 2);\n var index = 0;\n var value;\n while (index < middle) {\n value = that[index];\n that[index++] = that[--length];\n that[length] = value;\n } return that;\n});\n","module.exports = {\n IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },\n DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },\n HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },\n WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },\n InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },\n NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },\n NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },\n NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },\n NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },\n InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },\n InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },\n SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },\n InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },\n NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },\n InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },\n ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },\n TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },\n SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },\n NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },\n AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },\n URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },\n QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },\n TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },\n InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },\n DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }\n};\n","var createTypedArrayConstructor = require('../internals/typed-array-constructor');\n\n// `Float32Array` constructor\n// https://tc39.es/ecma262/#sec-typedarray-objects\ncreateTypedArrayConstructor('Float32', function (init) {\n return function Float32Array(data, byteOffset, length) {\n return init(this, data, byteOffset, length);\n };\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $find = require('../internals/array-iteration').find;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.find` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.find\nexportTypedArrayMethod('find', function find(predicate /* , thisArg */) {\n return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $forEach = require('../internals/array-iteration').forEach;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.forEach` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach\nexportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */) {\n $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n});\n","var lengthOfArrayLike = require('../internals/length-of-array-like');\n\nmodule.exports = function (Constructor, list) {\n var index = 0;\n var length = lengthOfArrayLike(list);\n var result = new Constructor(length);\n while (length > index) result[index] = list[index++];\n return result;\n};\n","export * from \"-!../../node_modules/mini-css-extract-plugin/dist/loader.js??ref--9-oneOf-1-0!../../node_modules/css-loader/dist/cjs.js??ref--9-oneOf-1-1!../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../node_modules/postcss-loader/src/index.js??ref--9-oneOf-1-2!../../node_modules/sass-loader/dist/cjs.js??ref--9-oneOf-1-3!../../node_modules/cache-loader/dist/cjs.js??ref--1-0!../../node_modules/vue-loader/lib/index.js??vue-loader-options!./FileUpload.vue?vue&type=style&index=0&id=29a6226e&prod&lang=scss&scoped=true&\"","'use strict';\n/* eslint-disable es/no-array-prototype-lastindexof -- safe */\nvar apply = require('../internals/function-apply');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toIntegerOrInfinity = require('../internals/to-integer-or-infinity');\nvar lengthOfArrayLike = require('../internals/length-of-array-like');\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\n\nvar min = Math.min;\nvar $lastIndexOf = [].lastIndexOf;\nvar NEGATIVE_ZERO = !!$lastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;\nvar STRICT_METHOD = arrayMethodIsStrict('lastIndexOf');\nvar FORCED = NEGATIVE_ZERO || !STRICT_METHOD;\n\n// `Array.prototype.lastIndexOf` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.lastindexof\nmodule.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {\n // convert -0 to +0\n if (NEGATIVE_ZERO) return apply($lastIndexOf, this, arguments) || 0;\n var O = toIndexedObject(this);\n var length = lengthOfArrayLike(O);\n var index = length - 1;\n if (arguments.length > 1) index = min(index, toIntegerOrInfinity(arguments[1]));\n if (index < 0) index = length + index;\n for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;\n return -1;\n} : $lastIndexOf;\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $indexOf = require('../internals/array-includes').indexOf;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.indexOf` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof\nexportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex */) {\n return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-basic-detection');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar isCallable = require('../internals/is-callable');\nvar isObject = require('../internals/is-object');\nvar hasOwn = require('../internals/has-own-property');\nvar classof = require('../internals/classof');\nvar tryToString = require('../internals/try-to-string');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar defineBuiltIn = require('../internals/define-built-in');\nvar defineProperty = require('../internals/object-define-property').f;\nvar isPrototypeOf = require('../internals/object-is-prototype-of');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar uid = require('../internals/uid');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar enforceInternalState = InternalStateModule.enforce;\nvar getInternalState = InternalStateModule.get;\nvar Int8Array = global.Int8Array;\nvar Int8ArrayPrototype = Int8Array && Int8Array.prototype;\nvar Uint8ClampedArray = global.Uint8ClampedArray;\nvar Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;\nvar TypedArray = Int8Array && getPrototypeOf(Int8Array);\nvar TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);\nvar ObjectPrototype = Object.prototype;\nvar TypeError = global.TypeError;\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');\nvar TYPED_ARRAY_CONSTRUCTOR = 'TypedArrayConstructor';\n// Fixing native typed arrays in Opera Presto crashes the browser, see #595\nvar NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';\nvar TYPED_ARRAY_TAG_REQUIRED = false;\nvar NAME, Constructor, Prototype;\n\nvar TypedArrayConstructorsList = {\n Int8Array: 1,\n Uint8Array: 1,\n Uint8ClampedArray: 1,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n Float32Array: 4,\n Float64Array: 8\n};\n\nvar BigIntArrayConstructorsList = {\n BigInt64Array: 8,\n BigUint64Array: 8\n};\n\nvar isView = function isView(it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return klass === 'DataView'\n || hasOwn(TypedArrayConstructorsList, klass)\n || hasOwn(BigIntArrayConstructorsList, klass);\n};\n\nvar getTypedArrayConstructor = function (it) {\n var proto = getPrototypeOf(it);\n if (!isObject(proto)) return;\n var state = getInternalState(proto);\n return (state && hasOwn(state, TYPED_ARRAY_CONSTRUCTOR)) ? state[TYPED_ARRAY_CONSTRUCTOR] : getTypedArrayConstructor(proto);\n};\n\nvar isTypedArray = function (it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return hasOwn(TypedArrayConstructorsList, klass)\n || hasOwn(BigIntArrayConstructorsList, klass);\n};\n\nvar aTypedArray = function (it) {\n if (isTypedArray(it)) return it;\n throw TypeError('Target is not a typed array');\n};\n\nvar aTypedArrayConstructor = function (C) {\n if (isCallable(C) && (!setPrototypeOf || isPrototypeOf(TypedArray, C))) return C;\n throw TypeError(tryToString(C) + ' is not a typed array constructor');\n};\n\nvar exportTypedArrayMethod = function (KEY, property, forced, options) {\n if (!DESCRIPTORS) return;\n if (forced) for (var ARRAY in TypedArrayConstructorsList) {\n var TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && hasOwn(TypedArrayConstructor.prototype, KEY)) try {\n delete TypedArrayConstructor.prototype[KEY];\n } catch (error) {\n // old WebKit bug - some methods are non-configurable\n try {\n TypedArrayConstructor.prototype[KEY] = property;\n } catch (error2) { /* empty */ }\n }\n }\n if (!TypedArrayPrototype[KEY] || forced) {\n defineBuiltIn(TypedArrayPrototype, KEY, forced ? property\n : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property, options);\n }\n};\n\nvar exportTypedArrayStaticMethod = function (KEY, property, forced) {\n var ARRAY, TypedArrayConstructor;\n if (!DESCRIPTORS) return;\n if (setPrototypeOf) {\n if (forced) for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && hasOwn(TypedArrayConstructor, KEY)) try {\n delete TypedArrayConstructor[KEY];\n } catch (error) { /* empty */ }\n }\n if (!TypedArray[KEY] || forced) {\n // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable\n try {\n return defineBuiltIn(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && TypedArray[KEY] || property);\n } catch (error) { /* empty */ }\n } else return;\n }\n for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {\n defineBuiltIn(TypedArrayConstructor, KEY, property);\n }\n }\n};\n\nfor (NAME in TypedArrayConstructorsList) {\n Constructor = global[NAME];\n Prototype = Constructor && Constructor.prototype;\n if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;\n else NATIVE_ARRAY_BUFFER_VIEWS = false;\n}\n\nfor (NAME in BigIntArrayConstructorsList) {\n Constructor = global[NAME];\n Prototype = Constructor && Constructor.prototype;\n if (Prototype) enforceInternalState(Prototype)[TYPED_ARRAY_CONSTRUCTOR] = Constructor;\n}\n\n// WebKit bug - typed arrays constructors prototype is Object.prototype\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !isCallable(TypedArray) || TypedArray === Function.prototype) {\n // eslint-disable-next-line no-shadow -- safe\n TypedArray = function TypedArray() {\n throw TypeError('Incorrect invocation');\n };\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);\n }\n}\n\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {\n TypedArrayPrototype = TypedArray.prototype;\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);\n }\n}\n\n// WebKit bug - one more object in Uint8ClampedArray prototype chain\nif (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {\n setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);\n}\n\nif (DESCRIPTORS && !hasOwn(TypedArrayPrototype, TO_STRING_TAG)) {\n TYPED_ARRAY_TAG_REQUIRED = true;\n defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {\n return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;\n } });\n for (NAME in TypedArrayConstructorsList) if (global[NAME]) {\n createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);\n }\n}\n\nmodule.exports = {\n NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,\n TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQUIRED && TYPED_ARRAY_TAG,\n aTypedArray: aTypedArray,\n aTypedArrayConstructor: aTypedArrayConstructor,\n exportTypedArrayMethod: exportTypedArrayMethod,\n exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,\n getTypedArrayConstructor: getTypedArrayConstructor,\n isView: isView,\n isTypedArray: isTypedArray,\n TypedArray: TypedArray,\n TypedArrayPrototype: TypedArrayPrototype\n};\n","var toPrimitive = require('../internals/to-primitive');\n\nvar $TypeError = TypeError;\n\n// `ToBigInt` abstract operation\n// https://tc39.es/ecma262/#sec-tobigint\nmodule.exports = function (argument) {\n var prim = toPrimitive(argument, 'number');\n if (typeof prim == 'number') throw $TypeError(\"Can't convert number to bigint\");\n // eslint-disable-next-line es/no-bigint -- safe\n return BigInt(prim);\n};\n","// `Math.sign` method implementation\n// https://tc39.es/ecma262/#sec-math.sign\n// eslint-disable-next-line es/no-math-sign -- safe\nmodule.exports = Math.sign || function sign(x) {\n var n = +x;\n // eslint-disable-next-line no-self-compare -- NaN check\n return n == 0 || n != n ? n : n < 0 ? -1 : 1;\n};\n","var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');\n\nvar $RangeError = RangeError;\n\nmodule.exports = function (it) {\n var result = toIntegerOrInfinity(it);\n if (result < 0) throw $RangeError(\"The argument can't be less than 0\");\n return result;\n};\n","/*!\n * FilePondPluginImageEdit 1.6.3\n * Licensed under MIT, https://opensource.org/licenses/MIT/\n * Please visit https://pqina.nl/filepond/ for details.\n */\n\n/* eslint-disable */\n\n(function(global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? (module.exports = factory())\n : typeof define === 'function' && define.amd\n ? define(factory)\n : ((global = global || self), (global.FilePondPluginImageEdit = factory()));\n})(this, function() {\n 'use strict';\n\n var isPreviewableImage = function isPreviewableImage(file) {\n return /^image/.test(file.type);\n };\n\n /**\n * Image Edit Proxy Plugin\n */\n var plugin = function plugin(_) {\n var addFilter = _.addFilter,\n utils = _.utils,\n views = _.views;\n var Type = utils.Type,\n createRoute = utils.createRoute,\n _utils$createItemAPI = utils.createItemAPI,\n createItemAPI =\n _utils$createItemAPI === void 0\n ? function(item) {\n return item;\n }\n : _utils$createItemAPI;\n var fileActionButton = views.fileActionButton;\n\n addFilter('SHOULD_REMOVE_ON_REVERT', function(shouldRemove, _ref) {\n var item = _ref.item,\n query = _ref.query;\n return new Promise(function(resolve) {\n var file = item.file;\n\n // if this file is editable it shouldn't be removed immidiately even when instant uploading\n var canEdit =\n query('GET_ALLOW_IMAGE_EDIT') &&\n query('GET_IMAGE_EDIT_ALLOW_EDIT') &&\n isPreviewableImage(file);\n\n // if the file cannot be edited it should be removed on revert\n resolve(!canEdit);\n });\n });\n\n // open editor when loading a new item\n addFilter('DID_LOAD_ITEM', function(item, _ref2) {\n var query = _ref2.query,\n dispatch = _ref2.dispatch;\n return new Promise(function(resolve, reject) {\n // if is temp or local file\n if (item.origin > 1) {\n resolve(item);\n return;\n }\n\n // get file reference\n var file = item.file;\n if (\n !query('GET_ALLOW_IMAGE_EDIT') ||\n !query('GET_IMAGE_EDIT_INSTANT_EDIT')\n ) {\n resolve(item);\n return;\n }\n\n // exit if this is not an image\n if (!isPreviewableImage(file)) {\n resolve(item);\n return;\n }\n\n var createEditorResponseHandler = function createEditorResponseHandler(\n item,\n resolve,\n reject\n ) {\n return function(userDidConfirm) {\n // remove item\n editRequestQueue.shift();\n\n // handle item\n if (userDidConfirm) {\n resolve(item);\n } else {\n reject(item);\n }\n\n // TODO: Fix, should not be needed to kick the internal loop in case no processes are running\n dispatch('KICK');\n\n // handle next item!\n requestEdit();\n };\n };\n\n var requestEdit = function requestEdit() {\n if (!editRequestQueue.length) return;\n var _editRequestQueue$ = editRequestQueue[0],\n item = _editRequestQueue$.item,\n resolve = _editRequestQueue$.resolve,\n reject = _editRequestQueue$.reject;\n\n dispatch('EDIT_ITEM', {\n id: item.id,\n handleEditorResponse: createEditorResponseHandler(\n item,\n resolve,\n reject\n )\n });\n };\n\n queueEditRequest({ item: item, resolve: resolve, reject: reject });\n\n if (editRequestQueue.length === 1) {\n requestEdit();\n }\n });\n });\n\n // extend item methods\n addFilter('DID_CREATE_ITEM', function(item, _ref3) {\n var query = _ref3.query,\n dispatch = _ref3.dispatch;\n item.extend('edit', function() {\n dispatch('EDIT_ITEM', { id: item.id });\n });\n });\n\n var editRequestQueue = [];\n var queueEditRequest = function queueEditRequest(editRequest) {\n editRequestQueue.push(editRequest);\n return editRequest;\n };\n\n // called for each view that is created right after the 'create' method\n addFilter('CREATE_VIEW', function(viewAPI) {\n // get reference to created view\n var is = viewAPI.is,\n view = viewAPI.view,\n query = viewAPI.query;\n\n if (!query('GET_ALLOW_IMAGE_EDIT')) return;\n\n var canShowImagePreview = query('GET_ALLOW_IMAGE_PREVIEW');\n\n // only run for either the file or the file info panel\n var shouldExtendView =\n (is('file-info') && !canShowImagePreview) ||\n (is('file') && canShowImagePreview);\n\n if (!shouldExtendView) return;\n\n // no editor defined, then exit\n var editor = query('GET_IMAGE_EDIT_EDITOR');\n if (!editor) return;\n\n // set default FilePond options and add bridge once\n if (!editor.filepondCallbackBridge) {\n editor.outputData = true;\n editor.outputFile = false;\n editor.filepondCallbackBridge = {\n onconfirm: editor.onconfirm || function() {},\n oncancel: editor.oncancel || function() {}\n };\n }\n\n // opens the editor, if it does not already exist, it creates the editor\n var openEditor = function openEditor(_ref4) {\n var root = _ref4.root,\n props = _ref4.props,\n action = _ref4.action;\n var id = props.id;\n var handleEditorResponse = action.handleEditorResponse;\n\n // update editor props that could have changed\n editor.cropAspectRatio =\n root.query('GET_IMAGE_CROP_ASPECT_RATIO') || editor.cropAspectRatio;\n editor.outputCanvasBackgroundColor =\n root.query('GET_IMAGE_TRANSFORM_CANVAS_BACKGROUND_COLOR') ||\n editor.outputCanvasBackgroundColor;\n\n // get item\n var item = root.query('GET_ITEM', id);\n if (!item) return;\n\n // file to open\n var file = item.file;\n\n // crop data to pass to editor\n var crop = item.getMetadata('crop');\n var cropDefault = {\n center: {\n x: 0.5,\n y: 0.5\n },\n\n flip: {\n horizontal: false,\n vertical: false\n },\n\n zoom: 1,\n rotation: 0,\n aspectRatio: null\n };\n\n // size data to pass to editor\n var resize = item.getMetadata('resize');\n\n // filter and color data to pass to editor\n var filter = item.getMetadata('filter') || null;\n var filters = item.getMetadata('filters') || null;\n var colors = item.getMetadata('colors') || null;\n var markup = item.getMetadata('markup') || null;\n\n // build parameters object\n var imageParameters = {\n crop: crop || cropDefault,\n size: resize\n ? {\n upscale: resize.upscale,\n mode: resize.mode,\n width: resize.size.width,\n height: resize.size.height\n }\n : null,\n filter: filters\n ? filters.id || filters.matrix\n : root.query('GET_ALLOW_IMAGE_FILTER') &&\n root.query('GET_IMAGE_FILTER_COLOR_MATRIX') &&\n !colors\n ? filter\n : null,\n color: colors,\n markup: markup\n };\n\n editor.onconfirm = function(_ref5) {\n var data = _ref5.data;\n var crop = data.crop,\n size = data.size,\n filter = data.filter,\n color = data.color,\n colorMatrix = data.colorMatrix,\n markup = data.markup;\n\n // create new metadata object\n var metadata = {};\n\n // append crop data\n if (crop) {\n metadata.crop = crop;\n }\n\n // append size data\n if (size) {\n var initialSize = (item.getMetadata('resize') || {}).size;\n var targetSize = {\n width: size.width,\n height: size.height\n };\n\n if (!(targetSize.width && targetSize.height) && initialSize) {\n targetSize.width = initialSize.width;\n targetSize.height = initialSize.height;\n }\n\n if (targetSize.width || targetSize.height) {\n metadata.resize = {\n upscale: size.upscale,\n mode: size.mode,\n size: targetSize\n };\n }\n }\n\n if (markup) {\n metadata.markup = markup;\n }\n\n // set filters and colors so we can restore them when re-editing the image\n metadata.colors = color;\n metadata.filters = filter;\n\n // set merged color matrix to use in preview plugin\n metadata.filter = colorMatrix;\n\n // update crop metadata\n item.setMetadata(metadata);\n\n // call\n editor.filepondCallbackBridge.onconfirm(data, createItemAPI(item));\n\n // used in instant edit mode\n if (!handleEditorResponse) return;\n editor.onclose = function() {\n handleEditorResponse(true);\n editor.onclose = null;\n };\n };\n\n editor.oncancel = function() {\n // call\n editor.filepondCallbackBridge.oncancel(createItemAPI(item));\n\n // used in instant edit mode\n if (!handleEditorResponse) return;\n editor.onclose = function() {\n handleEditorResponse(false);\n editor.onclose = null;\n };\n };\n\n editor.open(file, imageParameters);\n };\n\n /**\n * Image Preview related\n */\n\n // create the image edit plugin, but only do so if the item is an image\n var didLoadItem = function didLoadItem(_ref6) {\n var root = _ref6.root,\n props = _ref6.props;\n\n if (!query('GET_IMAGE_EDIT_ALLOW_EDIT')) return;\n var id = props.id;\n\n // try to access item\n var item = query('GET_ITEM', id);\n if (!item) return;\n\n // get the file object\n var file = item.file;\n\n // exit if this is not an image\n if (!isPreviewableImage(file)) return;\n\n // handle interactions\n root.ref.handleEdit = function(e) {\n e.stopPropagation();\n root.dispatch('EDIT_ITEM', { id: id });\n };\n\n if (canShowImagePreview) {\n // add edit button to preview\n var buttonView = view.createChildView(fileActionButton, {\n label: 'edit',\n icon: query('GET_IMAGE_EDIT_ICON_EDIT'),\n opacity: 0\n });\n\n // edit item classname\n buttonView.element.classList.add('filepond--action-edit-item');\n buttonView.element.dataset.align = query(\n 'GET_STYLE_IMAGE_EDIT_BUTTON_EDIT_ITEM_POSITION'\n );\n buttonView.on('click', root.ref.handleEdit);\n\n root.ref.buttonEditItem = view.appendChildView(buttonView);\n } else {\n // view is file info\n var filenameElement = view.element.querySelector(\n '.filepond--file-info-main'\n );\n var editButton = document.createElement('button');\n editButton.className = 'filepond--action-edit-item-alt';\n editButton.innerHTML =\n query('GET_IMAGE_EDIT_ICON_EDIT') + 'edit';\n editButton.addEventListener('click', root.ref.handleEdit);\n filenameElement.appendChild(editButton);\n\n root.ref.editButton = editButton;\n }\n };\n\n view.registerDestroyer(function(_ref7) {\n var root = _ref7.root;\n if (root.ref.buttonEditItem) {\n root.ref.buttonEditItem.off('click', root.ref.handleEdit);\n }\n if (root.ref.editButton) {\n root.ref.editButton.removeEventListener('click', root.ref.handleEdit);\n }\n });\n\n var routes = {\n EDIT_ITEM: openEditor,\n DID_LOAD_ITEM: didLoadItem\n };\n\n if (canShowImagePreview) {\n // view is file\n var didPreviewUpdate = function didPreviewUpdate(_ref8) {\n var root = _ref8.root;\n if (!root.ref.buttonEditItem) return;\n root.ref.buttonEditItem.opacity = 1;\n };\n\n routes.DID_IMAGE_PREVIEW_SHOW = didPreviewUpdate;\n } else {\n }\n\n // start writing\n view.registerWriter(createRoute(routes));\n });\n\n // Expose plugin options\n return {\n options: {\n // enable or disable image editing\n allowImageEdit: [true, Type.BOOLEAN],\n\n // location of processing button\n styleImageEditButtonEditItemPosition: ['bottom center', Type.STRING],\n\n // open editor when image is dropped\n imageEditInstantEdit: [false, Type.BOOLEAN],\n\n // allow editing\n imageEditAllowEdit: [true, Type.BOOLEAN],\n\n // the icon to use for the edit button\n imageEditIconEdit: [\n '',\n Type.STRING\n ],\n\n // editor object\n imageEditEditor: [null, Type.OBJECT]\n }\n };\n };\n\n // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags\n var isBrowser =\n typeof window !== 'undefined' && typeof window.document !== 'undefined';\n if (isBrowser) {\n document.dispatchEvent(\n new CustomEvent('FilePond:pluginloaded', { detail: plugin })\n );\n }\n\n return plugin;\n});\n"],"sourceRoot":""}