import { p as proxyCustomElement, H, c as createEvent, h, d as Host } from './p-D16h8pzh.js';
import { g as getDefaultExportFromCjs } from './p-BFTU3MAI.js';
import { VerdocsEndpoint, getTemplate, updateTemplateRole, createTemplateRole, formatFullName } from '@verdocs/js-sdk';
import { S as SDKError } from './p-C1sRVZWv.js';
import { S as Store } from './p-DmsV595e.js';
import { d as defineCustomElement$8 } from './p-BNrp2UP2.js';
import { d as defineCustomElement$7 } from './p-DsCKNQPC.js';
import { d as defineCustomElement$6 } from './p-BGZ_owBm.js';
import { d as defineCustomElement$5 } from './p-Bv-L0hsU.js';
import { d as defineCustomElement$4 } from './p-BQW1cLII.js';
import { d as defineCustomElement$3 } from './p-Cy-AXBKH.js';
import { d as defineCustomElement$2 } from './p-zcZJDJyB.js';
import { d as defineCustomElement$1 } from './p-C_SISdpZ.js';

var Sortable_min$1 = {exports: {}};

/*! Sortable 1.15.6 - MIT | git://github.com/SortableJS/Sortable.git */
var Sortable_min = Sortable_min$1.exports;

var hasRequiredSortable_min;

function requireSortable_min () {
	if (hasRequiredSortable_min) return Sortable_min$1.exports;
	hasRequiredSortable_min = 1;
	(function (module, exports) {
		!function(t,e){module.exports=e();}(Sortable_min,function(){function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?e(Object(i),true).forEach(function(t){var e,n;e=o,t=i[n=t],n in e?Object.defineProperty(e,n,{value:t,enumerable:true,configurable:true,writable:true}):e[n]=t;}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach(function(t){Object.defineProperty(o,t,Object.getOwnPropertyDescriptor(i,t));});}return o}function o(t){return (o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(){return (a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,o=arguments[e];for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[n]=o[n]);}return t}).apply(this,arguments)}function i(t,e){if(null==t)return {};var n,o=function(t,e){if(null==t)return {};for(var n,o={},i=Object.keys(t),r=0;r<i.length;r++)n=i[r],0<=e.indexOf(n)||(o[n]=t[n]);return o}(t,e);if(Object.getOwnPropertySymbols)for(var i=Object.getOwnPropertySymbols(t),r=0;r<i.length;r++)n=i[r],0<=e.indexOf(n)||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n]);return o}function r(t){return function(t){if(Array.isArray(t))return l(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return l(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Map"===(n="Object"===n&&t.constructor?t.constructor.name:n)||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?l(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,o=new Array(e);n<e;n++)o[n]=t[n];return o}function t(t){if("undefined"!=typeof window&&window.navigator)return !!navigator.userAgent.match(t)}var y=t(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),w=t(/Edge/i),s=t(/firefox/i),u=t(/safari/i)&&!t(/chrome/i)&&!t(/android/i),c=t(/iP(ad|od|hone)/i),n=t(/chrome/i)&&t(/android/i),d={capture:false,passive:false};function h(t,e,n){t.addEventListener(e,n,!y&&d);}function p(t,e,n){t.removeEventListener(e,n,!y&&d);}function f(t,e){if(e&&(">"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function g(t){return t.host&&t!==document&&t.host.nodeType?t.host:t.parentNode}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&f(t,e)||o&&t===n)return t}while(t!==n&&(t=g(t)))}return null}var m,v=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(v," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(v," ")));}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px");}}function b(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform");}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function D(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i<r;i++)n(o[i],i);return o}return []}function O(){var t=document.scrollingElement;return t||document.documentElement}function X(t,e,n,o,i){if(t.getBoundingClientRect||t===window){var r,a,l,s,c,u,d=t!==window&&t.parentNode&&t!==O()?(a=(r=t.getBoundingClientRect()).top,l=r.left,s=r.bottom,c=r.right,u=r.height,r.width):(l=a=0,s=window.innerHeight,c=window.innerWidth,u=window.innerHeight,window.innerWidth);if((e||n)&&t!==window&&(i=i||t.parentNode,!y))do{if(i&&i.getBoundingClientRect&&("none"!==R(i,"transform")||n&&"static"!==R(i,"position"))){var h=i.getBoundingClientRect();a-=h.top+parseInt(R(i,"border-top-width")),l-=h.left+parseInt(R(i,"border-left-width")),s=a+r.height,c=l+r.width;break}}while(i=i.parentNode);return o&&t!==window&&(o=(e=b(i||t))&&e.a,t=e&&e.d,e&&(s=(a/=t)+(u/=t),c=(l/=o)+(d/=o))),{top:a,left:l,bottom:s,right:c,width:d,height:u}}}function Y(t,e,n){for(var o=M(t,true),i=X(t)[e];o;){var r=X(o)[n];if(!(r<=i))return o;if(o===O())break;o=M(o,false);}return  false}function B(t,e,n,o){for(var i=0,r=0,a=t.children;r<a.length;){if("none"!==a[r].style.display&&a[r]!==jt.ghost&&(o||a[r]!==jt.dragged)&&P(a[r],n.draggable,t,false)){if(i===e)return a[r];i++;}r++;}return null}function F(t,e){for(var n=t.lastElementChild;n&&(n===jt.ghost||"none"===R(n,"display")||e&&!f(n,e));)n=n.previousElementSibling;return n||null}function j(t,e){var n=0;if(!t||!t.parentNode)return  -1;for(;t=t.previousElementSibling;)"TEMPLATE"===t.nodeName.toUpperCase()||t===jt.clone||e&&!f(t,e)||n++;return n}function E(t){var e=0,n=0,o=O();if(t)do{var i=b(t),r=i.a,i=i.d;}while(e+=t.scrollLeft*r,n+=t.scrollTop*i,t!==o&&(t=t.parentNode));return [e,n]}function M(t,e){if(!t||!t.getBoundingClientRect)return O();var n=t,o=false;do{if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=R(n);if(n.clientWidth<n.scrollWidth&&("auto"==i.overflowX||"scroll"==i.overflowX)||n.clientHeight<n.scrollHeight&&("auto"==i.overflowY||"scroll"==i.overflowY)){if(!n.getBoundingClientRect||n===document.body)return O();if(o||e)return n;o=true;}}}while(n=n.parentNode);return O()}function S(t,e){return Math.round(t.top)===Math.round(e.top)&&Math.round(t.left)===Math.round(e.left)&&Math.round(t.height)===Math.round(e.height)&&Math.round(t.width)===Math.round(e.width)}function _(e,n){return function(){var t;m||(1===(t=arguments).length?e.call(this,t[0]):e.apply(this,t),m=setTimeout(function(){m=void 0;},n));}}function H(t,e,n){t.scrollLeft+=e,t.scrollTop+=n;}function C(t){var e=window.Polymer,n=window.jQuery||window.Zepto;return e&&e.dom?e.dom(t).cloneNode(true):n?n(t).clone(true)[0]:t.cloneNode(true)}function T(t,e){R(t,"position","absolute"),R(t,"top",e.top),R(t,"left",e.left),R(t,"width",e.width),R(t,"height",e.height);}function x(t){R(t,"position",""),R(t,"top",""),R(t,"left",""),R(t,"width",""),R(t,"height","");}function L(n,o,i){var r={};return Array.from(n.children).forEach(function(t){var e;P(t,o.draggable,n,false)&&!t.animated&&t!==i&&(e=X(t),r.left=Math.min(null!==(t=r.left)&&void 0!==t?t:1/0,e.left),r.top=Math.min(null!==(t=r.top)&&void 0!==t?t:1/0,e.top),r.right=Math.max(null!==(t=r.right)&&void 0!==t?t:-1/0,e.right),r.bottom=Math.max(null!==(t=r.bottom)&&void 0!==t?t:-1/0,e.bottom));}),r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}var K="Sortable"+(new Date).getTime();function A(){var e,o=[];return {captureAnimationState:function(){o=[],this.options.animation&&[].slice.call(this.el.children).forEach(function(t){var e,n;"none"!==R(t,"display")&&t!==jt.ghost&&(o.push({target:t,rect:X(t)}),e=I({},o[o.length-1].rect),!t.thisAnimationDuration||(n=b(t,true))&&(e.top-=n.f,e.left-=n.e),t.fromRect=e);});},addAnimationState:function(t){o.push(t);},removeAnimationState:function(t){o.splice(function(t,e){for(var n in t)if(t.hasOwnProperty(n))for(var o in e)if(e.hasOwnProperty(o)&&e[o]===t[n][o])return Number(n);return  -1}(o,{target:t}),1);},animateAll:function(t){var c=this;if(!this.options.animation)return clearTimeout(e),void("function"==typeof t&&t());var u=false,d=0;o.forEach(function(t){var e=0,n=t.target,o=n.fromRect,i=X(n),r=n.prevFromRect,a=n.prevToRect,l=t.rect,s=b(n,true);s&&(i.top-=s.f,i.left-=s.e),n.toRect=i,n.thisAnimationDuration&&S(r,i)&&!S(o,i)&&(l.top-i.top)/(l.left-i.left)==(o.top-i.top)/(o.left-i.left)&&(t=l,s=r,r=a,a=c.options,e=Math.sqrt(Math.pow(s.top-t.top,2)+Math.pow(s.left-t.left,2))/Math.sqrt(Math.pow(s.top-r.top,2)+Math.pow(s.left-r.left,2))*a.animation),S(i,o)||(n.prevFromRect=o,n.prevToRect=i,e=e||c.options.animation,c.animate(n,l,i,e)),e&&(u=true,d=Math.max(d,e),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null;},e),n.thisAnimationDuration=e);}),clearTimeout(e),u?e=setTimeout(function(){"function"==typeof t&&t();},d):"function"==typeof t&&t(),o=[];},animate:function(t,e,n,o){var i,r;o&&(R(t,"transition",""),R(t,"transform",""),i=(r=b(this.el))&&r.a,r=r&&r.d,i=(e.left-n.left)/(i||1),r=(e.top-n.top)/(r||1),t.animatingX=!!i,t.animatingY=!!r,R(t,"transform","translate3d("+i+"px,"+r+"px,0)"),this.forRepaintDummy=t.offsetWidth,R(t,"transition","transform "+o+"ms"+(this.options.easing?" "+this.options.easing:"")),R(t,"transform","translate3d(0,0,0)"),"number"==typeof t.animated&&clearTimeout(t.animated),t.animated=setTimeout(function(){R(t,"transition",""),R(t,"transform",""),t.animated=false,t.animatingX=false,t.animatingY=false;},o));}}}var N=[],W={initializeByDefault:true},z={mount:function(e){for(var t in W)!W.hasOwnProperty(t)||t in e||(e[t]=W[t]);N.forEach(function(t){if(t.pluginName===e.pluginName)throw "Sortable: Cannot mount plugin ".concat(e.pluginName," more than once")}),N.push(e);},pluginEvent:function(e,n,o){var t=this;this.eventCanceled=false,o.cancel=function(){t.eventCanceled=true;};var i=e+"Global";N.forEach(function(t){n[t.pluginName]&&(n[t.pluginName][i]&&n[t.pluginName][i](I({sortable:n},o)),n.options[t.pluginName]&&n[t.pluginName][e]&&n[t.pluginName][e](I({sortable:n},o)));});},initializePlugins:function(n,o,i,t){for(var e in N.forEach(function(t){var e=t.pluginName;(n.options[e]||t.initializeByDefault)&&((t=new t(n,o,n.options)).sortable=n,t.options=n.options,n[e]=t,a(i,t.defaults));}),n.options){var r;n.options.hasOwnProperty(e)&&(void 0!==(r=this.modifyOption(n,e,n.options[e]))&&(n.options[e]=r));}},getEventProperties:function(e,n){var o={};return N.forEach(function(t){"function"==typeof t.eventProperties&&a(o,t.eventProperties.call(n[t.pluginName],e));}),o},modifyOption:function(e,n,o){var i;return N.forEach(function(t){e[t.pluginName]&&t.optionListeners&&"function"==typeof t.optionListeners[n]&&(i=t.optionListeners[n].call(e[t.pluginName],o));}),i}};function G(t){var e=t.sortable,n=t.rootEl,o=t.name,i=t.targetEl,r=t.cloneEl,a=t.toEl,l=t.fromEl,s=t.oldIndex,c=t.newIndex,u=t.oldDraggableIndex,d=t.newDraggableIndex,h=t.originalEvent,p=t.putSortable,f=t.extraEventProperties;if(e=e||n&&n[K]){var g,m=e.options,t="on"+o.charAt(0).toUpperCase()+o.substr(1);!window.CustomEvent||y||w?(g=document.createEvent("Event")).initEvent(o,true,true):g=new CustomEvent(o,{bubbles:true,cancelable:true}),g.to=a||n,g.from=l||n,g.item=i||n,g.clone=r,g.oldIndex=s,g.newIndex=c,g.oldDraggableIndex=u,g.newDraggableIndex=d,g.originalEvent=h,g.pullMode=p?p.lastPutMode:void 0;var v,b=I(I({},f),z.getEventProperties(o,e));for(v in b)g[v]=b[v];n&&n.dispatchEvent(g),m[t]&&m[t].call(e,g);}}function U(t,e){var n=(o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{}).evt,o=i(o,q);z.pluginEvent.bind(jt)(t,e,I({dragEl:Z,parentEl:$,ghostEl:Q,rootEl:J,nextEl:tt,lastDownEl:et,cloneEl:nt,cloneHidden:ot,dragStarted:mt,putSortable:ct,activeSortable:jt.active,originalEvent:n,oldIndex:it,oldDraggableIndex:at,newIndex:rt,newDraggableIndex:lt,hideGhostForTarget:Xt,unhideGhostForTarget:Yt,cloneNowHidden:function(){ot=true;},cloneNowShown:function(){ot=false;},dispatchSortableEvent:function(t){V({sortable:e,name:t,originalEvent:n});}},o));}var q=["evt"];function V(t){G(I({putSortable:ct,cloneEl:nt,targetEl:Z,rootEl:J,oldIndex:it,oldDraggableIndex:at,newIndex:rt,newDraggableIndex:lt},t));}var Z,$,Q,J,tt,et,nt,ot,it,rt,at,lt,st,ct,ut,dt,ht,pt,ft,gt,mt,vt,bt,yt,wt,Dt=false,Et=false,St=[],_t=false,Ct=false,Tt=[],xt=false,Ot=[],Mt="undefined"!=typeof document,At=c,Nt=w||y?"cssFloat":"float",It=Mt&&!n&&!c&&"draggable"in document.createElement("div"),Pt=function(){if(Mt){if(y)return  false;var t=document.createElement("x");return t.style.cssText="pointer-events:auto","auto"===t.style.pointerEvents}}(),kt=function(t,e){var n=R(t),o=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=B(t,0,e),r=B(t,1,e),a=i&&R(i),l=r&&R(r),s=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+X(i).width,t=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+X(r).width;if("flex"===n.display)return "column"===n.flexDirection||"column-reverse"===n.flexDirection?"vertical":"horizontal";if("grid"===n.display)return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(i&&a.float&&"none"!==a.float){e="left"===a.float?"left":"right";return !r||"both"!==l.clear&&l.clear!==e?"horizontal":"vertical"}return i&&("block"===a.display||"flex"===a.display||"table"===a.display||"grid"===a.display||o<=s&&"none"===n[Nt]||r&&"none"===n[Nt]&&o<s+t)?"vertical":"horizontal"},Rt=function(t){function l(r,a){return function(t,e,n,o){var i=t.options.group.name&&e.options.group.name&&t.options.group.name===e.options.group.name;if(null==r&&(a||i))return  true;if(null==r||false===r)return  false;if(a&&"clone"===r)return r;if("function"==typeof r)return l(r(t,e,n,o),a)(t,e,n,o);e=(a?t:e).options.group.name;return  true===r||"string"==typeof r&&r===e||r.join&&-1<r.indexOf(e)}}var e={},n=t.group;n&&"object"==o(n)||(n={name:n}),e.name=n.name,e.checkPull=l(n.pull,true),e.checkPut=l(n.put),e.revertClone=n.revertClone,t.group=e;},Xt=function(){!Pt&&Q&&R(Q,"display","none");},Yt=function(){!Pt&&Q&&R(Q,"display","");};Mt&&!n&&document.addEventListener("click",function(t){if(Et)return t.preventDefault(),t.stopPropagation&&t.stopPropagation(),t.stopImmediatePropagation&&t.stopImmediatePropagation(),Et=false},true);function Bt(t){if(Z){t=t.touches?t.touches[0]:t;var e=(i=t.clientX,r=t.clientY,St.some(function(t){var e=t[K].options.emptyInsertThreshold;if(e&&!F(t)){var n=X(t),o=i>=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o);}}var i,r,a;}function Ft(t){Z&&Z.parentNode[K]._isOutsideThisEl(t.target);}function jt(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:true,disabled:false,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:false,invertedSwapThreshold:null,removeCloneOnHide:true,direction:function(){return kt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:true,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent);},dropBubble:false,dragoverBubble:false,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:false,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:false,fallbackClass:"sortable-fallback",fallbackOnBody:false,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:false!==jt.supportPointer&&"PointerEvent"in window&&(!u||c),emptyInsertThreshold:5};for(n in z.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in Rt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&It,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),St.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,A());}function Ht(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return !window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",true,true):s=new CustomEvent("move",{bubbles:true,cancelable:true}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Lt(t){t.draggable=false;}function Kt(){xt=false;}function Wt(t){return setTimeout(t,0)}function zt(t){return clearTimeout(t)}jt.prototype={constructor:jt,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(vt=null);},_getDirection:function(t,e){return "function"==typeof this.options.direction?this.options.direction.call(this,t,e,Z):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){Ot.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&Ot.push(o);}}(o),!Z&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,false))&&l.animated||et===l)){if(it=j(l),at=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return V({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),U("filter",n,{evt:e}),void(i&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,false))return V({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),U("filter",n,{evt:e}),true}))return void(i&&e.preventDefault());t.handle&&!P(s,t.handle,o,false)||this._prepareDragStart(e,a,l);}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!Z&&n.parentNode===r&&(o=X(n),J=r,$=(Z=n).parentNode,tt=Z.nextSibling,et=n,st=a.group,ut={target:jt.dragged=Z,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ut.clientX-o.left,gt=ut.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,Z.style["will-change"]="all",o=function(){U("delayEnded",i,{evt:t}),jt.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(Z.draggable=true),i._triggerDragStart(t,e),V({sortable:i,name:"choose",originalEvent:t}),k(Z,a.chosenClass,true));},a.ignore.split(",").forEach(function(t){D(Z,t.trim(),Lt);}),h(l,"dragover",Bt),h(l,"mousemove",Bt),h(l,"touchmove",Bt),a.supportPointer?(h(l,"pointerup",i._onDrop),this.nativeDraggable||h(l,"pointercancel",i._onDrop)):(h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop)),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,Z.draggable=true),U("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():jt.eventCanceled?this._onDrop():(a.supportPointer?(h(l,"pointerup",i._disableDelayedDrag),h(l,"pointercancel",i._disableDelayedDrag)):(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag)),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)));},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag();},_disableDelayedDrag:function(){Z&&Lt(Z),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents();},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;p(t,"mouseup",this._disableDelayedDrag),p(t,"touchend",this._disableDelayedDrag),p(t,"touchcancel",this._disableDelayedDrag),p(t,"pointerup",this._disableDelayedDrag),p(t,"pointercancel",this._disableDelayedDrag),p(t,"mousemove",this._delayedDragTouchMoveHandler),p(t,"touchmove",this._delayedDragTouchMoveHandler),p(t,"pointermove",this._delayedDragTouchMoveHandler);},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(Z,"dragend",this),h(J,"dragstart",this._onDragStart));try{document.selection?Wt(function(){document.selection.empty();}):window.getSelection().removeAllRanges();}catch(t){}},_dragStarted:function(t,e){var n;Dt=false,J&&Z?(U("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Ft),n=this.options,t||k(Z,n.dragClass,false),k(Z,n.ghostClass,true),jt.active=this,t&&this._appendGhost(),V({sortable:this,name:"start",originalEvent:e})):this._nulling();},_emulateDragOver:function(){if(dt){this._lastX=dt.clientX,this._lastY=dt.clientY,Xt();for(var t=document.elementFromPoint(dt.clientX,dt.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(dt.clientX,dt.clientY))!==e;)e=t;if(Z.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:dt.clientX,clientY:dt.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=g(t=e));Yt();}},_onTouchMove:function(t){if(ut){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=Q&&b(Q,true),a=Q&&r&&r.a,l=Q&&r&&r.d,e=At&&wt&&E(wt),a=(i.clientX-ut.clientX+o.x)/(a||1)+(e?e[0]-Tt[0]:0)/(a||1),l=(i.clientY-ut.clientY+o.y)/(l||1)+(e?e[1]-Tt[1]:0)/(l||1);if(!jt.active&&!Dt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(t,true);}Q&&(r?(r.e+=a-(ht||0),r.f+=l-(pt||0)):r={a:1,b:0,c:0,d:1,e:a,f:l},r="matrix(".concat(r.a,",").concat(r.b,",").concat(r.c,",").concat(r.d,",").concat(r.e,",").concat(r.f,")"),R(Q,"webkitTransform",r),R(Q,"mozTransform",r),R(Q,"msTransform",r),R(Q,"transform",r),ht=a,pt=l,dt=i),t.cancelable&&t.preventDefault();}},_appendGhost:function(){if(!Q){var t=this.options.fallbackOnBody?document.body:J,e=X(Z,true,At,true,t),n=this.options;if(At){for(wt=t;"static"===R(wt,"position")&&"none"===R(wt,"transform")&&wt!==document;)wt=wt.parentNode;wt!==document.body&&wt!==document.documentElement?(wt===document&&(wt=O()),e.top+=wt.scrollTop,e.left+=wt.scrollLeft):wt=O(),Tt=E(wt);}k(Q=Z.cloneNode(true),n.ghostClass,false),k(Q,n.fallbackClass,true),k(Q,n.dragClass,true),R(Q,"transition",""),R(Q,"transform",""),R(Q,"box-sizing","border-box"),R(Q,"margin",0),R(Q,"top",e.top),R(Q,"left",e.left),R(Q,"width",e.width),R(Q,"height",e.height),R(Q,"opacity","0.8"),R(Q,"position",At?"absolute":"fixed"),R(Q,"zIndex","100000"),R(Q,"pointerEvents","none"),jt.ghost=Q,t.appendChild(Q),R(Q,"transform-origin",ft/parseInt(Q.style.width)*100+"% "+gt/parseInt(Q.style.height)*100+"%");}},_onDragStart:function(t,e){var n=this,o=t.dataTransfer,i=n.options;U("dragStart",this,{evt:t}),jt.eventCanceled?this._onDrop():(U("setupClone",this),jt.eventCanceled||((nt=C(Z)).removeAttribute("id"),nt.draggable=false,nt.style["will-change"]="",this._hideClone(),k(nt,this.options.chosenClass,false),jt.clone=nt),n.cloneId=Wt(function(){U("clone",n),jt.eventCanceled||(n.options.removeCloneOnHide||J.insertBefore(nt,Z),n._hideClone(),V({sortable:n,name:"clone"}));}),e||k(Z,i.dragClass,true),e?(Et=true,n._loopId=setInterval(n._emulateDragOver,50)):(p(document,"mouseup",n._onDrop),p(document,"touchend",n._onDrop),p(document,"touchcancel",n._onDrop),o&&(o.effectAllowed="move",i.setData&&i.setData.call(n,o,Z)),h(document,"drop",n),R(Z,"transform","translateZ(0)")),Dt=true,n._dragStartId=Wt(n._dragStarted.bind(n,e,t)),h(document,"selectstart",n),mt=true,window.getSelection().removeAllRanges(),u&&R(document.body,"user-select","none"));},_onDragOver:function(n){var o,i,r,t,e,a=this.el,l=n.target,s=this.options,c=s.group,u=jt.active,d=st===c,h=s.sort,p=ct||u,f=this,g=false;if(!xt){if(void 0!==n.preventDefault&&n.cancelable&&n.preventDefault(),l=P(l,s.draggable,a,true),O("dragOver"),jt.eventCanceled)return g;if(Z.contains(n.target)||l.animated&&l.animatingX&&l.animatingY||f._ignoreWhileAnimating===l)return A(false);if(Et=false,u&&!s.disabled&&(d?h||(i=$!==J):ct===this||(this.lastPutMode=st.checkPull(this,u,Z,n))&&c.checkPut(this,u,Z,n))){if(r="vertical"===this._getDirection(n,l),o=X(Z),O("dragOverValid"),jt.eventCanceled)return g;if(i)return $=J,M(),this._hideClone(),O("revert"),jt.eventCanceled||(tt?J.insertBefore(Z,tt):J.appendChild(Z)),A(true);var m=F(a,s.draggable);if(m&&(S=n,c=r,x=X(F((E=this).el,E.options.draggable)),E=L(E.el,E.options,Q),!(c?S.clientX>E.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>E.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,true)),_=L(_.el,_.options,Q),e?t.clientX<_.left-10||t.clientY<C.top&&t.clientX<C.right:t.clientY<_.top-10||t.clientY<C.bottom&&t.clientX<C.left)){var v=B(a,0,s,true);if(v===Z)return A(false);if(D=X(l=v),false!==Ht(J,a,Z,o,l,D,n,false))return M(),a.insertBefore(Z,v),$=a,N(),A(true)}else if(l.parentNode===a){var b,y,w,D=X(l),E=Z.parentNode!==a,S=(S=Z.animated&&Z.toRect||o,x=l.animated&&l.toRect||D,_=(e=r)?S.left:S.top,t=e?S.right:S.bottom,C=e?S.width:S.height,v=e?x.left:x.top,S=e?x.right:x.bottom,x=e?x.width:x.height,!(_===v||t===S||_+C/2===v+x/2)),_=r?"top":"left",C=Y(l,"top","top")||Y(Z,"top","top"),v=C?C.scrollTop:void 0;if(vt!==l&&(y=D[_],_t=false,Ct=!S&&s.invertSwap||E),0!==(b=function(t,e,n,o,i,r,a,l){var s=o?t.clientY:t.clientX,c=o?n.height:n.width,t=o?n.top:n.left,o=o?n.bottom:n.right,n=false;if(!a)if(l&&yt<c*i){if(_t=!_t&&(1===bt?t+c*r/2<s:s<o-c*r/2)?true:_t)n=true;else if(1===bt?s<t+yt:o-yt<s)return -bt}else if(t+c*(1-i)/2<s&&s<o-c*(1-i)/2)return function(t){return j(Z)<j(t)?1:-1}(e);if((n=n||a)&&(s<t+c*r/2||o-c*r/2<s))return t+c/2<s?1:-1;return 0}(n,l,D,r,S?1:s.swapThreshold,null==s.invertedSwapThreshold?s.swapThreshold:s.invertedSwapThreshold,Ct,vt===l)))for(var T=j(Z);(w=$.children[T-=b])&&("none"===R(w,"display")||w===Q););if(0===b||w===l)return A(false);bt=b;var x=(vt=l).nextElementSibling,E=false,S=Ht(J,a,Z,o,l,D,n,E=1===b);if(false!==S)return 1!==S&&-1!==S||(E=1===S),xt=true,setTimeout(Kt,30),M(),E&&!x?a.appendChild(Z):l.parentNode.insertBefore(Z,E?x:l),C&&H(C,0,v-C.scrollTop),$=Z.parentNode,void 0===y||Ct||(yt=Math.abs(y-X(l)[_])),N(),A(true)}}else {if(m===Z)return A(false);if((l=m&&a===n.target?m:l)&&(D=X(l)),false!==Ht(J,a,Z,o,l,D,n,!!l))return M(),m&&m.nextSibling?a.insertBefore(Z,m.nextSibling):a.appendChild(Z),$=a,N(),A(true)}if(a.contains(Z))return A(false)}return  false}function O(t,e){U(t,f,I({evt:n,isOwner:d,axis:r?"vertical":"horizontal",revert:i,dragRect:o,targetRect:D,canSort:h,fromSortable:p,target:l,completed:A,onMove:function(t,e){return Ht(J,a,Z,o,t,X(t),n,e)},changed:N},e));}function M(){O("dragOverAnimationCapture"),f.captureAnimationState(),f!==p&&p.captureAnimationState();}function A(t){return O("dragOverCompleted",{insertion:t}),t&&(d?u._hideClone():u._showClone(f),f!==p&&(k(Z,(ct||u).options.ghostClass,false),k(Z,s.ghostClass,true)),ct!==f&&f!==jt.active?ct=f:f===jt.active&&ct&&(ct=null),p===f&&(f._ignoreWhileAnimating=l),f.animateAll(function(){O("dragOverAnimationComplete"),f._ignoreWhileAnimating=null;}),f!==p&&(p.animateAll(),p._ignoreWhileAnimating=null)),(l===Z&&!Z.animated||l===a&&!l.animated)&&(vt=null),s.dragoverBubble||n.rootEl||l===document||(Z.parentNode[K]._isOutsideThisEl(n.target),t||Bt(n)),!s.dragoverBubble&&n.stopPropagation&&n.stopPropagation(),g=true}function N(){rt=j(Z),lt=j(Z,s.draggable),V({sortable:f,name:"change",toEl:a,newIndex:rt,newDraggableIndex:lt,originalEvent:n});}},_ignoreWhileAnimating:null,_offMoveEvents:function(){p(document,"mousemove",this._onTouchMove),p(document,"touchmove",this._onTouchMove),p(document,"pointermove",this._onTouchMove),p(document,"dragover",Bt),p(document,"mousemove",Bt),p(document,"touchmove",Bt);},_offUpEvents:function(){var t=this.el.ownerDocument;p(t,"mouseup",this._onDrop),p(t,"touchend",this._onDrop),p(t,"pointerup",this._onDrop),p(t,"pointercancel",this._onDrop),p(t,"touchcancel",this._onDrop),p(document,"selectstart",this);},_onDrop:function(t){var e=this.el,n=this.options;rt=j(Z),lt=j(Z,n.draggable),U("drop",this,{evt:t}),$=Z&&Z.parentNode,rt=j(Z),lt=j(Z,n.draggable),jt.eventCanceled||(_t=Ct=Dt=false,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),zt(this.cloneId),zt(this._dragStartId),this.nativeDraggable&&(p(document,"drop",this),p(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),u&&R(document.body,"user-select",""),R(Z,"transform",""),t&&(mt&&(t.cancelable&&t.preventDefault(),n.dropBubble||t.stopPropagation()),Q&&Q.parentNode&&Q.parentNode.removeChild(Q),(J===$||ct&&"clone"!==ct.lastPutMode)&&nt&&nt.parentNode&&nt.parentNode.removeChild(nt),Z&&(this.nativeDraggable&&p(Z,"dragend",this),Lt(Z),Z.style["will-change"]="",mt&&!Dt&&k(Z,(ct||this).options.ghostClass,false),k(Z,this.options.chosenClass,false),V({sortable:this,name:"unchoose",toEl:$,newIndex:null,newDraggableIndex:null,originalEvent:t}),J!==$?(0<=rt&&(V({rootEl:$,name:"add",toEl:$,fromEl:J,originalEvent:t}),V({sortable:this,name:"remove",toEl:$,originalEvent:t}),V({rootEl:$,name:"sort",toEl:$,fromEl:J,originalEvent:t}),V({sortable:this,name:"sort",toEl:$,originalEvent:t})),ct&&ct.save()):rt!==it&&0<=rt&&(V({sortable:this,name:"update",toEl:$,originalEvent:t}),V({sortable:this,name:"sort",toEl:$,originalEvent:t})),jt.active&&(null!=rt&&-1!==rt||(rt=it,lt=at),V({sortable:this,name:"end",toEl:$,originalEvent:t}),this.save())))),this._nulling();},_nulling:function(){U("nulling",this),J=Z=$=Q=tt=nt=et=ot=ut=dt=mt=rt=lt=it=at=vt=bt=ct=st=jt.dragged=jt.ghost=jt.clone=jt.active=null,Ot.forEach(function(t){t.checked=true;}),Ot.length=ht=pt=0;},handleEvent:function(t){switch(t.type){case "drop":case "dragend":this._onDrop(t);break;case "dragenter":case "dragover":Z&&(this._onDragOver(t),function(t){t.dataTransfer&&(t.dataTransfer.dropEffect="move");t.cancelable&&t.preventDefault();}(t));break;case "selectstart":t.preventDefault();}},toArray:function(){for(var t,e=[],n=this.el.children,o=0,i=n.length,r=this.options;o<i;o++)P(t=n[o],r.draggable,this.el,false)&&e.push(t.getAttribute(r.dataIdAttr)||function(t){var e=t.tagName+t.className+t.src+t.href+t.textContent,n=e.length,o=0;for(;n--;)o+=e.charCodeAt(n);return o.toString(36)}(t));return e},sort:function(t,e){var n={},o=this.el;this.toArray().forEach(function(t,e){e=o.children[e];P(e,this.options.draggable,o,false)&&(n[t]=e);},this),e&&this.captureAnimationState(),t.forEach(function(t){n[t]&&(o.removeChild(n[t]),o.appendChild(n[t]));}),e&&this.animateAll();},save:function(){var t=this.options.store;t&&t.set&&t.set(this);},closest:function(t,e){return P(t,e||this.options.draggable,this.el,false)},option:function(t,e){var n=this.options;if(void 0===e)return n[t];var o=z.modifyOption(this,t,e);n[t]=void 0!==o?o:e,"group"===t&&Rt(n);},destroy:function(){U("destroy",this);var t=this.el;t[K]=null,p(t,"mousedown",this._onTapStart),p(t,"touchstart",this._onTapStart),p(t,"pointerdown",this._onTapStart),this.nativeDraggable&&(p(t,"dragover",this),p(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(t){t.removeAttribute("draggable");}),this._onDrop(),this._disableDelayedDragEvents(),St.splice(St.indexOf(this.el),1),this.el=t=null;},_hideClone:function(){ot||(U("hideClone",this),jt.eventCanceled||(R(nt,"display","none"),this.options.removeCloneOnHide&&nt.parentNode&&nt.parentNode.removeChild(nt),ot=true));},_showClone:function(t){"clone"===t.lastPutMode?ot&&(U("showClone",this),jt.eventCanceled||(Z.parentNode!=J||this.options.group.revertClone?tt?J.insertBefore(nt,tt):J.appendChild(nt):J.insertBefore(nt,Z),this.options.group.revertClone&&this.animate(Z,nt),R(nt,"display",""),ot=false)):this._hideClone();}},Mt&&h(document,"touchmove",function(t){(jt.active||Dt)&&t.cancelable&&t.preventDefault();}),jt.utils={on:h,off:p,css:R,find:D,is:function(t,e){return !!P(t,e,t,false)},extend:function(t,e){if(t&&e)for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},throttle:_,closest:P,toggleClass:k,clone:C,index:j,nextTick:Wt,cancelNextTick:zt,detectDirection:kt,getChild:B,expando:K},jt.get=function(t){return t[K]},jt.mount=function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];(e=e[0].constructor===Array?e[0]:e).forEach(function(t){if(!t.prototype||!t.prototype.constructor)throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(t));t.utils&&(jt.utils=I(I({},jt.utils),t.utils)),z.mount(t);});},jt.create=function(t,e){return new jt(t,e)};var Gt,Ut,qt,Vt,Zt,$t,Qt=[],Jt=!(jt.version="1.15.6");function te(){Qt.forEach(function(t){clearInterval(t.pid);}),Qt=[];}function ee(){clearInterval($t);}var ne,oe=_(function(n,t,e,o){if(t.scroll){var i,r=(n.touches?n.touches[0]:n).clientX,a=(n.touches?n.touches[0]:n).clientY,l=t.scrollSensitivity,s=t.scrollSpeed,c=O(),u=false;Ut!==e&&(Ut=e,te(),Gt=t.scroll,i=t.scrollFn,true===Gt&&(Gt=M(e,true)));var d=0,h=Gt;do{var p=h,f=X(p),g=f.top,m=f.bottom,v=f.left,b=f.right,y=f.width,w=f.height,D=void 0,E=void 0,S=p.scrollWidth,_=p.scrollHeight,C=R(p),T=p.scrollLeft,f=p.scrollTop,E=p===c?(D=y<S&&("auto"===C.overflowX||"scroll"===C.overflowX||"visible"===C.overflowX),w<_&&("auto"===C.overflowY||"scroll"===C.overflowY||"visible"===C.overflowY)):(D=y<S&&("auto"===C.overflowX||"scroll"===C.overflowX),w<_&&("auto"===C.overflowY||"scroll"===C.overflowY)),T=D&&(Math.abs(b-r)<=l&&T+y<S)-(Math.abs(v-r)<=l&&!!T),f=E&&(Math.abs(m-a)<=l&&f+w<_)-(Math.abs(g-a)<=l&&!!f);if(!Qt[d])for(var x=0;x<=d;x++)Qt[x]||(Qt[x]={});Qt[d].vx==T&&Qt[d].vy==f&&Qt[d].el===p||(Qt[d].el=p,Qt[d].vx=T,Qt[d].vy=f,clearInterval(Qt[d].pid),0==T&&0==f||(u=true,Qt[d].pid=setInterval(function(){o&&0===this.layer&&jt.active._onTouchMove(Zt);var t=Qt[this.layer].vy?Qt[this.layer].vy*s:0,e=Qt[this.layer].vx?Qt[this.layer].vx*s:0;"function"==typeof i&&"continue"!==i.call(jt.dragged.parentNode[K],e,t,n,Zt,Qt[this.layer].el)||H(Qt[this.layer].el,e,t);}.bind({layer:d}),24))),d++;}while(t.bubbleScroll&&h!==c&&(h=M(h,false)));Jt=u;}},30),n=function(t){var e=t.originalEvent,n=t.putSortable,o=t.dragEl,i=t.activeSortable,r=t.dispatchSortableEvent,a=t.hideGhostForTarget,t=t.unhideGhostForTarget;e&&(i=n||i,a(),e=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,e=document.elementFromPoint(e.clientX,e.clientY),t(),i&&!i.el.contains(e)&&(r("spill"),this.onSpill({dragEl:o,putSortable:n})));};function ie(){}function re(){}ie.prototype={startIndex:null,dragStart:function(t){t=t.oldDraggableIndex;this.startIndex=t;},onSpill:function(t){var e=t.dragEl,n=t.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();t=B(this.sortable.el,this.startIndex,this.options);t?this.sortable.el.insertBefore(e,t):this.sortable.el.appendChild(e),this.sortable.animateAll(),n&&n.animateAll();},drop:n},a(ie,{pluginName:"revertOnSpill"}),re.prototype={onSpill:function(t){var e=t.dragEl,t=t.putSortable||this.sortable;t.captureAnimationState(),e.parentNode&&e.parentNode.removeChild(e),t.animateAll();},drop:n},a(re,{pluginName:"removeOnSpill"});var ae,le,se,ce,ue,de=[],he=[],pe=false,fe=false,ge=false;function me(n,o){he.forEach(function(t,e){e=o.children[t.sortableIndex+(n?Number(e):0)];e?o.insertBefore(t,e):o.appendChild(t);});}function ve(){de.forEach(function(t){t!==se&&t.parentNode&&t.parentNode.removeChild(t);});}return jt.mount(new function(){function t(){for(var t in this.defaults={scroll:true,forceAutoScrollFallback:false,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:true},this)"_"===t.charAt(0)&&"function"==typeof this[t]&&(this[t]=this[t].bind(this));}return t.prototype={dragStarted:function(t){t=t.originalEvent;this.sortable.nativeDraggable?h(document,"dragover",this._handleAutoScroll):this.options.supportPointer?h(document,"pointermove",this._handleFallbackAutoScroll):t.touches?h(document,"touchmove",this._handleFallbackAutoScroll):h(document,"mousemove",this._handleFallbackAutoScroll);},dragOverCompleted:function(t){t=t.originalEvent;this.options.dragOverBubble||t.rootEl||this._handleAutoScroll(t);},drop:function(){this.sortable.nativeDraggable?p(document,"dragover",this._handleAutoScroll):(p(document,"pointermove",this._handleFallbackAutoScroll),p(document,"touchmove",this._handleFallbackAutoScroll),p(document,"mousemove",this._handleFallbackAutoScroll)),ee(),te(),clearTimeout(m),m=void 0;},nulling:function(){Zt=Ut=Gt=Jt=$t=qt=Vt=null,Qt.length=0;},_handleFallbackAutoScroll:function(t){this._handleAutoScroll(t,true);},_handleAutoScroll:function(e,n){var o,i=this,r=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,t=document.elementFromPoint(r,a);Zt=e,n||this.options.forceAutoScrollFallback||w||y||u?(oe(e,this.options,t,n),o=M(t,true),!Jt||$t&&r===qt&&a===Vt||($t&&ee(),$t=setInterval(function(){var t=M(document.elementFromPoint(r,a),true);t!==o&&(o=t,te()),oe(e,i.options,t,n);},10),qt=r,Vt=a)):this.options.bubbleScroll&&M(t,true)!==O()?oe(e,this.options,M(t,false),false):te();}},a(t,{pluginName:"scroll",initializeByDefault:true})}),jt.mount(re,ie),jt.mount(new function(){function t(){this.defaults={swapClass:"sortable-swap-highlight"};}return t.prototype={dragStart:function(t){t=t.dragEl;ne=t;},dragOverValid:function(t){var e=t.completed,n=t.target,o=t.onMove,i=t.activeSortable,r=t.changed,a=t.cancel;i.options.swap&&(t=this.sortable.el,i=this.options,n&&n!==t&&(t=ne,ne=false!==o(n)?(k(n,i.swapClass,true),n):null,t&&t!==ne&&k(t,i.swapClass,false)),r(),e(true),a());},drop:function(t){var e,n,o=t.activeSortable,i=t.putSortable,r=t.dragEl,a=i||this.sortable,l=this.options;ne&&k(ne,l.swapClass,false),ne&&(l.swap||i&&i.options.swap)&&r!==ne&&(a.captureAnimationState(),a!==o&&o.captureAnimationState(),n=ne,t=(e=r).parentNode,l=n.parentNode,t&&l&&!t.isEqualNode(n)&&!l.isEqualNode(e)&&(i=j(e),r=j(n),t.isEqualNode(l)&&i<r&&r++,t.insertBefore(n,t.children[i]),l.insertBefore(e,l.children[r])),a.animateAll(),a!==o&&o.animateAll());},nulling:function(){ne=null;}},a(t,{pluginName:"swap",eventProperties:function(){return {swapItem:ne}}})}),jt.mount(new function(){function t(o){for(var t in this)"_"===t.charAt(0)&&"function"==typeof this[t]&&(this[t]=this[t].bind(this));o.options.avoidImplicitDeselect||(o.options.supportPointer?h(document,"pointerup",this._deselectMultiDrag):(h(document,"mouseup",this._deselectMultiDrag),h(document,"touchend",this._deselectMultiDrag))),h(document,"keydown",this._checkKeyDown),h(document,"keyup",this._checkKeyUp),this.defaults={selectedClass:"sortable-selected",multiDragKey:null,avoidImplicitDeselect:false,setData:function(t,e){var n="";de.length&&le===o?de.forEach(function(t,e){n+=(e?", ":"")+t.textContent;}):n=e.textContent,t.setData("Text",n);}};}return t.prototype={multiDragKeyDown:false,isMultiDrag:false,delayStartGlobal:function(t){t=t.dragEl;se=t;},delayEnded:function(){this.isMultiDrag=~de.indexOf(se);},setupClone:function(t){var e=t.sortable,t=t.cancel;if(this.isMultiDrag){for(var n=0;n<de.length;n++)he.push(C(de[n])),he[n].sortableIndex=de[n].sortableIndex,he[n].draggable=false,he[n].style["will-change"]="",k(he[n],this.options.selectedClass,false),de[n]===se&&k(he[n],this.options.chosenClass,false);e._hideClone(),t();}},clone:function(t){var e=t.sortable,n=t.rootEl,o=t.dispatchSortableEvent,t=t.cancel;this.isMultiDrag&&(this.options.removeCloneOnHide||de.length&&le===e&&(me(true,n),o("clone"),t()));},showClone:function(t){var e=t.cloneNowShown,n=t.rootEl,t=t.cancel;this.isMultiDrag&&(me(false,n),he.forEach(function(t){R(t,"display","");}),e(),ue=false,t());},hideClone:function(t){var e=this,n=(t.cloneNowHidden),t=t.cancel;this.isMultiDrag&&(he.forEach(function(t){R(t,"display","none"),e.options.removeCloneOnHide&&t.parentNode&&t.parentNode.removeChild(t);}),n(),ue=true,t());},dragStartGlobal:function(t){!this.isMultiDrag&&le&&le.multiDrag._deselectMultiDrag(),de.forEach(function(t){t.sortableIndex=j(t);}),de=de.sort(function(t,e){return t.sortableIndex-e.sortableIndex}),ge=true;},dragStarted:function(t){var e,n=this,t=t.sortable;this.isMultiDrag&&(this.options.sort&&(t.captureAnimationState(),this.options.animation&&(de.forEach(function(t){t!==se&&R(t,"position","absolute");}),e=X(se,false,true,true),de.forEach(function(t){t!==se&&T(t,e);}),pe=fe=true)),t.animateAll(function(){pe=fe=false,n.options.animation&&de.forEach(function(t){x(t);}),n.options.sort&&ve();}));},dragOver:function(t){var e=t.target,n=t.completed,t=t.cancel;fe&&~de.indexOf(e)&&(n(false),t());},revert:function(t){var n,o,e=t.fromSortable,i=t.rootEl,r=t.sortable,a=t.dragRect;1<de.length&&(de.forEach(function(t){r.addAnimationState({target:t,rect:fe?X(t):a}),x(t),t.fromRect=a,e.removeAnimationState(t);}),fe=false,n=!this.options.removeCloneOnHide,o=i,de.forEach(function(t,e){e=o.children[t.sortableIndex+(n?Number(e):0)];e?o.insertBefore(t,e):o.appendChild(t);}));},dragOverCompleted:function(t){var e,n=t.sortable,o=t.isOwner,i=t.insertion,r=t.activeSortable,a=t.parentEl,l=t.putSortable,t=this.options;i&&(o&&r._hideClone(),pe=false,t.animation&&1<de.length&&(fe||!o&&!r.options.sort&&!l)&&(e=X(se,false,true,true),de.forEach(function(t){t!==se&&(T(t,e),a.appendChild(t));}),fe=true),o||(fe||ve(),1<de.length?(o=ue,r._showClone(n),r.options.animation&&!ue&&o&&he.forEach(function(t){r.addAnimationState({target:t,rect:ce}),t.fromRect=ce,t.thisAnimationDuration=null;})):r._showClone(n)));},dragOverAnimationCapture:function(t){var e=t.dragRect,n=t.isOwner,t=t.activeSortable;de.forEach(function(t){t.thisAnimationDuration=null;}),t.options.animation&&!n&&t.multiDrag.isMultiDrag&&(ce=a({},e),e=b(se,true),ce.top-=e.f,ce.left-=e.e);},dragOverAnimationComplete:function(){fe&&(fe=false,ve());},drop:function(t){var o,i,r,a,n,e,l,s=t.originalEvent,c=t.rootEl,u=t.parentEl,d=t.sortable,h=t.dispatchSortableEvent,p=t.oldIndex,t=t.putSortable,f=t||this.sortable;s&&(o=this.options,i=u.children,ge||(o.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),k(se,o.selectedClass,!~de.indexOf(se)),~de.indexOf(se)?(de.splice(de.indexOf(se),1),ae=null,G({sortable:d,rootEl:c,name:"deselect",targetEl:se,originalEvent:s})):(de.push(se),G({sortable:d,rootEl:c,name:"select",targetEl:se,originalEvent:s}),s.shiftKey&&ae&&d.el.contains(ae)?(r=j(ae),a=j(se),~r&&~a&&r!==a&&function(){for(var e,t=r<a?(e=r,a):(e=a,r+1),n=o.filter;e<t;e++)~de.indexOf(i[e])||P(i[e],o.draggable,u,false)&&(n&&("function"==typeof n?n.call(d,s,i[e],d):n.split(",").some(function(t){return P(i[e],t.trim(),u,false)}))||(k(i[e],o.selectedClass,true),de.push(i[e]),G({sortable:d,rootEl:c,name:"select",targetEl:i[e],originalEvent:s})));}()):ae=se,le=f)),ge&&this.isMultiDrag&&(fe=false,(u[K].options.sort||u!==c)&&1<de.length&&(n=X(se),e=j(se,":not(."+this.options.selectedClass+")"),!pe&&o.animation&&(se.thisAnimationDuration=null),f.captureAnimationState(),pe||(o.animation&&(se.fromRect=n,de.forEach(function(t){var e;t.thisAnimationDuration=null,t!==se&&(e=fe?X(t):n,t.fromRect=e,f.addAnimationState({target:t,rect:e}));})),ve(),de.forEach(function(t){i[e]?u.insertBefore(t,i[e]):u.appendChild(t),e++;}),p===j(se)&&(l=false,de.forEach(function(t){t.sortableIndex!==j(t)&&(l=true);}),l&&(h("update"),h("sort")))),de.forEach(function(t){x(t);}),f.animateAll()),le=f),(c===u||t&&"clone"!==t.lastPutMode)&&he.forEach(function(t){t.parentNode&&t.parentNode.removeChild(t);}));},nullingGlobal:function(){this.isMultiDrag=ge=false,he.length=0;},destroyGlobal:function(){this._deselectMultiDrag(),p(document,"pointerup",this._deselectMultiDrag),p(document,"mouseup",this._deselectMultiDrag),p(document,"touchend",this._deselectMultiDrag),p(document,"keydown",this._checkKeyDown),p(document,"keyup",this._checkKeyUp);},_deselectMultiDrag:function(t){if(!(void 0!==ge&&ge||le!==this.sortable||t&&P(t.target,this.options.draggable,this.sortable.el,false)||t&&0!==t.button))for(;de.length;){var e=de[0];k(e,this.options.selectedClass,false),de.shift(),G({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:e,originalEvent:t});}},_checkKeyDown:function(t){t.key===this.options.multiDragKey&&(this.multiDragKeyDown=true);},_checkKeyUp:function(t){t.key===this.options.multiDragKey&&(this.multiDragKeyDown=false);}},a(t,{pluginName:"multiDrag",utils:{select:function(t){var e=t.parentNode[K];e&&e.options.multiDrag&&!~de.indexOf(t)&&(le&&le!==e&&(le.multiDrag._deselectMultiDrag(),le=e),k(t,e.options.selectedClass,true),de.push(t));},deselect:function(t){var e=t.parentNode[K],n=de.indexOf(t);e&&e.options.multiDrag&&~n&&(k(t,e.options.selectedClass,false),de.splice(n,1));}},eventProperties:function(){var n=this,o=[],i=[];return de.forEach(function(t){var e;o.push({multiDragElement:t,index:t.sortableIndex}),e=fe&&t!==se?-1:fe?j(t,":not(."+n.options.selectedClass+")"):j(t),i.push({multiDragElement:t,index:e});}),{items:r(de),clones:[].concat(he),oldIndicies:o,newIndicies:i}},optionListeners:{multiDragKey:function(t){return "ctrl"===(t=t.toLowerCase())?t="Control":1<t.length&&(t=t.charAt(0).toUpperCase()+t.substr(1)),t}}})}),jt}); 
	} (Sortable_min$1));
	return Sortable_min$1.exports;
}

var Sortable_minExports = requireSortable_min();
var Sortable = /*@__PURE__*/getDefaultExportFromCjs(Sortable_minExports);

const verdocsTemplateRolesCss = "@-webkit-keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}@keyframes verdocs-field-pulse{0%{background-color:rgba(0, 0, 0, 0.35)}50%{background-color:rgba(0, 0, 0, 0)}100%{background-color:rgba(0, 0, 0, 0.35)}}verdocs-template-roles{display:block;max-width:600px;font-family:\"Inter\", -apple-system, \"Segoe UI\", \"Roboto\", \"Helvetica Neue\", sans-serif}verdocs-template-roles .roles{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;gap:10px;margin-top:10px}verdocs-template-roles .roles .sequence{gap:10px;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;font-weight:500;padding:0 0 8px 0;-ms-flex-direction:row;flex-direction:row;border-bottom:1px dotted #e3e3e3}verdocs-template-roles .roles .sequence.add-sequence{color:#777777;line-height:34px}verdocs-template-roles .roles .sequence-label{font-size:18px;line-height:32px}verdocs-template-roles .roles .sequence-roles{gap:10px;display:-ms-flexbox;display:flex;position:relative;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-direction:row;flex-direction:row}verdocs-template-roles .roles .role{height:32px;cursor:move;display:-ms-flexbox;display:flex;max-width:200px;position:relative;border-radius:32px;background-color:#eff7fb;-webkit-box-sizing:border-box;box-sizing:border-box;padding:0 14px 0 34px;border:1px solid #ccc;-ms-flex-direction:column;flex-direction:column}verdocs-template-roles .roles .role .role-name{font-size:14px;overflow:hidden;font-weight:400;line-height:30px;white-space:nowrap;text-overflow:ellipsis}verdocs-template-roles .roles .role .icons{position:absolute;left:1px;top:-3px;cursor:pointer;padding:5px;z-index:10}verdocs-template-roles .roles .role .icons .gear-button{display:none;-webkit-transform:scale(1.1);transform:scale(1.1);margin:4px 0 0 1px}verdocs-template-roles .roles .role .icons .type-icon{opacity:0.6;display:block;-webkit-transform:scale(0.8);transform:scale(0.8)}verdocs-template-roles .roles .role .icons:hover .gear-button{display:block}verdocs-template-roles .roles .role .icons:hover .type-icon{display:none}verdocs-template-roles>form{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;background-color:#ffffff;padding:12px}verdocs-template-roles>form h5{font-size:16px;font-weight:bold;color:#46497d;margin:0 0 10px 0}verdocs-template-roles>form label{display:block;font-size:14px;font-weight:500;margin:0 0 4px 0;color:#5c6575}verdocs-template-roles>form input{border:none;font-size:18px;padding:3px 6px 3px 0;background:transparent;border-bottom:1px solid #33364b}verdocs-template-roles>form input:focus{outline:none}verdocs-template-roles .row.add-sequence{display:none}verdocs-template-roles .add-role{opacity:0.3;padding:0 10px;cursor:pointer;background:none;height:32px;border:1px solid #cccccc;border-radius:32px}verdocs-template-roles .add-role:hover{opacity:1}verdocs-template-roles .add-step{margin:0;padding:0;border:none;opacity:0.5;cursor:pointer;background:none}verdocs-template-roles .add-step:hover{opacity:1}verdocs-template-roles .add-step svg{width:32px;height:32px}verdocs-template-roles.dragging .row.add-sequence{display:-ms-flexbox;display:flex}verdocs-template-roles .buttons{display:-ms-flexbox;display:flex;-webkit-column-gap:8px;-moz-column-gap:8px;column-gap:8px;margin-top:16px;-ms-flex-direction:row;flex-direction:row}verdocs-template-roles .empty{font-size:13px;margin-top:15px;margin-bottom:5px}verdocs-template-roles .empty svg{width:16px;height:16px;stroke:#666666;margin-bottom:2px;display:inline-block}verdocs-template-roles .sequence-roles{display:-ms-flexbox;display:flex;max-width:400px}verdocs-template-roles ::-webkit-input-placeholder{color:#aaaaaa}verdocs-template-roles ::-moz-placeholder{color:#aaaaaa}verdocs-template-roles :-ms-input-placeholder{color:#aaaaaa}verdocs-template-roles ::-ms-input-placeholder{color:#aaaaaa}verdocs-template-roles ::placeholder{color:#aaaaaa}";

const settingsIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" fill="#00000089"><path d="m8.021 17.917-.313-2.5q-.27-.125-.625-.334-.354-.208-.625-.395l-2.312.979-1.979-3.438 1.979-1.5q-.021-.167-.031-.364-.011-.198-.011-.365 0-.146.011-.344.01-.198.031-.385l-1.979-1.5 1.979-3.417 2.312.958q.271-.187.615-.385t.635-.344l.313-2.5h3.958l.313 2.5q.312.167.625.344.312.177.604.385l2.333-.958 1.979 3.417-1.979 1.521q.021.187.021.364V10q0 .146-.01.333-.011.188-.011.396l1.958 1.5-1.979 3.438-2.312-.979q-.292.208-.615.395-.323.188-.614.334l-.313 2.5Zm1.937-5.355q1.063 0 1.813-.75t.75-1.812q0-1.062-.75-1.812t-1.813-.75q-1.041 0-1.802.75-.76.75-.76 1.812t.76 1.812q.761.75 1.802.75Zm0-1.333q-.5 0-.864-.364-.365-.365-.365-.865t.365-.865q.364-.364.864-.364t.865.364q.365.365.365.865t-.365.865q-.365.364-.865.364ZM10.021 10Zm-.854 6.583h1.666l.25-2.187q.605-.167 1.136-.49.531-.323 1.031-.802l2.021.875.854-1.375-1.792-1.354q.105-.333.136-.635.031-.303.031-.615 0-.292-.031-.573-.031-.281-.115-.635l1.792-1.396-.834-1.375-2.062.875q-.438-.438-1.021-.781-.583-.344-1.125-.49l-.271-2.208H9.167l-.271 2.208q-.584.146-1.125.458-.542.313-1.042.792l-2.021-.854-.833 1.375 1.75 1.354q-.083.333-.125.646-.042.312-.042.604t.042.594q.042.302.125.635l-1.75 1.375.833 1.375 2.021-.854q.479.458 1.021.771.542.312 1.146.479Z"/></svg>';
const plusIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="#ffffff" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>`;
const iconSigner = '<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.225 21.225 4.65-4.65h8.45v4.65Zm-5.35-2.2H5.05l8.5-8.5-1.175-1.175-8.5 8.5Zm14.25-9.95L13.8 4.8l1.325-1.325q.625-.65 1.525-.663.9-.012 1.6.663l1.225 1.175q.675.675.663 1.562-.013.888-.663 1.513ZM16.7 10.55 6 21.225H1.675V16.9L12.35 6.225Zm-3.725-.625-.6-.575 1.175 1.175Z"/></svg>';
const iconApprover = `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clip-rule="evenodd" /></svg>`;
const iconCC = `<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="M1.5 8.67v8.58a3 3 0 003 3h15a3 3 0 003-3V8.67l-8.928 5.493a3 3 0 01-3.144 0L1.5 8.67z" /><path d="M22.5 6.908V6.75a3 3 0 00-3-3h-15a3 3 0 00-3 3v.158l9.714 5.978a1.5 1.5 0 001.572 0L22.5 6.908z" /></svg>`;
const VerdocsTemplateRoles = /*@__PURE__*/ proxyCustomElement(class VerdocsTemplateRoles extends H {
    constructor() {
        super();
        this.__registerHost();
        this.next = createEvent(this, "next");
        this.exit = createEvent(this, "exit");
        this.sdkError = createEvent(this, "sdkError");
        this.rolesUpdated = createEvent(this, "rolesUpdated");
        this.templateListenerId = null;
        /**
         * The endpoint to use to communicate with Verdocs. If not set, the default endpoint will be used.
         */
        this.endpoint = VerdocsEndpoint.getDefault();
        /**
         * The template ID to edit.
         */
        this.templateId = '';
        this.showingRoleDialog = null;
        this.sender = null;
        this.dragging = false;
        this.loading = true;
        this.template = null;
        this.sortableRefs = [];
    }
    disconnectedCallback() {
        this.unlistenToTemplate();
        this.cleanupSortables();
    }
    async listenToTemplate() {
        console.log('[ROLES] Loading template', this.templateId);
        this.unlistenToTemplate();
        Store.subscribe('templates', this.templateId, () => getTemplate(this.endpoint, this.templateId), false, (template) => {
            console.log('[ROLES] Template Updated', template);
            this.template = template;
            this.loading = false;
        });
    }
    unlistenToTemplate() {
        if (this.templateListenerId) {
            Store.store.delListener(this.templateListenerId);
            this.templateListenerId = null;
        }
    }
    async componentWillLoad() {
        var _a, _b, _c;
        try {
            this.endpoint.loadSession();
            if (!this.templateId) {
                console.log(`[ROLES] Missing required template ID ${this.templateId}`);
                return;
            }
            if (!this.endpoint.session) {
                console.log('[ROLES] Unable to start builder session, must be authenticated');
                return;
            }
            this.listenToTemplate();
        }
        catch (e) {
            console.log('[ROLES] Error with preview session', e);
            (_a = this.sdkError) === null || _a === void 0 ? void 0 : _a.emit(new SDKError(e.message, (_b = e.response) === null || _b === void 0 ? void 0 : _b.status, (_c = e.response) === null || _c === void 0 ? void 0 : _c.data));
        }
    }
    cleanupSortables() {
        this.sortableRefs.forEach(sr => sr.destroy());
        this.sortableRefs.length = 0;
    }
    componentDidRender() {
        this.cleanupSortables();
        // Existing sequence numbers
        const sequenceNumbers = this.getSequenceNumbers();
        (sequenceNumbers || []).forEach(sequence => {
            const el = document.getElementById(`verdocs-roles-sequence-${sequence}`);
            if (el) {
                const sortable = new Sortable(el, {
                    group: 'roles',
                    animation: 150,
                    dragoverBubble: true,
                    filter: '.no-drag',
                    onEnd: this.handleMoveEnd.bind(this),
                    onChoose: () => (this.dragging = true),
                    onUnchoose: () => (this.dragging = false),
                });
                this.sortableRefs.push(sortable);
            }
        });
        const el = document.getElementById(`verdocs-roles-sequence-add-target`);
        if (el) {
            console.log('[ROLES] Applying sortable to add-sequence slot');
            const sortable = new Sortable(el, {
                group: 'roles',
                animation: 150,
                dragoverBubble: true,
                filter: '.no-drag',
                onEnd: this.handleMoveEnd.bind(this),
                onChoose: () => (this.dragging = true),
                onUnchoose: () => (this.dragging = false),
            });
            this.sortableRefs.push(sortable);
        }
    }
    handleMoveEnd(evt) {
        const fromSeq = +evt.from.dataset.sequence;
        const toSeq = +evt.to.dataset.sequence;
        const fromIndex = +evt.oldIndex + 1;
        const toIndex = +evt.newIndex + 1;
        console.log(`Move from ${fromSeq}:${fromIndex} to ${toSeq}:${toIndex}`, evt.item);
        const sortableRoles = {};
        const sequenceNumbers = this.getSequenceNumbers();
        sequenceNumbers.forEach(sequence => {
            const ras = this.getRolesAtSequence(sequence);
            sortableRoles[String(sequence)] = JSON.parse(JSON.stringify(ras));
        });
        // We might be adding a new sequence number now. Make sure we have an array to drop
        // the record into.
        sortableRoles[sequenceNumbers[sequenceNumbers.length - 1] + 1] = [];
        const role = sortableRoles[fromSeq].splice(fromIndex - 1, 1)[0];
        sortableRoles[toSeq] || (sortableRoles[toSeq] = []);
        sortableRoles[toSeq].splice(toIndex - 1, 0, role);
        const renumberRequests = [];
        Object.entries(sortableRoles).forEach(([targetSeq, roles]) => {
            roles.forEach((role, index) => {
                if (!role) {
                    return;
                }
                const targetOrder = +index + 1;
                if (role.sequence !== +targetSeq || role.order !== targetOrder) {
                    role.sequence = +targetSeq;
                    role.order = targetOrder;
                    renumberRequests.push(updateTemplateRole(this.endpoint, this.templateId, role.name, { sequence: +targetSeq, order: targetOrder })
                        .then(r => console.log('[ROLES] Updated role', role.name, r))
                        .catch(e => console.log('[ROLES] Error updating role', e)));
                }
            });
        });
        return Promise.all(renumberRequests)
            .then(async () => console.log('[ROLES] Done renumbering'))
            .catch(e => console.log('[ROLES] Error updating roles', e));
    }
    handleCancel() {
        var _a;
        (_a = this.exit) === null || _a === void 0 ? void 0 : _a.emit();
    }
    handleSubmit() {
        var _a;
        (_a = this.next) === null || _a === void 0 ? void 0 : _a.emit();
    }
    getSortedRoles() {
        var _a;
        // NOTE: This mutates the source array but that's OK because everything that touches
        // it will want the same thing done.
        return (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).sort((a, b) => {
            return a.sequence === b.sequence ? a.order - b.order : a.sequence - b.sequence;
        });
    }
    getSequenceNumbers() {
        // TODO: This is cleaner with a Set but we found a regression in some target environments where
        //  this breaks down. Reverting to an older technique while we diagnose it.
        const sequences = {};
        this.getSortedRoles().forEach(role => {
            sequences[role.sequence] = true;
        });
        console.log('[ROLES] Sequences', sequences);
        return Object.keys(sequences)
            .map(s => +s)
            .sort((a, b) => a - b);
        // const sequenceNumbers = (this.template?.roles || []).map(role => role.sequence);
        // const deduped = [...new Set(sequenceNumbers)];
        // deduped.sort((a, b) => a - b);
        // return deduped;
    }
    getRoleNames() {
        const roles = this.getSortedRoles();
        return roles.map(role => role.name);
    }
    getRolesAtSequence(sequence) {
        var _a;
        // Entries can be undefined when deleted because Stencil has no remove() operator yet for stores.
        // See https://github.com/ionic-team/stencil-store/issues/23
        return (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).filter(role => role && role.sequence === sequence);
    }
    // When the user drags a role around, we handle placement "between" items by assigning it a half-order number
    // e.g. 1.5 to place it between items 1 and 2, 0.5 to place it at the beginning, or last+0.5 to place it at the end.
    // Then we re-sort the list of roles and renumber them.
    async renumberTemplateRoles() {
        var _a;
        const sortableRoles = {};
        const renumberRequests = [];
        const sequenceNumbers = this.getSequenceNumbers();
        (sequenceNumbers || []).forEach(targetSeq => {
            (sortableRoles[targetSeq] || []).forEach((role, targetOrderMinusOne) => {
                const targetOrder = +targetOrderMinusOne + 1;
                if (role.sequence !== +targetSeq || role.order !== targetOrder) {
                    console.log('[ROLES] Updating role', role.name, 'from', role.sequence, role.order, 'to', targetSeq, targetOrder);
                    role.sequence = +targetSeq;
                    role.order = targetOrder;
                    renumberRequests.push(updateTemplateRole(this.endpoint, this.templateId, role.name, { sequence: +targetSeq, order: targetOrder })
                        .then(r => console.log('[ROLES] Updated role', role.name, r))
                        .catch(e => console.log('[ROLES] Error updating role', e)));
                }
            });
        });
        console.log(`[ROLES] Awaiting ${renumberRequests.length} renumber requests`);
        await Promise.all(renumberRequests).then(async () => {
            // When renumbering, we don't try to update the store for every individual item
            // changing. We just do it once at the end.
            const newTemplate = JSON.parse(JSON.stringify(this.template));
            newTemplate.roles = Object.keys(sortableRoles).reduce((acc, seq) => acc.concat(sortableRoles[seq]), []);
            console.log('[ROLES] Done renumbering', newTemplate.roles.map(r => ({ name: r.name, sequence: r.sequence, order: r.order })));
            Store.updateTemplate(this.templateId, newTemplate);
            // TODO: Explore race condition in reordering roles
            // this.template = await Store.getTemplate(this.endpoint, this.templateId, true);
        });
        (_a = this.rolesUpdated) === null || _a === void 0 ? void 0 : _a.emit({ event: 'updated', endpoint: this.endpoint, templateId: this.templateId, roles: this.getSortedRoles() });
    }
    // Look for name conflicts, because they're UGC and can be anything, regardless of order.
    getNextRoleName() {
        var _a, _b;
        let name = '';
        let nextNumber = (((_a = this.template) === null || _a === void 0 ? void 0 : _a.roles) || []).length;
        do {
            nextNumber++;
            name = `Recipient ${nextNumber}`;
        } while (!name || (((_b = this.template) === null || _b === void 0 ? void 0 : _b.roles) || []).some(role => role && role.name === name));
        return name;
    }
    callCreateRole(name, sequence, order) {
        console.log('[ROLES] Will create role', { name, sequence, order });
        createTemplateRole(this.endpoint, this.templateId, {
            template_id: this.templateId,
            name,
            sequence,
            message: '',
            order,
            full_name: null,
            first_name: '',
            last_name: '',
            email: '',
            phone: '',
            type: 'signer',
            delegator: false,
            // auth_method: null,
        })
            .then(async (role) => {
            var _a;
            console.log('[ROLES] Created role', role);
            // const newTemplate = JSON.parse(JSON.stringify(this.template));
            // newTemplate.roles.push(role);
            // TODO: Verify this immediately triggers a self-update
            console.log('Updating template in data store');
            await Store.getTemplate(this.endpoint, this.templateId, true);
            // Store.updateTemplate(this.templateId, newTemplate);
            // This will re-sort the roles and renumbers them via server calls if necessary
            // await this.renumberTemplateRoles();
            (_a = this.rolesUpdated) === null || _a === void 0 ? void 0 : _a.emit({ event: 'added', endpoint: this.endpoint, templateId: this.templateId, roles: this.getSortedRoles() });
        })
            .catch(e => {
            console.log('[ROLES] Error creating role', e);
        });
    }
    handleAddRole(e, sequence) {
        e.stopPropagation();
        const order = this.getRolesAtSequence(sequence).length + 1;
        const name = this.getNextRoleName();
        this.callCreateRole(name, sequence, order);
    }
    handleAddStep(e, sequence) {
        e.stopPropagation();
        const order = 1;
        const name = this.getNextRoleName();
        this.callCreateRole(name, sequence, order);
    }
    render() {
        if (!this.endpoint.session) {
            return (h(Host, null, h("verdocs-component-error", { message: "You must be authenticated to use this module." })));
        }
        if (this.loading || !this.template) {
            return (h(Host, { class: "loading" }, h("verdocs-loader", null)));
        }
        const roleNames = this.getRoleNames();
        const sequences = this.getSequenceNumbers();
        const nextSequence = sequences && sequences.length > 0 ? (sequences[sequences.length - 1] || 0) + 1 : 1;
        console.log('[ROLES] Rendering', { roleNames, sequences, nextSequence });
        return (h(Host, { class: { dragging: this.dragging } }, h("form", { onSubmit: e => e.preventDefault(), onClick: e => e.stopPropagation(), autocomplete: "off" }, h("h5", null, "Roles and Workflow"), h("div", { class: "roles" }, sequences.map((sequence, index) => (h("div", { class: "sequence" }, h("div", { class: "sequence-label no-drag" }, index + 1, "."), h("div", { class: "sequence-roles", id: `verdocs-roles-sequence-${sequence}`, "data-sequence": sequence }, this.getRolesAtSequence(sequence).map(role => {
            const unknown = !role.email || !role.first_name || !role.last_name;
            return unknown ? (h("div", { class: "role", "data-rolename": role.name, "data-sequence": sequence, "data-order": role.order }, h("div", { class: "role-name" }, role.name), h("div", { class: "icons" }, h("div", { class: "gear-button", innerHTML: settingsIcon, onClick: () => (this.showingRoleDialog = role.name), "aria-role": "button" }), h("span", { class: "type-icon", innerHTML: role.type === 'signer' ? iconSigner : role.type === 'cc' ? iconCC : iconApprover })))) : (h("div", { class: "role", "data-rolename": role.name, "data-sequence": sequence, "data-order": role.order }, h("div", { class: "role-name" }, formatFullName(role)), h("div", { class: "icons" }, h("div", { class: "gear-button", innerHTML: settingsIcon, onClick: () => (this.showingRoleDialog = role.name), "aria-role": "button" }), h("span", { class: "type-icon", innerHTML: role.type === 'signer' ? iconSigner : role.type === 'cc' ? iconCC : iconApprover }))));
        })), h("button", { class: "add-role no-drag", onClick: e => this.handleAddRole(e, sequence) }, "+ Add Role")))), h("div", { class: "sequence add-sequence" }, h("div", { class: "sequence-label no-drag" }, sequences.length + 1, "."), h("div", { class: "sequence-roles", id: `verdocs-roles-sequence-add-target`, "data-sequence": nextSequence }), h("button", { class: "add-role no-drag", onClick: e => this.handleAddRole(e, nextSequence) }, "+ Add Role"))), roleNames.length < 1 && (h("div", { class: "empty" }, "You must add at least one Role before proceeding.", h("br", null), " Click the ", h("span", { innerHTML: plusIcon }), " Add button above to get started.")), h("div", { class: "buttons" }, h("div", { class: "flex-fill" }), h("verdocs-button", { variant: "outline", label: "Cancel", size: "small", onClick: () => this.handleCancel() }), h("verdocs-button", { label: "OK", size: "small", onClick: () => this.handleSubmit(), disabled: roleNames.length < 1 }))), this.showingRoleDialog && (h("verdocs-menu-panel", { onClose: () => (this.showingRoleDialog = null) }, h("verdocs-template-role-properties", { endpoint: this.endpoint, templateId: this.templateId, roleName: this.showingRoleDialog, onClose: () => {
                var _a;
                (_a = document.getElementById('verdocs-menu-panel-overlay')) === null || _a === void 0 ? void 0 : _a.remove();
                this.showingRoleDialog = null;
            }, onDelete: async () => {
                var _a;
                this.showingRoleDialog = null;
                // This will re-sort the roles and renumbers them via server calls if necessary
                await this.renumberTemplateRoles();
                (_a = this.rolesUpdated) === null || _a === void 0 ? void 0 : _a.emit({ event: 'deleted', endpoint: this.endpoint, templateId: this.templateId, roles: this.getSortedRoles() });
            } })))));
    }
    get el() { return this; }
    static get style() { return verdocsTemplateRolesCss; }
}, [256, "verdocs-template-roles", {
        "endpoint": [16],
        "templateId": [1, "template-id"],
        "showingRoleDialog": [32],
        "sender": [32],
        "dragging": [32],
        "loading": [32],
        "template": [32]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["verdocs-template-roles", "verdocs-button", "verdocs-component-error", "verdocs-help-icon", "verdocs-loader", "verdocs-menu-panel", "verdocs-select-input", "verdocs-template-role-properties", "verdocs-text-input"];
    components.forEach(tagName => { switch (tagName) {
        case "verdocs-template-roles":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, VerdocsTemplateRoles);
            }
            break;
        case "verdocs-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "verdocs-component-error":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "verdocs-help-icon":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "verdocs-loader":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "verdocs-menu-panel":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "verdocs-select-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "verdocs-template-role-properties":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
        case "verdocs-text-input":
            if (!customElements.get(tagName)) {
                defineCustomElement$1();
            }
            break;
    } });
}

export { VerdocsTemplateRoles as V, defineCustomElement as d };
//# sourceMappingURL=p-OV-ZpJVv.js.map

//# sourceMappingURL=p-OV-ZpJVv.js.map