diff --git a/dist/grapes.min.js b/dist/grapes.min.js index ec0e5a879..fff2d1b07 100644 --- a/dist/grapes.min.js +++ b/dist/grapes.min.js @@ -1,3 +1,3 @@ -/*! grapesjs - 0.18.3 */ -!function(t,e){'object'==typeof exports&&'object'==typeof module?module.exports=e():'function'==typeof define&&define.amd?define([],e):'object'==typeof exports?exports["grapesjs"]=e():t["grapesjs"]=e()}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){'undefined'!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:'Module'}),Object.defineProperty(t,'__esModule',{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&'object'==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,'default',{enumerable:!0,value:t}),2&e&&'string'!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t['default']}:function(){return t};return n.d(e,'a',e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=100)}([function(t,e,n){"use strict";n.r(e),n.d(e,"default",(function(){return kn})),n.d(e,"VERSION",(function(){return i["e"]})),n.d(e,"restArguments",(function(){return o})),n.d(e,"isObject",(function(){return a})),n.d(e,"isNull",(function(){return s})),n.d(e,"isUndefined",(function(){return c})),n.d(e,"isBoolean",(function(){return l})),n.d(e,"isElement",(function(){return u})),n.d(e,"isString",(function(){return h})),n.d(e,"isNumber",(function(){return d})),n.d(e,"isDate",(function(){return p})),n.d(e,"isRegExp",(function(){return g})),n.d(e,"isError",(function(){return v})),n.d(e,"isSymbol",(function(){return m})),n.d(e,"isArrayBuffer",(function(){return y})),n.d(e,"isDataView",(function(){return j})),n.d(e,"isArray",(function(){return P})),n.d(e,"isFunction",(function(){return O})),n.d(e,"isArguments",(function(){return E})),n.d(e,"isFinite",(function(){return D})),n.d(e,"isNaN",(function(){return M})),n.d(e,"isTypedArray",(function(){return V})),n.d(e,"isEmpty",(function(){return U})),n.d(e,"isMatch",(function(){return W})),n.d(e,"isEqual",(function(){return Y})),n.d(e,"isMap",(function(){return ot})),n.d(e,"isWeakMap",(function(){return at})),n.d(e,"isSet",(function(){return st})),n.d(e,"isWeakSet",(function(){return ct})),n.d(e,"keys",(function(){return z})),n.d(e,"allKeys",(function(){return J})),n.d(e,"values",(function(){return lt})),n.d(e,"pairs",(function(){return ut})),n.d(e,"invert",(function(){return ft})),n.d(e,"functions",(function(){return ht})),n.d(e,"methods",(function(){return ht})),n.d(e,"extend",(function(){return pt})),n.d(e,"extendOwn",(function(){return gt})),n.d(e,"assign",(function(){return gt})),n.d(e,"defaults",(function(){return vt})),n.d(e,"create",(function(){return yt})),n.d(e,"clone",(function(){return bt})),n.d(e,"tap",(function(){return wt})),n.d(e,"get",(function(){return kt})),n.d(e,"has",(function(){return St})),n.d(e,"mapObject",(function(){return At})),n.d(e,"identity",(function(){return jt})),n.d(e,"constant",(function(){return A})),n.d(e,"noop",(function(){return Lt})),n.d(e,"toPath",(function(){return Ot})),n.d(e,"property",(function(){return _t})),n.d(e,"propertyOf",(function(){return Rt})),n.d(e,"matcher",(function(){return Pt})),n.d(e,"matches",(function(){return Pt})),n.d(e,"times",(function(){return Nt})),n.d(e,"random",(function(){return It})),n.d(e,"now",(function(){return Ft})),n.d(e,"escape",(function(){return Ht})),n.d(e,"unescape",(function(){return zt})),n.d(e,"templateSettings",(function(){return Ut})),n.d(e,"template",(function(){return Yt})),n.d(e,"result",(function(){return Jt})),n.d(e,"uniqueId",(function(){return Zt})),n.d(e,"chain",(function(){return Qt})),n.d(e,"iteratee",(function(){return Dt})),n.d(e,"partial",(function(){return ne})),n.d(e,"bind",(function(){return re})),n.d(e,"bindAll",(function(){return ae})),n.d(e,"memoize",(function(){return se})),n.d(e,"delay",(function(){return ce})),n.d(e,"defer",(function(){return le})),n.d(e,"throttle",(function(){return ue})),n.d(e,"debounce",(function(){return fe})),n.d(e,"wrap",(function(){return he})),n.d(e,"negate",(function(){return de})),n.d(e,"compose",(function(){return pe})),n.d(e,"after",(function(){return ge})),n.d(e,"before",(function(){return ve})),n.d(e,"once",(function(){return me})),n.d(e,"findKey",(function(){return ye})),n.d(e,"findIndex",(function(){return we})),n.d(e,"findLastIndex",(function(){return Oe})),n.d(e,"sortedIndex",(function(){return xe})),n.d(e,"indexOf",(function(){return ke})),n.d(e,"lastIndexOf",(function(){return Se})),n.d(e,"find",(function(){return je})),n.d(e,"detect",(function(){return je})),n.d(e,"findWhere",(function(){return Pe})),n.d(e,"each",(function(){return _e})),n.d(e,"forEach",(function(){return _e})),n.d(e,"map",(function(){return Te})),n.d(e,"collect",(function(){return Te})),n.d(e,"reduce",(function(){return De})),n.d(e,"foldl",(function(){return De})),n.d(e,"inject",(function(){return De})),n.d(e,"reduceRight",(function(){return Me})),n.d(e,"foldr",(function(){return Me})),n.d(e,"filter",(function(){return Ae})),n.d(e,"select",(function(){return Ae})),n.d(e,"reject",(function(){return Le})),n.d(e,"every",(function(){return Re})),n.d(e,"all",(function(){return Re})),n.d(e,"some",(function(){return Ne})),n.d(e,"any",(function(){return Ne})),n.d(e,"contains",(function(){return Ie})),n.d(e,"includes",(function(){return Ie})),n.d(e,"include",(function(){return Ie})),n.d(e,"invoke",(function(){return Fe})),n.d(e,"pluck",(function(){return Ve})),n.d(e,"where",(function(){return Be})),n.d(e,"max",(function(){return He})),n.d(e,"min",(function(){return ze})),n.d(e,"shuffle",(function(){return We})),n.d(e,"sample",(function(){return Ue})),n.d(e,"sortBy",(function(){return $e})),n.d(e,"groupBy",(function(){return Ge})),n.d(e,"indexBy",(function(){return Ke})),n.d(e,"countBy",(function(){return Ye})),n.d(e,"partition",(function(){return Je})),n.d(e,"toArray",(function(){return Ze})),n.d(e,"size",(function(){return Qe})),n.d(e,"pick",(function(){return en})),n.d(e,"omit",(function(){return nn})),n.d(e,"first",(function(){return on})),n.d(e,"head",(function(){return on})),n.d(e,"take",(function(){return on})),n.d(e,"initial",(function(){return rn})),n.d(e,"last",(function(){return sn})),n.d(e,"rest",(function(){return an})),n.d(e,"tail",(function(){return an})),n.d(e,"drop",(function(){return an})),n.d(e,"compact",(function(){return cn})),n.d(e,"flatten",(function(){return ln})),n.d(e,"without",(function(){return fn})),n.d(e,"uniq",(function(){return hn})),n.d(e,"unique",(function(){return hn})),n.d(e,"union",(function(){return dn})),n.d(e,"intersection",(function(){return pn})),n.d(e,"difference",(function(){return un})),n.d(e,"unzip",(function(){return gn})),n.d(e,"transpose",(function(){return gn})),n.d(e,"zip",(function(){return vn})),n.d(e,"object",(function(){return mn})),n.d(e,"range",(function(){return yn})),n.d(e,"chunk",(function(){return bn})),n.d(e,"mixin",(function(){return On}));var r={};n.r(r),n.d(r,"VERSION",(function(){return i["e"]})),n.d(r,"restArguments",(function(){return o})),n.d(r,"isObject",(function(){return a})),n.d(r,"isNull",(function(){return s})),n.d(r,"isUndefined",(function(){return c})),n.d(r,"isBoolean",(function(){return l})),n.d(r,"isElement",(function(){return u})),n.d(r,"isString",(function(){return h})),n.d(r,"isNumber",(function(){return d})),n.d(r,"isDate",(function(){return p})),n.d(r,"isRegExp",(function(){return g})),n.d(r,"isError",(function(){return v})),n.d(r,"isSymbol",(function(){return m})),n.d(r,"isArrayBuffer",(function(){return y})),n.d(r,"isDataView",(function(){return j})),n.d(r,"isArray",(function(){return P})),n.d(r,"isFunction",(function(){return O})),n.d(r,"isArguments",(function(){return E})),n.d(r,"isFinite",(function(){return D})),n.d(r,"isNaN",(function(){return M})),n.d(r,"isTypedArray",(function(){return V})),n.d(r,"isEmpty",(function(){return U})),n.d(r,"isMatch",(function(){return W})),n.d(r,"isEqual",(function(){return Y})),n.d(r,"isMap",(function(){return ot})),n.d(r,"isWeakMap",(function(){return at})),n.d(r,"isSet",(function(){return st})),n.d(r,"isWeakSet",(function(){return ct})),n.d(r,"keys",(function(){return z})),n.d(r,"allKeys",(function(){return J})),n.d(r,"values",(function(){return lt})),n.d(r,"pairs",(function(){return ut})),n.d(r,"invert",(function(){return ft})),n.d(r,"functions",(function(){return ht})),n.d(r,"methods",(function(){return ht})),n.d(r,"extend",(function(){return pt})),n.d(r,"extendOwn",(function(){return gt})),n.d(r,"assign",(function(){return gt})),n.d(r,"defaults",(function(){return vt})),n.d(r,"create",(function(){return yt})),n.d(r,"clone",(function(){return bt})),n.d(r,"tap",(function(){return wt})),n.d(r,"get",(function(){return kt})),n.d(r,"has",(function(){return St})),n.d(r,"mapObject",(function(){return At})),n.d(r,"identity",(function(){return jt})),n.d(r,"constant",(function(){return A})),n.d(r,"noop",(function(){return Lt})),n.d(r,"toPath",(function(){return Ot})),n.d(r,"property",(function(){return _t})),n.d(r,"propertyOf",(function(){return Rt})),n.d(r,"matcher",(function(){return Pt})),n.d(r,"matches",(function(){return Pt})),n.d(r,"times",(function(){return Nt})),n.d(r,"random",(function(){return It})),n.d(r,"now",(function(){return Ft})),n.d(r,"escape",(function(){return Ht})),n.d(r,"unescape",(function(){return zt})),n.d(r,"templateSettings",(function(){return Ut})),n.d(r,"template",(function(){return Yt})),n.d(r,"result",(function(){return Jt})),n.d(r,"uniqueId",(function(){return Zt})),n.d(r,"chain",(function(){return Qt})),n.d(r,"iteratee",(function(){return Dt})),n.d(r,"partial",(function(){return ne})),n.d(r,"bind",(function(){return re})),n.d(r,"bindAll",(function(){return ae})),n.d(r,"memoize",(function(){return se})),n.d(r,"delay",(function(){return ce})),n.d(r,"defer",(function(){return le})),n.d(r,"throttle",(function(){return ue})),n.d(r,"debounce",(function(){return fe})),n.d(r,"wrap",(function(){return he})),n.d(r,"negate",(function(){return de})),n.d(r,"compose",(function(){return pe})),n.d(r,"after",(function(){return ge})),n.d(r,"before",(function(){return ve})),n.d(r,"once",(function(){return me})),n.d(r,"findKey",(function(){return ye})),n.d(r,"findIndex",(function(){return we})),n.d(r,"findLastIndex",(function(){return Oe})),n.d(r,"sortedIndex",(function(){return xe})),n.d(r,"indexOf",(function(){return ke})),n.d(r,"lastIndexOf",(function(){return Se})),n.d(r,"find",(function(){return je})),n.d(r,"detect",(function(){return je})),n.d(r,"findWhere",(function(){return Pe})),n.d(r,"each",(function(){return _e})),n.d(r,"forEach",(function(){return _e})),n.d(r,"map",(function(){return Te})),n.d(r,"collect",(function(){return Te})),n.d(r,"reduce",(function(){return De})),n.d(r,"foldl",(function(){return De})),n.d(r,"inject",(function(){return De})),n.d(r,"reduceRight",(function(){return Me})),n.d(r,"foldr",(function(){return Me})),n.d(r,"filter",(function(){return Ae})),n.d(r,"select",(function(){return Ae})),n.d(r,"reject",(function(){return Le})),n.d(r,"every",(function(){return Re})),n.d(r,"all",(function(){return Re})),n.d(r,"some",(function(){return Ne})),n.d(r,"any",(function(){return Ne})),n.d(r,"contains",(function(){return Ie})),n.d(r,"includes",(function(){return Ie})),n.d(r,"include",(function(){return Ie})),n.d(r,"invoke",(function(){return Fe})),n.d(r,"pluck",(function(){return Ve})),n.d(r,"where",(function(){return Be})),n.d(r,"max",(function(){return He})),n.d(r,"min",(function(){return ze})),n.d(r,"shuffle",(function(){return We})),n.d(r,"sample",(function(){return Ue})),n.d(r,"sortBy",(function(){return $e})),n.d(r,"groupBy",(function(){return Ge})),n.d(r,"indexBy",(function(){return Ke})),n.d(r,"countBy",(function(){return Ye})),n.d(r,"partition",(function(){return Je})),n.d(r,"toArray",(function(){return Ze})),n.d(r,"size",(function(){return Qe})),n.d(r,"pick",(function(){return en})),n.d(r,"omit",(function(){return nn})),n.d(r,"first",(function(){return on})),n.d(r,"head",(function(){return on})),n.d(r,"take",(function(){return on})),n.d(r,"initial",(function(){return rn})),n.d(r,"last",(function(){return sn})),n.d(r,"rest",(function(){return an})),n.d(r,"tail",(function(){return an})),n.d(r,"drop",(function(){return an})),n.d(r,"compact",(function(){return cn})),n.d(r,"flatten",(function(){return ln})),n.d(r,"without",(function(){return fn})),n.d(r,"uniq",(function(){return hn})),n.d(r,"unique",(function(){return hn})),n.d(r,"union",(function(){return dn})),n.d(r,"intersection",(function(){return pn})),n.d(r,"difference",(function(){return un})),n.d(r,"unzip",(function(){return gn})),n.d(r,"transpose",(function(){return gn})),n.d(r,"zip",(function(){return vn})),n.d(r,"object",(function(){return mn})),n.d(r,"range",(function(){return yn})),n.d(r,"chunk",(function(){return bn})),n.d(r,"mixin",(function(){return On})),n.d(r,"default",(function(){return xn}));var i=n(9);function o(t,e){return e=null==e?t.length-1:+e,function(){for(var n=Math.max(arguments.length-e,0),r=Array(n),i=0;i=0&&n<=i["b"]}}function R(t){return function(e){return null==e?void 0:e[t]}}var N=R('byteLength'),I=L(N),F=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var V=i["r"]?function(t){return i["l"]?Object(i["l"])(t)&&!j(t):I(t)&&F.test(i["t"].call(t))}:A(!1),B=R('length');function H(t,e){e=function(t){for(var e={},n=t.length,r=0;r':'>','"':'"',"'":''','`':'`'},Ht=Vt(Bt),zt=Vt(ft(Bt)),Ut=$.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Wt=/(.)^/,$t={"'":"'",'\\':'\\','\r':'r','\n':'n','\u2028':'u2028','\u2029':'u2029'},qt=/\\|'|\r|\n|\u2028|\u2029/g;function Gt(t){return'\\'+$t[t]}var Kt=/^\s*(\w|\$)+\s*$/;function Yt(t,e,n){!e&&n&&(e=n),e=vt({},e,$.templateSettings);var r=RegExp([(e.escape||Wt).source,(e.interpolate||Wt).source,(e.evaluate||Wt).source].join('|')+'|$','g'),i=0,o="__p+='";t.replace(r,(function(e,n,r,a,s){return o+=t.slice(i,s).replace(qt,Gt),i=s+e.length,n?o+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'":r?o+="'+\n((__t=("+r+"))==null?'':__t)+\n'":a&&(o+="';\n"+a+"\n__p+='"),e})),o+="';\n";var a,s=e.variable;if(s){if(!Kt.test(s))throw new Error('variable is not a bare identifier: '+s)}else o='with(obj||{}){\n'+o+'}\n',s='obj';o="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+o+'return __p;\n';try{a=new Function(s,'_',o)}catch(t){throw t.source=o,t}var c=function(t){return a.call(this,t,$)};return c.source='function('+s+'){\n'+o+'}',c}function Jt(t,e,n){var r=(e=xt(e)).length;if(!r)return O(n)?n.call(t):n;for(var i=0;i1)oe(s,e-1,n,r),i=r.length;else for(var c=0,l=s.length;ce?(r&&(clearTimeout(r),r=null),s=l,a=t.apply(i,o),r||(i=o=null)):r||!1===n.trailing||(r=setTimeout(c,u)),a};return l.cancel=function(){clearTimeout(r),s=0,r=i=o=null},l}function fe(t,e,n){var r,i,a,s,c,l=function(){var o=Ft()-i;e>o?r=setTimeout(l,e-o):(r=null,n||(s=t.apply(c,a)),r||(a=c=null))},u=o((function(o){return c=this,a=o,i=Ft(),r||(r=setTimeout(l,e),n&&(s=t.apply(c,a))),s}));return u.cancel=function(){clearTimeout(r),r=a=c=null},u}function he(t,e){return ne(e,t)}function de(t){return function(){return!t.apply(this,arguments)}}function pe(){var t=arguments,e=t.length-1;return function(){for(var n=e,r=t[e].apply(this,arguments);n--;)r=t[n].call(this,r);return r}}function ge(t,e){return function(){if(--t<1)return e.apply(this,arguments)}}function ve(t,e){var n;return function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=null),n}}var me=ne(ve,2);function ye(t,e,n){e=Mt(e,n);for(var r,i=z(t),o=0,a=i.length;o0?0:i-1;o>=0&&o0?s=a>=0?a:Math.max(a+c,s):c=a>=0?Math.min(a+1,c):a+c+1;else if(n&&a&&c)return r[a=n(r,o)]===o?a:-1;if(o!=o)return(a=e(i["q"].call(r,s,c),M))>=0?a+s:-1;for(a=t>0?s:c-1;a>=0&&a0?0:a-1;for(i||(r=e[o?o[s]:s],s+=t);s>=0&&s=3;return e(t,Tt(n,i,4),r,o)}}var De=Ee(1),Me=Ee(-1);function Ae(t,e,n){var r=[];return e=Mt(e,n),_e(t,(function(t,n,i){e(t,n,i)&&r.push(t)})),r}function Le(t,e,n){return Ae(t,de(Mt(e)),n)}function Re(t,e,n){e=Mt(e,n);for(var r=!ie(t)&&z(t),i=(r||t).length,o=0;o=0}var Fe=o((function(t,e,n){var r,i;return O(e)?i=e:(e=xt(e),r=e.slice(0,-1),e=e[e.length-1]),Te(t,(function(t){var o=i;if(!o){if(r&&r.length&&(t=Ct(t,r)),null==t)return;o=t[e]}return null==o?o:o.apply(t,n)}))}));function Ve(t,e){return Te(t,_t(e))}function Be(t,e){return Ae(t,Pt(e))}function He(t,e,n){var r,i,o=-1/0,a=-1/0;if(null==e||'number'==typeof e&&'object'!=typeof t[0]&&null!=t)for(var s=0,c=(t=ie(t)?t:lt(t)).length;so&&(o=r);else e=Mt(e,n),_e(t,(function(t,n,r){((i=e(t,n,r))>a||i===-1/0&&o===-1/0)&&(o=t,a=i)}));return o}function ze(t,e,n){var r,i,o=1/0,a=1/0;if(null==e||'number'==typeof e&&'object'!=typeof t[0]&&null!=t)for(var s=0,c=(t=ie(t)?t:lt(t)).length;sr||void 0===n)return 1;if(n1&&(r=Tt(r,e[1])),e=J(t)):(r=tn,e=oe(e,!1,!1),t=Object(t));for(var i=0,o=e.length;i1&&(n=e[1])):(e=Te(oe(e,!1,!1),String),r=function(t,n){return!Ie(e,n)}),en(t,r,n)}));function rn(t,e,n){return i["q"].call(t,0,Math.max(0,t.length-(null==e||n?1:e)))}function on(t,e,n){return null==t||t.length<1?null==e||n?void 0:[]:null==e||n?t[0]:rn(t,t.length-e)}function an(t,e,n){return i["q"].call(t,null==e||n?1:e)}function sn(t,e,n){return null==t||t.length<1?null==e||n?void 0:[]:null==e||n?t[t.length-1]:an(t,Math.max(0,t.length-e))}function cn(t){return Ae(t,Boolean)}function ln(t,e){return oe(t,e,!1)}var un=o((function(t,e){return e=oe(e,!0,!0),Ae(t,(function(t){return!Ie(e,t)}))})),fn=o((function(t,e){return un(t,e)}));function hn(t,e,n,r){l(e)||(r=n,n=e,e=!1),null!=n&&(n=Mt(n,r));for(var i=[],o=[],a=0,s=B(t);a1&&void 0!==arguments[1]?arguments[1]:{},r=Object(s["isArray"])(e)?a()(e):[e];if(r.length){var i=r.shift();if(i&&(!n.unique||!document.querySelector("link[href=\"".concat(i,"\"]")))){var o=document,c=o.head,l=document.createElement('link');l.href=i,l.rel='stylesheet',n.prepand?c.insertBefore(l,c.firstChild):c.appendChild(l)}t(r)}},v=function(t,e){var n={},r=Object(s["keys"])(e);for(var i in t)if(t.hasOwnProperty(i)){var o=t[i],a=e[i];r.indexOf(i)>=0?o!==a&&(n[i]=a):n[i]=null}for(var c in e)e.hasOwnProperty(c)&&Object(s["isUndefined"])(t[c])&&(n[c]=e[c]);return n},m=function(t,e,n,r){e=e.split(/\s+/),t=t instanceof Array?t:[t];for(var i=function(i){t.forEach((function(t){return t&&t.addEventListener(e[i],n,r)}))},o=0;o1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=0;if(isNaN(t))return n;if(t=parseFloat(t),Math.floor(t)!==t){var i=e.toString().split('.')[1];r=i?i.length:0}return r?parseFloat(t.toFixed(r)):t},C=function(t){return'draggable'in document.createElement('i')&&(t?t.get('Config').nativeDnD:1)},k=function(t){return Object(s["isElement"])(t)||S(t)?t:t&&t.getEl?t.getEl():void 0},S=function(t){return t&&3===t.nodeType},j=function(t){return t&&8===t.nodeType},P=function(t){return t&&!S(t)&&!j(t)},_=function(t,e){var n=null;return t.some((function(r,i){return e(r,i,t)?(n=r,1):0})),n},T=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:'';return"".concat(t).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"').replace(/'/g,''').replace(/`/g,'`')},E=function(t,e){var n=t;return!e&&t&&t.__cashData?n=t.__cashData.model:Object(s["isElement"])(t)&&(n=e(t).data('model')),n},D=function(t){var e,n={top:0,left:0,width:0,height:0};if(!t)return n;if(S(t)){var r=document.createRange();r.selectNode(t),e=r.getBoundingClientRect(),r.detach()}return e||(t.getBoundingClientRect?t.getBoundingClientRect():n)},M=function(t){return t.touches&&t.touches[0]?t.touches[0]:t},A=function(t){return t.which||t.keyCode},L=function(t){return String.fromCharCode(A(t))},R=function(t){return 27===A(t)},N=function(t){return 13===A(t)},I=function(t){return null!==t&&!Array.isArray(t)&&'object'===i()(t)},F=function(t){return Object.keys(t).length<=0},V=function(t){return t&&t.charAt(0).toUpperCase()+t.substring(1)},B=function(t){return t&&t.toHTML},H=function(t){return t&&t.toCSS},z=function(t){return t.__gjsv},U=function(t,e){t.__gjsv=e},W=function(){for(var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,e='',n='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',r=n.length,i=0;ithis.length&&(i=this.length),i<0&&(i+=this.length+1);var o,a,s=[],c=[],l=[],u=[],f={},h=e.add,d=e.merge,p=e.remove,g=!1,v=this.comparator&&null==i&&!1!==e.sort,m=n.isString(this.comparator)?this.comparator:null;for(a=0;a7),this._useHashChange=this._wantsHashChange&&this._hasHashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!(!this.history||!this.history.pushState),this._usePushState=this._wantsPushState&&this._hasPushState,this.fragment=this.getFragment(),this.root=('/'+this.root+'/').replace(L,'/'),this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||'/';return this.location.replace(e+'#'+this.getPath()),!0}this._hasPushState&&this.atRoot()&&this.navigate(this.getHash(),{replace:!0})}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement('iframe'),this.iframe.src='javascript:0',this.iframe.style.display='none',this.iframe.tabIndex=-1;var r=document.body,i=r.insertBefore(this.iframe,r.firstChild).contentWindow;i.document.open(),i.document.close(),i.location.hash='#'+this.fragment}var o=window.addEventListener||function(t,e){return attachEvent('on'+t,e)};if(this._usePushState?o('popstate',this.checkUrl,!1):this._useHashChange&&!this.iframe?o('hashchange',this.checkUrl,!1):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent('on'+t,e)};this._usePushState?t('popstate',this.checkUrl,!1):this._useHashChange&&!this.iframe&&t('hashchange',this.checkUrl,!1),this.iframe&&(document.body.removeChild(this.iframe),this.iframe=null),this._checkUrlInterval&&clearInterval(this._checkUrlInterval),M.started=!1},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe&&(e=this.getHash(this.iframe.contentWindow)),e===this.fragment)return!1;this.iframe&&this.navigate(e),this.loadUrl()},loadUrl:function(t){return!!this.matchRoot()&&(t=this.fragment=this.getFragment(t),n.some(this.handlers,(function(e){if(e.route.test(t))return e.callback(t),!0})))},navigate:function(t,e){if(!M.started)return!1;e&&!0!==e||(e={trigger:!!e}),t=this.getFragment(t||'');var n=this.root;''!==t&&'?'!==t.charAt(0)||(n=n.slice(0,-1)||'/');var r=n+t;if(t=this.decodeFragment(t.replace(R,'')),this.fragment!==t){if(this.fragment=t,this._usePushState)this.history[e.replace?'replaceState':'pushState']({},document.title,r);else{if(!this._wantsHashChange)return this.location.assign(r);if(this._updateHash(this.location,t,e.replace),this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var i=this.iframe.contentWindow;e.replace||(i.document.open(),i.document.close()),this._updateHash(i.location,t,e.replace)}}return e.trigger?this.loadUrl(t):void 0}},_updateHash:function(t,e,n){if(n){var r=t.href.replace(/(javascript:|#).*$/,'');t.replace(r+'#'+e)}else t.hash='#'+e}}),e.history=new M;y.extend=b.extend=P.extend=C.extend=M.extend=function(t,e){var r,i=this;return r=t&&n.has(t,'constructor')?t.constructor:function(){return i.apply(this,arguments)},n.extend(r,i,e),r.prototype=n.create(i.prototype,t),r.prototype.constructor=r,r.__super__=i.prototype,r};var N=function(){throw new Error('A "url" property or function must be specified')},I=function(t,e){var n=e.error;e.error=function(r){n&&n.call(e.context,t,r,e),t.trigger('error',t,r,e)}};return e}(s,n,t,e)}.apply(e,i))||(t.exports=o);else;}()}).call(this,n(33))},function(t,e){function n(e){return t.exports=n=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},t.exports["default"]=t.exports,t.exports.__esModule=!0,n(e)}t.exports=n,t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e){function n(t,e){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{},n=this.target,r=this.get('name');if(!Object(O["isUndefined"])(t)){var i=t;if('false'===t?i=!1:'true'===t&&(i=!0),this.get('changeProp'))n.set(r,i,e);else{var o=E({},n.get('attributes'));o[r]=i,n.set('attributes',o,e)}}},setValueFromInput:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={value:t};this.set(r,E(E({},n),{},{avoidStore:1})),e&&(this.set('value','',n),this.set(r,n))},getInitValue:function(){var t,e=this.target,n=this.get('name');if(e){var r=e.get('attributes');t=this.get('changeProp')?e.get(n):r[n]}return t||this.get('value')||this.get('default')}}),A=S.a.Collection.extend({model:M,initialize:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.em=e.em||'',this.listenTo(this,'add',this.handleAdd),this.listenTo(this,'reset',this.handleReset)},handleReset:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.previousModels,r=void 0===n?[]:n;r.forEach((function(t){return t.trigger('remove')}))},handleAdd:function(t){var e=this.target;e&&(t.target=e)},setTarget:function(t){this.target=t},add:function(t,e){var n=this.em;if(Object(O["isString"])(t)||Object(O["isArray"])(t)){var r=n&&n.get&&n.get('TraitManager'),i=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{build:function(e){var n=[];'string'==typeof e&&(e=[e]);for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(O["bindAll"])(this,'__upSymbProps','__upSymbCls','__upSymbComps');var i=r.em,o=this.parent(),a=o&&o.attributes,s=this.get('propagate');if(s&&this.set('propagate',Object(O["isArray"])(s)?s:[s]),a&&a.propagate&&!s){var c={},l=a.propagate;l.forEach((function(t){return c[t]=o.get(t)})),c.propagate=l,this.set(R(R({},c),e))}if(r&&r.config&&r.config.voidElements.indexOf(this.get('tagName'))>=0&&this.set('void',!0),r.em=i,this.opt=r,this.em=i,this.frame=r.frame,this.config=r.config||{},this.set('attributes',R(R({},Object(O["result"])(this,'defaults').attributes||{}),this.get('attributes')||{})),this.ccid=n.createId(this,r),this.initClasses(),this.initTraits(),this.initComponents(),this.initToolbar(),this.initScriptProps(),this.listenTo(this,'change:script',this.scriptUpdated),this.listenTo(this,'change:tagName',this.tagUpdated),this.listenTo(this,'change:attributes',this.attrUpdated),this.listenTo(this,'change:attributes:id',this._idUpdated),this.on('change:toolbar',this.__emitUpdateTlb),this.on('change',this.__onChange),this.on(W,this.__propToParent),this.set('status',''),this.views=[],['classes','traits','components'].forEach((function(e){var n="add remove ".concat('components'!==e?'change':'');t.listenTo(t.get(e),n.trim(),(function(){for(var n=arguments.length,r=new Array(n),i=0;i0&&void 0!==arguments[0]?arguments[0]:{},e=this.em,n=e&&e.get('UndoManager'),r=this.components();n&&!this.__hasUm&&(n.add(r),n.add(this.getSelectors()),this.__hasUm=1),t.recursive&&r.map((function(e){return e.__postAdd(t)}))}},{key:"__postRemove",value:function(){var t=this.em,e=t&&t.get('UndoManager');e&&(e.remove(this.components()),e.remove(this.getSelectors()),delete this.__hasUm)}},{key:"__onChange",value:function(t,e){var n=this.changedAttributes();['status','open','toolbar','traits'].forEach((function(t){return delete n[t]})),Object(x["isEmptyObj"])(n)||(this.__changesUp(e),this.__propSelfToParent({component:this,changed:n,options:e}))}},{key:"__changesUp",value:function(t){var e=this.em;[this.frame,e].forEach((function(e){return e&&e.changesUp(t)}))}},{key:"__propSelfToParent",value:function(t){this.trigger(U,t),this.__propToParent(t)}},{key:"__propToParent",value:function(t){var e=this.parent();e&&e.trigger(W,t)}},{key:"__emitUpdateTlb",value:function(){this.emitUpdate('toolbar')}},{key:"is",value:function(t){return!(this.get('type')!=t)}},{key:"props",value:function(){return this.attributes}},{key:"index",value:function(){var t=this.collection;return t?t.indexOf(this):0}},{key:"setDragMode",value:function(t){return this.set('dmode',t)}},{key:"find",value:function(t){var e=[],n=this.view.$el.find(t);return n.each((function(t){var r=n.eq(t).data('model');r&&e.push(r)})),e}},{key:"findType",value:function(t){var e=[];return function n(r){return r.forEach((function(r){r.is(t)&&e.push(r),n(r.components())}))}(this.components()),e}},{key:"closest",value:function(t){var e=this.view.$el.closest(t);return e.length&&e.data('model')}},{key:"closestType",value:function(t){for(var e=this.parent();e&&!e.is(t);)e=e.parent();return e}},{key:"contains",value:function(t){var e=!1;if(!t)return e;var n=function n(r){!e&&r.forEach((function(r){r===t&&(e=!0),!e&&n(r.components())}))};return n(this.components()),e}},{key:"tagUpdated",value:function(){this.trigger('rerender')}},{key:"replaceWith",value:function(t){var e=this.collection,n=e.indexOf(this);return e.remove(this),e.add(t,{at:n})}},{key:"attrUpdated",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=this.get('attributes'),o=i.class;o&&this.setClass(o),delete i.class;var a=i.style;a&&this.setStyle(a),delete i.style;var s=R({},this.previous('attributes')),c=Object(x["shallowDiff"])(s,this.get('attributes'));Object(O["keys"])(c).forEach((function(t){return n.trigger("change:attributes:".concat(t),n,c[t],r)}))}},{key:"setAttributes",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.set('attributes',R({},t),e),this}},{key:"addAttributes",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.setAttributes(R(R({},this.getAttributes({noClass:1})),t),e)}},{key:"removeAttributes",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Array.isArray(t)?t:[t],r=this.getAttributes();return n.map((function(t){return delete r[t]})),this.setAttributes(r,e)}},{key:"getStyle",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.em,r=Object(O["isString"])(t)?t:'',i=r?e:t;if(n&&n.getConfig('avoidInlineStyle')&&!i.inline){var o=n.get('state'),a=n.get('CssComposer'),s=a.getIdRule(this.getId(),R({state:o},i));if(this.rule=s,s)return s.getStyle(r)}return C["a"].getStyle.call(this,r)}},{key:"setStyle",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,i=this.opt;if(r&&r.getConfig('avoidInlineStyle')&&!i.temporary&&!n.inline){var o=this.get('style')||{};e=R(R({},e=Object(O["isString"])(e)?this.parseStyle(e):e),o);var a=r.get('state'),s=r.get('CssComposer'),c=this.getStyle(n);this.rule=s.setIdRule(this.getId(),e,R(R({},n),{},{state:a}));var l=Object(x["shallowDiff"])(c,e);this.set('style','',{silent:1}),Object(O["keys"])(l).forEach((function(e){return t.trigger("change:style:".concat(e))}))}else e=C["a"].setStyle.apply(this,arguments);return e}},{key:"getAttributes",value:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=this.em,r=[],i=R({},this.get('attributes')),o=n&&n.get('SelectorManager'),a=this.getId();if(e.noClass||(this.get('classes').forEach((function(t){return r.push(Object(O["isString"])(t)?t:t.get('name'))})),r.length&&(i.class=r.join(' '))),!e.noStyle){var s=this.get('style');Object(x["isObject"])(s)&&!Object(x["isEmptyObj"])(s)&&(i.style=this.styleToString({inline:1}))}Object(O["has"])(i,'id')||(F(n)?t=o&&o.get(a,o.Selector.TYPE_ID):Object(O["isEmpty"])(this.getStyle())||(t=1),(this.__getSymbol()||this.__getSymbols())&&(t=1),t&&(i.id=a));return i}},{key:"addClass",value:function(t){var e=this.em.get('SelectorManager').addClass(t);return this.get('classes').add(e)}},{key:"setClass",value:function(t){return this.get('classes').reset(),this.addClass(t)}},{key:"removeClass",value:function(t){var e=[];t=Object(O["isArray"])(t)?t:[t];var n=this.get('classes'),r=P["a"].TYPE_CLASS;return t.forEach((function(t){t.split(' ').forEach((function(t){var i=n.where({name:t,type:r})[0];i&&e.push(n.remove(i))}))})),e}},{key:"getClasses",value:function(){var t=this.getAttributes().class;return t?t.split(' '):[]}},{key:"__logSymbol",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.__getSymbol(),i=this.__getSymbols();(r||i)&&this.em.log(t,{model:this,toUp:e,context:'symbols',opts:n})}},{key:"__initSymb",value:function(){this.__symbReady||(this.on('change',this.__upSymbProps),this.__symbReady=1)}},{key:"__isSymbol",value:function(){return Object(O["isArray"])(this.get(B))}},{key:"__isSymbolOrInst",value:function(){return!(!this.__isSymbol()&&!this.get(H))}},{key:"__isSymbolTop",value:function(){var t=this.parent();return this.__isSymbolOrInst()&&(!t||t&&!t.__isSymbol()&&!t.__getSymbol())}},{key:"__isSymbolNested",value:function(){if(!this.__isSymbolOrInst()||this.__isSymbolTop())return!1;var t=(this.__isSymbol()?this:this.__getSymbol()).__getSymbTop(),e=this.__getSymbTop();return(e.__isSymbol()?e:e.__getSymbol())!==t}},{key:"__getAllById",value:function(){var t=this.em;return t?t.get('DomComponents').allById():{}}},{key:"__getSymbol",value:function(){var t=this.get(H);if(t&&Object(O["isString"])(t)){var e=this.__getAllById()[t];e?(t=e,this.set(H,e)):t=0}return t}},{key:"__getSymbols",value:function(){var t=this,e=this.get(B);return e&&Object(O["isArray"])(e)&&(e.forEach((function(n,r){n&&Object(O["isString"])(n)&&(e[r]=t.__getAllById()[n])})),e=e.filter((function(t){return t&&!Object(O["isString"])(t)}))),e}},{key:"__isSymbOvrd",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:'',e=this.get(z),n=t.split(':'),r=c()(n,1),i=r[0],o=t!==i?[t,i]:[t];return!0===e||Object(O["isArray"])(e)&&o.some((function(t){return e.indexOf(t)>=0}))}},{key:"__getSymbToUp",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=[],r=this.em,i=e.changed,o=r&&r.get('symbols');if(e.fromInstance||e.noPropagate||e.fromUndo||!o||i&&this.__isSymbOvrd(i))return n;var s=this.__getSymbols()||[],c=this.__getSymbol(),l=c?[c].concat(a()(c.__getSymbols()||[])):s;return n=l.filter((function(e){return e!==t})).filter((function(t){return!(i&&t.__isSymbOvrd(i))}))}},{key:"__getSymbTop",value:function(t){for(var e=this,n=this.parent(t);n&&(n.__isSymbol()||n.__getSymbol());)e=n,n=n.parent(t);return e}},{key:"__upSymbProps",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.changedAttributes(),i=r.attributes||{};if(delete r.status,delete r.open,delete r[B],delete r[H],delete r[z],delete r.attributes,delete i.id,Object(x["isEmptyObj"])(i)||(r.attributes=i),!Object(x["isEmptyObj"])(r)){var o=this.__getSymbToUp(n);Object(O["keys"])(r).map((function(t){e.__isSymbOvrd(t)&&delete r[t]})),this.__logSymbol('props',o,{opts:n,changed:r}),o.forEach((function(t){var i=R({},r);Object(O["keys"])(i).map((function(e){t.__isSymbOvrd(e)&&delete i[e]})),t.set(i,R({fromInstance:e},n))}))}}},{key:"__upSymbCls",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=this.__getSymbToUp(r);this.__logSymbol('classes',i,{opts:r}),i.forEach((function(t){t.set('classes',n.get('classes'),{fromInstance:n})})),this.__changesUp(r)}},{key:"__upSymbComps",value:function(t,e,n){var r=this,i=n||e||{},o={fromInstance:i.fromInstance,fromUndo:i.fromUndo},s=t.opt.temporary;if(n)if(n.add){var c=[],l=!!this.__getSymbols(),u=this.__getSymbToUp(R(R({},o),{},{changed:'components:add'}));if(u.length){var f=t.__getSymbol();c=(f?f.__getSymbols():t.__getSymbols())||[],(c=a()(c)).push(f||t)}!s&&this.__logSymbol('add',u,{opts:n,addedInstances:c.map((function(t){return t.cid})),added:t.cid}),u.forEach((function(e){var i=e.__getSymbTop(),o=c.filter((function(t){var e=t.__getSymbTop({prev:1});return i&&e&&e===i}))[0]||t.clone({symbol:1,symbolInv:l});e.append(o,R({fromInstance:r},n))}))}else{var h=t.__getSymbol();if(h&&!n.temporary&&h.set(B,h.__getSymbols().filter((function(e){return e!==t}))),!t.__isSymbolTop()){var d='components:remove',p=n.index,g=t.parent(),v=R({fromInstance:t},n),m=t.__isSymbolNested(),y=function(t){var e=t.parent();e&&!e.__isSymbOvrd(d)&&t.remove(v)},b=g.__isSymbOvrd(d)?[]:t.__getSymbToUp(o);m&&(b=g.__getSymbToUp(R(R({},o),{},{changed:d})),y=function(t){var e=t.components().at(p);e&&e.remove(R({fromInstance:g},v))}),!s&&this.__logSymbol('remove',b,{opts:n,removed:t.cid,isSymbNested:m}),b.forEach(y)}}else{var w=this.__getSymbToUp(R(R({},o),{},{changed:'components:reset'}));this.__logSymbol('reset',w,{components:t.models}),w.forEach((function(n){var i=t.models.map((function(t){return t.clone({symbol:1})}));n.components().reset(i,R({fromInstance:r},e))}))}this.__changesUp(i)}},{key:"initClasses",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r='change:classes',i=this.get('attributes').class||[],o=[this,r,this.initClasses],a=this.get('classes')||i,s=Object(O["isString"])(a)?a.split(' '):a;this.stopListening.apply(this,o);var c=this.normalizeClasses(s),l=new _["a"]([]);return this.set('classes',l,n),l.add(c),l.on('add remove reset',this.__upSymbCls),this.listenTo.apply(this,o),this}},{key:"initComponents",value:function(){var t=[this,'change:components',this.initComponents];this.stopListening.apply(this,t);var e=new j["a"](null,this.opt);e.parent=this;var n=this.get('components'),r=!this.opt.avoidChildren;return this.set('components',e),r&&n&&e.add(Object(O["isFunction"])(n)?n(this):n,this.opt),e.on('add remove reset',this.__upSymbComps),this.listenTo.apply(this,t),this}},{key:"initTraits",value:function(t){var e=this.em,n='change:traits';this.off(n,this.initTraits),this.__loadTraits();var r=R({},this.get('attributes')),i=this.get('traits');return i.each((function(t){if(!t.get('changeProp')){var e=t.get('name'),n=t.getInitValue();e&&n&&(r[e]=n)}})),i.length&&this.set('attributes',r),this.on(n,this.initTraits),t&&e&&e.trigger('component:toggled'),this}},{key:"initScriptProps",value:function(){if(!this.opt.temporary){var t='script-props',e=["change:".concat(t),this.initScriptProps];this.off.apply(this,e);var n=this.previous(t)||[],r=this.get(t)||[],i=n.map((function(t){return"change:".concat(t)})).join(' '),o=r.map((function(t){return"change:".concat(t)})).join(' ');i&&this.off(i,this.__scriptPropsChange),o&&this.on(o,this.__scriptPropsChange),this.on.apply(this,e)}}},{key:"__scriptPropsChange",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};n.avoidStore||this.trigger('rerender')}},{key:"append",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Object(O["isArray"])(t)?t:[t],r=n.map((function(t){return Object(O["isString"])(t)||t.collection&&t.collection.remove(t,{temporary:1}),t})),i=this.components().add(r,e);return Object(O["isArray"])(i)?i:[i]}},{key:"components",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.get('components');return Object(O["isUndefined"])(t)?n:(n.reset(null,e),t?this.append(t,e):[])}},{key:"getChildAt",value:function(t){return this.components().at(t||0)||null}},{key:"getLastChild",value:function(){var t=this.components();return t.at(t.length-1)||null}},{key:"empty",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.components().reset(null,t),this}},{key:"parent",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.collection||t.prev&&this.prevColl;return e?e.parent:null}},{key:"scriptUpdated",value:function(){this.set('scriptUpdated',1)}},{key:"initToolbar",value:function(){var t=this.em,e=t&&t.getConfig('stylePrefix')||'';if(!this.get('toolbar')){var n=[];this.collection&&n.push({attributes:{class:'fa fa-arrow-up'},command:function(t){return t.runCommand('core:component-exit',{force:1})}}),this.get('draggable')&&n.push({attributes:{class:"fa fa-arrows ".concat(e,"no-touch-actions"),draggable:!0},command:'tlb-move'}),this.get('copyable')&&n.push({attributes:{class:'fa fa-clone'},command:'tlb-clone'}),this.get('removable')&&n.push({attributes:{class:'fa fa-trash-o'},command:'tlb-delete'}),this.set('toolbar',n)}}},{key:"__loadTraits",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t||this.get('traits');if(!(n instanceof A)){n=Object(O["isFunction"])(n)?n(this):n;var r=new A([],this.opt);r.setTarget(this),n.length&&(n.forEach((function(t){return t.attributes&&delete t.attributes.value})),r.add(n)),this.set({traits:r},e)}return this}},{key:"getTraits",value:function(){return this.__loadTraits(),a()(this.get('traits').models)}},{key:"setTraits",value:function(t){var e=Object(O["isArray"])(t)?t:[t];return this.set({traits:e}),this.getTraits()}},{key:"getTrait",value:function(t){return this.getTraits().filter((function(e){return e.get('id')===t||e.get('name')===t}))[0]||null}},{key:"updateTrait",value:function(t,e){var n,r=this.getTrait(t);return r&&r.set(e),null===(n=this.em)||void 0===n||n.trigger('component:toggled'),this}},{key:"getTraitIndex",value:function(t){var e=this.getTrait(t);return e?this.get('traits').indexOf(e):-1}},{key:"removeTrait",value:function(t){var e,n=this,r=(Object(O["isArray"])(t)?t:[t]).map((function(t){return n.getTrait(t)})),i=this.get('traits'),o=r.length?i.remove(r):[];return null===(e=this.em)||void 0===e||e.trigger('component:toggled'),Object(O["isArray"])(o)?o:[o]}},{key:"addTrait",value:function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.__loadTraits();var r=this.get('traits').add(t,n);return null===(e=this.em)||void 0===e||e.trigger('component:toggled'),Object(O["isArray"])(r)?r:[r]}},{key:"normalizeClasses",value:function(t){var e=[],n=this.em,r=n&&n.get('SelectorManager');if(r)return t.models?a()(t.models):(t.forEach((function(t){return e.push(r.add(t))})),e)}},{key:"clone",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.em,n=R({},this.attributes),r=R({},this.opt),i=this.getId(),o=e&&e.get('CssComposer');n.attributes=R({},n.attributes),delete n.attributes.id,n.components=[],n.classes=[],n.traits=[],this.__isSymbolTop()&&(t.symbol=1),this.get('components').each((function(e,r){n.components[r]=e.clone(R(R({},t),{},{_inner:1}))})),this.get('traits').each((function(t,e){n.traits[e]=t.clone()})),this.get('classes').each((function(t,e){n.classes[e]=t.get('name')})),n.status='',r.collection=null;var s=new this.constructor(n,r),c="#".concat(s.getId()),l=o?o.getRules("#".concat(i)):[];l.forEach((function(t){var e=t.clone();e.set('selectors',[c]),o.getAll().add(e)})),s.set(B,0);var u=this.__getSymbol(),f=this.__getSymbols();t.symbol||!u&&!f?u?(u.set(B,[].concat(a()(u.__getSymbols()),[s])),s.__initSymb()):t.symbol&&(this.__isSymbol()?(this.set(B,[].concat(a()(f),[s])),s.set(H,this),s.__initSymb()):t.symbolInv?(this.set(B,[s]),s.set(H,this),[this,s].map((function(t){return t.__initSymb()}))):(s.set(B,[this]),[this,s].map((function(t){return t.__initSymb()})),this.set(H,s))):(s.set(H,0),s.set(B,0));var h='component:clone';return e&&e.trigger(h,s),this.trigger(h,s),s}},{key:"getName",value:function(){var t=this.em,e=this.attributes,n=e.type,r=e.tagName,i=e.name,o=n||r,a=!n&&r,s='domComponents.names.',c=i&&(null==t?void 0:t.t("".concat(s).concat(i))),l=a&&(null==t?void 0:t.t("".concat(s).concat(a))),u=t&&(t.t("".concat(s).concat(n))||t.t("".concat(s).concat(r)));return this.get('custom-name')||c||i||l||Object(x["capitalize"])(a)||u||Object(x["capitalize"])(o)}},{key:"getIcon",value:function(){var t=this.get('icon');return t?t+' ':''}},{key:"toHTML",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this,n=[],r=t.tag,i=r||e.get('tagName'),o=e.get('void'),a=t.attributes,s=this.getAttrToHTML();if(delete t.tag,a&&(Object(O["isFunction"])(a)?s=a(e,s)||{}:Object(x["isObject"])(a)&&(s=a)),t.withProps){var c=this.toJSON();Object(O["forEach"])(c,(function(t,e){'_'!==e[0]&&['classes','attributes','components'].indexOf(e)<0&&(s["data-gjs-".concat(e)]=Object(O["isArray"])(t)||Object(x["isObject"])(t)?JSON.stringify(t):t)}))}for(var l in s){var u=s[l];if(!Object(O["isUndefined"])(u)&&null!==u)if(Object(O["isBoolean"])(u))u&&n.push(l);else{var f='';if(t.altQuoteAttr&&Object(O["isString"])(u)&&u.indexOf('"')>=0)f="'".concat(u.replace(/'/g,'''),"'");else{var h=Object(O["isString"])(u)?u.replace(/"/g,'"'):u;f="\"".concat(h,"\"")}n.push("".concat(l,"=").concat(f))}}var d=n.length?" ".concat(n.join(' ')):'',p=e.getInnerHTML(t),g="<".concat(i).concat(d).concat(o?'/':'',">").concat(p);return!o&&(g+="")),g}},{key:"getInnerHTML",value:function(t){return this.__innerHTML(t)}},{key:"__innerHTML",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.components();return e.length?e.map((function(e){return e.toHTML(t)})).join(''):this.get('content')}},{key:"getAttrToHTML",value:function(){var t=this.getAttributes();return delete t.style,t}},{key:"toJSON",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=k["Model"].prototype.toJSON.call(this,t);if(e.attributes=this.getAttributes(),delete e.attributes.class,delete e.toolbar,delete e.traits,delete e.status,delete e.open,!t.fromUndo){var n=e[H],r=e[B];r&&Object(O["isArray"])(r)&&(e[B]=r.filter((function(t){return t})).map((function(t){return t.getId?t.getId():t}))),n&&!Object(O["isString"])(n)&&(e[H]=n.getId())}return this.em.getConfig('avoidDefaults')&&this.getChangedProps(e),e}},{key:"getChangedProps",value:function(t){var e=t||k["Model"].prototype.toJSON.apply(this),n=Object(O["result"])(this,'defaults');return Object(O["forEach"])(n,(function(t,n){-1===['type'].indexOf(n)&&e[n]===t&&delete e[n]})),Object(O["isEmpty"])(e.type)&&delete e.type,Object(O["forEach"])(['attributes','style'],(function(t){Object(O["isEmpty"])(n[t])&&Object(O["isEmpty"])(e[t])&&delete e[t]})),Object(O["forEach"])(['classes','components'],(function(t){(!e[t]||Object(O["isEmpty"])(n[t])&&!e[t].length)&&delete e[t]})),e}},{key:"getId",value:function(){return(this.get('attributes')||{}).id||this.ccid||this.cid}},{key:"setId",value:function(t,e){var n=R({},this.get('attributes'));return n.id=t,this.set('attributes',n,e),this}},{key:"getEl",value:function(t){var e=this.getView(t);return e&&e.el}},{key:"getView",value:function(t){var e=this.view,n=this.views;return t&&(e=n.filter((function(e){return e._getFrame()===t.view}))[0]),e}},{key:"getCurrentView",value:function(){var t=(this.em.get('currentFrame')||{}).model;return this.getView(t)}},{key:"__getScriptProps",value:function(){var t=this.props();return(this.get('script-props')||[]).reduce((function(e,n){return e[n]=t[n],e}),{})}},{key:"getScriptString",value:function(t){var e=this,n=t||this.get('script');if(!n)return n;if(this.get('script-props'))n=n.toString().trim();else{if('function'==typeof n){var r=n.toString().trim();n=(r=r.replace(/^function[\s\w]*\(\)\s?\{/,'').replace(/\}$/,'')).trim()}var o=this.em.getConfig(),a=I(o.tagVarStart||'{[ '),s=I(o.tagVarEnd||' ]}'),c=new RegExp("".concat(a,"([\\w\\d-]*)").concat(s),'g');n=n.replace(c,(function(t,n){e.scriptUpdated();var r=e.attributes[n]||'';return Object(O["isArray"])(r)||'object'==i()(r)?JSON.stringify(r):r}))}return n}},{key:"emitUpdate",value:function(t){for(var e=this.em,n=U+(t?":".concat(t):''),r=t&&this.get(t),i=arguments.length,o=new Array(i>1?i-1:0),a=1;a=0&&this.__propSelfToParent({component:this,changed:u()({},t,r),options:o[2]||o[1]||{}})}},{key:"onAll",value:function(t){return Object(O["isFunction"])(t)&&(t(this),this.components().forEach((function(e){return e.onAll(t)}))),this}},{key:"remove",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=this.em,r=this.collection,i=function(){r&&r.remove(t,R(R({},e),{},{action:'remove-component'})),e.root&&t.components('')},o=R({},e);return[this,n].map((function(e){return e.trigger('component:remove:before',t,i,o)})),!o.abort&&i(),this}},{key:"move",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.remove({temporary:1}),t&&t.append(this,e),this}},{key:"isInstanceOf",value:function(t){var e,n,r=null===(e=this.em)||void 0===e||null===(n=e.get('DomComponents').getType(t))||void 0===n?void 0:n.model;return!!r&&this instanceof r}},{key:"isChildOf",value:function(t){for(var e=Object(O["isString"])(t),n=this.parent();n;){if(e){if(n.isInstanceOf(t))return!0}else if(n===t)return!0;n=n.parent()}return!1}},{key:"resetId",value:function(){var t=this.em,e=this.getId();if(e){var r=n.createId(this);this.setId(r);var i=t&&t.get('CssComposer').getIdRule(e),o=i&&i.get('selectors').at(0);return o&&o.set('name',r),this}}},{key:"_getStyleRule",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.id,n=this.em,r=e||this.getId();return n&&n.get('CssComposer').getIdRule(r)}},{key:"_getStyleSelector",value:function(t){var e=this._getStyleRule(t);return e&&e.get('selectors').at(0)}},{key:"_idUpdated",value:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!r.idUpdate){var i=this.ccid,o=this.get('attributes')||{},a=o.id,s=(this.previous('attributes')||{}).id||i,c=n.getList(this);if(c[a]||!a&&s)return this.setId(s,{idUpdate:1});delete c[s],c[a]=this,this.ccid=a;var l=this._getStyleSelector({id:s});l&&l.set({name:a,label:a})}}}]),n}(k["Model"].extend(C["a"]));$.isComponent=function(t){return{tagName:Object(x["toLowerCase"])(t.tagName)}},$.ensureInList=function(t){var e=$.getList(t),n=t.getId(),r=e[n];if(r){if(r!==t){var i=$.getIncrementId(n,e);t.setId(i),e[i]=t}}else e[n]=t;t.components().forEach((function(t){return $.ensureInList(t)}))},$.createId=function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=$.getList(t),i=n.idMap,o=void 0===i?{}:i,a=t.get('attributes'),s=a.id;return s?(e=$.getIncrementId(s,r,n),t.setId(e),s!==e&&(o[s]=e)):e=$.getNewId(r),r[e]=t,e},$.getNewId=function(t){for(var e=Object.keys(t).length.toString().length+2,n=(Math.random()+1.1).toString(36).slice(-e),r="i".concat(n);t[r];)r=$.getNewId(t);return r},$.getIncrementId=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.keepIds,i=void 0===r?[]:r,o=1,a=t;if(i.indexOf(t)<0)for(;e[a];)o++,a="".concat(t,"-").concat(o);return a},$.getList=function(t){var e=t.opt,n=void 0===e?{}:e,r=n.domc,i=n.em,o=r||i&&i.get('DomComponents');return o?o.componentsById:{}},$.checkId=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=Object(O["isArray"])(t)?t:[t],o=r.keepIds,a=void 0===o?[]:o;i.forEach((function(t){var i=t.attributes,o=void 0===i?{}:i,s=t.components,c=o.id;if(c&&n[c]&&a.indexOf(c)<0){var l=$.getIncrementId(c,n);o.id=l,Object(O["isArray"])(e)&&e.forEach((function(t){var e=t.selectors;e.forEach((function(t,n){t==="#".concat(c)&&(e[n]="#".concat(l))}))}))}s&&$.checkId(s,e,n,r)}))},$.getDefaults=function(){return Object(O["result"])(this.prototype,'defaults')},$.prototype.defaults=(D={tagName:'div',type:'',name:'',removable:!0,draggable:!0,droppable:!0,badgable:!0,stylable:!0,'stylable-require':'','style-signature':'',unstylable:'',highlightable:!0,copyable:!0,resizable:!1,editable:!1,layerable:!0,selectable:!0,hoverable:!0,void:!1,state:'',status:'',content:'',icon:'',style:'',styles:'',classes:'',script:'','script-props':'','script-export':'',attributes:'',traits:['id','title'],propagate:'',dmode:'',toolbar:null},u()(D,H,0),u()(D,B,0),u()(D,z,0),u()(D,"_undo",!0),u()(D,"_undoexc",['status','open']),D)},function(t,e,n){var r=n(78),i=n(79),o=n(49),a=n(80);t.exports=function(t){return r(t)||i(t)||o(t)||a()},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";n.r(e);var r=n(2),i=n.n(r),o=n(3),a=n.n(o),s=n(0),c=n(27),l=n(40),u=n(20),f=n(13),h=n(1);function d(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function p(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=this.model,n=t.config||{},r=n.em,i=e.opt||{},o=this.$el,a=this.el;this.opts=t,this.modelOpt=i,this.config=n,this.em=r||'',this.pfx=n.stylePrefix||'',this.ppfx=n.pStylePrefix||'',this.attr=e.get('attributes'),this.classe=this.attr.class||[],this.listenTo(e,'change:style',this.updateStyle),this.listenTo(e,'change:attributes',this.renderAttributes),this.listenTo(e,'change:highlightable',this.updateHighlight),this.listenTo(e,'change:status',this.updateStatus),this.listenTo(e,'change:script rerender',this.reset),this.listenTo(e,'change:content',this.updateContent),this.listenTo(e,'change',this.handleChange),this.listenTo(e,'active',this.onActive),this.listenTo(e,'disable',this.onDisable),o.data('model',e),Object(h["setViewEl"])(a,this),e.view=this,this._getFrame()&&e.views.push(this),this.initClasses(),this.initComponents({avoidRender:1}),this.events=p(p({},this.events),{},{dragstart:'handleDragStart'}),this.delegateEvents(),!i.temporary&&this.init(this._clbObj())},__isDraggable:function(){var t=this.model,e=this.config,n=t.attributes.draggable;return e.draggableComponents&&n},_clbObj:function(){var t=this.em,e=this.model,n=this.el;return{editor:t&&t.getEditor(),model:e,el:n}},init:function(){},removed:function(){},onActive:function(){},onDisable:function(){},remove:function(){var t;a.a.View.prototype.remove.apply(this,arguments);var e=this.model,n=this.$el,r=e.views,i=this._getFrame()||{};return e.components().forEach((function(t){var e=t.getView(i.model);null==e||e.remove()})),null===(t=this.childrenView)||void 0===t||t.remove(),r.splice(r.indexOf(this),1),this.removed(this._clbObj()),n.data({model:'',collection:'',view:''}),this},handleDragStart:function(t){if(!this.__isDraggable())return!1;t.stopPropagation(),t.preventDefault(),this.em.get('Commands').run('tlb-move',{target:this.model,event:t})},initClasses:function(){var t=this.model,e='change:classes',n=t.get('classes');n instanceof u["a"]&&(this.stopListening(t,e,this.initClasses),this.listenTo(t,e,this.initClasses),this.listenTo(n,'add remove change',this.updateClasses),n.length&&this.importClasses())},initComponents:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.model,n=this.$el,r=this.childrenView,i='change:components',o=e.get('components'),a=[e,i,this.initComponents];o instanceof c["a"]&&(n.data('collection',o),r&&r.remove(),this.stopListening.apply(this,a),!t.avoidRender&&this.renderChildren(),this.listenTo.apply(this,a))},handleChange:function(){var t=this.model,e=Object(s["keys"])(t.changed);if(1!==e.length||'status'!==e[0])for(var n in t.emitUpdate(),t.changed)t.emitUpdate(n)},importClasses:function(){var t=this.config.em.get('SelectorManager');t&&this.model.get('classes').each((function(e){t.add(e.get('name'))}))},updateStatus:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.em,n=e?e.get('Canvas').getConfig():{},r=n.extHl,i=this.el,o=this.model.get('status'),a=this.ppfx,s="".concat(a,"selected"),c="".concat(s,"-parent"),l="".concat(a,"freezed"),u="".concat(a,"hovered"),f=[s,c,l,u],h=r&&!t.noExtHl?'':s;this.$el.removeClass(f.join(' '));var d=i.getAttribute('class')||'',p='';switch(o){case'selected':p="".concat(d," ").concat(h);break;case'selected-parent':p="".concat(d," ").concat(c);break;case'freezed':p="".concat(d," ").concat(l);break;case'freezed-selected':p="".concat(d," ").concat(l," ").concat(h);break;case'hovered':p=t.avoidHover?'':"".concat(d," ").concat(u)}(p=p.trim())&&i.setAttribute('class',p)},updateHighlight:function(){var t=this.model,e=t.get('textable'),n=t.get('highlightable')&&(e||!t.isChildOf('text'));this.setAttribute('data-gjs-highlightable',!!n||'')},updateStyle:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.model,i=this.em;if(i&&i.getConfig('avoidInlineStyle')&&!n.inline){var o=r.getStyle();!Object(s["isEmpty"])(o)&&r.setStyle(o)}else this.setAttribute('style',r.styleToString(n))},updateClasses:function(){var t=this.model.get('classes').pluck('name').join(' ');this.setAttribute('class',t),this.updateStatus(),this.onAttrUpdate()},setAttribute:function(t,e){var n=this.$el;e?n.attr(t,e):n.removeAttr(t)},getClasses:function(){return this.model.getClasses().join(' ')},updateAttributes:function(){var t=[],e=this.model,n=this.$el,r=this.el,i=e.attributes,o=i.textable,a=i.type,c=p(p({id:e.getId(),'data-gjs-type':a||'default'},this.__isDraggable()&&{draggable:!0}),o&&{contenteditable:'false'});Object(s["each"])(r.attributes,(function(e){return t.push(e.nodeName)})),t.forEach((function(t){return n.removeAttr(t)})),this.updateStyle(),this.updateHighlight();var l=p(p({},c),e.getAttributes());Object(s["keys"])(l).forEach((function(t){return!1===l[t]&&delete l[t]})),n.attr(l)},updateContent:function(){var t=this.model.get('content'),e=this.model.components().length;this.getChildrenContainer().innerHTML=e?'':t},prevDef:function(t){t.preventDefault()},updateScript:function(){var t=this.model,e=this.em;t.get('script')&&e&&e.get('Canvas').getCanvasView().updateScript(this)},getChildrenContainer:function(){var t=this.el;return'function'==typeof this.getChildrenSelector?t=this.el.querySelector(this.getChildrenSelector()):this.getTemplate,t},getOffsetRect:function(){var t={},e=this.el,n=0,r=0;return function i(o){var a=o.offsetParent;a?(n+=a.offsetTop,r+=a.offsetLeft,i(a)):(t.top=e.offsetTop+n,t.left=e.offsetLeft+r,t.bottom=t.top+e.offsetHeight,t.right=t.left+e.offsetWidth)}(e),t},isInViewport:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.rect,n=this.el,r=n.ownerDocument,i=r.body,o=r.defaultView.frameElement,a=e||this.getOffsetRect(),s=a.top,c=a.left,l=this._getFrame().getOffsetRect();return s>=l.scrollTop&&c>=l.scrollLeft&&s<=l.scrollBottom&&c<=o.offsetWidth+i.scrollLeft},scrollIntoView:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.getOffsetRect(),n=this.isInViewport({rect:e});if(!n||t.force){var r=this.el;'smooth'!==t.behavior?r.ownerDocument.defaultView.scrollTo(0,e.top):r.scrollIntoView(p({behavior:'smooth',block:'nearest'},t))}},reset:function(){var t=this.el;this.el='',this._ensureElement(),this._setData(),Object(f["m"])(t,this.el),this.render()},_setData:function(){var t=this.model,e=t.components();this.$el.data({model:t,collection:e,view:this})},_getFrame:function(){return this.config.frameView},renderChildren:function(){this.updateContent();var t=this.getChildrenContainer(),e=this.childrenView||new l["a"]({collection:this.model.get('components'),config:this.config,componentTypes:this.opts.componentTypes});e.render(t),this.childrenView=e;for(var n=Array.prototype.slice.call(e.el.childNodes),r=0,i=n.length;r1&&void 0!==arguments[1]?arguments[1]:{};return t&&t.setAttribute&&Object(r["each"])(e,(function(e,n){return t.setAttribute(n,e)}))},f=function(t){return t&&!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)},h=function(t,e){t.parentNode.replaceChild(e,t)},d=function(t,e,n){var i=t.childNodes,o=i.length,a=Object(r["isUndefined"])(n)?o:n;Object(r["isString"])(e)&&(t.insertAdjacentHTML('beforeEnd',e),e=t.lastChild,t.removeChild(e)),a>=o?t.appendChild(e):t.insertBefore(e,i[a])},p=function(t,e){return d(t,e)},g=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:'',n=arguments.length>2?arguments[2]:void 0,i=document.createElement(t);return e&&Object(r["each"])(e,(function(t,e){return i.setAttribute(e,t)})),n&&(Object(r["isString"])(n)?i.innerHTML=n:i.appendChild(n)),i},v=function(t){return document.createTextNode(t)},m=function(t,e){var n,r=t.type;try{n=new window[e](r,t)}catch(t){(n=document.createEvent(e)).initEvent(r,!0,!0)}return n._parentEvent=t,0===r.indexOf('key')&&(n.keyCodeVal=t.keyCode,['keyCode','which'].forEach((function(t){Object.defineProperty(n,t,{get:function(){return this.keyCodeVal}})}))),n},y=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=Array.isArray(e)?e:[e];n.forEach((function(e){var n=e[i]||'div',a=e[o]||{},s=document.createElement(n);Object(r["each"])(a,(function(t,e){s.setAttribute(e,t)})),t.appendChild(s)}))}},function(t,e){function n(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?(t.exports=n=function(t){return typeof t},t.exports["default"]=t.exports,t.exports.__esModule=!0):(t.exports=n=function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports["default"]=t.exports,t.exports.__esModule=!0),n(e)}t.exports=n,t.exports["default"]=t.exports,t.exports.__esModule=!0},,function(t,e,n){"use strict";n.d(e,"a",(function(){return i}));var r=n(1);function i(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),i=1;i=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";n.d(e,"a",(function(){return y}));var r=n(5),i=n.n(r),o=n(6),a=n.n(o),s=n(7),c=n.n(s),l=n(8),u=n.n(l),f=n(4),h=n.n(f),d=n(3),p=n(0);function g(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=h()(t);if(e){var i=h()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return u()(this,n)}}var v=1,m=2,y=function(t){c()(n,t);var e=g(n);function n(){return i()(this,n),e.apply(this,arguments)}return a()(n,[{key:"defaults",value:function(){return{name:'',label:'',type:v,active:!0,private:!1,protected:!1,_undo:!0}}},{key:"initialize",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.config,i=void 0===r?{}:r,o=this.get('name'),a=this.get('label');o?a||this.set('label',o):this.set('name',a);var s=this.get('name'),c=i.escapeName,l=c?c(s):n.escapeName(s);this.set('name',l),this.em=i.em}},{key:"isId",value:function(){return this.get('type')===m}},{key:"isClass",value:function(){return this.get('type')===v}},{key:"getFullName",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.escape,n=this.get('name'),r='';switch(this.get('type')){case v:r='.';break;case m:r='#'}return r+(e?e(n):n)}},{key:"toString",value:function(){return this.getFullName()}},{key:"getLabel",value:function(){return this.get('label')}},{key:"setLabel",value:function(t){return this.set('label',t)}},{key:"getActive",value:function(){return this.get('active')}},{key:"setActive",value:function(t){return this.set('active',t)}},{key:"toJSON",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.em,n=d["Model"].prototype.toJSON.call(this,[t]),r=Object(p["result"])(this,'defaults');if(e&&e.getConfig('avoidDefaults')){Object(p["forEach"])(r,(function(t,e){n[e]===t&&delete n[e]})),n.label===n.name&&delete n.label;var i=Object(p["keys"])(n).length;1===i&&n.name&&(n=n.name),2===i&&n.name&&n.type&&(n=this.getFullName())}return n}}]),n}(d["Model"]);y.prototype.idAttribute='name',y.TYPE_CLASS=v,y.TYPE_ID=m,y.escapeName=function(t){return"".concat(t).trim().replace(/([^a-z0-9\w-\:]+)/gi,'-')}},function(t,e,n){"use strict";n.d(e,"a",(function(){return y}));var r=n(5),i=n.n(r),o=n(6),a=n.n(o),s=n(7),c=n.n(s),l=n(8),u=n.n(l),f=n(4),h=n.n(f),d=n(0),p=n(3),g=n(19);function v(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=h()(t);if(e){var i=h()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return u()(this,n)}}var m=function t(e,n){return e.reduce((function(r,i,o){return r.concat(t(e.slice(o+1),"".concat(n).concat(i)))}),[n])},y=function(t){c()(n,t);var e=v(n);function n(){return i()(this,n),e.apply(this,arguments)}return a()(n,[{key:"modelId",value:function(t){return"".concat(t.name,"_").concat(t.type||g["a"].TYPE_CLASS)}},{key:"getStyleable",value:function(){return Object(d["filter"])(this.models,(function(t){return t.get('active')&&!t.get('private')}))}},{key:"getValid",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.noDisabled;return Object(d["filter"])(this.models,(function(t){return!t.get('private')})).filter((function(t){return e?t.get('active'):1}))}},{key:"getFullString",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=[],r=t||this;return r.forEach((function(t){return n.push(t.getFullName(e))})),n.join('').trim()}},{key:"getFullName",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.combination,n=t.array,r=[],i=this.map((function(e){return e.getFullName(t)})).sort();return e?i.forEach((function(t,e){r=r.concat(m(i.slice(e+1),t))})):r=i,n?r:e?r.join(','):r.join('')}}]),n}(p["Collection"]);y.prototype.model=g["a"]},function(t,e,n){"use strict";n.r(e);var r='undefined'!=typeof document?document:null,i='undefined'!=typeof window?window:null,o=Array.prototype,a=o.filter,s=o.indexOf,c=o.map,l=o.push,u=o.reverse,f=o.slice,h=o.splice,d=/^#[\w-]*$/,p=/^\.[\w-]*$/,g=/<.+>/,v=/^\w+$/;function m(t,e){return void 0===e&&(e=r),p.test(t)?e.getElementsByClassName(t.slice(1)):v.test(t)?e.getElementsByTagName(t):e.querySelectorAll(t)}function y(t,e){if(void 0===e&&(e=r),t){if(t.__cash)return t;var n=t;if(_(t)){if(e.__cash&&(e=e[0]),!(n=d.test(t)?e.getElementById(t.slice(1)):g.test(t)?dt(t):m(t,e)))return}else if(P(t))return this.ready(t);(n.nodeType||n===i)&&(n=[n]),this.length=n.length;for(var o=0,a=this.length;o=0})):n.value=i}))},w.clone=function(){return this.map((function(t,e){return e.cloneNode(!0)}))},w.detach=function(){return this.each((function(t,e){e.parentNode&&e.parentNode.removeChild(e)}))};var ut,ft=/^\s*<(\w+)[^>]*>/,ht=/^\s*<(\w+)\s*\/?>(?:<\/\1>)?\s*$/;function dt(t){if(function(){if(!ut){var t=r.createElement('table'),e=r.createElement('tr');ut={'*':r.createElement('div'),tr:r.createElement('tbody'),td:e,th:e,thead:t,tbody:t,tfoot:t}}}(),!_(t))return[];if(ht.test(t))return[r.createElement(RegExp.$1)];var e=ft.test(t)&&RegExp.$1,n=ut[e]||ut['*'];return n.innerHTML=t,b(n.childNodes).detach().get()}function pt(t,e,n){if(void 0!==e){var r=_(e);!r&&e.length?k(e,(function(e){return pt(t,e,n)})):k(t,r?function(t){t.insertAdjacentHTML(n?'afterbegin':'beforeend',e)}:function(t,r){return function(t,e,n){n?t.insertBefore(e,t.childNodes[0]):t.appendChild(e)}(t,r?e.cloneNode(!0):e,n)})}}b.parseHTML=dt,w.empty=function(){var t=this[0];if(t)for(;t.firstChild;)t.removeChild(t.firstChild);return this},w.append=function(){var t=this;return k(arguments,(function(e){pt(t,e)})),this},w.appendTo=function(t){return pt(b(t),this),this},w.html=function(t){if(void 0===t)return this[0]&&this[0].innerHTML;var e=t.nodeType?t[0].outerHTML:t;return this.each((function(t,n){n.innerHTML=e}))},w.insertAfter=function(t){var e=this;return b(t).each((function(t,n){var r=n.parentNode;e.each((function(e,i){r.insertBefore(t?i.cloneNode(!0):i,n.nextSibling)}))})),this},w.after=function(){var t=this;return k(u.apply(arguments),(function(e){u.apply(b(e).slice()).insertAfter(t)})),this},w.insertBefore=function(t){var e=this;return b(t).each((function(t,n){var r=n.parentNode;e.each((function(e,i){r.insertBefore(t?i.cloneNode(!0):i,n)}))})),this},w.before=function(){var t=this;return k(arguments,(function(e){b(e).insertBefore(t)})),this},w.prepend=function(){var t=this;return k(arguments,(function(e){pt(t,e,!0)})),this},w.prependTo=function(t){return pt(b(t),u.apply(this.slice()),!0),this},w.remove=function(){return this.detach().off()},w.replaceWith=function(t){var e=this;return this.each((function(n,r){var i=r.parentNode;if(i){var o=n?b(t).clone():b(t);if(!o[0])return e.remove(),!1;i.replaceChild(o[0],r),b(o[0]).after(o.slice(1))}}))},w.replaceAll=function(t){return b(t).replaceWith(this),this},w.text=function(t){return void 0===t?this[0]?this[0].textContent:'':this.each((function(e,n){n.textContent=t}))};var gt=r&&r.documentElement;w.offset=function(){var t=this[0];if(t){var e=t.getBoundingClientRect();return{top:e.top+i.pageYOffset-gt.clientTop,left:e.left+i.pageXOffset-gt.clientLeft}}},w.offsetParent=function(){return b(this[0]&&this[0].offsetParent)},w.position=function(){var t=this[0];if(t)return{left:t.offsetLeft,top:t.offsetTop}},w.children=function(t){var e=[];return this.each((function(t,n){l.apply(e,n.children)})),e=b(L(e)),t?e.filter((function(e,n){return j(n,t)})):e},w.contents=function(){var t=[];return this.each((function(e,n){l.apply(t,'IFRAME'===n.tagName?[n.contentDocument]:n.childNodes)})),b(t.length&&L(t))},w.find=function(t){for(var e=[],n=0,r=this.length;n0&&void 0!==arguments[0]?arguments[0]:{};return this.all?t.array?a()(this.all.models):this.all:[]},getAllMap:function(){return this.getAll().reduce((function(t,e){return t[e.get(e.idAttribute)]=e,t}),{})},__initConfig:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.config=u(u({},t),e),this.em=this.config.em},__initListen:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.all,n=this.em,r=this.events;e&&n&&e.on('add',(function(t,e,i){return n.trigger(r.add,t,i)})).on('remove',(function(t,e,i){return n.trigger(r.remove,t,i)})).on('change',(function(t,e){return n.trigger(r.update,t,t.changedAttributes(),e)})).on('all',this.__catchAllEvent,this),this.cls=[e].concat(t.collections||[]),(t.propagate||[]).forEach((function(t){var r=t.entity,i=t.event;r.on('all',(function(t,r,o,a){var s=u({event:t},a||o);[n,e].map((function(t){return t.trigger(i,r,s)}))}))}))},__remove:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,i=Object(s["isString"])(t)?this.get(t):t,o=function(){return i&&e.all.remove(i,n),i};return!n.silent&&r&&r.trigger(this.events.removeBefore,i,o,n),!n.abort&&o()},__catchAllEvent:function(t,e,n,r){var i=this.em,o=this.events,a=r||n;i&&o.all&&i.trigger(o.all,{event:t,model:e,options:a}),this.__onAllEvent()},__appendTo:function(){var t=this.getConfig().appendTo;if(t){var e=Object(s["isElement"])(t)?t:document.querySelector(t);if(!e)return this.__logWarn('"appendTo" element not found');e.appendChild(this.render())}},__onAllEvent:function(){},__logWarn:function(t){this.em.logWarning("[".concat(this.name,"]: ").concat(t))},_createId:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,n=this.getAll(),r=n.length+e,i=this.getAllMap();do{t=Object(c["createId"])(r)}while(i[t]);return t},__listenAdd:function(t,e){var n=this;t.on('add',(function(t,r,i){return n.em.trigger(e,t,i)}))},__listenRemove:function(t,e){var n=this;t.on('remove',(function(t,r,i){return n.em.trigger(e,t,i)}))},__listenUpdate:function(t,e){var n=this;t.on('change',(function(t,r){return n.em.trigger(e,t,t.changedAttributes(),r)}))},__destroy:function(){this.cls.forEach((function(t){t.stopListening(),t.reset()})),this.em=0}}},function(t,e,n){"use strict";n.r(e);var r=n(14),i=n.n(r),o=n(2),a=n.n(o),s=n(3),c=n.n(s),l=n(0),u=n(1),f=n(13),h=n(30);function d(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function p(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=t.config,n=void 0===e?{}:e;this.em=n.em,this.editor=n.editor},handleClick:function(t){t.preventDefault(),t.stopPropagation();var e=this.editor,n=this.em,r=e.Canvas.getFrameEl().getBoundingClientRect(),i=r.left,o=r.top,a=p(p({},t),{},{clientX:t.clientX-i,clientY:t.clientY-o});n.trigger('toolbar:run:before'),this.execCommand(a)},execCommand:function(t){var e={event:t},n=this.model.get('command'),r=this.editor;'function'==typeof n&&n(r,null,e),'string'==typeof n&&r.runCommand(n,e)},render:function(){var t=this.editor,e=this.$el,n=this.model,r=n.get('id'),i=n.get('label'),o=t.getConfig('stylePrefix');return e.addClass("".concat(o,"toolbar-item")),r&&e.addClass("".concat(o,"toolbar-item__").concat(r)),i&&e.append(i),this}}),v=h["a"].extend({itemView:g,initialize:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.config={editor:t.editor||'',em:t.em},this.listenTo(this.collection,'reset',this.render)}}),m=c.a.Model.extend({defaults:{command:'',attributes:{}}}),y=c.a.Collection.extend({model:m});function b(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function w(t){for(var e=1;e2&&void 0!==arguments[2]?arguments[2]:{},r=n.el||this.canvas.getToolsEl(e);return r&&(r.style.display=t?'':'none'),r||{}},showElementOffset:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};O&&this.editor.runCommand('show-offset',{el:t,elPos:e,view:n.view,force:1,top:0,left:0})},hideElementOffset:function(t){this.editor.stopCommand('show-offset',{view:t})},showFixedElementOffset:function(t,e){this.editor.runCommand('show-offset',{el:t,elPos:e,state:'Fixed'})},hideFixedElementOffset:function(t,e){this.editor&&this.editor.stopCommand('show-offset',{state:'Fixed'})},hideHighlighter:function(t){this.canvas.getHighlighter(t).style.opacity=0},onClick:function(t){t.stopPropagation(),t.preventDefault();var e=this.em;if(e.get('_cmpDrag'))return e.set('_cmpDrag');var n=x(t.target),r=n.data('model');if(!r)for(var i=n.parent();!r&&i.length&&!Object(f["i"])(i[0]);)r=i.data('model'),i=i.parent();if(r){if(e.isEditing()&&!r.get('textable')&&r.isChildOf('text'))return;this.select(r,t)}},select:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t&&(this.editor.select(t,{event:e,useValid:!0}),this.initResize(t))},updateBadge:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.canvas,i=x(t).data('model');if(i&&i.get('badgable')){var o=this.getBadge(n);if(!n.posOnly){var a=this.canvas.getConfig(),s=i.getIcon(),c=a.pStylePrefix||'',l="".concat(c,"badge"),u=a.customBadgeLabel,f="".concat(s?"
").concat(s,"
"):'',"\n
").concat(i.getName(),"
");o.innerHTML=u?u(i):f}var h='px',d=o.style;d.display='block';var p=r.getTargetToElementFixed(t,o,{pos:e}),g=p.top,v=n.leftOff<0?-n.leftOff:0;d.top=g+h,d.left=v+h}},showHighlighter:function(t){this.canvas.getHighlighter(t).style.opacity=''},initResize:function(t){var e,n=this.em,r=this.canvas,o=n?n.get('Editor'):'',a=(n?n.get('Config'):'').stylePrefix||'',s="".concat(a,"resizing"),c=!Object(l["isElement"])(t)&&Object(u["isTaggableNode"])(t)?t:n.getSelected(),f=c&&c.get('resizable'),h={},d=function(t,e,n){var r=n.docs;r&&r.forEach((function(e){var n=e.body,r=n.className||'';n.className=('add'==t?"".concat(r," ").concat(s):r.replace(s,'')).trim()}))};if(o&&f){var p=Object(l["isElement"])(t)?t:c.getEl();h={onStart:function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=i.el,a=i.config,s=i.resizer,l=a.keyHeight,f=a.keyWidth,h=a.currentUnit,p=a.keepAutoHeight,g=a.keepAutoWidth;d('add',0,i),e=n.get('StyleManager').getModelToStyle(c),r.toggleFramesEvents();var v=getComputedStyle(o),m=e.getStyle(),y=m[f];a.autoWidth=g&&'auto'===y,isNaN(parseFloat(y))&&(y=v[f]);var b=m[l];a.autoHeight=p&&'auto'===b,isNaN(parseFloat(b))&&(b=v[l]),s.startDim.w=parseFloat(y),s.startDim.h=parseFloat(b),O=0,h&&(a.unitHeight=Object(u["getUnitFromValue"])(b),a.unitWidth=Object(u["getUnitFromValue"])(y))},onMove:function(){o.trigger('component:resize')},onEnd:function(t,e){d('remove',0,e),o.trigger('component:resize'),r.toggleFramesEvents(1),O=1},updateTarget:function(t,i){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(e){var a=o.store,s=o.selectedHandler,c=o.config,l=c.keyHeight,u=c.keyWidth,f=c.autoHeight,h=c.autoWidth,d=c.unitWidth,p=c.unitHeight,g=['tc','bc'].indexOf(s)>=0,v=['cl','cr'].indexOf(s)>=0,m={},y=a?'':1;if(!g){var b=r.getBody().offsetWidth,O=i.w0&&void 0!==arguments[0]?arguments[0]:{};return this.canvas.getBadgeEl(t.view)},onFrameScroll:function(){this.updateTools()},updateTools:function(){this.updateLocalPos(),this.updateGlobalPos()},isCompSelected:function(t){return t&&'selected'===t.get('status')},updateToolsLocal:function(t){var e=t||this.getElHovered(),n=e.el,r=e.pos,i=e.view,o=e.component;if(n){var a=o.get('hoverable'),s=this.lastHovered!==n,c=s?{}:{posOnly:1};s&&a&&(this.lastHovered=n,this.showHighlighter(i),this.showElementOffset(n,r,{view:i})),this.isCompSelected(o)&&(this.hideHighlighter(i),this.hideElementOffset(i));var l='px',u=this.toggleToolsEl(1,i),f=u.style,h=this.canvas.canvasRectOffset(n,r),d=h.top,p=h.left;this.updateBadge(n,r,w(w({},c),{},{view:i,topOff:d,leftOff:p})),f.top=d+l,f.left=p+l,f.width=r.width+l,f.height=r.height+l,this._trgToolUp('local',{component:o,el:u,top:d,left:p,width:r.width,height:r.height})}else this.lastHovered=0},_upToolbar:Object(l["debounce"])((function(){this.updateToolsGlobal({force:1})})),_trgToolUp:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.em.trigger('canvas:tools:update',w({type:t},e))},updateToolsGlobal:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.getElSelected(),n=e.el,r=e.pos,i=e.component;if(!n)return this.toggleToolsEl(),void(this.lastSelected=0);var o=this.canvas,a=this.lastSelected!==n;(a||t.force)&&(this.lastSelected=n,this.updateToolbar(i));var s='px',c=this.toggleToolsEl(1),l=c.style,u=o.getTargetToElementFixed(n,o.getToolbarEl(),{pos:r}),f=u.canvasOffsetTop,h=u.canvasOffsetLeft;l.top=f+s,l.left=h+s,l.width=r.width+s,l.height=r.height+s,this.updateToolbarPos({top:u.top,left:u.left}),this._trgToolUp('global',{component:i,el:c,top:f,left:h,width:r.width,height:r.height})},updateAttached:Object(l["debounce"])((function(){this.updateGlobalPos()})),onContainerChange:Object(l["debounce"])((function(){this.em.refreshCanvas()}),150),getElementPos:function(t){return this.canvas.getCanvasView().getElementPos(t)},hideBadge:function(){this.getBadge().style.display='none'},cleanPrevious:function(t){t&&t.set({status:'',state:''})},getContentWindow:function(){return this.canvas.getWindow()},run:function(t){Object(u["hasWin"])()&&(this.editor=t&&t.get('Editor'),this.enable())},stop:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(Object(u["hasWin"])()){var r=this.em,i=this.editor;this.onHovered(),this.stopSelectComponent(),!n.preserveSelected&&r.setSelected(null),this.toggleToolsEl(),i&&i.stopCommand('resize')}}}},function(t,e,n){"use strict";n.d(e,"a",(function(){return d}));var r=n(2),i=n.n(r),o=n(5),a=n.n(o),s=n(6),c=n.n(s),l=n(0),u=n(1);function f(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function h(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{};return a()(this,t),this.opts={container:null,onStart:null,onDrag:null,onEnd:null,setPosition:null,getPosition:null,guidesStatic:null,guidesTarget:null,snapOffset:5,doc:0,scale:1},Object(l["bindAll"])(this,'drag','stop','keyHandle','handleScroll'),this.setOptions(e),this.delta={x:0,y:0},this}return c()(t,[{key:"setOptions",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.opts=h(h({},this.opts),t)}},{key:"toggleDrag",value:function(t){var e=this.getDocumentEl(),n=this.getContainerEl(),r=this.getWindowEl(),i=t?'on':'off',o={on:u["on"],off:u["off"]};o[i](n,'mousemove dragover',this.drag),o[i](e,'mouseup dragend touchend',this.stop),o[i](e,'keydown',this.keyHandle),o[i](r,'scroll',this.handleScroll)}},{key:"handleScroll",value:function(){var t=this.lastScroll,e=this.delta,n=this.getScrollInfo(),r={x:n.x-t.x,y:n.y-t.y};this.move(e.x+r.x,e.y+r.y),this.lastScrollDiff=r}},{key:"start",value:function(t){var e=this.opts,n=e.onStart;this.toggleDrag(1),this.startPointer=this.getPointerPos(t),this.guidesStatic=Object(l["result"])(e,'guidesStatic')||[],this.guidesTarget=Object(l["result"])(e,'guidesTarget')||[],Object(l["isFunction"])(n)&&n(t,this),this.startPosition=this.getStartPosition(),this.lastScrollDiff={x:0,y:0},this.globScrollDiff={x:0,y:0},this.drag(t)}},{key:"drag",value:function(t){var e=this,n=this.opts,r=this.lastScrollDiff,i=this.globScrollDiff,o=n.onDrag,a=this.startPointer,s=this.getPointerPos(t),c={x:i.x+r.x,y:i.y+r.y};this.globScrollDiff=c;var u={x:s.x-a.x+c.x,y:s.y-a.y+c.y};this.lastScrollDiff={x:0,y:0};var f=this.lockedAxis;'x'===(f=t.shiftKey?!f&&this.detectAxisLock(u.x,u.y):null)?u.x=a.x:'y'===f&&(u.y=a.y);var d=function(r){['x','y'].forEach((function(t){return r[t]=r[t]*Object(l["result"])(n,'scale')})),e.delta=r,e.move(r.x,r.y),Object(l["isFunction"])(o)&&o(t,e)},p=h({},u);if(this.currentPointer=s,this.lockedAxis=f,this.lastScroll=this.getScrollInfo(),d(u),this.guidesTarget.length){var g=this.snapGuides(p),v=g.newDelta,m=g.trgX,y=g.trgY;(m||y)&&d(v)}0===t.which&&this.stop(t)}},{key:"snapGuides",value:function(t){var e=this,n=t,r=this.trgX,i=this.trgY;return this.guidesTarget.forEach((function(n){n.x&&e.trgX||n.y&&e.trgY||(n.active=0,e.guidesStatic.forEach((function(o){if(!(n.y&&o.x||n.x&&o.y)){var a=n.y&&o.y,s=a?'y':'x',c=n[s],u=o[s],f=t[s],h=a?i:r;if(e.isPointIn(c,u)&&Object(l["isUndefined"])(h)){var d=f-(c-u);e.setGuideLock(n,d)}}})))})),r=this.trgX,i=this.trgY,['x','y'].forEach((function(r){var i=r.toUpperCase(),o=e["trg".concat(i)];o&&!e.isPointIn(t[r],o.lock)&&(e.setGuideLock(o,null),o=null),o&&!Object(l["isUndefined"])(o.lock)&&(n[r]=o.lock)})),{newDelta:n,trgX:this.trgX,trgY:this.trgY}}},{key:"isPointIn",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.offset,i=r||this.opts.snapOffset;return t>=e&&t<=e+i||t<=e&&t>=e-i}},{key:"setGuideLock",value:function(t,e){var n=Object(l["isUndefined"])(t.x)?'Y':'X',r="trg".concat(n);return null!==e?(t.active=1,t.lock=e,this[r]=t):(delete t.active,delete t.lock,delete this[r]),t}},{key:"stop",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.delta,r=e.cancel,i=r?0:n.x,o=r?0:n.y;this.toggleDrag(),this.lockedAxis=null,this.move(i,o,1);var a=this.opts.onEnd;Object(l["isFunction"])(a)&&a(t,this,{cancelled:r})}},{key:"keyHandle",value:function(t){Object(u["isEscKey"])(t)&&this.stop(t,{cancel:1})}},{key:"move",value:function(t,e,n){var r=this.el,i=this.opts,o=this.startPosition;if(o){var a=i.setPosition,s=o.x+t,c=o.y+e;this.position={x:s,y:c,end:n},Object(l["isFunction"])(a)&&a(this.position),r&&(r.style.left="".concat(s,"px"),r.style.top="".concat(c,"px"))}}},{key:"getContainerEl",value:function(){var t=this.opts.container;return t?[t]:this.getDocumentEl()}},{key:"getWindowEl",value:function(){return this.getContainerEl().map((function(t){var e=t.ownerDocument||t;return e.defaultView||e.parentWindow}))}},{key:"getDocumentEl",value:function(t){var e=this.opts.doc;if(t=t||this.el,!this.docs){var n=[document];t&&n.push(t.ownerDocument),e&&n.push(e),this.docs=n}return this.docs}},{key:"getPointerPos",value:function(t){var e=this.opts.getPointerPosition,n=Object(u["getPointerEvent"])(t);return e?e(t):{x:n.clientX,y:n.clientY}}},{key:"getStartPosition",value:function(){var t=this.el,e=this.opts.getPosition,n={x:0,y:0};return Object(l["isFunction"])(e)?n=e():t&&(n={x:parseFloat(t.style.left),y:parseFloat(t.style.top)}),n}},{key:"getScrollInfo",value:function(){var t=this.opts.doc,e=t&&t.body;return{y:e?e.scrollTop:0,x:e?e.scrollLeft:0}}},{key:"detectAxisLock",value:function(t,e){var n=t,r=e,i=Math.abs(n),o=Math.abs(r);return r>=i||r<=-i?'x':n>o||n<-o?'y':void 0}}]),t}()},function(t,e,n){"use strict";var r=n(3),i=n.n(r),o=i.a.$;e["a"]=i.a.View.extend({events:{change:'handleChange'},template:function(){return"")},inputClass:function(){return"".concat(this.ppfx,"field")},holderClass:function(){return"".concat(this.ppfx,"input-holder")},initialize:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.ppfx||'';this.opts=t,this.ppfx=e,this.em=t.target||{},!t.onChange&&this.listenTo(this.model,'change:value',this.handleModelChange)},elementUpdated:function(){this.model.trigger('el:change')},setValue:function(t){var e=this.model,n=t||e.get('defaults'),r=this.getInputEl();r&&(r.value=n)},handleModelChange:function(t,e,n){this.setValue(e,n)},handleChange:function(t){t.stopPropagation();var e=this.getInputEl().value;this.__onInputChange(e),this.elementUpdated()},__onInputChange:function(t){this.model.set({value:t},{fromInput:1})},getInputEl:function(){if(!this.inputEl){var t=this.model,e=this.opts.type||'text',n=t.get('placeholder')||t.get('defaults')||t.get('default')||'';this.inputEl=o(""))}return this.inputEl.get(0)},render:function(){this.inputEl=null;var t=this.$el;return t.addClass(this.inputClass()),t.html(this.template()),t.find(".".concat(this.holderClass())).append(this.getInputEl()),this}})},function(t,e,n){t.exports=n(95)},function(t,e,n){"use strict";var r=n(14),i=n.n(r),o=n(11),a=n.n(o),s=n(18),c=n.n(s),l=n(2),u=n.n(l),f=n(3),h=n.n(f),d=n(0),p=n(10),g=["at"];function v(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function m(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:[];if(!e)return[];var r=Object(d["isArray"])(e)||Object(d["isFunction"])(e.map)?e:[e];return r.map((function(e){n.push(e.getId()),t(e.components().models,n)})),n},b=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=Object(d["isArray"])(e)?e:[e];return i.map((function(e){var i=e.attributes,o=void 0===i?{}:i,a=e.components,s=e.tagName,c=o.id,l=e;if(c&&n[c]&&(l=n[c],s&&l.set({tagName:s},m(m({},r),{},{silent:!0}))),a){var u=t(a,n);if(Object(d["isFunction"])(l.components)){var f=l.components();f.length>0&&f.reset(u,r)}else l.components=u}return l}))};e["a"]=h.a.Collection.extend({initialize:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.opt=e,this.listenTo(this,'add',this.onAdd),this.listenTo(this,'remove',this.removeChildren),this.listenTo(this,'reset',this.resetChildren);var n=e.em,r=e.config;this.config=r,this.em=n,this.domc=e.domc||n&&n.get('DomComponents')},resetChildren:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this,i=n.previousModels||[],o=i.filter((function(e){return!t.get(e.cid)})),a=y(t);n.keepIds=y(i).filter((function(t){return a.indexOf(t)>=0})),o.forEach((function(t){return e.removeChildren(t,r,n)})),t.each((function(t){return e.onAdd(t)}))},resetFromString:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:'',n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n.keepIds=y(this);var r=this.domc,i=(null==r?void 0:r.allById())||{},o=this.parseString(e,n),a=Object(d["isArray"])(o)?o:[o],s=b(a,i,n);this.reset(s,n),null===(t=this.em)||void 0===t||t.trigger('component:content',this.parent,n,e)},removeChildren:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(t){var i=this.domc,o=this.em,a=r.temporary||r.fromUndo;if(t.prevColl=this,!a){var s=t.getId(),c=o.get('SelectorManager').getAll(),l=o.get('CssComposer').getAll(),u=(r.keepIds||[]).indexOf(s)<0,f=i?i.allById():{};delete f[s];var h=u?l.remove(l.filter((function(t){return t.getSelectors().getFullString()==="#".concat(s)})),r):[];c.remove(h.map((function(t){return t.getSelectors().at(0)}))),t.opt.temporary||(o.get('Commands').run('core:component-style-clear',{target:t}),t.removed(),t.trigger('removed'),o.trigger('component:remove',t));var d=t.components();d.forEach((function(t){return n.removeChildren(t,e,r)}))}var p=t.components();o.stopListening(p),o.stopListening(t),o.stopListening(t.get('classes')),t.__postRemove()}},model:function(t,e){var n,r=e.collection.opt,i=r.em,o=i.get('DomComponents').componentTypes;e.em=i,e.config=r.config,e.componentTypes=o,e.domc=r.domc;for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:{},n=this.em,r=this.domc,i=n.get('CssComposer'),o=n.get('Parser').parseHtml(t);if(p["a"].checkId(o.html,o.css,r.componentsById,e),o.css&&i&&!e.temporary){e.at;var a=c()(e,g);i.addCollection(o.css,m(m({},a),{},{extend:1}))}return o.html},add:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n.keepIds=[].concat(a()(n.keepIds||[]),a()(y(n.previousModels))),Object(d["isString"])(t)?t=this.parseString(t,n):Object(d["isArray"])(t)&&(t=a()(t)).forEach((function(r,i){if(Object(d["isString"])(r)){var o=e.parseString(r,n);t[i]=Object(d["isArray"])(o)&&!o.length?null:o}}));var r=Object(d["isArray"])(t);t=(r?t:[t]).filter((function(t){return t})).map((function(t){return e.processDef(t)})),t=r?Object(d["flatten"])(t,1):t[0];var i=h.a.Collection.prototype.add.apply(this,[t,n]);return this.__firstAdd=i,i},processDef:function(t){if(t.cid&&t.ccid)return t;var e=this.em,n=this.config,r=(void 0===n?{}:n).processor,o=t;if(r){var a=r(o=m({},o));a&&(Object(d["each"])(o,(function(t,e){return delete o[e]})),Object(d["extend"])(o,a))}if(o.$$typeof&&'object'==i()(o.props)){(o=m({},o)).props=m({},o.props);var s=e.get('DomComponents'),c=e.get('Parser').parserHtml;Object(d["each"])(o,(function(t,e){Object(d["includes"])(['props','type'],e)||delete o[e]}));var l=o.props,u=l.children;delete l.children,delete o.props;var f=c.splitPropsFromAttr(l);o.attributes=f.attrs,u&&(o.components=u),o.type?s.getType(o.type)||(o.tagName=o.type,delete o.type):o.type='textnode',Object(d["extend"])(o,f.props)}return o},onAdd:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.domc,i=this.em,o=t.getStyle(),a=i&&i.getConfig('avoidInlineStyle');if(r&&r.Component.ensureInList(t),!Object(d["isEmpty"])(o)&&!a&&i&&i.get&&i.getConfig('forceClass')&&!n.temporary){var s=t.cid;i.get('CssComposer').setClassRule(s,o);t.setStyle({}),t.addClass(s)}t.__postAdd({recursive:1}),this.__onAddEnd()},__onAddEnd:Object(d["debounce"])((function(){}))})},function(t,e,n){1&&(t.exports=function(){'use strict';var t=navigator.userAgent,e=navigator.platform,n=/gecko\/\d/i.test(t),r=/MSIE \d/.test(t),i=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(t),o=/Edge\/(\d+)/.exec(t),a=r||i||o,s=a&&(r?document.documentMode||6:+(o||i)[1]),c=!o&&/WebKit\//.test(t),l=c&&/Qt\/\d+\.\d+/.test(t),u=!o&&/Chrome\//.test(t),f=/Opera\//.test(t),h=/Apple Computer/.test(navigator.vendor),d=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(t),p=/PhantomJS/.test(t),g=h&&(/Mobile\/\w+/.test(t)||navigator.maxTouchPoints>2),v=/Android/.test(t),m=g||v||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(t),y=g||/Mac/.test(e),b=/\bCrOS\b/.test(t),w=/win/i.test(e),O=f&&t.match(/Version\/(\d*\.\d*)/);O&&(O=Number(O[1])),O&&O>=15&&(f=!1,c=!0);var x=y&&(l||f&&(null==O||O<12.11)),C=n||a&&s>=9;function k(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}var S,j=function(t,e){var n=t.className,r=k(e).exec(n);if(r){var i=n.slice(r.index+r[0].length);t.className=n.slice(0,r.index)+(i?r[1]+i:"")}};function P(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function _(t,e){return P(t).appendChild(e)}function T(t,e,n,r){var i=document.createElement(t);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof e)i.appendChild(document.createTextNode(e));else if(e)for(var o=0;o=e)return a+(e-o);a+=s-o,a+=n-a%n,o=s+1}}g?R=function(t){t.selectionStart=0,t.selectionEnd=t.value.length}:a&&(R=function(t){try{t.select()}catch(t){}});var V=function(){this.id=null,this.f=null,this.time=0,this.handler=N(this.onTimeout,this)};function B(t,e){for(var n=0;n=e)return r+Math.min(a,e-i);if(i+=o-r,r=o+1,(i+=n-i%n)>=e)return r}}var G=[""];function K(t){for(;G.length<=t;)G.push(Y(G)+" ");return G[t]}function Y(t){return t[t.length-1]}function J(t,e){for(var n=[],r=0;r"€"&&(t.toUpperCase()!=t.toLowerCase()||Q.test(t))}function et(t,e){return e?!!(e.source.indexOf("\\w")>-1&&tt(t))||e.test(t):tt(t)}function nt(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return!1;return!0}var rt=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function it(t){return t.charCodeAt(0)>=768&&rt.test(t)}function ot(t,e,n){for(;(n<0?e>0:en?-1:1;;){if(e==n)return e;var i=(e+n)/2,o=r<0?Math.ceil(i):Math.floor(i);if(o==e)return t(o)?e:n;t(o)?n=o:e=o+r}}var st=null;function ct(t,e,n){var r;st=null;for(var i=0;ie)return i;o.to==e&&(o.from!=o.to&&"before"==n?r=i:st=i),o.from==e&&(o.from!=o.to&&"before"!=n?r=i:st=i)}return null!=r?r:st}var lt=function(){var t="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",e="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,r=/[stwN]/,i=/[LRr]/,o=/[Lb1n]/,a=/[1n]/;function s(t,e,n){this.level=t,this.from=e,this.to=n}return function(c,l){var u="ltr"==l?"L":"R";if(0==c.length||"ltr"==l&&!n.test(c))return!1;for(var f,h=c.length,d=[],p=0;p-1&&(r[e]=i.slice(0,o).concat(i.slice(o+1)))}}}function gt(t,e){var n=dt(t,e);if(n.length)for(var r=Array.prototype.slice.call(arguments,2),i=0;i0}function bt(t){t.prototype.on=function(t,e){ht(this,t,e)},t.prototype.off=function(t,e){pt(this,t,e)}}function wt(t){t.preventDefault?t.preventDefault():t.returnValue=!1}function Ot(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0}function xt(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function Ct(t){wt(t),Ot(t)}function kt(t){return t.target||t.srcElement}function St(t){var e=t.which;return null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2)),y&&t.ctrlKey&&1==e&&(e=3),e}var jt,Pt,_t=function(){if(a&&s<9)return!1;var t=T('div');return"draggable"in t||"dragDrop"in t}();function Tt(t){if(null==jt){var e=T("span","​");_(t,T("span",[e,document.createTextNode("x")])),0!=t.firstChild.offsetHeight&&(jt=e.offsetWidth<=1&&e.offsetHeight>2&&!(a&&s<8))}var n=jt?T("span","​"):T("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function Et(t){if(null!=Pt)return Pt;var e=_(t,document.createTextNode("AخA")),n=S(e,0,1).getBoundingClientRect(),r=S(e,1,2).getBoundingClientRect();return P(t),!(!n||n.left==n.right)&&(Pt=r.right-n.right<3)}var Dt,Mt=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,n=[],r=t.length;e<=r;){var i=t.indexOf("\n",e);-1==i&&(i=t.length);var o=t.slice(e,"\r"==t.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),e+=a+1):(n.push(o),e=i+1)}return n}:function(t){return t.split(/\r\n?|\n/)},At=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(t){return!1}}:function(t){var e;try{e=t.ownerDocument.selection.createRange()}catch(t){}return!(!e||e.parentElement()!=t)&&0!=e.compareEndPoints("StartToEnd",e)},Lt="oncopy"in(Dt=T("div"))||(Dt.setAttribute("oncopy","return;"),"function"==typeof Dt.oncopy),Rt=null,Nt={},It={};function Ft(t,e){arguments.length>2&&(e.dependencies=Array.prototype.slice.call(arguments,2)),Nt[t]=e}function Vt(t){if("string"==typeof t&&It.hasOwnProperty(t))t=It[t];else if(t&&"string"==typeof t.name&&It.hasOwnProperty(t.name)){var e=It[t.name];"string"==typeof e&&(e={name:e}),(t=Z(e,t)).name=e.name}else{if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return Vt("application/xml");if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+json$/.test(t))return Vt("application/json")}return"string"==typeof t?{name:t}:t||{name:"null"}}function Bt(t,e){e=Vt(e);var n=Nt[e.name];if(!n)return Bt(t,"text/plain");var r=n(t,e);if(Ht.hasOwnProperty(e.name)){var i=Ht[e.name];for(var o in i)i.hasOwnProperty(o)&&(r.hasOwnProperty(o)&&(r["_"+o]=r[o]),r[o]=i[o])}if(r.name=e.name,e.helperType&&(r.helperType=e.helperType),e.modeProps)for(var a in e.modeProps)r[a]=e.modeProps[a];return r}var Ht={};function zt(t,e){I(e,Ht.hasOwnProperty(t)?Ht[t]:Ht[t]={})}function Ut(t,e){if(!0===e)return e;if(t.copyState)return t.copyState(e);var n={};for(var r in e){var i=e[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n}function Wt(t,e){for(var n;t.innerMode&&(n=t.innerMode(e))&&n.mode!=t;)e=n.state,t=n.mode;return n||{mode:t,state:e}}function $t(t,e,n){return!t.startState||t.startState(e,n)}var qt=function(t,e,n){this.pos=this.start=0,this.string=t,this.tabSize=e||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Gt(t,e){if((e-=t.first)<0||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var n=t;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(e=t.first&&en?ee(n,Gt(t,n).text.length):function(t,e){var n=t.ch;return null==n||n>e?ee(t.line,e):n<0?ee(t.line,0):t}(e,Gt(t,e.line).text.length)}function le(t,e){for(var n=[],r=0;r=this.string.length},qt.prototype.sol=function(){return this.pos==this.lineStart},qt.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},qt.prototype.next=function(){if(this.pose},qt.prototype.eatSpace=function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},qt.prototype.skipToEnd=function(){this.pos=this.string.length},qt.prototype.skipTo=function(t){var e=this.string.indexOf(t,this.pos);if(e>-1)return this.pos=e,!0},qt.prototype.backUp=function(t){this.pos-=t},qt.prototype.column=function(){return this.lastColumnPos0?null:(r&&!1!==e&&(this.pos+=r[0].length),r)}var i=function(t){return n?t.toLowerCase():t};if(i(this.string.substr(this.pos,t.length))==i(t))return!1!==e&&(this.pos+=t.length),!0},qt.prototype.current=function(){return this.string.slice(this.start,this.pos)},qt.prototype.hideFirstChars=function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t}},qt.prototype.lookAhead=function(t){var e=this.lineOracle;return e&&e.lookAhead(t)},qt.prototype.baseToken=function(){var t=this.lineOracle;return t&&t.baseToken(this.pos)};var ue=function(t,e){this.state=t,this.lookAhead=e},fe=function(t,e,n,r){this.state=e,this.doc=t,this.line=n,this.maxLookAhead=r||0,this.baseTokens=null,this.baseTokenPos=1};function he(t,e,n,r){var i=[t.state.modeGen],o={};Oe(t,e.text,t.doc.mode,n,(function(t,e){return i.push(t,e)}),o,r);for(var a=n.state,s=function(r){n.baseTokens=i;var s=t.state.overlays[r],c=1,l=0;n.state=!0,Oe(t,e.text,s.mode,n,(function(t,e){for(var n=c;lt&&i.splice(c,1,t,i[c+1],r),c+=2,l=Math.min(t,r)}if(e)if(s.opaque)i.splice(n,c-n,t,"overlay "+e),c=n+2;else for(;nt.options.maxHighlightLength&&Ut(t.doc.mode,r.state),o=he(t,e,r);i&&(r.state=i),e.stateAfter=r.save(!i),e.styles=o.styles,o.classes?e.styleClasses=o.classes:e.styleClasses&&(e.styleClasses=null),n===t.doc.highlightFrontier&&(t.doc.modeFrontier=Math.max(t.doc.modeFrontier,++t.doc.highlightFrontier))}return e.styles}function pe(t,e,n){var r=t.doc,i=t.display;if(!r.mode.startState)return new fe(r,!0,e);var o=function(t,e,n){for(var r,i,o=t.doc,a=n?-1:e-(t.doc.mode.innerMode?1e3:100),s=e;s>a;--s){if(s<=o.first)return o.first;var c=Gt(o,s-1),l=c.stateAfter;if(l&&(!n||s+(l instanceof ue?l.lookAhead:0)<=o.modeFrontier))return s;var u=F(c.text,null,t.options.tabSize);(null==i||r>u)&&(i=s-1,r=u)}return i}(t,e,n),a=o>r.first&&Gt(r,o-1).stateAfter,s=a?fe.fromSaved(r,a,o):new fe(r,$t(r.mode),o);return r.iter(o,e,(function(n){ge(t,n.text,s);var r=s.line;n.stateAfter=r==e-1||r%5==0||r>=i.viewFrom&&re.start)return o}throw new Error("Mode "+t.name+" failed to advance stream.")}fe.prototype.lookAhead=function(t){var e=this.doc.getLine(this.line+t);return null!=e&&t>this.maxLookAhead&&(this.maxLookAhead=t),e},fe.prototype.baseToken=function(t){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=t;)this.baseTokenPos+=2;var e=this.baseTokens[this.baseTokenPos+1];return{type:e&&e.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-t}},fe.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},fe.fromSaved=function(t,e,n){return e instanceof ue?new fe(t,Ut(t.mode,e.state),n,e.lookAhead):new fe(t,Ut(t.mode,e),n)},fe.prototype.save=function(t){var e=!1!==t?Ut(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new ue(e,this.maxLookAhead):e};var ye=function(t,e,n){this.start=t.start,this.end=t.pos,this.string=t.current(),this.type=e||null,this.state=n};function be(t,e,n,r){var i,o,a=t.doc,s=a.mode,c=Gt(a,(e=ce(a,e)).line),l=pe(t,e.line,n),u=new qt(c.text,t.options.tabSize,l);for(r&&(o=[]);(r||u.post.options.maxHighlightLength?(s=!1,a&&ge(t,e,r,f.pos),f.pos=e.length,c=null):c=we(me(n,f,r.state,h),o),h){var d=h[0].name;d&&(c="m-"+(c?d+" "+c:d))}if(!s||u!=c){for(;l=e:o.to>e);(r||(r=[])).push(new ke(a,o.from,s?null:o.to))}}return r}(n,i,a),c=function(t,e,n){var r;if(t)for(var i=0;i=e:o.to>e)||o.from==e&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var s=null==o.from||(a.inclusiveLeft?o.from<=e:o.from0&&s)for(var b=0;be)&&(!n||Ae(n,o.marker)<0)&&(n=o.marker)}return n}function Fe(t,e,n,r,i){var o=Gt(t,e),a=Ce&&o.markedSpans;if(a)for(var s=0;s=0&&f<=0||u<=0&&f>=0)&&(u<=0&&(c.marker.inclusiveRight&&i.inclusiveLeft?ne(l.to,n)>=0:ne(l.to,n)>0)||u>=0&&(c.marker.inclusiveRight&&i.inclusiveLeft?ne(l.from,r)<=0:ne(l.from,r)<0)))return!0}}}function Ve(t){for(var e;e=Re(t);)t=e.find(-1,!0).line;return t}function Be(t,e){var n=Gt(t,e),r=Ve(n);return n==r?e:Xt(r)}function He(t,e){if(e>t.lastLine())return e;var n,r=Gt(t,e);if(!ze(t,r))return e;for(;n=Ne(r);)r=n.find(1,!0).line;return Xt(r)+1}function ze(t,e){var n=Ce&&e.markedSpans;if(n)for(var r=void 0,i=0;ie.maxLineLength&&(e.maxLineLength=n,e.maxLine=t)}))}var Ge=function(t,e,n){this.text=t,Ee(this,e),this.height=n?n(this):1};function Ke(t){t.parent=null,Te(t)}Ge.prototype.lineNo=function(){return Xt(this)},bt(Ge);var Ye={},Je={};function Xe(t,e){if(!t||/^\s*$/.test(t))return null;var n=e.addModeClass?Je:Ye;return n[t]||(n[t]=t.replace(/\S+/g,"cm-$&"))}function Ze(t,e){var n=E("span",null,null,c?"padding-right: .1px":null),r={pre:E("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:t,trailingSpace:!1,splitSpaces:t.getOption("lineWrapping")};e.measure={};for(var i=0;i<=(e.rest?e.rest.length:0);i++){var o=i?e.rest[i-1]:e.line,a=void 0;r.pos=0,r.addToken=tn,Et(t.display.measure)&&(a=ut(o,t.doc.direction))&&(r.addToken=en(r.addToken,a)),r.map=[],rn(o,r,de(t,o,e!=t.display.externalMeasured&&Xt(o))),o.styleClasses&&(o.styleClasses.bgClass&&(r.bgClass=L(o.styleClasses.bgClass,r.bgClass||"")),o.styleClasses.textClass&&(r.textClass=L(o.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Tt(t.display.measure))),0==i?(e.measure.map=r.map,e.measure.cache={}):((e.measure.maps||(e.measure.maps=[])).push(r.map),(e.measure.caches||(e.measure.caches=[])).push({}))}if(c){var s=r.content.lastChild;(/\bcm-tab\b/.test(s.className)||s.querySelector&&s.querySelector(".cm-tab"))&&(r.content.className="cm-tab-wrap-hack")}return gt(t,"renderLine",t,e.line,r.pre),r.pre.className&&(r.textClass=L(r.pre.className,r.textClass||"")),r}function Qe(t){var e=T("span","•","cm-invalidchar");return e.title="\\u"+t.charCodeAt(0).toString(16),e.setAttribute("aria-label",e.title),e}function tn(t,e,n,r,i,o,c){if(e){var l,u=t.splitSpaces?function(t,e){if(t.length>1&&!/ /.test(t))return t;for(var n=e,r="",i=0;il&&f.from<=l);h++);if(f.to>=u)return t(n,r,i,o,a,s,c);t(n,r.slice(0,f.to-l),i,o,null,s,c),o=null,r=r.slice(f.to-l),l=f.to}}}function nn(t,e,n,r){var i=!r&&n.widgetNode;i&&t.map.push(t.pos,t.pos+e,i),!r&&t.cm.display.input.needsContentAttribute&&(i||(i=t.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",n.id)),i&&(t.cm.display.input.setUneditable(i),t.content.appendChild(i)),t.pos+=e,t.trailingSpace=!1}function rn(t,e,n){var r=t.markedSpans,i=t.text,o=0;if(r)for(var a,s,c,l,u,f,h,d=i.length,p=0,g=1,v="",m=0;;){if(m==p){c=l=u=s="",h=null,f=null,m=1/0;for(var y=[],b=void 0,w=0;wp||x.collapsed&&O.to==p&&O.from==p)){if(null!=O.to&&O.to!=p&&m>O.to&&(m=O.to,l=""),x.className&&(c+=" "+x.className),x.css&&(s=(s?s+";":"")+x.css),x.startStyle&&O.from==p&&(u+=" "+x.startStyle),x.endStyle&&O.to==m&&(b||(b=[])).push(x.endStyle,O.to),x.title&&((h||(h={})).title=x.title),x.attributes)for(var C in x.attributes)(h||(h={}))[C]=x.attributes[C];x.collapsed&&(!f||Ae(f.marker,x)<0)&&(f=O)}else O.from>p&&m>O.from&&(m=O.from)}if(b)for(var k=0;k=d)break;for(var j=Math.min(d,m);1;){if(v){var P=p+v.length;if(!f){var _=P>j?v.slice(0,j-p):v;e.addToken(e,_,a?a+c:c,u,p+_.length==m?l:"",s,h)}if(P>=j){v=v.slice(j-p),p=j;break}p=P,u=""}v=i.slice(o,o=n[g++]),a=Xe(n[g++],e.cm.options)}}else for(var T=1;Tn)return{map:t.measure.maps[i],cache:t.measure.caches[i],before:!0}}function Dn(t,e,n,r){return Ln(t,An(t,e),n,r)}function Mn(t,e){if(e>=t.display.viewFrom&&e=n.lineN&&e2&&o.push((c.bottom+l.top)/2-n.top)}}o.push(n.bottom-n.top)}}(t,e.view,e.rect),e.hasHeights=!0),(o=function(t,e,n,r){var i,o=In(e.map,n,r),c=o.node,l=o.start,u=o.end,f=o.collapse;if(3==c.nodeType){for(var h=0;h<4;h++){for(;l&&it(e.line.text.charAt(o.coverStart+l));)--l;for(;o.coverStart+u1}(t))return e;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:e.left*n,right:e.right*n,top:e.top*r,bottom:e.bottom*r}}(t.display.measure,i))}else{var d;l>0&&(f=r="right"),i=t.options.lineWrapping&&(d=c.getClientRects()).length>1?d["right"==r?d.length-1:0]:c.getBoundingClientRect()}if(a&&s<9&&!l&&(!i||!i.left&&!i.right)){var p=c.parentNode.getClientRects()[0];i=p?{left:p.left,right:p.left+or(t.display),top:p.top,bottom:p.bottom}:Nn}for(var g=i.top-e.rect.top,v=i.bottom-e.rect.top,m=(g+v)/2,y=e.view.measure.heights,b=0;be)&&(i=(o=c-s)-1,e>=c&&(a="right")),null!=i){if(r=t[l+2],s==c&&n==(r.insertLeft?"left":"right")&&(a=n),"left"==n&&0==i)for(;l&&t[l-2]==t[l-3]&&t[l-1].insertLeft;)r=t[(l-=3)+2],a="left";if("right"==n&&i==c-s)for(;l=0&&(n=t[i]).left==n.right;i--);return n}function Vn(t){if(t.measure&&(t.measure.cache={},t.measure.heights=null,t.rest))for(var e=0;e=r.text.length?(c=r.text.length,l="before"):c<=0&&(c=0,l="after"),!s)return a("before"==l?c-1:c,"before"==l);function u(t,e,n){return a(n?t-1:t,1==s[e].level!=n)}var f=ct(s,c,l),h=st,d=u(c,f,"before"==l);return null!=h&&(d.other=u(c,h,"before"!=l)),d}function Yn(t,e){var n=0;e=ce(t.doc,e),t.options.lineWrapping||(n=or(t.display)*e.ch);var r=Gt(t.doc,e.line),i=We(r)+kn(t.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Jn(t,e,n,r,i){var o=ee(t,e,n);return o.xRel=i,r&&(o.outside=r),o}function Xn(t,e,n){var r=t.doc;if((n+=t.display.viewOffset)<0)return Jn(r.first,0,null,-1,-1);var i=Zt(r,n),o=r.first+r.size-1;if(i>o)return Jn(r.first+r.size-1,Gt(r,o).text.length,null,1,1);e<0&&(e=0);for(var a=Gt(r,i);;){var s=er(t,a,i,e,n),c=Ie(a,s.ch+(s.xRel>0||s.outside>0?1:0));if(!c)return s;var l=c.find(1);if(l.line==i)return l;a=Gt(r,i=l.line)}}function Zn(t,e,n,r){r-=Wn(e);var i=e.text.length,o=at((function(e){return Ln(t,n,e-1).bottom<=r}),i,0);return{begin:o,end:i=at((function(e){return Ln(t,n,e).top>r}),o,i)}}function Qn(t,e,n,r){return n||(n=An(t,e)),Zn(t,e,n,$n(t,e,Ln(t,n,r),"line").top)}function tr(t,e,n,r){return!(t.bottom<=n)&&(t.top>n||(r?t.left:t.right)>e)}function er(t,e,n,r,i){i-=We(e);var o=An(t,e),a=Wn(e),s=0,c=e.text.length,l=!0,u=ut(e,t.doc.direction);if(u){var f=(t.options.lineWrapping?rr:nr)(t,e,n,o,u,r,i);s=(l=1!=f.level)?f.from:f.to-1,c=l?f.to:f.from-1}var h,d,p=null,g=null,v=at((function(e){var n=Ln(t,o,e);return n.top+=a,n.bottom+=a,!!tr(n,r,i,!1)&&(n.top<=i&&n.left<=r&&(p=e,g=n),!0)}),s,c),m=!1;if(g){var y=r-g.left=w.bottom?1:0}return Jn(n,v=ot(e.text,v,1),d,m,r-h)}function nr(t,e,n,r,i,o,a){var s=at((function(s){var c=i[s],l=1!=c.level;return tr(Kn(t,ee(n,l?c.to:c.from,l?"before":"after"),"line",e,r),o,a,!0)}),0,i.length-1),c=i[s];if(s>0){var l=1!=c.level,u=Kn(t,ee(n,l?c.from:c.to,l?"after":"before"),"line",e,r);tr(u,o,a,!0)&&u.top>a&&(c=i[s-1])}return c}function rr(t,e,n,r,i,o,a){var s=Zn(t,e,r,a),c=s.begin,l=s.end;/\s/.test(e.text.charAt(l-1))&&l--;for(var u=null,f=null,h=0;h=l||d.to<=c)){var p=Ln(t,r,1!=d.level?Math.min(l,d.to)-1:Math.max(c,d.from)).right,g=pg)&&(u=d,f=g)}}return u||(u=i[i.length-1]),u.froml&&(u={from:u.from,to:l,level:u.level}),u}function ir(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==Rn){Rn=T("pre",null,"CodeMirror-line-like");for(var e=0;e<49;++e)Rn.appendChild(document.createTextNode("x")),Rn.appendChild(T("br"));Rn.appendChild(document.createTextNode("x"))}_(t.measure,Rn);var n=Rn.offsetHeight/50;return n>3&&(t.cachedTextHeight=n),P(t.measure),n||1}function or(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=T("span","xxxxxxxxxx"),n=T("pre",[e],"CodeMirror-line-like");_(t.measure,n);var r=e.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(t.cachedCharWidth=i),i||10}function ar(t){for(var e=t.display,n={},r={},i=e.gutters.clientLeft,o=e.gutters.firstChild,a=0;o;o=o.nextSibling,++a){var s=t.display.gutterSpecs[a].className;n[s]=o.offsetLeft+o.clientLeft+i,r[s]=o.clientWidth}return{fixedPos:sr(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:e.wrapper.clientWidth}}function sr(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function cr(t){var e=ir(t.display),n=t.options.lineWrapping,r=n&&Math.max(5,t.display.scroller.clientWidth/or(t.display)-3);return function(i){if(ze(t.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a0&&(c=Gt(t.doc,l.line).text).length==l.ch){var u=F(c,c.length,t.options.tabSize)-c.length;l=ee(l.line,Math.max(0,Math.round((o-jn(t.display).left)/or(t.display))-u))}return l}function fr(t,e){if(e>=t.display.viewTo)return null;if((e-=t.display.viewFrom)<0)return null;for(var n=t.display.view,r=0;re)&&(i.updateLineNumbers=e),t.curOp.viewChanged=!0,e>=i.viewTo)Ce&&Be(t.doc,e)i.viewFrom?pr(t):(i.viewFrom+=r,i.viewTo+=r);else if(e<=i.viewFrom&&n>=i.viewTo)pr(t);else if(e<=i.viewFrom){var o=gr(t,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):pr(t)}else if(n>=i.viewTo){var a=gr(t,e,e,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):pr(t)}else{var s=gr(t,e,e,-1),c=gr(t,n,n+r,1);s&&c?(i.view=i.view.slice(0,s.index).concat(an(t,s.lineN,c.lineN)).concat(i.view.slice(c.index)),i.viewTo+=r):pr(t)}var l=i.externalMeasured;l&&(n=i.lineN&&e=r.viewTo)){var o=r.view[fr(t,e)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==B(a,n)&&a.push(n)}}}function pr(t){t.display.viewFrom=t.display.viewTo=t.doc.first,t.display.view=[],t.display.viewOffset=0}function gr(t,e,n,r){var i,o=fr(t,e),a=t.display.view;if(!Ce||n==t.doc.first+t.doc.size)return{index:o,lineN:n};for(var s=t.display.viewFrom,c=0;c0){if(o==a.length-1)return null;i=s+a[o].size-e,o++}else i=s-e;e+=i,n+=i}for(;Be(t.doc,n)!=n;){if(o==(r<0?0:a.length-1))return null;n+=r*a[o-(r<0?1:0)].size,o+=r}return{index:o,lineN:n}}function vr(t){for(var e=t.display.view,n=0,r=0;r=t.display.viewTo||s.to().line0&&(i.style.width=o.right-o.left+"px")}if(r.other){var a=n.appendChild(T("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));a.style.display="",a.style.left=r.other.left+"px",a.style.top=r.other.top+"px",a.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function wr(t,e){return t.top-e.top||t.left-e.left}function Or(t,e,n){var r=t.display,i=t.doc,o=document.createDocumentFragment(),a=jn(t.display),s=a.left,c=Math.max(r.sizerWidth,_n(t)-r.sizer.offsetLeft)-a.right,l="ltr"==i.direction;function u(t,e,n,r){e<0&&(e=0),e=Math.round(e),r=Math.round(r),o.appendChild(T("div",null,"CodeMirror-selected","position: absolute; left: "+t+"px;\n top: "+e+"px; width: "+(null==n?c-t:n)+"px;\n height: "+(r-e)+"px"))}function f(e,n,r){var o,a,f=Gt(i,e),h=f.text.length;function d(n,r){return Gn(t,ee(e,n),"div",f,r)}function p(e,n,r){var i=Qn(t,f,null,e),o="ltr"==n==("after"==r)?"left":"right";return d("after"==r?i.begin:i.end-(/\s/.test(f.text.charAt(i.end-1))?2:1),o)[o]}var g=ut(f,i.direction);return function(t,e,n,r){if(!t)return r(e,n,"ltr",0);for(var i=!1,o=0;oe||e==n&&a.to==e)&&(r(Math.max(a.from,e),Math.min(a.to,n),1==a.level?"rtl":"ltr",o),i=!0)}i||r(e,n,"ltr")}(g,n||0,null==r?h:r,(function(t,e,i,f){var v="ltr"==i,m=d(t,v?"left":"right"),y=d(e-1,v?"right":"left"),b=null==n&&0==t,w=null==r&&e==h,O=0==f,x=!g||f==g.length-1;if(y.top-m.top<=3){var C=(l?w:b)&&x,k=(l?b:w)&&O?s:(v?m:y).left,S=C?c:(v?y:m).right;u(k,m.top,S-k,m.bottom)}else{var j,P,_,T;v?(j=l&&b&&O?s:m.left,P=l?c:p(t,i,"before"),_=l?s:p(e,i,"after"),T=l&&w&&x?c:y.right):(j=l?p(t,i,"before"):s,P=!l&&b&&O?c:m.right,_=!l&&w&&x?s:y.left,T=l?p(e,i,"after"):c),u(j,m.top,P-j,m.bottom),m.bottom0?e.blinker=setInterval((function(){t.hasFocus()||jr(t),e.cursorDiv.style.visibility=(n=!n)?"":"hidden"}),t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden")}}function Cr(t){t.hasFocus()||(t.display.input.focus(),t.state.focused||Sr(t))}function kr(t){t.state.delayingBlurEvent=!0,setTimeout((function(){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1,t.state.focused&&jr(t))}),100)}function Sr(t,e){t.state.delayingBlurEvent&&!t.state.draggingText&&(t.state.delayingBlurEvent=!1),"nocursor"!=t.options.readOnly&&(t.state.focused||(gt(t,"focus",t,e),t.state.focused=!0,A(t.display.wrapper,"CodeMirror-focused"),t.curOp||t.display.selForContextMenu==t.doc.sel||(t.display.input.reset(),c&&setTimeout((function(){return t.display.input.reset(!0)}),20)),t.display.input.receivedFocus()),xr(t))}function jr(t,e){t.state.delayingBlurEvent||(t.state.focused&&(gt(t,"blur",t,e),t.state.focused=!1,j(t.display.wrapper,"CodeMirror-focused")),clearInterval(t.display.blinker),setTimeout((function(){t.state.focused||(t.display.shift=!1)}),150))}function Pr(t){for(var e=t.display,n=e.lineDiv.offsetTop,r=Math.max(0,e.scroller.getBoundingClientRect().top),i=e.lineDiv.getBoundingClientRect().top,o=0,c=0;c.005||g<-.005)&&(it.display.sizerWidth){var m=Math.ceil(h/or(t.display));m>t.display.maxLineLength&&(t.display.maxLineLength=m,t.display.maxLine=l.line,t.display.maxLineChanged=!0)}}}Math.abs(o)>2&&(e.scroller.scrollTop+=o)}function _r(t){if(t.widgets)for(var e=0;e=a&&(o=Zt(e,We(Gt(e,c))-t.wrapper.clientHeight),a=c)}return{from:o,to:Math.max(a,o+1)}}function Er(t,e){var n=t.display,r=ir(t.display);e.top<0&&(e.top=0);var i=t.curOp&&null!=t.curOp.scrollTop?t.curOp.scrollTop:n.scroller.scrollTop,o=Tn(t),a={};e.bottom-e.top>o&&(e.bottom=e.top+o);var s=t.doc.height+Sn(n),c=e.tops-r;if(e.topi+o){var u=Math.min(e.top,(l?s:e.bottom)-o);u!=i&&(a.scrollTop=u)}var f=t.options.fixedGutter?0:n.gutters.offsetWidth,h=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:n.scroller.scrollLeft-f,d=_n(t)-n.gutters.offsetWidth,p=e.right-e.left>d;return p&&(e.right=e.left+d),e.left<10?a.scrollLeft=0:e.leftd+h-3&&(a.scrollLeft=e.right+(p?0:10)-d),a}function Dr(t,e){null!=e&&(Lr(t),t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+e)}function Mr(t){Lr(t);var e=t.getCursor();t.curOp.scrollToPos={from:e,to:e,margin:t.options.cursorScrollMargin}}function Ar(t,e,n){null==e&&null==n||Lr(t),null!=e&&(t.curOp.scrollLeft=e),null!=n&&(t.curOp.scrollTop=n)}function Lr(t){var e=t.curOp.scrollToPos;e&&(t.curOp.scrollToPos=null,Rr(t,Yn(t,e.from),Yn(t,e.to),e.margin))}function Rr(t,e,n,r){var i=Er(t,{left:Math.min(e.left,n.left),top:Math.min(e.top,n.top)-r,right:Math.max(e.right,n.right),bottom:Math.max(e.bottom,n.bottom)+r});Ar(t,i.scrollLeft,i.scrollTop)}function Nr(t,e){Math.abs(t.doc.scrollTop-e)<2||(n||li(t,{top:e}),Ir(t,e,!0),n&&li(t),ii(t,100))}function Ir(t,e,n){e=Math.max(0,Math.min(t.display.scroller.scrollHeight-t.display.scroller.clientHeight,e)),(t.display.scroller.scrollTop!=e||n)&&(t.doc.scrollTop=e,t.display.scrollbars.setScrollTop(e),t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e))}function Fr(t,e,n,r){e=Math.max(0,Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth)),(n?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)&&!r||(t.doc.scrollLeft=e,hi(t),t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e),t.display.scrollbars.setScrollLeft(e))}function Vr(t){var e=t.display,n=e.gutters.offsetWidth,r=Math.round(t.doc.height+Sn(t.display));return{clientHeight:e.scroller.clientHeight,viewHeight:e.wrapper.clientHeight,scrollWidth:e.scroller.scrollWidth,clientWidth:e.scroller.clientWidth,viewWidth:e.wrapper.clientWidth,barLeft:t.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+Pn(t)+e.barHeight,nativeBarWidth:e.nativeBarWidth,gutterWidth:n}}var Br=function(t,e,n){this.cm=n;var r=this.vert=T("div",[T("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=T("div",[T("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");r.tabIndex=i.tabIndex=-1,t(r),t(i),ht(r,"scroll",(function(){r.clientHeight&&e(r.scrollTop,"vertical")})),ht(i,"scroll",(function(){i.clientWidth&&e(i.scrollLeft,"horizontal")})),this.checkedZeroWidth=!1,a&&s<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Br.prototype.update=function(t){var e=t.scrollWidth>t.clientWidth+1,n=t.scrollHeight>t.clientHeight+1,r=t.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=e?r+"px":"0";var i=t.viewHeight-(e?r:0);this.vert.firstChild.style.height=Math.max(0,t.scrollHeight-t.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(e){this.horiz.style.display="block",this.horiz.style.right=n?r+"px":"0",this.horiz.style.left=t.barLeft+"px";var o=t.viewWidth-t.barLeft-(n?r:0);this.horiz.firstChild.style.width=Math.max(0,t.scrollWidth-t.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&t.clientHeight>0&&(0==r&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?r:0,bottom:e?r:0}},Br.prototype.setScrollLeft=function(t){this.horiz.scrollLeft!=t&&(this.horiz.scrollLeft=t),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},Br.prototype.setScrollTop=function(t){this.vert.scrollTop!=t&&(this.vert.scrollTop=t),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},Br.prototype.zeroWidthHack=function(){var t=y&&!d?"12px":"18px";this.horiz.style.height=this.vert.style.width=t,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new V,this.disableVert=new V},Br.prototype.enableZeroWidthBar=function(t,e,n){t.style.pointerEvents="auto",e.set(1e3,(function r(){var i=t.getBoundingClientRect();("vert"==n?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=t?t.style.pointerEvents="none":e.set(1e3,r)}))},Br.prototype.clear=function(){var t=this.horiz.parentNode;t.removeChild(this.horiz),t.removeChild(this.vert)};var Hr=function(){};function zr(t,e){e||(e=Vr(t));var n=t.display.barWidth,r=t.display.barHeight;Ur(t,e);for(var i=0;i<4&&n!=t.display.barWidth||r!=t.display.barHeight;i++)n!=t.display.barWidth&&t.options.lineWrapping&&Pr(t),Ur(t,Vr(t)),n=t.display.barWidth,r=t.display.barHeight}function Ur(t,e){var n=t.display,r=n.scrollbars.update(e);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px",n.heightForcer.style.borderBottom=r.bottom+"px solid transparent",r.right&&r.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=r.bottom+"px",n.scrollbarFiller.style.width=r.right+"px"):n.scrollbarFiller.style.display="",r.bottom&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r.bottom+"px",n.gutterFiller.style.width=e.gutterWidth+"px"):n.gutterFiller.style.display=""}Hr.prototype.update=function(){return{bottom:0,right:0}},Hr.prototype.setScrollLeft=function(){},Hr.prototype.setScrollTop=function(){},Hr.prototype.clear=function(){};var Wr={native:Br,null:Hr};function $r(t){t.display.scrollbars&&(t.display.scrollbars.clear(),t.display.scrollbars.addClass&&j(t.display.wrapper,t.display.scrollbars.addClass)),t.display.scrollbars=new Wr[t.options.scrollbarStyle]((function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller),ht(e,"mousedown",(function(){t.state.focused&&setTimeout((function(){return t.display.input.focus()}),0)})),e.setAttribute("cm-not-content","true")}),(function(e,n){"horizontal"==n?Fr(t,e):Nr(t,e)}),t),t.display.scrollbars.addClass&&A(t.display.wrapper,t.display.scrollbars.addClass)}var qr=0;function Gr(t){var e;t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++qr,markArrays:null},e=t.curOp,sn?sn.ops.push(e):e.ownsGroup=sn={ops:[e],delayedCallbacks:[]}}function Kr(t){var e=t.curOp;e&&function(t,e){var n=t.ownsGroup;if(n)try{!function(t){var e=t.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&e.options.lineWrapping,t.update=t.mustUpdate&&new ai(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate)}function Jr(t){t.updatedDisplay=t.mustUpdate&&si(t.cm,t.update)}function Xr(t){var e=t.cm,n=e.display;t.updatedDisplay&&Pr(e),t.barMeasure=Vr(e),n.maxLineChanged&&!e.options.lineWrapping&&(t.adjustWidthTo=Dn(e,n.maxLine,n.maxLine.text.length).left+3,e.display.sizerWidth=t.adjustWidthTo,t.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+t.adjustWidthTo+Pn(e)+e.display.barWidth),t.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+t.adjustWidthTo-_n(e))),(t.updatedDisplay||t.selectionChanged)&&(t.preparedSelection=n.input.prepareSelection())}function Zr(t){var e=t.cm;null!=t.adjustWidthTo&&(e.display.sizer.style.minWidth=t.adjustWidthTo+"px",t.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!p){var o=T("div","​",null,"position: absolute;\n top: "+(e.top-n.viewOffset-kn(t.display))+"px;\n height: "+(e.bottom-e.top+Pn(t)+n.barHeight)+"px;\n left: "+e.left+"px; width: "+Math.max(2,e.right-e.left)+"px;");t.display.lineSpace.appendChild(o),o.scrollIntoView(i),t.display.lineSpace.removeChild(o)}}}(e,function(t,e,n,r){var i;null==r&&(r=0),t.options.lineWrapping||e!=n||(n="before"==e.sticky?ee(e.line,e.ch+1,"before"):e,e=e.ch?ee(e.line,"before"==e.sticky?e.ch-1:e.ch,"after"):e);for(var o=0;o<5;o++){var a=!1,s=Kn(t,e),c=n&&n!=e?Kn(t,n):s,l=Er(t,i={left:Math.min(s.left,c.left),top:Math.min(s.top,c.top)-r,right:Math.max(s.left,c.left),bottom:Math.max(s.bottom,c.bottom)+r}),u=t.doc.scrollTop,f=t.doc.scrollLeft;if(null!=l.scrollTop&&(Nr(t,l.scrollTop),Math.abs(t.doc.scrollTop-u)>1&&(a=!0)),null!=l.scrollLeft&&(Fr(t,l.scrollLeft),Math.abs(t.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}(e,ce(r,t.scrollToPos.from),ce(r,t.scrollToPos.to),t.scrollToPos.margin));var i=t.maybeHiddenMarkers,o=t.maybeUnhiddenMarkers;if(i)for(var a=0;a=t.display.viewTo)){var n=+new Date+t.options.workTime,r=pe(t,e.highlightFrontier),i=[];e.iter(r.line,Math.min(e.first+e.size,t.display.viewTo+500),(function(o){if(r.line>=t.display.viewFrom){var a=o.styles,s=o.text.length>t.options.maxHighlightLength?Ut(e.mode,r.state):null,c=he(t,o,r,!0);s&&(r.state=s),o.styles=c.styles;var l=o.styleClasses,u=c.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),h=0;!f&&hn)return ii(t,t.options.workDelay),!0})),e.highlightFrontier=r.line,e.modeFrontier=Math.max(e.modeFrontier,r.line),i.length&&ti(t,(function(){for(var e=0;e=n.viewFrom&&e.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==vr(t))return!1;di(t)&&(pr(t),e.dims=ar(t));var i=r.first+r.size,o=Math.max(e.visible.from-t.options.viewportMargin,r.first),a=Math.min(i,e.visible.to+t.options.viewportMargin);n.viewFroma&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo)),Ce&&(o=Be(t.doc,o),a=He(t.doc,a));var s=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=e.wrapperHeight||n.lastWrapWidth!=e.wrapperWidth;!function(t,e,n){var r=t.display;0==r.view.length||e>=r.viewTo||n<=r.viewFrom?(r.view=an(t,e,n),r.viewFrom=e):(r.viewFrom>e?r.view=an(t,e,r.viewFrom).concat(r.view):r.viewFromn&&(r.view=r.view.slice(0,fr(t,n)))),r.viewTo=n}(t,o,a),n.viewOffset=We(Gt(t.doc,n.viewFrom)),t.display.mover.style.top=n.viewOffset+"px";var l=vr(t);if(!s&&0==l&&!e.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=function(t){if(t.hasFocus())return null;var e=M();if(!e||!D(t.display.lineDiv,e))return null;var n={activeElt:e};if(window.getSelection){var r=window.getSelection();r.anchorNode&&r.extend&&D(t.display.lineDiv,r.anchorNode)&&(n.anchorNode=r.anchorNode,n.anchorOffset=r.anchorOffset,n.focusNode=r.focusNode,n.focusOffset=r.focusOffset)}return n}(t);return l>4&&(n.lineDiv.style.display="none"),function(t,e,n){var r=t.display,i=t.options.lineNumbers,o=r.lineDiv,a=o.firstChild;function s(e){var n=e.nextSibling;return c&&y&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e),n}for(var l=r.view,u=r.viewFrom,f=0;f-1&&(d=!1),fn(t,h,u,n)),d&&(P(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(te(t.options,u)))),a=h.node.nextSibling}else{var p=yn(t,h,u,n);o.insertBefore(p,a)}u+=h.size}for(;a;)a=s(a)}(t,n.updateLineNumbers,e.dims),l>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,function(t){if(t&&t.activeElt&&t.activeElt!=M()&&(t.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(t.activeElt.nodeName)&&t.anchorNode&&D(document.body,t.anchorNode)&&D(document.body,t.focusNode))){var e=window.getSelection(),n=document.createRange();n.setEnd(t.anchorNode,t.anchorOffset),n.collapse(!1),e.removeAllRanges(),e.addRange(n),e.extend(t.focusNode,t.focusOffset)}}(u),P(n.cursorDiv),P(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,s&&(n.lastWrapHeight=e.wrapperHeight,n.lastWrapWidth=e.wrapperWidth,ii(t,400)),n.updateLineNumbers=null,!0}function ci(t,e){for(var n=e.viewport,r=!0;;r=!1){if(r&&t.options.lineWrapping&&e.oldDisplayWidth!=_n(t))r&&(e.visible=Tr(t.display,t.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(t.doc.height+Sn(t.display)-Tn(t),n.top)}),e.visible=Tr(t.display,t.doc,n),e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)break;if(!si(t,e))break;Pr(t);var i=Vr(t);mr(t),zr(t,i),fi(t,i),e.force=!1}e.signal(t,"update",t),t.display.viewFrom==t.display.reportedViewFrom&&t.display.viewTo==t.display.reportedViewTo||(e.signal(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo),t.display.reportedViewFrom=t.display.viewFrom,t.display.reportedViewTo=t.display.viewTo)}function li(t,e){var n=new ai(t,e);if(si(t,n)){Pr(t),ci(t,n);var r=Vr(t);mr(t),zr(t,r),fi(t,r),n.finish()}}function ui(t){var e=t.gutters.offsetWidth;t.sizer.style.marginLeft=e+"px",ln(t,"gutterChanged",t)}function fi(t,e){t.display.sizer.style.minHeight=e.docHeight+"px",t.display.heightForcer.style.top=e.docHeight+"px",t.display.gutters.style.height=e.docHeight+t.display.barHeight+Pn(t)+"px"}function hi(t){var e=t.display,n=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var r=sr(e)-e.scroller.scrollLeft+t.doc.scrollLeft,i=e.gutters.offsetWidth,o=r+"px",a=0;as.clientWidth,u=s.scrollHeight>s.clientHeight;if(i&&l||o&&u){if(o&&y&&c)t:for(var h=e.target,d=a.view;h!=s;h=h.parentNode)for(var p=0;p=0&&ne(t,r.to())<=0)return n}return-1};var ki=function(t,e){this.anchor=t,this.head=e};function Si(t,e,n){var r=t&&t.options.selectionsMayTouch,i=e[n];e.sort((function(t,e){return ne(t.from(),e.from())})),n=B(e,i);for(var o=1;o0:c>=0){var l=ae(s.from(),a.from()),u=oe(s.to(),a.to()),f=s.empty()?a.from()==a.head:s.from()==s.head;o<=n&&--n,e.splice(--o,2,new ki(f?u:l,f?l:u))}}return new Ci(e,n)}function ji(t,e){return new Ci([new ki(t,e||t)],0)}function Pi(t){return t.text?ee(t.from.line+t.text.length-1,Y(t.text).length+(1==t.text.length?t.from.ch:0)):t.to}function _i(t,e){if(ne(t,e.from)<0)return t;if(ne(t,e.to)<=0)return Pi(e);var n=t.line+e.text.length-(e.to.line-e.from.line)-1,r=t.ch;return t.line==e.to.line&&(r+=Pi(e).ch-e.to.ch),ee(n,r)}function Ti(t,e){for(var n=[],r=0;r1&&t.remove(s.line+1,p-1),t.insert(s.line+1,m)}ln(t,"change",t,e)}function Ri(t,e,n){!function t(r,i,o){if(r.linked)for(var a=0;as-(t.cm?t.cm.options.historyEventDelay:500)||"*"==e.origin.charAt(0)))&&(o=function(t,e){return e?(Bi(t.done),Y(t.done)):t.done.length&&!Y(t.done).ranges?Y(t.done):t.done.length>1&&!t.done[t.done.length-2].ranges?(t.done.pop(),Y(t.done)):void 0}(i,i.lastOp==r)))a=Y(o.changes),0==ne(e.from,e.to)&&0==ne(e.from,a.to)?a.to=Pi(e):o.changes.push(Vi(t,e));else{var c=Y(i.done);for(c&&c.ranges||Ui(t.sel,i.done),o={changes:[Vi(t,e)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=e.origin,a||gt(t,"historyAdded")}function zi(t,e,n,r){var i=t.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||function(t,e,n,r){var i=e.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}(t,o,Y(i.done),e))?i.done[i.done.length-1]=e:Ui(e,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&!1!==r.clearRedo&&Bi(i.undone)}function Ui(t,e){var n=Y(e);n&&n.ranges&&n.equals(t)||e.push(t)}function Wi(t,e,n,r){var i=e["spans_"+t.id],o=0;t.iter(Math.max(t.first,n),Math.min(t.first+t.size,r),(function(n){n.markedSpans&&((i||(i=e["spans_"+t.id]={}))[o]=n.markedSpans),++o}))}function $i(t){if(!t)return null;for(var e,n=0;n-1&&(Y(s)[f]=l[f],delete l[f])}}}return r}function Ki(t,e,n,r){if(r){var i=t.anchor;if(n){var o=ne(e,i)<0;o!=ne(n,i)<0?(i=e,e=n):o!=ne(e,n)<0&&(e=n)}return new ki(i,e)}return new ki(n||e,e)}function Yi(t,e,n,r,i){null==i&&(i=t.cm&&(t.cm.display.shift||t.extend)),to(t,new Ci([Ki(t.sel.primary(),e,n,i)],0),r)}function Ji(t,e,n){for(var r=[],i=t.cm&&(t.cm.display.shift||t.extend),o=0;o=e.ch:s.to>e.ch))){if(i&&(gt(c,"beforeCursorEnter"),c.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!c.atomic)continue;if(n){var f=c.find(r<0?1:-1),h=void 0;if((r<0?u:l)&&(f=so(t,f,-r,f&&f.line==e.line?o:null)),f&&f.line==e.line&&(h=ne(f,n))&&(r<0?h<0:h>0))return oo(t,f,e,r,i)}var d=c.find(r<0?-1:1);return(r<0?l:u)&&(d=so(t,d,r,d.line==e.line?o:null)),d?oo(t,d,e,r,i):null}}return e}function ao(t,e,n,r,i){var o=r||1,a=oo(t,e,n,o,i)||!i&&oo(t,e,n,o,!0)||oo(t,e,n,-o,i)||!i&&oo(t,e,n,-o,!0);return a||(t.cantEdit=!0,ee(t.first,0))}function so(t,e,n,r){return n<0&&0==e.ch?e.line>t.first?ce(t,ee(e.line-1)):null:n>0&&e.ch==(r||Gt(t,e.line)).text.length?e.line0)){var u=[c,1],f=ne(l.from,s.from),h=ne(l.to,s.to);(f<0||!a.inclusiveLeft&&!f)&&u.push({from:l.from,to:s.from}),(h>0||!a.inclusiveRight&&!h)&&u.push({from:s.to,to:l.to}),i.splice.apply(i,u),c+=u.length-3}}return i}(t,e.from,e.to);if(r)for(var i=r.length-1;i>=0;--i)fo(t,{from:r[i].from,to:r[i].to,text:i?[""]:e.text,origin:e.origin});else fo(t,e)}}function fo(t,e){if(1!=e.text.length||""!=e.text[0]||0!=ne(e.from,e.to)){var n=Ti(t,e);Hi(t,e,n,t.cm?t.cm.curOp.id:NaN),go(t,e,n,Pe(t,e));var r=[];Ri(t,(function(t,n){n||-1!=B(r,t.history)||(bo(t.history,e),r.push(t.history)),go(t,e,null,Pe(t,e))}))}}function ho(t,e,n){var r=t.cm&&t.cm.state.suppressEdits;if(!r||n){for(var i,o=t.history,a=t.sel,s="undo"==e?o.done:o.undone,c="undo"==e?o.undone:o.done,l=0;l=0;--d){var p=h(d);if(p)return p.v}}}}function po(t,e){if(0!=e&&(t.first+=e,t.sel=new Ci(J(t.sel.ranges,(function(t){return new ki(ee(t.anchor.line+e,t.anchor.ch),ee(t.head.line+e,t.head.ch))})),t.sel.primIndex),t.cm)){hr(t.cm,t.first,t.first-e,e);for(var n=t.cm.display,r=n.viewFrom;rt.lastLine())){if(e.from.lineo&&(e={from:e.from,to:ee(o,Gt(t,o).text.length),text:[e.text[0]],origin:e.origin}),e.removed=Kt(t,e.from,e.to),n||(n=Ti(t,e)),t.cm?function(t,e,n){var r=t.doc,i=t.display,o=e.from,a=e.to,s=!1,c=o.line;t.options.lineWrapping||(c=Xt(Ve(Gt(r,o.line))),r.iter(c,a.line+1,(function(t){if(t==i.maxLine)return s=!0,!0}))),r.sel.contains(e.from,e.to)>-1&&mt(t),Li(r,e,n,cr(t)),t.options.lineWrapping||(r.iter(c,o.line+e.text.length,(function(t){var e=$e(t);e>i.maxLineLength&&(i.maxLine=t,i.maxLineLength=e,i.maxLineChanged=!0,s=!1)})),s&&(t.curOp.updateMaxLine=!0)),function(t,e){if(t.modeFrontier=Math.min(t.modeFrontier,e),!(t.highlightFrontiern;r--){var i=Gt(t,r).stateAfter;if(i&&(!(i instanceof ue)||r+i.lookAhead1||!(this.children[0]instanceof Oo))){var s=[];this.collapse(s),this.children=[new Oo(s)],this.children[0].parent=this}},collapse:function(t){for(var e=0;e50){for(var a=i.lines.length%25+25,s=a;s10);t.parent.maybeSpill()}},iterN:function(t,e,n){for(var r=0;r0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=E("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Fe(t,e.line,e,n,o)||e.line!=n.line&&Fe(t,n.line,e,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ce=!0}o.addToHistory&&Hi(t,{from:e,to:n,origin:"markText"},t.sel,NaN);var s,c=e.line,l=t.cm;if(t.iter(c,n.line+1,(function(r){l&&o.collapsed&&!l.options.lineWrapping&&Ve(r)==l.display.maxLine&&(s=!0),o.collapsed&&c!=e.line&&Jt(r,0),function(t,e,n){var r=n&&window.WeakSet&&(n.markedSpans||(n.markedSpans=new WeakSet));r&&r.has(t.markedSpans)?t.markedSpans.push(e):(t.markedSpans=t.markedSpans?t.markedSpans.concat([e]):[e],r&&r.add(t.markedSpans)),e.marker.attachLine(t)}(r,new ke(o,c==e.line?e.ch:null,c==n.line?n.ch:null),t.cm&&t.cm.curOp),++c})),o.collapsed&&t.iter(e.line,n.line+1,(function(e){ze(t,e)&&Jt(e,0)})),o.clearOnEnter&&ht(o,"beforeCursorEnter",(function(){return o.clear()})),o.readOnly&&(xe=!0,(t.history.done.length||t.history.undone.length)&&t.clearHistory()),o.collapsed&&(o.id=++So,o.atomic=!0),l){if(s&&(l.curOp.updateMaxLine=!0),o.collapsed)hr(l,e.line,n.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var u=e.line;u<=n.line;u++)dr(l,u,"text");o.atomic&&ro(l.doc),ln(l,"markerAdded",l,o)}return o}jo.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;if(e&&Gr(t),yt(this,"clear")){var n=this.find();n&&ln(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;ot.display.maxLineLength&&(t.display.maxLine=l,t.display.maxLineLength=u,t.display.maxLineChanged=!0)}null!=r&&t&&this.collapsed&&hr(t,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&ro(t.doc)),t&&ln(t,"markerCleared",t,this,r,i),e&&Kr(t),this.parent&&this.parent.clear()}},jo.prototype.find=function(t,e){var n,r;null==t&&"bookmark"==this.type&&(t=1);for(var i=0;i=0;c--)uo(this,r[c]);s?Qi(this,s):this.cm&&Mr(this.cm)})),undo:ri((function(){ho(this,"undo")})),redo:ri((function(){ho(this,"redo")})),undoSelection:ri((function(){ho(this,"undo",!0)})),redoSelection:ri((function(){ho(this,"redo",!0)})),setExtending:function(t){this.extend=t},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,n=0,r=0;r=t.ch)&&e.push(i.marker.parent||i.marker)}return e},findMarks:function(t,e,n){t=ce(this,t),e=ce(this,e);var r=[],i=t.line;return this.iter(t.line,e.line+1,(function(o){var a=o.markedSpans;if(a)for(var s=0;s=c.to||null==c.from&&i!=t.line||null!=c.from&&i==e.line&&c.from>=e.ch||n&&!n(c.marker)||r.push(c.marker.parent||c.marker)}++i})),r},getAllMarks:function(){var t=[];return this.iter((function(e){var n=e.markedSpans;if(n)for(var r=0;rt)return e=t,!0;t-=o,++n})),ce(this,ee(n,e))},indexFromPos:function(t){var e=(t=ce(this,t)).ch;if(t.linee&&(e=t.from),null!=t.to&&t.to-1)return e.state.draggingText(t),void setTimeout((function(){return e.display.input.focus()}),20);try{var f=t.dataTransfer.getData("Text");if(f){var h;if(e.state.draggingText&&!e.state.draggingText.copy&&(h=e.listSelections()),eo(e.doc,ji(n,n)),h)for(var d=0;d=0;e--)vo(t.doc,"",r[e].from,r[e].to,"+delete");Mr(t)}))}function Qo(t,e,n){var r=ot(t.text,e+n,n);return r<0||r>t.text.length?null:r}function ta(t,e,n){var r=Qo(t,e.ch,n);return null==r?null:new ee(e.line,r,n<0?"after":"before")}function ea(t,e,n,r,i){if(t){"rtl"==e.doc.direction&&(i=-i);var o=ut(n,e.doc.direction);if(o){var a,s=i<0?Y(o):o[0],c=i<0==(1==s.level)?"after":"before";if(s.level>0||"rtl"==e.doc.direction){var l=An(e,n);a=i<0?n.text.length-1:0;var u=Ln(e,l,a).top;a=at((function(t){return Ln(e,l,t).top==u}),i<0==(1==s.level)?s.from:s.to-1,a),"before"==c&&(a=Qo(n,a,1))}else a=i<0?s.to:s.from;return new ee(r,a,c)}}return new ee(r,i<0?n.text.length:0,i<0?"before":"after")}Wo.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Wo.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Wo.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Wo.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Wo["default"]=y?Wo.macDefault:Wo.pcDefault;var na={selectAll:co,singleSelection:function(t){return t.setSelection(t.getCursor("anchor"),t.getCursor("head"),U)},killLine:function(t){return Zo(t,(function(e){if(e.empty()){var n=Gt(t.doc,e.head.line).text.length;return e.head.ch==n&&e.head.line0)i=new ee(i.line,i.ch+1),t.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),ee(i.line,i.ch-2),i,"+transpose");else if(i.line>t.doc.first){var a=Gt(t.doc,i.line-1).text;a&&(i=new ee(i.line,1),t.replaceRange(o.charAt(0)+t.doc.lineSeparator()+a.charAt(a.length-1),ee(i.line-1,a.length-1),i,"+transpose"))}n.push(new ki(i,i))}t.setSelections(n)}))},newlineAndIndent:function(t){return ti(t,(function(){for(var e=t.listSelections(),n=e.length-1;n>=0;n--)t.replaceRange(t.doc.lineSeparator(),e[n].anchor,e[n].head,"+input");e=t.listSelections();for(var r=0;r-1&&(ne((i=l.ranges[i]).from(),e)<0||e.xRel>0)&&(ne(i.to(),e)>0||e.xRel<0)?function(t,e,n,r){var i=t.display,o=!1,l=ei(t,(function(e){c&&(i.scroller.draggable=!1),t.state.draggingText=!1,t.state.delayingBlurEvent&&(t.hasFocus()?t.state.delayingBlurEvent=!1:kr(t)),pt(i.wrapper.ownerDocument,"mouseup",l),pt(i.wrapper.ownerDocument,"mousemove",u),pt(i.scroller,"dragstart",f),pt(i.scroller,"drop",l),o||(wt(e),r.addNew||Yi(t.doc,n,null,null,r.extend),c&&!h||a&&9==s?setTimeout((function(){i.wrapper.ownerDocument.body.focus({preventScroll:!0}),i.input.focus()}),20):i.input.focus())})),u=function(t){o=o||Math.abs(e.clientX-t.clientX)+Math.abs(e.clientY-t.clientY)>=10},f=function(){return o=!0};c&&(i.scroller.draggable=!0),t.state.draggingText=l,l.copy=!r.moveOnDrag,ht(i.wrapper.ownerDocument,"mouseup",l),ht(i.wrapper.ownerDocument,"mousemove",u),ht(i.scroller,"dragstart",f),ht(i.scroller,"drop",l),t.state.delayingBlurEvent=!0,setTimeout((function(){return i.input.focus()}),20),i.scroller.dragDrop&&i.scroller.dragDrop()}(t,r,e,o):function(t,e,n,r){a&&kr(t);var i=t.display,o=t.doc;wt(e);var s,c,l=o.sel,u=l.ranges;if(r.addNew&&!r.extend?(c=o.sel.contains(n),s=c>-1?u[c]:new ki(n,n)):(s=o.sel.primary(),c=o.sel.primIndex),"rectangle"==r.unit)r.addNew||(s=new ki(n,n)),n=ur(t,e,!0,!0),c=-1;else{var f=ba(t,n,r.unit);s=r.extend?Ki(s,f.anchor,f.head,r.extend):f}r.addNew?-1==c?(c=u.length,to(o,Si(t,u.concat([s]),c),{scroll:!1,origin:"*mouse"})):u.length>1&&u[c].empty()&&"char"==r.unit&&!r.extend?(to(o,Si(t,u.slice(0,c).concat(u.slice(c+1)),0),{scroll:!1,origin:"*mouse"}),l=o.sel):Xi(o,c,s,W):(c=0,to(o,new Ci([s],0),W),l=o.sel);var h=n;function d(e){if(0!=ne(h,e))if(h=e,"rectangle"==r.unit){for(var i=[],a=t.options.tabSize,u=F(Gt(o,n.line).text,n.ch,a),f=F(Gt(o,e.line).text,e.ch,a),d=Math.min(u,f),p=Math.max(u,f),g=Math.min(n.line,e.line),v=Math.min(t.lastLine(),Math.max(n.line,e.line));g<=v;g++){var m=Gt(o,g).text,y=q(m,d,a);d==p?i.push(new ki(ee(g,y),ee(g,y))):m.length>y&&i.push(new ki(ee(g,y),ee(g,q(m,p,a))))}i.length||i.push(new ki(n,n)),to(o,Si(t,l.ranges.slice(0,c).concat(i),c),{origin:"*mouse",scroll:!1}),t.scrollIntoView(e)}else{var b,w=s,O=ba(t,e,r.unit),x=w.anchor;ne(O.anchor,x)>0?(b=O.head,x=ae(w.from(),O.anchor)):(b=O.anchor,x=oe(w.to(),O.head));var C=l.ranges.slice(0);C[c]=function(t,e){var n=e.anchor,r=e.head,i=Gt(t.doc,n.line);if(0==ne(n,r)&&n.sticky==r.sticky)return e;var o=ut(i);if(!o)return e;var a=ct(o,n.ch,n.sticky),s=o[a];if(s.from!=n.ch&&s.to!=n.ch)return e;var c,l=a+(s.from==n.ch==(1!=s.level)?0:1);if(0==l||l==o.length)return e;if(r.line!=n.line)c=(r.line-n.line)*("ltr"==t.doc.direction?1:-1)>0;else{var u=ct(o,r.ch,r.sticky),f=u-a||(r.ch-n.ch)*(1==s.level?-1:1);c=u==l-1||u==l?f<0:f>0}var h=o[l+(c?-1:0)],d=c==(1==h.level),p=d?h.from:h.to,g=d?"after":"before";return n.ch==p&&n.sticky==g?e:new ki(new ee(n.line,p,g),r)}(t,new ki(ce(o,x),b)),to(o,Si(t,C,c),W)}}var p=i.wrapper.getBoundingClientRect(),g=0;function v(e){t.state.selectingText=!1,g=1/0,e&&(wt(e),i.input.focus()),pt(i.wrapper.ownerDocument,"mousemove",m),pt(i.wrapper.ownerDocument,"mouseup",y),o.history.lastSelOrigin=null}var m=ei(t,(function(e){0!==e.buttons&&St(e)?function e(n){var a=++g,s=ur(t,n,!0,"rectangle"==r.unit);if(s)if(0!=ne(s,h)){t.curOp.focus=M(),d(s);var c=Tr(i,o);(s.line>=c.to||s.linep.bottom?20:0;l&&setTimeout(ei(t,(function(){g==a&&(i.scroller.scrollTop+=l,e(n))})),50)}}(e):v(e)})),y=ei(t,v);t.state.selectingText=y,ht(i.wrapper.ownerDocument,"mousemove",m),ht(i.wrapper.ownerDocument,"mouseup",y)}(t,r,e,o)}(e,r,o,t):kt(t)==n.scroller&&wt(t):2==i?(r&&Yi(e.doc,r),setTimeout((function(){return n.input.focus()}),20)):3==i&&(C?e.display.input.onContextMenu(t):kr(e)))}}function ba(t,e,n){if("char"==n)return new ki(e,e);if("word"==n)return t.findWordAt(e);if("line"==n)return new ki(ee(e.line,0),ce(t.doc,ee(e.line+1,0)));var r=n(t,e);return new ki(r.from,r.to)}function wa(t,e,n,r){var i,o;if(e.touches)i=e.touches[0].clientX,o=e.touches[0].clientY;else try{i=e.clientX,o=e.clientY}catch(t){return!1}if(i>=Math.floor(t.display.gutters.getBoundingClientRect().right))return!1;r&&wt(e);var a=t.display,s=a.lineDiv.getBoundingClientRect();if(o>s.bottom||!yt(t,n))return xt(e);o-=s.top-a.viewOffset;for(var c=0;c=i)return gt(t,n,t,Zt(t.doc,o),t.display.gutterSpecs[c].className,e),xt(e)}}function Oa(t,e){return wa(t,e,"gutterClick",!0)}function xa(t,e){Cn(t.display,e)||function(t,e){return!!yt(t,"gutterContextMenu")&&wa(t,e,"gutterContextMenu",!1)}(t,e)||vt(t,e,"contextmenu")||C||t.display.input.onContextMenu(e)}function Ca(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Hn(t)}ma.prototype.compare=function(t,e,n){return this.time+va>t&&0==ne(e,this.pos)&&n==this.button};var ka={toString:function(){return"CodeMirror.Init"}},Sa={},ja={};function Pa(t,e,n){if(!e!=!(n&&n!=ka)){var r=t.display.dragFunctions,i=e?ht:pt;i(t.display.scroller,"dragstart",r.start),i(t.display.scroller,"dragenter",r.enter),i(t.display.scroller,"dragover",r.over),i(t.display.scroller,"dragleave",r.leave),i(t.display.scroller,"drop",r.drop)}}function _a(t){t.options.lineWrapping?(A(t.display.wrapper,"CodeMirror-wrap"),t.display.sizer.style.minWidth="",t.display.sizerWidth=null):(j(t.display.wrapper,"CodeMirror-wrap"),qe(t)),lr(t),hr(t),Hn(t),setTimeout((function(){return zr(t)}),100)}function Ta(t,e){var n=this;if(!(this instanceof Ta))return new Ta(t,e);this.options=e=e?I(e):{},I(Sa,e,!1);var r=e.value;"string"==typeof r?r=new Mo(r,e.mode,null,e.lineSeparator,e.direction):e.mode&&(r.modeOption=e.mode),this.doc=r;var i=new Ta.inputStyles[e.inputStyle](this),o=this.display=new mi(t,r,i,e);for(var l in o.wrapper.CodeMirror=this,Ca(this),e.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),$r(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new V,keySeq:null,specialChars:null},e.autofocus&&!m&&o.input.focus(),a&&s<11&&setTimeout((function(){return n.display.input.reset(!0)}),20),function(t){var e=t.display;ht(e.scroller,"mousedown",ei(t,ya)),ht(e.scroller,"dblclick",a&&s<11?ei(t,(function(e){if(!vt(t,e)){var n=ur(t,e);if(n&&!Oa(t,e)&&!Cn(t.display,e)){wt(e);var r=t.findWordAt(n);Yi(t.doc,r.anchor,r.head)}}})):function(e){return vt(t,e)||wt(e)}),ht(e.scroller,"contextmenu",(function(e){return xa(t,e)})),ht(e.input.getField(),"contextmenu",(function(n){e.scroller.contains(n.target)||xa(t,n)}));var n,r={end:0};function i(){e.activeTouch&&(n=setTimeout((function(){return e.activeTouch=null}),1e3),(r=e.activeTouch).end=+new Date)}function o(t,e){if(null==e.left)return!0;var n=e.left-t.left,r=e.top-t.top;return n*n+r*r>20*20}ht(e.scroller,"touchstart",(function(i){if(!vt(t,i)&&!function(t){if(1!=t.touches.length)return!1;var e=t.touches[0];return e.radiusX<=1&&e.radiusY<=1}(i)&&!Oa(t,i)){e.input.ensurePolled(),clearTimeout(n);var o=+new Date;e.activeTouch={start:o,moved:!1,prev:o-r.end<=300?r:null},1==i.touches.length&&(e.activeTouch.left=i.touches[0].pageX,e.activeTouch.top=i.touches[0].pageY)}})),ht(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0)})),ht(e.scroller,"touchend",(function(n){var r=e.activeTouch;if(r&&!Cn(e,n)&&null!=r.left&&!r.moved&&new Date-r.start<300){var a,s=t.coordsChar(e.activeTouch,"page");a=!r.prev||o(r,r.prev)?new ki(s,s):!r.prev.prev||o(r,r.prev.prev)?t.findWordAt(s):new ki(ee(s.line,0),ce(t.doc,ee(s.line+1,0))),t.setSelection(a.anchor,a.head),t.focus(),wt(n)}i()})),ht(e.scroller,"touchcancel",i),ht(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(Nr(t,e.scroller.scrollTop),Fr(t,e.scroller.scrollLeft,!0),gt(t,"scroll",t))})),ht(e.scroller,"mousewheel",(function(e){return xi(t,e)})),ht(e.scroller,"DOMMouseScroll",(function(e){return xi(t,e)})),ht(e.wrapper,"scroll",(function(){return e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(e){vt(t,e)||Ct(e)},over:function(e){vt(t,e)||(function(t,e){var n=ur(t,e);if(n){var r=document.createDocumentFragment();br(t,n,r),t.display.dragCursor||(t.display.dragCursor=T("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),t.display.lineSpace.insertBefore(t.display.dragCursor,t.display.cursorDiv)),_(t.display.dragCursor,r)}}(t,e),Ct(e))},start:function(e){return function(t,e){if(a&&(!t.state.draggingText||+new Date-Ao<100))Ct(e);else if(!vt(t,e)&&!Cn(t.display,e)&&(e.dataTransfer.setData("Text",t.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!h)){var n=T("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f&&(n.width=n.height=1,t.display.wrapper.appendChild(n),n._top=n.offsetTop),e.dataTransfer.setDragImage(n,0,0),f&&n.parentNode.removeChild(n)}}(t,e)},drop:ei(t,Lo),leave:function(e){vt(t,e)||Ro(t)}};var c=e.input.getField();ht(c,"keyup",(function(e){return ha.call(t,e)})),ht(c,"keydown",ei(t,fa)),ht(c,"keypress",ei(t,da)),ht(c,"focus",(function(e){return Sr(t,e)})),ht(c,"blur",(function(e){return jr(t,e)}))}(this),Fo(),Gr(this),this.curOp.forceUpdate=!0,Ni(this,r),e.autofocus&&!m||this.hasFocus()?setTimeout((function(){n.hasFocus()&&!n.state.focused&&Sr(n)}),20):jr(this),ja)ja.hasOwnProperty(l)&&ja[l](this,e[l],ka);di(this),e.finishInit&&e.finishInit(this);for(var u=0;u150)){if(!r)return;n="prev"}}else l=0,n="not";"prev"==n?l=e>o.first?F(Gt(o,e-1).text,null,a):0:"add"==n?l=c+t.options.indentUnit:"subtract"==n?l=c-t.options.indentUnit:"number"==typeof n&&(l=c+n),l=Math.max(0,l);var f="",h=0;if(t.options.indentWithTabs)for(var d=Math.floor(l/a);d;--d)h+=a,f+="\t";if(ha,c=Mt(e),l=null;if(s&&r.ranges.length>1)if(Ma&&Ma.text.join("\n")==e){if(r.ranges.length%Ma.text.length==0){l=[];for(var u=0;u=0;h--){var d=r.ranges[h],p=d.from(),g=d.to();d.empty()&&(n&&n>0?p=ee(p.line,p.ch-n):t.state.overwrite&&!s?g=ee(g.line,Math.min(Gt(o,g.line).text.length,g.ch+Y(c).length)):s&&Ma&&Ma.lineWise&&Ma.text.join("\n")==c.join("\n")&&(p=g=ee(p.line,0)));var v={from:p,to:g,text:l?l[h%l.length]:c,origin:i||(s?"paste":t.state.cutIncoming>a?"cut":"+input")};uo(t.doc,v),ln(t,"inputRead",t,v)}e&&!s&&Na(t,e),Mr(t),t.curOp.updateInput<2&&(t.curOp.updateInput=f),t.curOp.typing=!0,t.state.pasteIncoming=t.state.cutIncoming=-1}function Ra(t,e){var n=t.clipboardData&&t.clipboardData.getData("Text");if(n)return t.preventDefault(),e.isReadOnly()||e.options.disableInput||ti(e,(function(){return La(e,n,0,null,"paste")})),!0}function Na(t,e){if(t.options.electricChars&&t.options.smartIndent)for(var n=t.doc.sel,r=n.ranges.length-1;r>=0;r--){var i=n.ranges[r];if(!(i.head.ch>100||r&&n.ranges[r-1].head.line==i.head.line)){var o=t.getModeAt(i.head),a=!1;if(o.electricChars){for(var s=0;s-1){a=Da(t,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(Gt(t.doc,i.head.line).text.slice(0,i.head.ch))&&(a=Da(t,i.head.line,"smart"));a&&ln(t,"electricInput",t,i.head.line)}}}function Ia(t){for(var e=[],n=[],r=0;r0?0:-1));if(isNaN(u))a=null;else{var f=n>0?u>=55296&&u<56320:u>=56320&&u<57343;a=new ee(e.line,Math.max(0,Math.min(s.text.length,e.ch+n*(f?2:1))),-n)}}else a=i?function(t,e,n,r){var i=ut(e,t.doc.direction);if(!i)return ta(e,n,r);n.ch>=e.text.length?(n.ch=e.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var o=ct(i,n.ch,n.sticky),a=i[o];if("ltr"==t.doc.direction&&a.level%2==0&&(r>0?a.to>n.ch:a.from=a.from&&h>=u.begin)){var d=f?"before":"after";return new ee(n.line,h,d)}}var p=function(t,e,r){for(var o=function(t,e){return e?new ee(n.line,c(t,1),"before"):new ee(n.line,t,"after")};t>=0&&t0==(1!=a.level),l=s?r.begin:c(r.end,-1);if(a.from<=l&&l0?u.end:c(u.begin,-1);return null==v||r>0&&v==e.text.length||!(g=p(r>0?0:i.length-1,r,l(v)))?null:g}(t.cm,s,e,n):ta(s,e,n);if(null==a){if(o||(l=e.line+c)=t.first+t.size||(e=new ee(l,e.ch,e.sticky),!(s=Gt(t,l))))return!1;e=ea(i,t.cm,s,e.line,c)}else e=a;return!0}if("char"==r||"codepoint"==r)l();else if("column"==r)l(!0);else if("word"==r||"group"==r)for(var u=null,f="group"==r,h=t.cm&&t.cm.getHelper(e,"wordChars"),d=!0;!(n<0)||l(!d);d=!1){var p=s.text.charAt(e.ch)||"\n",g=et(p,h)?"w":f&&"\n"==p?"n":!f||/\s/.test(p)?null:"p";if(!f||d||g||(g="s"),u&&u!=g){n<0&&(n=1,l(),e.sticky="after");break}if(g&&(u=g),n>0&&!l(!d))break}var v=ao(t,e,o,a,!0);return re(o,v)&&(v.hitSide=!0),v}function Ha(t,e,n,r){var i,o,a=t.doc,s=e.left;if("page"==r){var c=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),l=Math.max(c-.5*ir(t.display),3);i=(n>0?e.bottom:e.top)+n*l}else"line"==r&&(i=n>0?e.bottom+3:e.top-3);for(;(o=Xn(t,s,i)).outside;){if(n<0?i<=0:i>=a.height){o.hitSide=!0;break}i+=5*n}return o}var za=function(t){this.cm=t,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new V,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Ua(t,e){var n=Mn(t,e.line);if(!n||n.hidden)return null;var r=Gt(t.doc,e.line),i=En(n,r,e.line),o=ut(r,t.doc.direction),a="left";o&&(a=ct(o,e.ch)%2?"right":"left");var s=In(i.map,e.ch,a);return s.offset="right"==s.collapse?s.end:s.start,s}function Wa(t,e){return e&&(t.bad=!0),t}function $a(t,e,n){var r;if(e==t.display.lineDiv){if(!(r=t.display.lineDiv.childNodes[n]))return Wa(t.clipPos(ee(t.display.viewTo-1)),!0);e=null,n=0}else for(r=e;;r=r.parentNode){if(!r||r==t.display.lineDiv)return null;if(r.parentNode&&r.parentNode==t.display.lineDiv)break}for(var i=0;i=e.display.viewTo||o.line=e.display.viewFrom&&Ua(e,i)||{node:c[0].measure.map[2],offset:0},u=o.liner.firstLine()&&(a=ee(a.line-1,Gt(r.doc,a.line-1).length)),s.ch==Gt(r.doc,s.line).text.length&&s.linei.viewTo-1)return!1;a.line==i.viewFrom||0==(t=fr(r,a.line))?(e=Xt(i.view[0].line),n=i.view[0].node):(e=Xt(i.view[t].line),n=i.view[t-1].node.nextSibling);var c,l,u=fr(r,s.line);if(u==i.view.length-1?(c=i.viewTo-1,l=i.lineDiv.lastChild):(c=Xt(i.view[u+1].line)-1,l=i.view[u+1].node.previousSibling),!n)return!1;for(var f=r.doc.splitLines(function(t,e,n,r,i){var o="",a=!1,s=t.doc.lineSeparator(),c=!1;function l(){a&&(o+=s,c&&(o+=s),a=c=!1)}function u(t){t&&(l(),o+=t)}function f(e){if(1==e.nodeType){var n=e.getAttribute("cm-text");if(n)return void u(n);var o,h=e.getAttribute("cm-marker");if(h){var d=t.findMarks(ee(r,0),ee(i+1,0),(v=+h,function(t){return t.id==v}));return void(d.length&&(o=d[0].find(0))&&u(Kt(t.doc,o.from,o.to).join(s)))}if("false"==e.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;p&&l();for(var g=0;g1&&h.length>1;)if(Y(f)==Y(h))f.pop(),h.pop(),c--;else{if(f[0]!=h[0])break;f.shift(),h.shift(),e++}for(var d=0,p=0,g=f[0],v=h[0],m=Math.min(g.length,v.length);da.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)d--,p++;f[f.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(d).replace(/\u200b+$/,"");var O=ee(e,d),x=ee(c,h.length?Y(h).length-p:0);return f.length>1||f[0]||ne(O,x)?(vo(r.doc,f,O,x,"+input"),!0):void 0},za.prototype.ensurePolled=function(){this.forceCompositionEnd()},za.prototype.reset=function(){this.forceCompositionEnd()},za.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},za.prototype.readFromDOMSoon=function(){var t=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(t.readDOMTimeout=null,t.composing){if(!t.composing.done)return;t.composing=null}t.updateFromDOM()}),80))},za.prototype.updateFromDOM=function(){var t=this;!this.cm.isReadOnly()&&this.pollContent()||ti(this.cm,(function(){return hr(t.cm)}))},za.prototype.setUneditable=function(t){t.contentEditable="false"},za.prototype.onKeyPress=function(t){0==t.charCode||this.composing||(t.preventDefault(),this.cm.isReadOnly()||ei(this.cm,La)(this.cm,String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),0))},za.prototype.readOnlyChanged=function(t){this.div.contentEditable=String("nocursor"!=t)},za.prototype.onContextMenu=function(){},za.prototype.resetPosition=function(){},za.prototype.needsContentAttribute=!0;var Ga=function(t){this.cm=t,this.prevInput="",this.pollingFast=!1,this.polling=new V,this.hasSelection=!1,this.composing=null};Ga.prototype.init=function(t){var e=this,n=this,r=this.cm;this.createField(t);var i=this.textarea;function o(t){if(!vt(r,t)){if(r.somethingSelected())Aa({lineWise:!1,text:r.getSelections()});else{if(!r.options.lineWiseCopyCut)return;var e=Ia(r);Aa({lineWise:!0,text:e.text}),"cut"==t.type?r.setSelections(e.ranges,null,U):(n.prevInput="",i.value=e.text.join("\n"),R(i))}"cut"==t.type&&(r.state.cutIncoming=+new Date)}}t.wrapper.insertBefore(this.wrapper,t.wrapper.firstChild),g&&(i.style.width="0px"),ht(i,"input",(function(){a&&s>=9&&e.hasSelection&&(e.hasSelection=null),n.poll()})),ht(i,"paste",(function(t){vt(r,t)||Ra(t,r)||(r.state.pasteIncoming=+new Date,n.fastPoll())})),ht(i,"cut",o),ht(i,"copy",o),ht(t.scroller,"paste",(function(e){if(!Cn(t,e)&&!vt(r,e)){if(!i.dispatchEvent)return r.state.pasteIncoming=+new Date,void n.focus();var o=new Event("paste");o.clipboardData=e.clipboardData,i.dispatchEvent(o)}})),ht(t.lineSpace,"selectstart",(function(e){Cn(t,e)||wt(e)})),ht(i,"compositionstart",(function(){var t=r.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:t,range:r.markText(t,r.getCursor("to"),{className:"CodeMirror-composing"})}})),ht(i,"compositionend",(function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)}))},Ga.prototype.createField=function(t){this.wrapper=Va(),this.textarea=this.wrapper.firstChild},Ga.prototype.screenReaderLabelChanged=function(t){t?this.textarea.setAttribute('aria-label',t):this.textarea.removeAttribute('aria-label')},Ga.prototype.prepareSelection=function(){var t=this.cm,e=t.display,n=t.doc,r=yr(t);if(t.options.moveInputWithCursor){var i=Kn(t,n.sel.primary().head,"div"),o=e.wrapper.getBoundingClientRect(),a=e.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,i.top+a.top-o.top)),r.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,i.left+a.left-o.left))}return r},Ga.prototype.showSelection=function(t){var e=this.cm.display;_(e.cursorDiv,t.cursors),_(e.selectionDiv,t.selection),null!=t.teTop&&(this.wrapper.style.top=t.teTop+"px",this.wrapper.style.left=t.teLeft+"px")},Ga.prototype.reset=function(t){if(!this.contextMenuPending&&!this.composing){var e=this.cm;if(e.somethingSelected()){this.prevInput="";var n=e.getSelection();this.textarea.value=n,e.state.focused&&R(this.textarea),a&&s>=9&&(this.hasSelection=n)}else t||(this.prevInput=this.textarea.value="",a&&s>=9&&(this.hasSelection=null))}},Ga.prototype.getField=function(){return this.textarea},Ga.prototype.supportsTouch=function(){return!1},Ga.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!m||M()!=this.textarea))try{this.textarea.focus()}catch(t){}},Ga.prototype.blur=function(){this.textarea.blur()},Ga.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},Ga.prototype.receivedFocus=function(){this.slowPoll()},Ga.prototype.slowPoll=function(){var t=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){t.poll(),t.cm.state.focused&&t.slowPoll()}))},Ga.prototype.fastPoll=function(){var t=!1,e=this;e.pollingFast=!0,e.polling.set(20,(function n(){e.poll()||t?(e.pollingFast=!1,e.slowPoll()):(t=!0,e.polling.set(60,n))}))},Ga.prototype.poll=function(){var t=this,e=this.cm,n=this.textarea,r=this.prevInput;if(this.contextMenuPending||!e.state.focused||At(n)&&!r&&!this.composing||e.isReadOnly()||e.options.disableInput||e.state.keySeq)return!1;var i=n.value;if(i==r&&!e.somethingSelected())return!1;if(a&&s>=9&&this.hasSelection===i||y&&/[\uf700-\uf7ff]/.test(i))return e.display.input.reset(),!1;if(e.doc.sel==e.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||r||(r="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var c=0,l=Math.min(r.length,i.length);c1e3||i.indexOf("\n")>-1?n.value=t.prevInput="":t.prevInput=i,t.composing&&(t.composing.range.clear(),t.composing.range=e.markText(t.composing.start,e.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},Ga.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},Ga.prototype.onKeyPress=function(){a&&s>=9&&(this.hasSelection=null),this.fastPoll()},Ga.prototype.onContextMenu=function(t){var e=this,n=e.cm,r=n.display,i=e.textarea;e.contextMenuPending&&e.contextMenuPending();var o=ur(n,t),l=r.scroller.scrollTop;if(o&&!f){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(o)&&ei(n,to)(n.doc,ji(o),U);var u,h=i.style.cssText,d=e.wrapper.style.cssText,p=e.wrapper.offsetParent.getBoundingClientRect();if(e.wrapper.style.cssText="position: static",i.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(t.clientY-p.top-5)+"px; left: "+(t.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",c&&(u=window.scrollY),r.input.focus(),c&&window.scrollTo(null,u),r.input.reset(),n.somethingSelected()||(i.value=e.prevInput=" "),e.contextMenuPending=m,r.selForContextMenu=n.doc.sel,clearTimeout(r.detectingSelectAll),a&&s>=9&&v(),C){Ct(t);var g=function(){pt(window,"mouseup",g),setTimeout(m,20)};ht(window,"mouseup",g)}else setTimeout(m,50)}function v(){if(null!=i.selectionStart){var t=n.somethingSelected(),o="​"+(t?i.value:"");i.value="⇚",i.value=o,e.prevInput=t?"":"​",i.selectionStart=1,i.selectionEnd=o.length,r.selForContextMenu=n.doc.sel}}function m(){if(e.contextMenuPending==m&&(e.contextMenuPending=!1,e.wrapper.style.cssText=d,i.style.cssText=h,a&&s<9&&r.scrollbars.setScrollTop(r.scroller.scrollTop=l),null!=i.selectionStart)){(!a||a&&s<9)&&v();var t=0,o=function(){r.selForContextMenu==n.doc.sel&&0==i.selectionStart&&i.selectionEnd>0&&"​"==e.prevInput?ei(n,co)(n):t++<10?r.detectingSelectAll=setTimeout(o,500):(r.selForContextMenu=null,r.input.reset())};r.detectingSelectAll=setTimeout(o,200)}}},Ga.prototype.readOnlyChanged=function(t){t||this.reset(),this.textarea.disabled="nocursor"==t,this.textarea.readOnly=!!t},Ga.prototype.setUneditable=function(){},Ga.prototype.needsContentAttribute=!1,function(t){var e=t.optionHandlers;function n(n,r,i,o){t.defaults[n]=r,i&&(e[n]=o?function(t,e,n){n!=ka&&i(t,e,n)}:i)}t.defineOption=n,t.Init=ka,n("value","",(function(t,e){return t.setValue(e)}),!0),n("mode",null,(function(t,e){t.doc.modeOption=e,Di(t)}),!0),n("indentUnit",2,Di,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,(function(t){Mi(t),Hn(t),hr(t)}),!0),n("lineSeparator",null,(function(t,e){if(t.doc.lineSep=e,e){var n=[],r=t.doc.first;t.doc.iter((function(t){for(var i=0;;){var o=t.text.indexOf(e,i);if(-1==o)break;i=o+e.length,n.push(ee(r,o))}r++}));for(var i=n.length-1;i>=0;i--)vo(t.doc,e,n[i],ee(n[i].line,n[i].ch+e.length))}})),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,(function(t,e,n){t.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g"),n!=ka&&t.refresh()})),n("specialCharPlaceholder",Qe,(function(t){return t.refresh()}),!0),n("electricChars",!0),n("inputStyle",m?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),n("spellcheck",!1,(function(t,e){return t.getInputField().spellcheck=e}),!0),n("autocorrect",!1,(function(t,e){return t.getInputField().autocorrect=e}),!0),n("autocapitalize",!1,(function(t,e){return t.getInputField().autocapitalize=e}),!0),n("rtlMoveVisually",!w),n("wholeLineUpdateBefore",!0),n("theme","default",(function(t){Ca(t),vi(t)}),!0),n("keyMap","default",(function(t,e,n){var r=Xo(e),i=n!=ka&&Xo(n);i&&i.detach&&i.detach(t,r),r.attach&&r.attach(t,i||null)})),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,_a,!0),n("gutters",[],(function(t,e){t.display.gutterSpecs=pi(e,t.options.lineNumbers),vi(t)}),!0),n("fixedGutter",!0,(function(t,e){t.display.gutters.style.left=e?sr(t.display)+"px":"0",t.refresh()}),!0),n("coverGutterNextToScrollbar",!1,(function(t){return zr(t)}),!0),n("scrollbarStyle","native",(function(t){$r(t),zr(t),t.display.scrollbars.setScrollTop(t.doc.scrollTop),t.display.scrollbars.setScrollLeft(t.doc.scrollLeft)}),!0),n("lineNumbers",!1,(function(t,e){t.display.gutterSpecs=pi(t.options.gutters,e),vi(t)}),!0),n("firstLineNumber",1,vi,!0),n("lineNumberFormatter",(function(t){return t}),vi,!0),n("showCursorWhenSelecting",!1,mr,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,(function(t,e){"nocursor"==e&&(jr(t),t.display.input.blur()),t.display.input.readOnlyChanged(e)})),n("screenReaderLabel",null,(function(t,e){e=''===e?null:e,t.display.input.screenReaderLabelChanged(e)})),n("disableInput",!1,(function(t,e){e||t.display.input.reset()}),!0),n("dragDrop",!0,Pa),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,mr,!0),n("singleCursorHeightPerLine",!0,mr,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,Mi,!0),n("addModeClass",!1,Mi,!0),n("pollInterval",100),n("undoDepth",200,(function(t,e){return t.doc.history.undoDepth=e})),n("historyEventDelay",1250),n("viewportMargin",10,(function(t){return t.refresh()}),!0),n("maxHighlightLength",1e4,Mi,!0),n("moveInputWithCursor",!0,(function(t,e){e||t.display.input.resetPosition()})),n("tabindex",null,(function(t,e){return t.display.input.getField().tabIndex=e||""})),n("autofocus",null),n("direction","ltr",(function(t,e){return t.doc.setDirection(e)}),!0),n("phrases",null)}(Ta),function(t){var e=t.optionHandlers,n=t.helpers={};t.prototype={constructor:t,focus:function(){window.focus(),this.display.input.focus()},setOption:function(t,n){var r=this.options,i=r[t];r[t]==n&&"mode"!=t||(r[t]=n,e.hasOwnProperty(t)&&ei(this,e[t])(this,n,i),gt(this,"optionChange",this,t))},getOption:function(t){return this.options[t]},getDoc:function(){return this.doc},addKeyMap:function(t,e){this.state.keyMaps[e?"push":"unshift"](Xo(t))},removeKeyMap:function(t){for(var e=this.state.keyMaps,n=0;nn&&(Da(this,i.head.line,t,!0),n=i.head.line,r==this.doc.sel.primIndex&&Mr(this));else{var o=i.from(),a=i.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var c=s;c0&&Xi(this.doc,r,new ki(o,l[r].to()),U)}}})),getTokenAt:function(t,e){return be(this,t,e)},getLineTokens:function(t,e){return be(this,ee(t),e,!0)},getTokenTypeAt:function(t){t=ce(this.doc,t);var e,n=de(this,Gt(this.doc,t.line)),r=0,i=(n.length-1)/2,o=t.ch;if(0==o)e=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]o&&(t=o,i=!0),r=Gt(this.doc,t)}else r=t;return $n(this,r,{top:0,left:0},e||"page",n||i).top+(i?this.doc.height-We(r):0)},defaultTextHeight:function(){return ir(this.display)},defaultCharWidth:function(){return or(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,n,r,i){var o,a,s,c=this.display,l=(t=Kn(this,ce(this.doc,t))).bottom,u=t.left;if(e.style.position="absolute",e.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(e),c.sizer.appendChild(e),"over"==r)l=t.top;else if("above"==r||"near"==r){var f=Math.max(c.wrapper.clientHeight,this.doc.height),h=Math.max(c.sizer.clientWidth,c.lineSpace.clientWidth);('above'==r||t.bottom+e.offsetHeight>f)&&t.top>e.offsetHeight?l=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=f&&(l=t.bottom),u+e.offsetWidth>h&&(u=h-e.offsetWidth)}e.style.top=l+"px",e.style.left=e.style.right="","right"==i?(u=c.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(c.sizer.clientWidth-e.offsetWidth)/2),e.style.left=u+"px"),n&&(o=this,a={left:u,top:l,right:u+e.offsetWidth,bottom:l+e.offsetHeight},null!=(s=Er(o,a)).scrollTop&&Nr(o,s.scrollTop),null!=s.scrollLeft&&Fr(o,s.scrollLeft))},triggerOnKeyDown:ni(fa),triggerOnKeyPress:ni(da),triggerOnKeyUp:ha,triggerOnMouseDown:ni(ya),execCommand:function(t){if(na.hasOwnProperty(t))return na[t].call(null,this)},triggerElectric:ni((function(t){Na(this,t)})),findPosH:function(t,e,n,r){var i=1;e<0&&(i=-1,e=-e);for(var o=ce(this.doc,t),a=0;a0&&a(e.charAt(n-1));)--n;for(;r.5||this.options.lineWrapping)&&lr(this),gt(this,"refresh",this)})),swapDoc:ni((function(t){var e=this.doc;return e.cm=null,this.state.selectingText&&this.state.selectingText(),Ni(this,t),Hn(this),this.display.input.reset(),Ar(this,t.scrollLeft,t.scrollTop),this.curOp.forceScroll=!0,ln(this,"swapDoc",this,e),e})),phrase:function(t){var e=this.options.phrases;return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:t},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},bt(t),t.registerHelper=function(e,r,i){n.hasOwnProperty(e)||(n[e]=t[e]={_global:[]}),n[e][r]=i},t.registerGlobalHelper=function(e,r,i,o){t.registerHelper(e,r,o),n[e]._global.push({pred:i,val:o})}}(Ta);var Ka="iter insert remove copy getEditor constructor".split(" ");for(var Ya in Mo.prototype)Mo.prototype.hasOwnProperty(Ya)&&B(Ka,Ya)<0&&(Ta.prototype[Ya]=function(t){return function(){return t.apply(this.doc,arguments)}}(Mo.prototype[Ya]));return bt(Mo),Ta.inputStyles={textarea:Ga,contenteditable:za},Ta.defineMode=function(t){Ta.defaults.mode||"null"==t||(Ta.defaults.mode=t),Ft.apply(this,arguments)},Ta.defineMIME=function(t,e){It[t]=e},Ta.defineMode("null",(function(){return{token:function(t){return t.skipToEnd()}}})),Ta.defineMIME("text/plain","null"),Ta.defineExtension=function(t,e){Ta.prototype[t]=e},Ta.defineDocExtension=function(t,e){Mo.prototype[t]=e},Ta.fromTextArea=function(t,e){if((e=e?I(e):{}).value=t.value,!e.tabindex&&t.tabIndex&&(e.tabindex=t.tabIndex),!e.placeholder&&t.placeholder&&(e.placeholder=t.placeholder),null==e.autofocus){var n=M();e.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}function r(){t.value=s.getValue()}var i;if(t.form&&(ht(t.form,"submit",r),!e.leaveSubmitMethodAlone)){var o=t.form;i=o.submit;try{var a=o.submit=function(){r(),o.submit=i,o.submit(),o.submit=a}}catch(t){}}e.finishInit=function(n){n.save=r,n.getTextArea=function(){return t},n.toTextArea=function(){n.toTextArea=isNaN,r(),t.parentNode.removeChild(n.getWrapperElement()),t.style.display="",t.form&&(pt(t.form,"submit",r),e.leaveSubmitMethodAlone||"function"!=typeof t.form.submit||(t.form.submit=i))}},t.style.display="none";var s=Ta((function(e){return t.parentNode.insertBefore(e,t.nextSibling)}),e);return s},function(t){t.off=pt,t.on=ht,t.wheelEventPixels=Oi,t.Doc=Mo,t.splitLines=Mt,t.countColumn=F,t.findColumn=q,t.isWordChar=tt,t.Pass=z,t.signal=gt,t.Line=Ge,t.changeEnd=Pi,t.scrollbarModel=Wr,t.Pos=ee,t.cmpPos=ne,t.modes=Nt,t.mimeModes=It,t.resolveMode=Vt,t.getMode=Bt,t.modeExtensions=Ht,t.extendMode=zt,t.copyState=Ut,t.startState=$t,t.innerMode=Wt,t.commands=na,t.keyMap=Wo,t.keyName=Jo,t.isModifierKey=Ko,t.lookupKey=Go,t.normalizeKeyMap=qo,t.StringStream=qt,t.SharedTextMarker=_o,t.TextMarker=jo,t.LineWidget=Co,t.e_preventDefault=wt,t.e_stopPropagation=Ot,t.e_stop=Ct,t.addClass=A,t.contains=D,t.rmClass=j,t.keyNames=Bo}(Ta),Ta.version="5.63.0",Ta}())},function(t,e,n){var r=n(88),i=n(89),o=n(49),a=n(90);t.exports=function(t,e){return r(t)||i(t,e)||o(t,e)||a()},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";var r=n(0),i=n(3),o=n.n(i);e["a"]=o.a.View.extend({itemView:'',itemsView:'',itemType:'type',autoAdd:0,initialize:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;this.config=e||t.config||{},this.autoAdd&&this.listenTo(this.collection,'add',this.addTo),this.items=[],this.init()},init:function(){},addTo:function(t){this.add(t)},itemViewNotFound:function(t){var e=this.config,n=this.ns,r=e.em,i="".concat(n?"[".concat(n,"]: "):'',"'").concat(t,"' type not found");r&&r.logWarning(i)},add:function(t,e){var n,i=this.config,o=this.reuseView,a=this.items,s=this.itemsView,c=void 0===s?{}:s,l=e||null,u=this.itemView,f=t.get(this.itemType);c[f]?u=c[f]:!f||c[f]||Object(r["includes"])(['button','checkbox','color','date','datetime-local','email','file','hidden','image','month','number','password','radio','range','reset','search','submit','tel','text','time','url','week'],f)||this.itemViewNotFound(f),n=t.view&&o?t.view:new u({model:t,config:i},i),a&&a.push(n);var h=n.render().el;l?l.appendChild(h):this.$el.append(h)},render:function(){var t=document.createDocumentFragment();return this.clearItems(),this.$el.empty(),this.collection.length&&this.collection.each((function(e){this.add(e,t)}),this),this.$el.append(t),this.onRender(),this},onRender:function(){},onRemoveBefore:function(){},onRemove:function(){},remove:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.items;this.onRemoveBefore(e,t),this.clearItems(),o.a.View.prototype.remove.apply(this,arguments),this.onRemove(e,t)},clearItems:function(){this.items}})},function(t,e,n){"use strict";n.r(e);var r=n(3);e["default"]=r["Model"].extend({initialize:function(t){this.config=t||{},this.editorModel=this.em=this.config.em||{},this.pfx=this.config.stylePrefix,this.ppfx=this.config.pStylePrefix,this.hoverClass=this.pfx+'hover',this.badgeClass=this.pfx+'badge',this.plhClass=this.pfx+'placeholder',this.freezClass=this.ppfx+'freezed',this.canvas=this.em.get&&this.em.get('Canvas'),this.init(this.config)},onFrameScroll:function(t){},getCanvas:function(){return this.canvas.getElement()},getCanvasBody:function(){return this.canvas.getBody()},getCanvasTools:function(){return this.canvas.getToolsEl()},offset:function(t){var e=t.getBoundingClientRect();return{top:e.top+t.ownerDocument.body.scrollTop,left:e.left+t.ownerDocument.body.scrollLeft}},init:function(t){},callRun:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.id;if(t.trigger("run:".concat(n,":before"),e),!e||!e.abort){var r=e.sender||t,i=this.run(t,r,e);return t.trigger("run:".concat(n),i,e),t.trigger('run',n,i,e),i}t.trigger("abort:".concat(n),e)},callStop:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.id,r=e.sender||t;t.trigger("stop:".concat(n,":before"),e);var i=this.stop(t,r,e);return t.trigger("stop:".concat(n),i,e),t.trigger('stop',n,i,e),i},stopCommand:function(){this.em.get('Commands').stop(this.id)},run:function(t,e){},stop:function(t,e){}})},function(t,e,n){"use strict";var r=n(2),i=n.n(r),o=n(0),a=n(1),s=n(42);function c(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function l(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object(o["isString"])(e)&&(e=u(e));var r=this.getStyle(n),i=l({},e);this.set('style',i,n);var s=Object(a["shallowDiff"])(r,i);return Object(o["keys"])(s).forEach((function(e){var r=t.em;n.noEvent||(t.trigger("change:style:".concat(e)),r&&(r.trigger("styleable:change",t,e,n),r.trigger("styleable:change:".concat(e),t,e,n)))})),i},addStyle:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:'',n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};'string'==typeof t?t={prop:e}:n=e||{},t=this.extendStyle(t),this.setStyle(t,n)},removeStyle:function(t){var e=this.getStyle();delete e[t],this.setStyle(e)},styleToString:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=[],n=this.getStyle(t);for(var r in n){var i=t.important,a=Object(o["isArray"])(i)?i.indexOf(r)>=0:i,s="".concat(n[r]).concat(a?' !important':''),c='__'==r.substr(0,2);s&&!c&&e.push("".concat(r,":").concat(s,";"))}return e.join('')},getSelectors:function(){return this.get('selectors')||this.get('classes')},getSelectorsString:function(t){return this.selectorsToString?this.selectorsToString(t):this.getSelectors().getFullString()},_validate:function(t,e){var n,r=t.style,i=this.em||e.em,a=null==i||null===(n=i.get('CssComposer'))||void 0===n?void 0:n.getConfig().onBeforeStyle;if(r&&a){var s=a(l({},r));s&&Object(o["keys"])(r).map((function(e){Object(o["isUndefined"])(s[e])&&delete t.style[e]})),s&&Object(o["keys"])(s).map((function(e){t.style[e]=s[e]}))}return!0}}},function(t,e){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e){function n(t,e,n,r,i,o,a){try{var s=t[o](a),c=s.value}catch(t){return void n(t)}s.done?e(c):Promise.resolve(c).then(r,i)}t.exports=function(t){return function(){var e=this,r=arguments;return new Promise((function(i,o){var a=t.apply(e,r);function s(t){n(a,i,o,s,c,"next",t)}function c(t){n(a,i,o,s,c,"throw",t)}s(void 0)}))}},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n.n(r).a.$;e["default"]={startSelectPosition:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.isPointed=!1;var i=this.editorModel.get('Utils'),o=t.ownerDocument.body;i&&!this.sorter&&(this.sorter=new i.Sorter({container:o,placer:this.canvas.getPlacerEl(),containerSel:'*',itemSel:'*',pfx:this.ppfx,direction:'a',document:e,wmargin:1,nested:1,em:this.editorModel,canvasRelative:1,scale:function(){return n.em.getZoomDecimal()}})),r.onStart&&(this.sorter.onStart=r.onStart),t&&this.sorter.startSort(t,{container:o})},getOffsetDim:function(){var t=this.offset(this.canvas.getFrameEl()),e=this.offset(this.canvas.getElement());return{top:t.top-e.top,left:t.left-e.left}},stopSelectPosition:function(){this.posTargetCollection=null,this.posIndex='after'==this.posMethod&&0!==this.cDim.length?this.posIndex+1:this.posIndex,this.sorter&&(this.sorter.moved=0,this.sorter.endMove()),this.cDim&&(this.posIsLastEl=0!==this.cDim.length&&'after'==this.posMethod&&this.posIndex==this.cDim.length,this.posTargetEl=0===this.cDim.length?i(this.outsideElem):!this.posIsLastEl&&this.cDim[this.posIndex]?i(this.cDim[this.posIndex][5]).parent():i(this.outsideElem),this.posTargetModel=this.posTargetEl.data('model'),this.posTargetCollection=this.posTargetEl.data('model-comp'))},enable:function(){this.startSelectPosition()},nearFloat:function(t,e,n){var r=t||0,i=e||'before',o=n.length,a=0!==o&&'after'==i&&r==o;return 0!==o&&(!a&&!n[r][4]||n[r-1]&&!n[r-1][4]||a&&!n[r-1][4])?1:0},run:function(){this.enable()},stop:function(){this.stopSelectPosition(),this.$wrapper.css('cursor',''),this.$wrapper.unbind()}}},function(t,e,n){"use strict";var r=n(45),i=n(1);Object(i["hasWin"])()&&(window.Promise=window.Promise||r["a"]),e["a"]='function'==typeof fetch?fetch.bind():function(t,e){return new r["a"]((function(n,i){var o=new XMLHttpRequest;for(var a in o.open(e.method||'get',t),o.withCredentials='include'==e.credentials,e.headers||{})o.setRequestHeader(a,e.headers[a]);o.onload=function(t){return n({status:o.status,statusText:o.statusText,text:function(){return r["a"].resolve(o.responseText)}})},o.onerror=i,o.upload&&e.onProgress&&(o.upload.onprogress=e.onProgress),e.body?o.send(e.body):o.send()}))}},function(t,e,n){"use strict";var r=n(2),i=n.n(r),o=n(0),a=n(3),s=n.n(a);function c(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function l(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},r=n.em;this.em=r,this.opts=n,this.model=function(){var t,n,i,o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(o&&o.type){var s=e.getBaseType();t=(i=e.getType(o.type))?i.model:s.model,n=i?i.view:s.view}else{var c=e.recognizeType(o);t=(i=c.type).model,n=i.view,o=c.attributes}var u=new t(o,l(l({},a),{},{em:r}));return u.typeView=n,u};var i=this.init&&this.init.bind(this);i&&i()},recognizeType:function(t){for(var e=this.getTypes(),n=0;n\n \n
\n
\n
\n
\n ")},inputClass:function(){var t=this.ppfx;return this.opts.contClass||"".concat(t,"field ").concat(t,"field-integer")},initialize:function(){s["a"].prototype.initialize.apply(this,arguments),Object(o["bindAll"])(this,'moveIncrement','upIncrement'),this.doc=document,this.listenTo(this.model,'change:unit',this.handleModelChange)},setValue:function(t,e){var n=e||{},r=this.validateInputValue(t,{deepCheck:1}),i={value:r.value};(r.unit||r.force)&&(i.unit=r.unit),this.model.set(i,n),n.silent&&this.handleModelChange()},handleChange:function(t){t.stopPropagation(),this.setValue(this.getInputEl().value),this.elementUpdated()},handleUnitChange:function(t){t.stopPropagation();var e=this.getUnitEl().value;this.model.set('unit',e),this.elementUpdated()},handleKeyDown:function(t){'ArrowUp'===t.key&&(t.preventDefault(),this.upArrowClick()),'ArrowDown'===t.key&&(t.preventDefault(),this.downArrowClick())},elementUpdated:function(){this.model.trigger('el:change')},handleModelChange:function(){var t=this.model;this.getInputEl().value=t.get('value');var e=this.getUnitEl();e&&(e.value=t.get('unit')||'')},getUnitEl:function(){if(!this.unitEl){var t=this.model,e=t.get('units')||[];if(e.length){var n=[''];e.forEach((function(e){var r=e==t.get('unit')?'selected':'';n.push(""))}));var r=document.createElement('div');r.innerHTML=""),this.unitEl=r.firstChild}}return this.unitEl},upArrowClick:function(){var t=this.model,e=t.get('step'),n=parseFloat(t.get('value'));this.setValue(this.normalizeValue(n+e)),this.elementUpdated()},downArrowClick:function(){var t=this.model,e=t.get('step'),n=parseFloat(t.get('value'));this.setValue(this.normalizeValue(n-e)),this.elementUpdated()},downIncrement:function(t){t.preventDefault(),this.moved=0;var e=this.model.get('value')||0;e=this.normalizeValue(e),this.current={y:t.pageY,val:e},Object(a["on"])(this.doc,'mousemove',this.moveIncrement),Object(a["on"])(this.doc,'mouseup',this.upIncrement)},moveIncrement:function(t){this.moved=1;var e=this.model,n=e.get('step'),r=this.current,i=this.normalizeValue(r.val+(r.y-t.pageY)*n),o=this.validateInputValue(i),a=o.value,s=o.unit;return this.prValue=a,e.set({value:a,unit:s},{avoidStore:1}),!1},upIncrement:function(){var t=this.model,e=t.get('step');if(Object(a["off"])(this.doc,'mouseup',this.upIncrement),Object(a["off"])(this.doc,'mousemove',this.moveIncrement),this.prValue&&this.moved){var n=this.prValue-e;t.set('value',n,{avoidStore:1}).set('value',n+e),this.elementUpdated()}},normalizeValue:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=this.model,r=n.get('step'),i=0;if(isNaN(t))return e;if(t=parseFloat(t),Math.floor(t)!==t){var o=r.toString().split('.')[1];i=o?o.length:0}return i?parseFloat(t.toFixed(i)):t},validateInputValue:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=0,r=e||{},i=this.model,a='',s=Object(o["isUndefined"])(t)?a:t,c=e.units||i.get('units')||[],l=i.get('unit')||c.length&&c[0]||'',u=Object(o["isUndefined"])(e.max)?i.get('max'):e.max,f=Object(o["isUndefined"])(e.min)?i.get('min'):e.min,h=!!i.get('limitlessMax'),d=!!i.get('limitlessMin');if(r.deepCheck){var p=i.get('fixedValues')||[];if(''===s&&(l=''),s){var g=new RegExp('^'+p.join('|'),'g');if(p.length&&g.test(s))s=s.match(g)[0],l='',n=1;else{var v=s+'';s+='',s=parseFloat(s.replace(',','.')),s=isNaN(s)?a:s;var m=v.replace(s,'');Object(o["indexOf"])(c,m)>=0&&(l=m)}}}return h||Object(o["isUndefined"])(u)||''===u||(s=s>u?u:s),d||Object(o["isUndefined"])(f)||''===f||(s=s1&&void 0!==arguments[1]?arguments[1]:{},r='',i=this.em,o=i&&i.getConfig('avoidInlineStyle'),a=t.styleToString(),s=t.get('classes'),c=n.wrapperIsBody,l=t.get('wrapper');if(this.ids.push("#".concat(t.getId())),s.each((function(t){return e.compCls.push(t.getFullName())})),!o&&a){var u="#".concat(t.getId());r="".concat(u=c&&l?'body':u,"{").concat(a,"}")}var f=t.components();return f.each((function(t){return r+=e.buildFromModel(t,n)})),r},build:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.json,i=n.em||'',s=n.cssc||i&&i.get('CssComposer');this.em=i,this.compCls=[],this.ids=[],this.model=t;var c=[],l=t?this.buildFromModel(t,n):'',u=Object(o["isUndefined"])(n.clearStyles)&&i?i.getConfig('clearStyles'):n.clearStyles;if(s){var f=n.rules||s.getAll(),h={},d=[];n.onlyMatched&&t&&Object(a["hasWin"])()&&(f=this.matchedRules(t,f)),f.forEach((function(t){var i=t.getAtRule();if(i){var o=h[i];o?o.push(t):h[i]=[t]}else{var a=e.buildFromRule(t,d,n);r?c.push(a):l+=a}})),this.sortMediaObject(h).forEach((function(t){var i='',o=t.key;t.value.forEach((function(t){var a=e.buildFromRule(t,d,n);t.get('singleAtRule')?l+="".concat(o,"{").concat(a,"}"):i+=a,r&&c.push(a)})),i&&(l+="".concat(o,"{").concat(i,"}"))})),i&&u&&f.remove&&f.remove(d)}return r?c.filter((function(t){return t})):l},buildFromRule:function(t,e){var n,r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o='',a=this.model,s=t.selectorsToString({skipAdd:1}),c=t.get('selectorsAdd'),l=t.get('singleAtRule');if(t.get('selectors').each((function(t){var e=t.getFullName();(r.compCls.indexOf(e)>=0||r.ids.indexOf(e)>=0||i.keepUnusedStyles)&&(n=1)})),s&&n||c||l||!a){var u=t.getDeclaration({body:1});u&&(i.json?o=t:o+=u)}else e.push(t);return o},matchedRules:function(t,e){var n=this,r=t.getEl(),i=[];return e.forEach((function(t){try{t.selectorsToString().split(',').some((function(t){return r.matches(n.__cleanSelector(t))}))&&i.push(t)}catch(t){}})),t.components().forEach((function(t){i=i.concat(n.matchedRules(t,e))})),i=i.filter((function(t,e){return i.indexOf(t)===e}))},getQueryLength:function(t){var e=/(-?\d*\.?\d+)\w{0,}/.exec(t);return e?parseFloat(e[1]):s},sortMediaObject:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=[];return Object(o["each"])(e,(function(t,e){return n.push({key:e,value:t})})),n.sort((function(e,n){var r=[e.key,n.key].every((function(t){return-1!==t.indexOf('min-width')})),i=r?e.key:n.key,o=r?n.key:e.key;return t.getQueryLength(i)-t.getQueryLength(o)}))},sortRules:function(t,e){var n=function(t){return t.get('mediaText')},r=[n(t),n(e)].every((function(t){return-1!==t.indexOf('min-width')})),i=n(r?t:e),o=n(r?e:t);return this.getQueryLength(i)-this.getQueryLength(o)},__cleanSelector:function(t){return t.split(' ').map((function(t){return t.split(':')[0]})).join(' ')}})},function(t,e,n){"use strict";var r=n(3),i=n.n(r),o=n(0);e["a"]=i.a.View.extend({initialize:function(t){this.opts=t||{},this.config=t.config||{},this.em=this.config.em;var e=this.collection;this.listenTo(e,'add',this.addTo),this.listenTo(e,'reset',this.resetChildren),this.listenTo(e,'remove',this.removeChildren)},removeChildren:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};t.views.forEach((function(t){if(t){var e=t.childrenView,n=t.scriptContainer;e&&e.stopListening(),n&&n.remove(),t.remove.apply(t)}}));var i=t.components();i.forEach((function(t){return n.removeChildren(t,e,r)}))},addTo:function(t){var e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.config.em,r=this.collection.indexOf(t);if(this.addToCollection(t,null,r),n&&!e.temporary){var i=function t(e){n.trigger('component:add',e),e.components().forEach((function(e){return t(e)}))};i(t)}},addToCollection:function(t,e,r){this.compView||(this.compView=n(12).default);for(var i=this.config,a=this.opts,s=this.em,c=e||null,l=i.frameView,u=void 0===l?{}:l,f=u.model&&t.getView(u.model),h=a.componentTypes||s&&s.get('DomComponents').getTypes(),d=t.get('type')||'default',p=this.compView,g=0;g1&&void 0!==arguments[1]?arguments[1]:{},r=n.previousModels,i=void 0===r?[]:r;this.parentEl.innerHTML='',i.forEach((function(t){return e.removeChildren(t,e.collection)})),t.each((function(t){return e.addToCollection(t)}))},render:function(t){var e=this,n=this.el,r=document.createDocumentFragment();return this.parentEl=t||this.el,this.collection.each((function(t){return e.addToCollection(t,r)})),n.innerHTML='',n.appendChild(r),this}})},function(t,e,n){"use strict";var r=n(3),i=n.n(r),o=i.a.View.extend({tagName:'style',initialize:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.config=t.config||{};var e=this.model;this.listenTo(e,'change',this.render),this.listenTo(e,'destroy remove',this.remove),this.listenTo(e.get('selectors'),'change',this.render)},render:function(){var t=this.model,e=this.el,n=t.get('important');return e.innerHTML=t.toCSS({important:n}),this}}),a=o.extend({_createElement:function(t){return document.createTextNode('')},render:function(){var t=this.model,e=t.get('important');return this.el.textContent=t.getDeclaration({important:e}),this}}),s=i.a.$,c=function(t,e){return"".concat(t).concat(e?"-".concat(parseFloat(e)):'')};e["a"]=i.a.View.extend({initialize:function(t){var e=t.config||{};this.atRules={},this.config=e,this.em=e.em,this.pfx=e.stylePrefix||'',this.className=this.pfx+'rules';var n=this.collection;this.listenTo(n,'add',this.addTo),this.listenTo(n,'reset',this.render)},addTo:function(t){this.addToCollection(t)},addToCollection:function(t,e){if(this.renderStarted){var n,r,i=e||null,s={model:t,config:this.config};if('keyframes'===t.get('atRuleType')){var l=t.getAtRule(),u=this.atRules[l];if(!u){var f=document.createElement('style');u=document.createTextNode(''),f.appendChild(document.createTextNode("".concat(l,"{"))),f.appendChild(u),f.appendChild(document.createTextNode("}")),this.atRules[l]=u,n=f}r=new a(s),u.appendData(r.render().el.textContent)}else n=(r=new o(s)).render().el;var h=this.className,d=t.get('mediaText'),p=c(h),g=p;if(d&&(g=c(h,this.getMediaWidth(d))),n){var v,m=i||this.el;try{v=m.querySelector("#".concat(g))}catch(t){}v||(v=m.querySelector("#".concat(p))),v.appendChild(n)}return n}},getMediaWidth:function(t){return t&&t.replace("(".concat(this.em.getConfig('mediaCondition'),": "),'').replace(')','')},render:function(){var t=this;this.renderStarted=1,this.atRules={};var e=this.em,n=this.$el,r=this.className,i=this.collection,o=document.createDocumentFragment();n.empty();var a=e.get('DeviceManager').getAll().pluck('priority');return a.every((function(t){return t}))&&a.unshift(0),a.forEach((function(t){return s("
")).appendTo(o)})),i.each((function(e){return t.addToCollection(e,o)})),n.append(o),n.attr('class',r),this}})},function(t,e,n){"use strict";var r=n(2),i=n.n(r),o=n(14),a=n.n(o),s=n(0),c='text/html',l=c,u=function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=new DOMParser,i=n.htmlType||l,o=i===c,a=o?t:"
".concat(t,"
"),u=r.parseFromString(a,i);if(o){var f=u.head,h=u.body,d=f.querySelectorAll('script');Object(s["each"])(d,(function(t){return h.appendChild(t)}));var p=[];Object(s["each"])(f.children,(function(t){return p.push(t)})),Object(s["each"])(p,(function(t,e){return h.insertBefore(t,h.children[e])})),e=h}else e=u.firstChild;return e};function f(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function h(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},r={},i={};return Object(s["each"])(e,(function(e,o){if(0===o.indexOf(t.modelAttrStart)){var a=o.replace(n,''),c=e.length,l=e&&Object(s["isString"])(e),u=l&&e.substr(0,1),f=l&&e.substr(c-1);e='false'!==(e='true'===e||e)&&e;try{e='{'==u&&'}'==f||'['==u&&']'==f?JSON.parse(e):e}catch(t){}r[a]=e}else i[o]=e})),{props:r,attrs:i}},parseStyle:function(t){for(var e={},n=t.split(';'),r=0,i=n.length;r1&&void 0!==arguments[1]?arguments[1]:{},o=[],s=r.childNodes,c=0,l=s.length;c'!=="".concat(u.outerHTML).slice(-2)||(m.void=!0);var D=m.components;if(!m.type&&D){for(var M=1,A=0,L=0;L2&&void 0!==arguments[2]?arguments[2]:{},c=e.em,l=c&&c.get('Config')||{},f={html:null,css:null},d=h(h({},t),a),p=h(h({},t.optionsHtml),{},{htmlType:(null===(o=t.optionsHtml)||void 0===o?void 0:o.htmlType)||t.htmlType},a),g=Object(s["isFunction"])(d.parserHtml)?d.parserHtml(n,p):u(n,p),v=g.querySelectorAll('script'),m=v.length,y=Object(s["isUndefined"])(l.allowScripts)?p.allowScripts:l.allowScripts;if(!y)for(;m--;)v[m].parentNode.removeChild(v[m]);if(p.allowUnsafeAttr||this.__clearUnsafeAttr(g),i){for(var b=g.querySelectorAll('style'),w=b.length,O='';w--;)O=b[w].innerHTML+O,b[w].parentNode.removeChild(b[w]);O&&(f.css=i.parse(O))}c&&c.trigger("".concat(r,":root"),{input:n,root:g});var x=this.parseNode(g),C=1!==x.length||e.returnArray?x:x[0];return f.html=C,c&&c.trigger(r,{input:n,output:f}),f},__clearUnsafeAttr:function(t){var e=this,n=t.attributes||[],r=t.childNodes||[],i=[];Object(s["each"])(n,(function(t){var e=t.nodeName||'';0===e.indexOf('on')&&i.push(e)})),i.map((function(e){return t.removeAttribute(e)})),Object(s["each"])(r,(function(t){return e.__clearUnsafeAttr(t)}))}}}},function(t,e,n){"use strict";var r=n(2),i=n.n(r),o=n(3),a=n.n(o),s=n(0),c=n(14),l=n.n(c),u=n(1),f=n(25);function h(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function d(t){for(var e=1;e","
","
",''].join(''),s=function(){var t='';if(i)for(var e=1;e<=6;e++)t+="
";return["
","
","
","
","",'
','
',"
","
","
","
","
","
","
","
",'
','
','
',"
",'
',"
","
",t,'
','
',"
",'
',"
","",'
',"
","
","","",'
','
','
'].join('')}(),c='spectrum.id';t.fn.spectrum=function(e,n){if('string'==typeof e){var i=this,o=Array.prototype.slice.call(arguments,1);return this.each((function(){var n=r[t(this).data(c)];if(n){var a=n[e];if(!a)throw new Error("Spectrum: no such method: '"+e+"'");'get'==e?i=n.get():'container'==e?i=n.container:'option'==e?i=n.option.apply(n,o):'destroy'==e?(n.destroy(),t(this).removeData(c)):a.apply(n,o)}})),i}return this.spectrum('destroy').each((function(){var n=P(this,t.extend({},e,t(this).data()));t(this).data(c,n.id)}))},t.fn.spectrum.load=!0,t.fn.spectrum.loadOpts={},t.fn.spectrum.draggable=D,t.fn.spectrum.defaults=n,t.fn.spectrum.inputTypeColorSupport=function e(){if(void 0===e._cachedResult){var n=t("")[0];e._cachedResult='color'===n.type&&''!==n.value}return e._cachedResult},t.spectrum={},t.spectrum.localization={},t.spectrum.palettes={},t.fn.spectrum.processNativeColorInputs=function(){var e=t('input[type=color]');e.length&&!M()&&e.spectrum({preferredFormat:'hex6'})};var f=/^[\s,#]+/,h=/\s+$/,d=0,p=Math,g=p.round,v=p.min,m=p.max,y=p.random,b=function t(e,n){if(n=n||{},(e=e||'')instanceof t)return e;if(!(this instanceof t))return new t(e,n);var r=function(t){var e={r:0,g:0,b:0},n=1,r=!1,i=!1;'string'==typeof t&&(t=function(t){t=t.replace(f,'').replace(h,'').toLowerCase();var e,n=!1;if(C[t])t=C[t],n=!0;else if('transparent'==t)return{r:0,g:0,b:0,a:0,format:'name'};if(e=S.rgb.exec(t))return{r:e[1],g:e[2],b:e[3]};if(e=S.rgba.exec(t))return{r:e[1],g:e[2],b:e[3],a:e[4]};if(e=S.hsl.exec(t))return{h:e[1],s:e[2],l:e[3]};if(e=S.hsla.exec(t))return{h:e[1],s:e[2],l:e[3],a:e[4]};if(e=S.hsv.exec(t))return{h:e[1],s:e[2],v:e[3]};if(e=S.hsva.exec(t))return{h:e[1],s:e[2],v:e[3],a:e[4]};if(e=S.hex8.exec(t))return{a:(r=e[1],Q(r)/255),r:Q(e[2]),g:Q(e[3]),b:Q(e[4]),format:n?'name':'hex8'};var r;if(e=S.hex6.exec(t))return{r:Q(e[1]),g:Q(e[2]),b:Q(e[3]),format:n?'name':'hex'};if(e=S.hex3.exec(t))return{r:Q(e[1]+''+e[1]),g:Q(e[2]+''+e[2]),b:Q(e[3]+''+e[3]),format:n?'name':'hex'};return!1}(t));'object'==l()(t)&&(t.hasOwnProperty('r')&&t.hasOwnProperty('g')&&t.hasOwnProperty('b')?(o=t.r,a=t.g,s=t.b,e={r:255*X(o,255),g:255*X(a,255),b:255*X(s,255)},r=!0,i='%'===String(t.r).substr(-1)?'prgb':'rgb'):t.hasOwnProperty('h')&&t.hasOwnProperty('s')&&t.hasOwnProperty('v')?(t.s=et(t.s),t.v=et(t.v),e=function(t,e,n){t=6*X(t,360),e=X(e,100),n=X(n,100);var r=p.floor(t),i=t-r,o=n*(1-e),a=n*(1-i*e),s=n*(1-(1-i)*e),c=r%6;return{r:255*[n,a,o,o,s,n][c],g:255*[s,n,n,a,o,o][c],b:255*[o,o,s,n,n,a][c]}}(t.h,t.s,t.v),r=!0,i='hsv'):t.hasOwnProperty('h')&&t.hasOwnProperty('s')&&t.hasOwnProperty('l')&&(t.s=et(t.s),t.l=et(t.l),e=function(t,e,n){var r,i,o;function a(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}if(t=X(t,360),e=X(e,100),n=X(n,100),0===e)r=i=o=n;else{var s=n<.5?n*(1+e):n+e-n*e,c=2*n-s;r=a(c,s,t+1/3),i=a(c,s,t),o=a(c,s,t-1/3)}return{r:255*r,g:255*i,b:255*o}}(t.h,t.s,t.l),r=!0,i='hsl'),t.hasOwnProperty('a')&&(n=t.a));var o,a,s;return n=J(n),{ok:r,format:t.format||i,r:v(255,m(e.r,0)),g:v(255,m(e.g,0)),b:v(255,m(e.b,0)),a:n}}(e);this._originalInput=e,this._r=r.r,this._g=r.g,this._b=r.b,this._a=r.a,this._roundA=g(100*this._a)/100,this._format=n.format||r.format,this._gradientType=n.gradientType,this._r<1&&(this._r=g(this._r)),this._g<1&&(this._g=g(this._g)),this._b<1&&(this._b=g(this._b)),this._ok=r.ok,this._tc_id=d++};b.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},setAlpha:function(t){return this._a=J(t),this._roundA=g(100*this._a)/100,this},toHsv:function(){var t=L(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=L(this._r,this._g,this._b),e=g(360*t.h),n=g(100*t.s),r=g(100*t.v);return 1==this._a?'hsv('+e+', '+n+'%, '+r+'%)':'hsva('+e+', '+n+'%, '+r+'%, '+this._roundA+')'},toHsl:function(){var t=A(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=A(this._r,this._g,this._b),e=g(360*t.h),n=g(100*t.s),r=g(100*t.l);return 1==this._a?'hsl('+e+', '+n+'%, '+r+'%)':'hsla('+e+', '+n+'%, '+r+'%, '+this._roundA+')'},toHex:function(t){return R(this._r,this._g,this._b,t)},toHexString:function(t){return'#'+this.toHex(t)},toHex8:function(){return N(this._r,this._g,this._b,this._a)},toHex8String:function(){return'#'+this.toHex8()},toRgb:function(){return{r:g(this._r),g:g(this._g),b:g(this._b),a:this._a}},toRgbString:function(){return 1==this._a?'rgb('+g(this._r)+', '+g(this._g)+', '+g(this._b)+')':'rgba('+g(this._r)+', '+g(this._g)+', '+g(this._b)+', '+this._roundA+')'},toPercentageRgb:function(){return{r:g(100*X(this._r,255))+'%',g:g(100*X(this._g,255))+'%',b:g(100*X(this._b,255))+'%',a:this._a}},toPercentageRgbString:function(){return 1==this._a?'rgb('+g(100*X(this._r,255))+'%, '+g(100*X(this._g,255))+'%, '+g(100*X(this._b,255))+'%)':'rgba('+g(100*X(this._r,255))+'%, '+g(100*X(this._g,255))+'%, '+g(100*X(this._b,255))+'%, '+this._roundA+')'},toName:function(){return 0===this._a?'transparent':!(this._a<1)&&(k[R(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e='#'+N(this._r,this._g,this._b,this._a),n=e,r=this._gradientType?'GradientType = 1, ':'';t&&(n=b(t).toHex8String());return'progid:DXImageTransform.Microsoft.gradient('+r+'startColorstr='+e+',endColorstr='+n+')'},toString:function(t){var e=!!t;t=t||this._format;var n=!1,r=this._a<1&&this._a>=0;return e||!r||'hex'!==t&&'hex6'!==t&&'hex3'!==t&&'name'!==t?('rgb'===t&&(n=this.toRgbString()),'prgb'===t&&(n=this.toPercentageRgbString()),'hex'!==t&&'hex6'!==t||(n=this.toHexString()),'hex3'===t&&(n=this.toHexString(!0)),'hex8'===t&&(n=this.toHex8String()),'name'===t&&(n=this.toName()),'hsl'===t&&(n=this.toHslString()),'hsv'===t&&(n=this.toHsvString()),n||this.toHexString()):'name'===t&&0===this._a?this.toName():this.toRgbString()},_applyModification:function(t,e){var n=t.apply(null,[this].concat([].slice.call(e)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(B,arguments)},brighten:function(){return this._applyModification(H,arguments)},darken:function(){return this._applyModification(z,arguments)},desaturate:function(){return this._applyModification(I,arguments)},saturate:function(){return this._applyModification(F,arguments)},greyscale:function(){return this._applyModification(V,arguments)},spin:function(){return this._applyModification(U,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(K,arguments)},complement:function(){return this._applyCombination(W,arguments)},monochromatic:function(){return this._applyCombination(Y,arguments)},splitcomplement:function(){return this._applyCombination(G,arguments)},triad:function(){return this._applyCombination($,arguments)},tetrad:function(){return this._applyCombination(q,arguments)}},b.fromRatio=function(t,e){if('object'==l()(t)){var n={};for(var r in t)t.hasOwnProperty(r)&&(n[r]='a'===r?t[r]:et(t[r]));t=n}return b(t,e)},b.equals=function(t,e){return!(!t||!e)&&b(t).toRgbString()==b(e).toRgbString()},b.random=function(){return b.fromRatio({r:y(),g:y(),b:y()})},b.mix=function(t,e,n){n=0===n?0:n||50;var r,i=b(t).toRgb(),o=b(e).toRgb(),a=n/100,s=2*a-1,c=o.a-i.a,l=1-(r=((r=s*c==-1?s:(s+c)/(1+s*c))+1)/2),u={r:o.r*r+i.r*l,g:o.g*r+i.g*l,b:o.b*r+i.b*l,a:o.a*a+i.a*(1-a)};return b(u)},b.readability=function(t,e){var n=b(t),r=b(e),i=n.toRgb(),o=r.toRgb(),a=n.getBrightness(),s=r.getBrightness(),c=Math.max(i.r,o.r)-Math.min(i.r,o.r)+Math.max(i.g,o.g)-Math.min(i.g,o.g)+Math.max(i.b,o.b)-Math.min(i.b,o.b);return{brightness:Math.abs(a-s),color:c}},b.isReadable=function(t,e){var n=b.readability(t,e);return n.brightness>125&&n.color>500},b.mostReadable=function(t,e){for(var n=null,r=0,i=!1,o=0;o125&&a.color>500,c=3*(a.brightness/125)+a.color/500;(s&&!i||s&&i&&c>r||!s&&!i&&c>r)&&(i=s,r=c,n=b(e[o]))}return n};var w,O,x,C=b.names={aliceblue:'f0f8ff',antiquewhite:'faebd7',aqua:'0ff',aquamarine:'7fffd4',azure:'f0ffff',beige:'f5f5dc',bisque:'ffe4c4',black:'000',blanchedalmond:'ffebcd',blue:'00f',blueviolet:'8a2be2',brown:'a52a2a',burlywood:'deb887',burntsienna:'ea7e5d',cadetblue:'5f9ea0',chartreuse:'7fff00',chocolate:'d2691e',coral:'ff7f50',cornflowerblue:'6495ed',cornsilk:'fff8dc',crimson:'dc143c',cyan:'0ff',darkblue:'00008b',darkcyan:'008b8b',darkgoldenrod:'b8860b',darkgray:'a9a9a9',darkgreen:'006400',darkgrey:'a9a9a9',darkkhaki:'bdb76b',darkmagenta:'8b008b',darkolivegreen:'556b2f',darkorange:'ff8c00',darkorchid:'9932cc',darkred:'8b0000',darksalmon:'e9967a',darkseagreen:'8fbc8f',darkslateblue:'483d8b',darkslategray:'2f4f4f',darkslategrey:'2f4f4f',darkturquoise:'00ced1',darkviolet:'9400d3',deeppink:'ff1493',deepskyblue:'00bfff',dimgray:'696969',dimgrey:'696969',dodgerblue:'1e90ff',firebrick:'b22222',floralwhite:'fffaf0',forestgreen:'228b22',fuchsia:'f0f',gainsboro:'dcdcdc',ghostwhite:'f8f8ff',gold:'ffd700',goldenrod:'daa520',gray:'808080',green:'008000',greenyellow:'adff2f',grey:'808080',honeydew:'f0fff0',hotpink:'ff69b4',indianred:'cd5c5c',indigo:'4b0082',ivory:'fffff0',khaki:'f0e68c',lavender:'e6e6fa',lavenderblush:'fff0f5',lawngreen:'7cfc00',lemonchiffon:'fffacd',lightblue:'add8e6',lightcoral:'f08080',lightcyan:'e0ffff',lightgoldenrodyellow:'fafad2',lightgray:'d3d3d3',lightgreen:'90ee90',lightgrey:'d3d3d3',lightpink:'ffb6c1',lightsalmon:'ffa07a',lightseagreen:'20b2aa',lightskyblue:'87cefa',lightslategray:'789',lightslategrey:'789',lightsteelblue:'b0c4de',lightyellow:'ffffe0',lime:'0f0',limegreen:'32cd32',linen:'faf0e6',magenta:'f0f',maroon:'800000',mediumaquamarine:'66cdaa',mediumblue:'0000cd',mediumorchid:'ba55d3',mediumpurple:'9370db',mediumseagreen:'3cb371',mediumslateblue:'7b68ee',mediumspringgreen:'00fa9a',mediumturquoise:'48d1cc',mediumvioletred:'c71585',midnightblue:'191970',mintcream:'f5fffa',mistyrose:'ffe4e1',moccasin:'ffe4b5',navajowhite:'ffdead',navy:'000080',oldlace:'fdf5e6',olive:'808000',olivedrab:'6b8e23',orange:'ffa500',orangered:'ff4500',orchid:'da70d6',palegoldenrod:'eee8aa',palegreen:'98fb98',paleturquoise:'afeeee',palevioletred:'db7093',papayawhip:'ffefd5',peachpuff:'ffdab9',peru:'cd853f',pink:'ffc0cb',plum:'dda0dd',powderblue:'b0e0e6',purple:'800080',rebeccapurple:'663399',red:'f00',rosybrown:'bc8f8f',royalblue:'4169e1',saddlebrown:'8b4513',salmon:'fa8072',sandybrown:'f4a460',seagreen:'2e8b57',seashell:'fff5ee',sienna:'a0522d',silver:'c0c0c0',skyblue:'87ceeb',slateblue:'6a5acd',slategray:'708090',slategrey:'708090',snow:'fffafa',springgreen:'00ff7f',steelblue:'4682b4',tan:'d2b48c',teal:'008080',thistle:'d8bfd8',tomato:'ff6347',turquoise:'40e0d0',violet:'ee82ee',wheat:'f5deb3',white:'fff',whitesmoke:'f5f5f5',yellow:'ff0',yellowgreen:'9acd32'},k=b.hexNames=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[t[n]]=n);return e}(C),S=(O='[\\s|\\(]+('+(w='(?:'+'[-\\+]?\\d*\\.\\d+%?'+')|(?:'+'[-\\+]?\\d+%?'+')')+')[,|\\s]+('+w+')[,|\\s]+('+w+')\\s*\\)?',x='[\\s|\\(]+('+w+')[,|\\s]+('+w+')[,|\\s]+('+w+')[,|\\s]+('+w+')\\s*\\)?',{rgb:new RegExp('rgb'+O),rgba:new RegExp('rgba'+x),hsl:new RegExp('hsl'+O),hsla:new RegExp('hsla'+x),hsv:new RegExp('hsv'+O),hsva:new RegExp('hsva'+x),hex3:/^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});window.tinycolor=b,t((function(){t.fn.spectrum.load&&t.fn.spectrum.processNativeColorInputs()}))}function j(e,n,r,i){for(var a=[],s=0;s')}else{a.push(t('
').append(t('').attr('title',i.noColorSelectedText)).html())}}return"
"+a.join('')+'
'}function P(c,l){var u,f,h,d,p=function(e,r){var i=t.extend({},n,e);return i.callbacks={move:E(i.move,r),change:E(i.change,r),show:E(i.show,r),hide:E(i.hide,r),beforeShow:E(i.beforeShow,r)},i}(l,c),g=p.flat,v=p.showSelectionPalette,m=p.localStorageKey,y=p.theme,w=p.callbacks,O=(u=$t,f=10,function(){var t=this,e=arguments,n=function(){d=null,u.apply(t,e)};h&&clearTimeout(d),!h&&d||(d=setTimeout(n,f))}),x=!1,C=!1,k=!0,S=0,P=0,_=0,A=0,L=0,R=0,N=0,I=0,F=0,V=0,B=1,H=[],z=[],U={},W=p.selectionPalette.slice(0),$=p.maxSelectionSize,q='sp-dragging',G=null,K=c.ownerDocument,Y=(K.body,t(c)),J=!1,X=t(s,K).addClass(y),Z=X.find('.sp-picker-container'),Q=X.find('.sp-color'),tt=X.find('.sp-dragger'),et=X.find('.sp-hue'),nt=X.find('.sp-slider'),rt=X.find('.sp-alpha-inner'),it=X.find('.sp-alpha'),ot=X.find('.sp-alpha-handle'),at=X.find('.sp-input'),st=X.find('.sp-palette'),ct=X.find('.sp-initial'),lt=X.find('.sp-cancel'),ut=X.find('.sp-clear'),ft=X.find('.sp-choose'),ht=X.find('.sp-palette-toggle'),dt=Y.is('input'),pt=dt&&'color'===Y.attr('type')&&M(),gt=dt&&!g,vt=gt?t(a).addClass(y).addClass(p.className).addClass(p.replacerClassName):t([]),mt=gt?vt:Y,yt=vt.find('.sp-preview-inner'),bt=p.color||dt&&Y.val(),wt=!1,Ot=p.preferredFormat,xt=!p.showButtons||p.clickoutFiresChange,Ct=!bt,kt=p.allowEmpty&&!pt;function St(){if(p.showPaletteOnly&&(p.showPalette=!0),ht.text(p.showPaletteOnly?p.togglePaletteMoreText:p.togglePaletteLessText),p.palette){H=p.palette.slice(0),z=t.isArray(H[0])?H:[H],U={};for(var e=0;e1&&(delete window.localStorage[m],t.each(e,(function(t,e){Pt(e)})))}catch(t){}try{W=window.localStorage[m].split(';')}catch(t){}}}function Pt(e){if(v){var n=b(e).toRgbString();if(!U[n]&&-1===t.inArray(n,W))for(W.push(n);W.length>$;)W.shift();if(m&&window.localStorage)try{window.localStorage[m]=W.join(';')}catch(t){}}}function _t(){var e=Bt(),n=t.map(z,(function(t,n){return j(t,e,'sp-palette-row sp-palette-row-'+n,p)}));jt(),W&&n.push(j(function(){var t=[];if(p.showPalette)for(var e=0;ed&&d>i?Math.abs(g.left+i-d):0),g.top-=Math.min(g.top,g.top+o>p&&p>o?Math.abs(o+a-r):r),g}(X,mt))),Ut(),p.showPalette&&_t(),Y.trigger('reflow.spectrum'))}function qt(){It(),J=!0,Y.attr('disabled',!0),mt.addClass('sp-disabled')}!function(){if(i&&X.find('*:not(input)').attr('unselectable','on'),St(),gt&&Y.after(vt).hide(),kt||ut.hide(),g)Y.after(X).hide();else{var e='parent'===p.appendTo?Y.parent():t(p.appendTo);1!==e.length&&(e=t('body')),e.append(X)}function n(e){return e.data&&e.data.ignore?(Vt(t(e.target).closest('.sp-thumb-el').data('color')),Ht()):(Vt(t(e.target).closest('.sp-thumb-el').data('color')),Ht(),p.hideAfterPaletteSelect&&(Wt(!0),It())),!1}jt(),mt.bind('click.spectrum touchstart.spectrum',(function(e){J||At(),e.stopPropagation(),t(e.target).is('input')||e.preventDefault()})),(Y.is(':disabled')||!0===p.disabled)&&qt(),X.click(T),at.change(Mt),at.bind('paste',(function(){setTimeout(Mt,1)})),at.keydown((function(t){13==t.keyCode&&Mt()})),lt.text(p.cancelText),lt.bind('click.spectrum',(function(t){t.stopPropagation(),t.preventDefault(),Ft(),It()})),ut.attr('title',p.clearText),ut.bind('click.spectrum',(function(t){t.stopPropagation(),t.preventDefault(),Ct=!0,Ht(),g&&Wt(!0)})),ft.text(p.chooseText),ft.bind('click.spectrum',(function(t){t.stopPropagation(),t.preventDefault(),i&&at.is(':focus')&&at.trigger('change'),at.hasClass('sp-validation-error')||(Wt(!0),It())})),ht.text(p.showPaletteOnly?p.togglePaletteMoreText:p.togglePaletteLessText),ht.bind('click.spectrum',(function(t){t.stopPropagation(),t.preventDefault(),p.showPaletteOnly=!p.showPaletteOnly,p.showPaletteOnly||g||X.css('left','-='+(Z.outerWidth(!0)+5)),St()})),D(it,(function(t,e,n){B=t/L,Ct=!1,n.shiftKey&&(B=Math.round(10*B)/10),Ht()}),Et,Dt),D(et,(function(t,e){I=parseFloat(e/A),Ct=!1,p.showAlpha||(B=1),Ht()}),Et,Dt),D(Q,(function(t,e,n){if(n.shiftKey){if(!G){var r=F*S,i=P-V*P,o=Math.abs(t-r)>Math.abs(e-i);G=o?'x':'y'}}else G=null;var a=!G||'y'===G;(!G||'x'===G)&&(F=parseFloat(t/S)),a&&(V=parseFloat((P-e)/P)),Ct=!1,p.showAlpha||(B=1),Ht()}),Et,Dt),bt?(Vt(bt),zt(),Ot=p.preferredFormat||b(bt).getFormat(),Pt(bt)):zt(),g&&Lt();var r=i?'mousedown.spectrum':'click.spectrum touchstart.spectrum';st.delegate('.sp-thumb-el',r,n),ct.delegate('.sp-thumb-el:nth-child(1)',r,{ignore:!0},n)}();var Gt={show:Lt,hide:It,toggle:At,reflow:$t,option:function(n,r){return n===e?t.extend({},p):r===e?p[n]:(p[n]=r,'preferredFormat'===n&&(Ot=p.preferredFormat),void St())},enable:function(){J=!1,Y.attr('disabled',!1),mt.removeClass('sp-disabled')},disable:qt,offset:function(t){p.offset=t,$t()},set:function(t){Vt(t),Wt()},get:Bt,destroy:function(){Y.show(),mt.unbind('click.spectrum touchstart.spectrum'),X.remove(),vt.remove(),r[Gt.id]=null},container:X};return Gt.id=r.push(Gt)-1,Gt}function _(){}function T(t){t.stopPropagation()}function E(t,e){var n=Array.prototype.slice,r=n.call(arguments,2);return function(){return t.apply(e,r.concat(n.call(arguments)))}}function D(e,n,r,o){n=n||function(){},r=r||function(){},o=o||function(){};var a=document,s=!1,c={},l=0,u=0,f='ontouchstart'in window,h={};function d(t){t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),t.returnValue=!1}function p(t){if(s){if(i&&a.documentMode<9&&!t.button)return g();var r=t&&t.touches&&t.touches[0],o=r&&r.pageX||t.pageX,h=r&&r.pageY||t.pageY,p=Math.max(0,Math.min(o-c.left,u)),v=Math.max(0,Math.min(h-c.top,l));f&&d(t),n.apply(e,[p,v,t])}}function g(){s&&(t(a).unbind(h),t(a.body).removeClass('sp-dragging'),setTimeout((function(){o.apply(e,arguments)}),0)),s=!1}h['selectstart']=d,h['dragstart']=d,h['touchmove mousemove']=p,h['touchend mouseup']=g,t(e).bind('touchstart mousedown',(function(n){var i=n.which?3==n.which:2==n.button;i||s||!1!==r.apply(e,arguments)&&(s=!0,l=t(e).height(),u=t(e).width(),c=t(e).offset(),t(a).bind(h),t(a.body).addClass('sp-dragging'),p(n),d(n))}))}function M(){return t.fn.spectrum.inputTypeColorSupport()}function A(t,e,n){t=X(t,255),e=X(e,255),n=X(n,255);var r,i,o=m(t,e,n),a=v(t,e,n),s=(o+a)/2;if(o==a)r=i=0;else{var c=o-a;switch(i=s>.5?c/(2-o-a):c/(o+a),o){case t:r=(e-n)/c+(e>1)+720)%360;--e;)r.h=(r.h+i)%360,o.push(b(r));return o}function Y(t,e){e=e||6;for(var n=b(t).toHsv(),r=n.h,i=n.s,o=n.v,a=[],s=1/e;e--;)a.push(b({h:r,s:i,v:o})),o=(o+s)%1;return a}function J(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function X(t,e){(function(t){return'string'==typeof t&&-1!=t.indexOf('.')&&1===parseFloat(t)})(t)&&(t='100%');var n=function(t){return'string'==typeof t&&-1!=t.indexOf('%')}(t);return t=v(e,m(0,parseFloat(t))),n&&(t=parseInt(t*e,10)/100),p.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function Z(t){return v(1,m(0,t))}function Q(t){return parseInt(t,16)}function tt(t){return 1==t.length?'0'+t:''+t}function et(t){return t<=1&&(t=100*t+'%'),t}}(p);var g=function(t){var e='name'===t.getFormat()&&t.toName(),n=1==t.getAlpha()?t.toHexString():t.toRgbString();return e||n.replace(/ /g,'')};e["a"]=f["a"].extend({template:function(){var t=this.ppfx;return"\n
\n
\n
\n
\n
\n
\n ")},inputClass:function(){var t=this.ppfx;return"".concat(t,"field ").concat(t,"field-color")},holderClass:function(){return"".concat(this.ppfx,"input-holder")},remove:function(){f["a"].prototype.remove.apply(this,arguments),this.colorEl.spectrum('destroy')},handleChange:function(t){t.stopPropagation();var e=t.target.value;Object(s["isUndefined"])(e)||this.__onInputChange(e)},__onInputChange:function(t){var e=this.model,n=this.opts.onChange,r=t,i=this.getColorEl();if(i){i.spectrum('set',r);var o=i.spectrum('get'),a=r&&g(o);a&&(r=a)}n?n(r):e.set({value:r},{fromInput:1})},setValue:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.model,r=Object(s["isUndefined"])(e.def)?n.get('defaults'):e.def,i=Object(s["isUndefined"])(t)?Object(s["isUndefined"])(r)?'':r:t,o=this.getInputEl(),a=this.getColorEl(),c='none'!=i?i:'';o.value=i,a.get(0).style.backgroundColor=c,(e.fromTarget||e.fromInput&&!e.avoidStore)&&(a.spectrum('set',c),this.noneColor='none'==i)},getColorEl:function(){if(!this.colorEl){var t,e=this.em,n=this.model,r=this.opts,i=this,o=this.ppfx,a=r.onChange,s=p("
")),c=s.get(0).style,l=e&&e.config?e.config.el:'',u=e&&e.getConfig&&e.getConfig('colorPicker')||{},f=0;this.$el.find("[data-colorp-c]").append(s),s.spectrum(d(d(d({color:n.getValue()||!1,containerClassName:"".concat(o,"one-bg ").concat(o,"two-color"),appendTo:l||'body',maxSelectionSize:8,showPalette:!0,showAlpha:!0,chooseText:'Ok',cancelText:'⨯',palette:[]},u),n.get('colorPicker')||{}),{},{move:function(t){var e=g(t);c.backgroundColor=e,a?a(e,!0):n.setValueFromInput(e,0)},change:function(t){f=1;var e=g(t);c.backgroundColor=e,a?a(e):(n.setValueFromInput(0,0),n.setValueFromInput(e)),i.noneColor=0},show:function(e){f=0,t=a?n.getValue({noDefault:!0}):g(e)},hide:function(e){f||!t&&!a||(i.noneColor&&(t=''),c.backgroundColor=t,s.spectrum('set',t),a?a(t,!0):n.setValueFromInput(t,0))}})),e&&e.on&&this.listenTo(e,'component:selected',(function(){f=1,s.spectrum('hide')})),this.colorEl=s}return this.colorEl},render:function(){return f["a"].prototype.render.call(this),this.getColorEl(),this}})},function(t,e,n){"use strict";n.d(e,"a",(function(){return T}));var r=n(2),i=n.n(r),o=n(5),a=n.n(o),s=n(6),c=n.n(s),l=n(7),u=n.n(l),f=n(8),h=n.n(f),d=n(4),p=n.n(d),g=n(0),v=n(3),m=n(11),y=n.n(m),b=n(1);function w(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function O(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},n=e.config,r=n.em,i=this.attributes,o=i.styles,a=i.component,s=r.get('DomComponents'),c=s.getConfig(),l=r.get('CssComposer').getAll(),u={};this.em=r;var f={em:r,config:c,frame:this,idMap:u};if(!Object(b["isComponent"])(a)){var h=Object(b["isObject"])(a)?a:{components:a};!h.type&&(h.type='wrapper');var d=s.getType('wrapper').model;this.set('component',new d(h,f))}if(o){if(!Object(b["isObject"])(o)){var p=Object.keys(u);p.length&&Array.isArray(o)&&o.forEach((function(t){var e=t.selectors;if(e&&1==e.length){var n=e[0],r=n.name&&2===n.type&&n;if(r&&u[r.name])r.name=u[r.name];else if(Object(g["isString"])(n)&&'#'===n[0]){var i=n.substring(1);i&&u[i]&&(e[0]="#".concat(u[i]))}}})),l.add(o),this.set('styles',l)}}else this.set('styles',l);!t.width&&this.set(C,1),!t.height&&this.set(k,1)}},{key:"onRemove",value:function(){this.getComponent().remove({root:1})}},{key:"changesUp",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.temporary||t.noCount||t.avoidStore||this.set('changesCount',this.get('changesCount')+1)}},{key:"getComponent",value:function(){return this.get('component')}},{key:"getStyles",value:function(){return this.get('styles')}},{key:"disable",value:function(){this.trigger('disable')}},{key:"remove",value:function(){this.view=0;var t=this.collection;return t&&t.remove(this)}},{key:"getHead",value:function(){var t=this.get('head')||[];return y()(t)}},{key:"setHead",value:function(t){return this.set('head',y()(t))}},{key:"addHeadItem",value:function(t){var e=this.getHead();e.push(t),this.setHead(e)}},{key:"getHeadByAttr",value:function(t,e,n){return this.getHead().filter((function(r){return r.attributes&&r.attributes[t]==e&&(!n||n===r.tag)}))[0]}},{key:"removeHeadByAttr",value:function(t,e,n){var r=this.getHead(),i=this.getHeadByAttr(t,e,n),o=r.indexOf(i);o>=0&&(r.splice(o,1),this.setHead(r))}},{key:"addLink",value:function(t){var e='link';!this.getHeadByAttr('href',t,e)&&this.addHeadItem({tag:e,attributes:{href:t,rel:'stylesheet'}})}},{key:"removeLink",value:function(t){this.removeHeadByAttr('href',t,'link')}},{key:"addScript",value:function(t){var e='script';!this.getHeadByAttr('src',t,e)&&this.addHeadItem({tag:e,attributes:{src:t}})}},{key:"removeScript",value:function(t){this.removeHeadByAttr('src',t,'script')}},{key:"getPage",value:function(){var t=this.collection;return t&&t.page}},{key:"_emitUpdated",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.em.trigger('frame:updated',O({frame:this},t))}},{key:"toJSON",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=v["Model"].prototype.toJSON.call(this,t),n=this.em,r=n&&n.get('StorageManager'),i=r&&r.getConfig(),o=Object(g["result"])(this,'defaults');if(i&&!t.fromUndo){var a={component:this.getComponent()};i.storeHtml&&(e.html=n.getHtml(a)),i.storeCss&&(e.css=n.getCss(a))}return t.fromUndo&&delete e.component,delete e.styles,delete e.changesCount,e[C]&&delete e.width,e[k]&&delete e.height,Object(g["forEach"])(e,(function(t,n){0===n.indexOf('_')&&delete e[n]})),Object(g["forEach"])(o,(function(t,n){e[n]===t&&delete e[n]})),Object(g["forEach"])(['attributes','head'],(function(t){Object(g["isEmpty"])(e[t])&&delete e[t]})),e}}]),n}(v["Model"]);function j(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function P(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{};Object(g["bindAll"])(this,'itemLoaded'),this.config=e,this.on('reset',this.onReset),this.on('remove',this.onRemove)}},{key:"onReset",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.previousModels||[];r.map((function(t){return e.onRemove(t)}))}},{key:"onRemove",value:function(t){t&&t.onRemove()}},{key:"itemLoaded",value:function(){this.loadedItems++,this.loadedItems>=this.itemsToLoad&&(this.trigger('loaded:all'),this.listenToLoadItems(0))}},{key:"listenToLoad",value:function(){this.loadedItems=0,this.itemsToLoad=this.length,this.listenToLoadItems(1)}},{key:"listenToLoadItems",value:function(t){var e=this;this.forEach((function(n){return n[t?'on':'off']('loaded',e.itemLoaded)}))}},{key:"add",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.config;return v["Collection"].prototype.add.call(this,t,P(P({},e),{},{config:n}))}}]),n}(v["Collection"]);T.prototype.model=S},function(t,e,n){"use strict";(function(t){var r=n(14),i=n.n(r),o=n(76),a=n(77),s=setTimeout;function c(t){return Boolean(t&&void 0!==t.length)}function l(){}function u(t){if(!(this instanceof u))throw new TypeError('Promises must be constructed via new');if('function'!=typeof t)throw new TypeError('not a function');this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],v(t,this)}function f(t,e){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,u._immediateFn((function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var r;try{r=n(t._value)}catch(t){return void d(e.promise,t)}h(e.promise,r)}else(1===t._state?h:d)(e.promise,t._value)}))):t._deferreds.push(e)}function h(t,e){try{if(e===t)throw new TypeError('A promise cannot be resolved with itself.');if(e&&('object'===i()(e)||'function'==typeof e)){var n=e.then;if(e instanceof u)return t._state=3,t._value=e,void p(t);if('function'==typeof n)return void v((r=n,o=e,function(){r.apply(o,arguments)}),t)}t._state=1,t._value=e,p(t)}catch(e){d(t,e)}var r,o}function d(t,e){t._state=2,t._value=e,p(t)}function p(t){2===t._state&&0===t._deferreds.length&&u._immediateFn((function(){t._handled||u._unhandledRejectionFn(t._value)}));for(var e=0,n=t._deferreds.length;e1&&void 0!==arguments[1]?arguments[1]:{},r=n.config,i=void 0===r?{}:r,o=i.em,a={};this.em=o,t.frames||(a.component=t.component,a.styles=t.styles,['component','styles'].map((function(t){return e.unset(t)})));var s=t.frames||[a],c=new w["a"](s,i);c.page=this,this.set('frames',c);var l=o&&o.get('UndoManager');l&&l.add(c)}},{key:"onRemove",value:function(){this.get('frames').reset()}},{key:"getFrames",value:function(){return this.get('frames')}},{key:"getId",value:function(){return this.id}},{key:"getName",value:function(){return this.get('name')}},{key:"setName",value:function(t){return this.get({name:t})}},{key:"getAllFrames",value:function(){return this.getFrames().models||[]}},{key:"getMainFrame",value:function(){return this.getFrames().at(0)}},{key:"getMainComponent",value:function(){var t=this.getMainFrame();return t&&t.getComponent()}},{key:"toJSON",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=l["Model"].prototype.toJSON.call(this,t),n=Object(s["result"])(this,'defaults');return Object(s["forEach"])(e,(function(t,n){0===n.indexOf('_')&&delete e[n]})),Object(s["forEach"])(n,(function(t,n){e[n]===t&&delete e[n]})),e}}]),n}(l["Model"]);function C(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function k(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{};this.config=e,this.on('reset',this.onReset),this.on('remove',this.onRemove)}},{key:"onReset",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.previousModels||[];r.map((function(t){return e.onRemove(t)}))}},{key:"onRemove",value:function(t){t&&t.onRemove()}},{key:"add",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.config;return l["Collection"].prototype.add.call(this,t,k(k({},e),{},{config:n}))}}]),n}(l["Collection"]);function P(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function _(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{};Object(s["bindAll"])(this,'_onPageChange');var n=e.em,r=_({},e);this.config=r,this.em=n;var i=new j([],r);this.pages=i;var o=new l["Model"]({_undo:!0});return this.model=o,i.on('add',(function(t,e,r){return n.trigger(L,t,r)})),i.on('remove',(function(t,e,r){return n.trigger(N,t,r)})),i.on('change',(function(t,e){n.trigger(A,t,t.changedAttributes(),e)})),i.on('reset',(function(e){return e.at(0)&&t.select(e.at(0))})),i.on('all',this.__onChange,this),o.on(F,this._onPageChange),this},__onChange:function(t,e,n,r){var i=r||n;this.em.trigger(T,{event:t,page:e,options:i})},onLoad:function(){var t=this.pages,e={silent:!0};t.add(this.config.pages||[],e);var n=t.length?this.getMain():this.add({type:V},e);this.select(n,e)},_onPageChange:function(t,e,n){var r=this.em,i=r.get('LayerManager'),o=e.getMainComponent();i&&o&&i.setRoot(o),r.trigger(D,e,t.previous('selected')),this.__onChange(F,e,n)},postLoad:function(){var t=this.em,e=this.model,n=t.get('UndoManager');n&&n.add(e),n&&n.add(this.pages)},add:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em;t.id=t.id||this._createId();var i=function(){var r=e.pages.add(t,n);return n.select&&e.select(r),r};return!n.silent&&r.trigger(R,t,i,n),!n.abort&&i()},remove:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,i=Object(s["isString"])(t)?this.get(t):t,o=function(){return i&&e.pages.remove(i,n),i};return!n.silent&&r.trigger(I,i,o,n),!n.abort&&o()},get:function(t){return this.pages.filter((function(e){return e.get('id')===t}))[0]},getMain:function(){var t=this.pages;return t.filter((function(t){return t.get('type')===V}))[0]||t.at(0)},getAll:function(){return i()(this.pages.models)},getAllWrappers:function(){var t=this.getAll();return Object(s["unique"])(Object(s["flatten"])(t.map((function(t){return t.getAllFrames().map((function(t){return t.getComponent()}))}))))},getAllMap:function(){return this.getAll().reduce((function(t,e){return t[e.get('id')]=e,t}),{})},select:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Object(s["isString"])(t)?this.get(t):t;return n&&(this.em.trigger(M,n,e),this.model.set('selected',n,e)),this},getSelected:function(){return this.model.get('selected')},destroy:function(){var t=this;this.pages.off().reset(),this.model.stopListening(),this.model.clear({silent:!0}),['selected','config','em','pages','model'].map((function(e){return t[e]=0}))},store:function(t){if(!this.em.get('hasPages'))return{};var e={},n=this.config;return e[this.storageKey]=JSON.stringify(this.getAll()),!t&&n.stm&&n.stm.store(e),e},load:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.storageKey,n=t[e]||[];if('string'==typeof n)try{n=JSON.parse(t[e])}catch(t){}return n&&n.length&&this.pages.reset(n),n},_createId:function(){var t,e=this.getAll().length+16,n=this.getAllMap();do{t=Object(c["createId"])(e)}while(n[t]);return t}}}},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n.n(r),o=i.a.Model.extend({defaults:{id:'',label:'',tagName:'span',className:'',command:'',context:'',buttons:[],attributes:{},options:{},active:!1,dragDrop:!1,togglable:!0,runDefaultCommand:!0,stopDefaultCommand:!1,disable:!1},initialize:function(t){if(this.get('buttons').length){var e=n(47).default;this.set('buttons',new e(this.get('buttons')))}}});e["default"]=i.a.Collection.extend({model:o,deactivateAllExceptOne:function(t,e){this.forEach((function(n,r){n!==t&&(n.set('active',!1),e&&n.get('buttons').length&&n.get('buttons').deactivateAllExceptOne(t,e))}))},deactivateAll:function(t,e){var n=t||'';this.forEach((function(t){t.get('context')==n&&t!==e&&t.set('active',!1,{fromCollection:1})}))},disableAllButtons:function(t){var e=t||'';this.forEach((function(t,n){t.get('context')==e&&t.set('disable',!0)}))},disableAllButtonsExceptOne:function(t,e){this.forEach((function(n,r){n!==t&&(n.set('disable',!0),e&&n.get('buttons').length&&n.get('buttons').disableAllButtonsExceptOne(t,e))}))}})},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n*\/]/.test(n)?x(null,"select-op"):"."==n&&t.match(/^-?[_a-z][_a-z0-9-]*/i)?x("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(n)?x(null,n):t.match(/^[\w-.]+(?=\()/)?(/^(url(-prefix)?|domain|regexp)$/i.test(t.current())&&(e.tokenize=S),x("variable callee","variable")):/[\w\\\-]/.test(n)?(t.eatWhile(/[\w\\\-]/),x("property","word")):x(null,null):/[\d.]/.test(t.peek())?(t.eatWhile(/[\w.%]/),x("number","unit")):t.match(/^-[\w\\\-]*/)?(t.eatWhile(/[\w\\\-]/),t.match(/^\s*:/,!1)?x("variable-2","variable-definition"):x("variable-2","variable")):t.match(/^\w+-/)?x("meta","meta"):void 0}function k(t){return function(e,n){for(var r,i=!1;null!=(r=e.next());){if(r==t&&!i){")"==t&&e.backUp(1);break}i=!i&&"\\"==r}return(r==t||!i&&")"!=t)&&(n.tokenize=null),x("string","string")}}function S(t,e){return t.next(),t.match(/^\s*[\"\')]/,!1)?e.tokenize=null:e.tokenize=k(")"),x(null,"(")}function j(t,e,n){this.type=t,this.indent=e,this.prev=n}function P(t,e,n,r){return t.context=new j(n,e.indentation()+(!1===r?0:a),t.context),n}function _(t){return t.context.prev&&(t.context=t.context.prev),t.context.type}function T(t,e,n){return M[n.context.type](t,e,n)}function E(t,e,n,r){for(var i=r||1;i>0;i--)n.context=n.context.prev;return T(t,e,n)}function D(t){var e=t.current().toLowerCase();o=m.hasOwnProperty(e)?"atom":v.hasOwnProperty(e)?"keyword":"variable"}var M={top:function(t,e,n){if("{"==t)return P(n,e,"block");if("}"==t&&n.context.prev)return _(n);if(w&&/@component/i.test(t))return P(n,e,"atComponentBlock");if(/^@(-moz-)?document$/i.test(t))return P(n,e,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/i.test(t))return P(n,e,"atBlock");if(/^@(font-face|counter-style)/i.test(t))return n.stateArg=t,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(t))return"keyframes";if(t&&"@"==t.charAt(0))return P(n,e,"at");if("hash"==t)o="builtin";else if("word"==t)o="tag";else{if("variable-definition"==t)return"maybeprop";if("interpolation"==t)return P(n,e,"interpolation");if(":"==t)return"pseudo";if(y&&"("==t)return P(n,e,"parens")}return n.context.type},block:function(t,e,n){if("word"==t){var r=e.current().toLowerCase();return h.hasOwnProperty(r)?(o="property","maybeprop"):d.hasOwnProperty(r)?(o=O?"string-2":"property","maybeprop"):y?(o=e.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(o+=" error","maybeprop")}return"meta"==t?"block":y||"hash"!=t&&"qualifier"!=t?M.top(t,e,n):(o="error","block")},maybeprop:function(t,e,n){return":"==t?P(n,e,"prop"):T(t,e,n)},prop:function(t,e,n){if(";"==t)return _(n);if("{"==t&&y)return P(n,e,"propBlock");if("}"==t||"{"==t)return E(t,e,n);if("("==t)return P(n,e,"parens");if("hash"!=t||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(e.current())){if("word"==t)D(e);else if("interpolation"==t)return P(n,e,"interpolation")}else o+=" error";return"prop"},propBlock:function(t,e,n){return"}"==t?_(n):"word"==t?(o="property","maybeprop"):n.context.type},parens:function(t,e,n){return"{"==t||"}"==t?E(t,e,n):")"==t?_(n):"("==t?P(n,e,"parens"):"interpolation"==t?P(n,e,"interpolation"):("word"==t&&D(e),"parens")},pseudo:function(t,e,n){return"meta"==t?"pseudo":"word"==t?(o="variable-3",n.context.type):T(t,e,n)},documentTypes:function(t,e,n){return"word"==t&&c.hasOwnProperty(e.current())?(o="tag",n.context.type):M.atBlock(t,e,n)},atBlock:function(t,e,n){if("("==t)return P(n,e,"atBlock_parens");if("}"==t||";"==t)return E(t,e,n);if("{"==t)return _(n)&&P(n,e,y?"block":"top");if("interpolation"==t)return P(n,e,"interpolation");if("word"==t){var r=e.current().toLowerCase();o="only"==r||"not"==r||"and"==r||"or"==r?"keyword":l.hasOwnProperty(r)?"attribute":u.hasOwnProperty(r)?"property":f.hasOwnProperty(r)?"keyword":h.hasOwnProperty(r)?"property":d.hasOwnProperty(r)?O?"string-2":"property":m.hasOwnProperty(r)?"atom":v.hasOwnProperty(r)?"keyword":"error"}return n.context.type},atComponentBlock:function(t,e,n){return"}"==t?E(t,e,n):"{"==t?_(n)&&P(n,e,y?"block":"top",!1):("word"==t&&(o="error"),n.context.type)},atBlock_parens:function(t,e,n){return")"==t?_(n):"{"==t||"}"==t?E(t,e,n,2):M.atBlock(t,e,n)},restricted_atBlock_before:function(t,e,n){return"{"==t?P(n,e,"restricted_atBlock"):"word"==t&&"@counter-style"==n.stateArg?(o="variable","restricted_atBlock_before"):T(t,e,n)},restricted_atBlock:function(t,e,n){return"}"==t?(n.stateArg=null,_(n)):"word"==t?(o="@font-face"==n.stateArg&&!p.hasOwnProperty(e.current().toLowerCase())||"@counter-style"==n.stateArg&&!g.hasOwnProperty(e.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},keyframes:function(t,e,n){return"word"==t?(o="variable","keyframes"):"{"==t?P(n,e,"top"):T(t,e,n)},at:function(t,e,n){return";"==t?_(n):"{"==t||"}"==t?E(t,e,n):("word"==t?o="tag":"hash"==t&&(o="builtin"),"at")},interpolation:function(t,e,n){return"}"==t?_(n):"{"==t||";"==t?E(t,e,n):("word"==t?o="variable":"variable"!=t&&"("!=t&&")"!=t&&(o="error"),"interpolation")}};return{startState:function(t){return{tokenize:null,state:r?"block":"top",stateArg:null,context:new j(r?"block":"top",t||0,null)}},token:function(t,e){if(!e.tokenize&&t.eatSpace())return null;var n=(e.tokenize||C)(t,e);return n&&"object"==typeof n&&(i=n[1],n=n[0]),o=n,"comment"!=i&&(e.state=M[e.state](i,t,e)),o},indent:function(t,e){var n=t.context,r=e&&e.charAt(0),i=n.indent;return"prop"!=n.type||"}"!=r&&")"!=r||(n=n.prev),n.prev&&("}"!=r||"block"!=n.type&&"top"!=n.type&&"interpolation"!=n.type&&"restricted_atBlock"!=n.type?(")"!=r||"parens"!=n.type&&"atBlock_parens"!=n.type)&&("{"!=r||"at"!=n.type&&"atBlock"!=n.type)||(i=Math.max(0,n.indent-a)):i=(n=n.prev).indent),i},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:b,fold:"brace"}}));var n=["domain","regexp","url","url-prefix"],r=e(n),i=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],o=e(i),a=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover","prefers-color-scheme"],s=e(a),c=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive","dark","light"],l=e(c),u=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","all","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","binding","bleed","block-size","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-content","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","gap","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","inset","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-height-step","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotate","rotation","rotation-point","row-gap","ruby-align","ruby-overhang","ruby-position","ruby-span","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-type","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-orientation","text-outline","text-overflow","text-rendering","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","touch-action","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","paint-order","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],f=e(u),h=["accent-color","aspect-ratio","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","content-visibility","margin-block","margin-block-end","margin-block-start","margin-inline","margin-inline-end","margin-inline-start","overflow-anchor","overscroll-behavior","padding-block","padding-block-end","padding-block-start","padding-inline","padding-inline-end","padding-inline-start","scroll-snap-stop","scrollbar-3d-light-color","scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-track-color","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","shape-inside","zoom"],d=e(h),p=e(["font-display","font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]),g=e(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),v=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],m=e(v),y=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","blur","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","brightness","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","contrast","copy","counter","counters","cover","crop","cross","crosshair","cubic-bezier","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","drop-shadow","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","grayscale","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","hue-rotate","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","manipulation","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiple_mask_images","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturate","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","sepia","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],b=e(y),w=n.concat(i).concat(a).concat(c).concat(u).concat(h).concat(v).concat(y);function O(t,e){for(var n,r=!1;null!=(n=t.next());){if(r&&"/"==n){e.tokenize=null;break}r="*"==n}return["comment","comment"]}t.registerHelper("hintWords","css",w),t.defineMIME("text/css",{documentTypes:r,mediaTypes:o,mediaFeatures:s,mediaValueKeywords:l,propertyKeywords:f,nonStandardPropertyKeywords:d,fontProperties:p,counterDescriptors:g,colorKeywords:m,valueKeywords:b,tokenHooks:{"/":function(t,e){return!!t.eat("*")&&(e.tokenize=O,O(t,e))}},name:"css"}),t.defineMIME("text/x-scss",{mediaTypes:o,mediaFeatures:s,mediaValueKeywords:l,propertyKeywords:f,nonStandardPropertyKeywords:d,colorKeywords:m,valueKeywords:b,fontProperties:p,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(t,e){return t.eat("/")?(t.skipToEnd(),["comment","comment"]):t.eat("*")?(e.tokenize=O,O(t,e)):["operator","operator"]},":":function(t){return!!t.match(/^\s*\{/,!1)&&[null,null]},$:function(t){return t.match(/^[\w-]+/),t.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(t){return!!t.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),t.defineMIME("text/x-less",{mediaTypes:o,mediaFeatures:s,mediaValueKeywords:l,propertyKeywords:f,nonStandardPropertyKeywords:d,colorKeywords:m,valueKeywords:b,fontProperties:p,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(t,e){return t.eat("/")?(t.skipToEnd(),["comment","comment"]):t.eat("*")?(e.tokenize=O,O(t,e)):["operator","operator"]},"@":function(t){return t.eat("{")?[null,"interpolation"]:!t.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(t.eatWhile(/[\w\\\-]/),t.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),t.defineMIME("text/x-gss",{documentTypes:r,mediaTypes:o,mediaFeatures:s,propertyKeywords:f,nonStandardPropertyKeywords:d,fontProperties:p,counterDescriptors:g,colorKeywords:m,valueKeywords:b,supportsAtComponent:!0,tokenHooks:{"/":function(t,e){return!!t.eat("*")&&(e.tokenize=O,O(t,e))}},name:"css",helperType:"gss"})}(n(28))},function(t,e,n){"use strict";n.r(e),e["default"]={run:function(t){t.DomComponents.clear(),t.CssComposer.clear()}}},function(t,e,n){"use strict";n.r(e);var r=n(0),i=n(1),o=n(24);e["default"]={run:function(t){Object(r["bindAll"])(this,'onKeyUp','enableDragger','disableDragger'),this.editor=t,this.canvasModel=this.canvas.getCanvasView().model,this.toggleMove(1)},stop:function(t){this.toggleMove(),this.disableDragger()},onKeyUp:function(t){' '===Object(i["getKeyChar"])(t)&&this.editor.stopCommand(this.id)},enableDragger:function(t){this.toggleDragger(1,t)},disableDragger:function(t){this.toggleDragger(0,t)},toggleDragger:function(t,e){var n=this.canvasModel,r=this.em,i=this.dragger,a=t?'add':'remove';this.getCanvas().classList[a]("".concat(this.ppfx,"is__grabbing")),i||(i=new o["a"]({getPosition:function(){return{x:n.get('x'),y:n.get('y')}},setPosition:function(t){var e=t.x,r=t.y;n.set({x:e,y:r})},onStart:function(t,e){r.trigger('canvas:move:start',e)},onDrag:function(t,e){r.trigger('canvas:move',e)},onEnd:function(t,e){r.trigger('canvas:move:end',e)}}),this.dragger=i),t?i.start(e):i.stop()},toggleMove:function(t){var e=this.ppfx,n=t?'add':'remove',r=t?'on':'off',o={on:i["on"],off:i["off"]},a=this.getCanvas(),s=["".concat(e,"is__grab")];!t&&s.push("".concat(e,"is__grabbing")),s.forEach((function(t){return a.classList[n](t)})),o[r](document,'keyup',this.onKeyUp),o[r](a,'mousedown',this.enableDragger),o[r](document,'mouseup',this.disableDragger)}}},function(t,e,n){"use strict";n.r(e);var r=n(11),i=n.n(r),o=n(0);e["default"]={run:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=[],s=r.component||t.getSelectedAll();return s=Object(o["isArray"])(s)?i()(s):[s],t.select(null),s.forEach((function(t){if(!t||!t.get('removable'))return n.em.logWarning('The element is not removable',{component:t});t.remove(),t.collection&&a.push(t)})),a.length&&t.select(a),s}}},function(t,e,n){"use strict";n.r(e);var r=n(2),i=n.n(r),o=n(0),a=n(24);function s(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function c(t){for(var e=1;e2&&void 0!==arguments[2]?arguments[2]:{};Object(o["bindAll"])(this,'setPosition','onStart','onDrag','onEnd','getPosition','getGuidesStatic','renderGuide','getGuidesTarget');var i=r.target,s=r.event,u=r.mode,f=r.dragger,h=void 0===f?{}:f,d=i.getEl(),p=c({doc:d.ownerDocument,onStart:this.onStart,onEnd:this.onEnd,onDrag:this.onDrag,getPosition:this.getPosition,setPosition:this.setPosition,guidesStatic:function(){return n.guidesStatic},guidesTarget:function(){return n.guidesTarget}},h);this.setupGuides(),this.opts=r,this.editor=t,this.em=t.getModel(),this.target=i,this.isTran='translate'==u,this.guidesContainer=this.getGuidesContainer(),this.guidesTarget=this.getGuidesTarget(),this.guidesStatic=this.getGuidesStatic();var g=this.dragger;return g?g.setOptions(p):(g=new a["a"](p),this.dragger=g),s&&g.start(s),this.toggleDrag(1),this.em.trigger("".concat(l,":start"),this.getEventOpts()),g},getEventOpts:function(){return{mode:this.opts.mode,target:this.target,guidesTarget:this.guidesTarget,guidesStatic:this.guidesStatic}},stop:function(){this.toggleDrag()},setupGuides:function(){(this.guides||[]).forEach((function(t){var e=t.guide;e&&e.parentNode.removeChild(e)})),this.guides=[]},getGuidesContainer:function(){var t=this,e=this.guidesEl;if(!e){var n=this.editor,r=this.em,i=this.opts,a=n.getConfig('stylePrefix'),s=document.createElement('div'),c=document.createElement('div'),l="
\n
\n
");(e=document.createElement('div')).className="".concat(a,"guides"),s.className="".concat(a,"guide-info ").concat(a,"guide-info__x"),c.className="".concat(a,"guide-info ").concat(a,"guide-info__y"),s.innerHTML=l,c.innerHTML=l,e.appendChild(s),e.appendChild(c),n.Canvas.getGlobalToolsEl().appendChild(e),this.guidesEl=e,this.elGuideInfoX=s,this.elGuideInfoY=c,this.elGuideInfoContentX=s.querySelector(".".concat(a,"guide-info__content")),this.elGuideInfoContentY=c.querySelector(".".concat(a,"guide-info__content")),r.on('canvas:update frame:scroll',Object(o["debounce"])((function(){t.updateGuides(),i.debug&&t.guides.forEach((function(e){return t.renderGuide(e)}))}),200))}return e},getGuidesStatic:function(){var t=this,e=[],n=this.target.getEl(),r=n.parentNode,i=void 0===r?{}:r;return Object(o["each"])(i.children,(function(r){return e=e.concat(n!==r?t.getElementGuides(r):[])})),e.concat(this.getElementGuides(i))},getGuidesTarget:function(){return this.getElementGuides(this.target.getEl())},updateGuides:function(t){var e,n,r=this;(t||this.guides).forEach((function(t){var i=t.origin,a=e===i?n:r.getElementPos(i);e=i,n=a,Object(o["each"])(r.getGuidePosUpdate(t,a),(function(e,n){return t[n]=e})),t.originRect=a}))},getGuidePosUpdate:function(t,e){var n={},r=e.top,i=e.height,o=e.left,a=e.width;switch(t.type){case't':n.y=r;break;case'b':n.y=r+i;break;case'l':n.x=o;break;case'r':n.x=o+a;break;case'x':n.x=o+a/2;break;case'y':n.y=r+i/2}return n},renderGuide:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.guide||document.createElement('div'),n='px',r=t.active?2:1,i=e.children[0];return e.style="position: absolute; background-color: ".concat(t.active?'green':'red',";"),e.children.length||((i=document.createElement('div')).style='position: absolute; color: red; padding: 5px; top: 0; left: 0;',e.appendChild(i)),t.y?(e.style.width='100%',e.style.height="".concat(r).concat(n),e.style.top="".concat(t.y).concat(n),e.style.left=0):(e.style.width="".concat(r).concat(n),e.style.height='100%',e.style.left="".concat(t.x).concat(n),e.style.top="0".concat(n)),!t.guide&&this.guidesContainer.appendChild(e),e},getElementPos:function(t){return this.editor.Canvas.getElementPos(t,{noScroll:1})},getElementGuides:function(t){var e=this,n=this.opts,r=this.getElementPos(t),i=r.top,o=r.height,a=r.left,s=r.width,l=[{type:'t',y:i},{type:'b',y:i+o},{type:'l',x:a},{type:'r',x:a+s},{type:'x',x:a+s/2},{type:'y',y:i+o/2}].map((function(i){return c(c({},i),{},{origin:t,originRect:r,guide:n.debug&&e.renderGuide(i)})}));return l.forEach((function(t){return e.guides.push(t)})),l},getTranslate:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:'x',n=0;return(t||'').split(' ').forEach((function(t){var r=t.trim(),i="translate".concat(e.toUpperCase(),"(");0===r.indexOf(i)&&(n=parseFloat(r.replace(i,'')))})),n},setTranslate:function(t,e,n){var r="translate".concat(e.toUpperCase(),"("),i="".concat(r).concat(n,")"),o=(t||'').split(' ').map((function(t){return 0===t.trim().indexOf(r)&&(t=i),t})).join(' ');return o.indexOf(r)<0&&(o+=" ".concat(i)),o},getPosition:function(){var t=this.target,e=this.isTran,n=t.getStyle(),r=n.left,i=n.top,o=n.transform,a=0,s=0;return e?(a=this.getTranslate(o),s=this.getTranslate(o,'y')):(a=parseFloat(r||0),s=parseFloat(i||0)),{x:a,y:s}},setPosition:function(t){var e=t.x,n=t.y,r=t.end,i=t.position,a=t.width,s=t.height,c=this.target,l=this.isTran,u=this.em,f='px',h=r?'':1,d="".concat(e).concat(f),p="".concat(n).concat(f),g={};if(l){var v=c.getStyle()['transform']||'';v=this.setTranslate(v,'x',d),g={transform:v=this.setTranslate(v,'y',p),en:h},c.addStyle(g,{avoidStore:!r})}else{var m={position:i,width:a,height:s},y={left:d,top:p,en:h};Object(o["keys"])(m).forEach((function(t){var e=m[t];e&&(y[t]=e)})),g=y,c.addStyle(g,{avoidStore:!r})}u.getSelected()&&Object(o["keys"])(g).forEach((function(t){return u.trigger("update:component:style:".concat(t))}))},_getDragData:function(){var t=this.target;return{target:t,parent:t.parent(),index:t.index()}},onStart:function(t){var e=this.target,n=this.editor,r=this.isTran,i=this.opts,o=i.center,a=i.onStart,s=n.Canvas,c=e.getStyle(),l='absolute',u=[l,'relative'];if(a&&a(this._getDragData()),!r&&c.position!==l){var f,h=s.offset(e.getEl()),d=h.left,p=h.top,g=h.width,v=h.height,m=e.parent();do{var y=m.getStyle();f=u.indexOf(y.position)>=0?m:null,m=m.parent()}while(m&&!f);if(o){var b=s.getMouseRelativeCanvas(t);d=b.x,p=b.y}else if(f){var w=s.offset(f.getEl());d-=w.left,p-=w.top}this.setPosition({x:d,y:p,width:"".concat(g,"px"),height:"".concat(v,"px"),position:l})}},onDrag:function(){var t=this,e=this.guidesTarget,n=this.opts,r=n.onDrag;this.updateGuides(e),n.debug&&e.forEach((function(e){return t.renderGuide(e)})),n.guidesInfo&&this.renderGuideInfo(e.filter((function(t){return t.active}))),r&&r(this._getDragData())},onEnd:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.editor,i=this.opts,o=this.id,a=i.onEnd;a&&a(t,n,c(c({event:t},n),this._getDragData())),r.stopCommand(o),this.hideGuidesInfo(),this.em.trigger("".concat(l,":end"),this.getEventOpts())},hideGuidesInfo:function(){var t=this;['X','Y'].forEach((function(e){var n=t["elGuideInfo".concat(e)];n&&(n.style.display='none')}))},renderGuideInfo:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=this.guidesStatic;this.hideGuidesInfo(),e.forEach((function(e){var r=e.origin,i=e.x,a=t.getElementPos(r),s=Object(o["isUndefined"])(i)?'y':'x',u='y'===s,f=a[u?'left':'top'],h=a.rect[u?'left':'top'],d=u?f+a.width:f+a.height,p=u?h+a.rect.width:h+a.rect.height,g=t["elGuideInfo".concat(s.toUpperCase())],v=t["elGuideInfoContent".concat(s.toUpperCase())],m=g.style,y=n.filter((function(t){return t.type===e.type})).map((function(t){var e=t.originRect,n=e.left,r=e.width,i=e.top,o=e.height,a=u?n+r:i+o;return{gap:a0})).sort((function(t,e){return t.gap-e.gap})).map((function(t){return t.guide}))[0];if(y){var b=y.originRect,w=b.left,O=b.width,x=b.top,C=b.height,k=b.rect,S=u?w2&&void 0!==arguments[2]?arguments[2]:{};if(t.Canvas.hasFocus()||n.force){var r=[];t.getSelectedAll().forEach((function(t){for(var e=t.parent();e&&!e.get('selectable');)e=e.parent();e&&r.push(e)})),r.length&&t.select(r)}}}},function(t,e,n){"use strict";n.r(e),e["default"]={run:function(t){if(t.Canvas.hasFocus()){var e=[];t.getSelectedAll().forEach((function(t){var n=t.parent();if(n){var r,i=n.components().length,o=0,a=0;do{o++,r=(a=t.index()+o)<=i?n.getChildAt(a):null}while(r&&!r.get('selectable'));e.push(r||t)}})),e.length&&t.select(e)}}}},function(t,e,n){"use strict";n.r(e),e["default"]={run:function(t){if(t.Canvas.hasFocus()){var e=[];t.getSelectedAll().forEach((function(t){var n=t.parent();if(n){var r,i=0,o=0;do{i++,r=(o=t.index()-i)>=0?n.getChildAt(o):null}while(r&&!r.get('selectable'));e.push(r||t)}})),e.length&&t.select(e)}}}},function(t,e,n){"use strict";n.r(e);var r=n(0);e["default"]={run:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=n.target,o=[];if(!i.get('styles'))return o;var a=i.get('type'),s=t.Pages.getAllWrappers(),c=Object(r["flatten"])(s.map((function(t){return t.findType(a)}))).length;if(!c){var l=t.CssComposer.getAll();o=l.filter((function(t){return t.get('group')==="cmp:".concat(a)})),l.remove(o)}return o}}},function(t,e,n){"use strict";n.r(e);var r=n(11),i=n.n(r);e["default"]={run:function(t){var e=t.getModel(),n=i()(t.getSelectedAll());n.length&&e.set('clipboard',n)}}},function(t,e,n){"use strict";n.r(e);var r=n(0),i=n(3),o=n.n(i),a=n(23),s=o.a.$;e["default"]=Object(r["extend"])({},a["default"],{init:function(t){Object(r["bindAll"])(this,'startDelete','stopDelete','onDelete'),this.hoverClass=this.pfx+'hover-delete',this.badgeClass=this.pfx+'badge-red'},enable:function(){this.$el.find('*').mouseover(this.startDelete).mouseout(this.stopDelete).click(this.onDelete)},startDelete:function(t){t.stopPropagation();var e=s(t.target);e.data('model').get('removable')&&(e.addClass(this.hoverClass),this.attachBadge(e.get(0)))},stopDelete:function(t){t.stopPropagation(),s(t.target).removeClass(this.hoverClass),this.badge&&this.badge.css({left:-1e3,top:-1e3})},onDelete:function(t){t.stopPropagation();var e=s(t.target);e.data('model').get('removable')&&(e.data('model').destroy(),this.removeBadge(),this.clean())},updateBadgeLabel:function(t){this.badge.html('Remove '+t.getName())}})},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n.n(r).a.$;e["default"]={run:function(t,e){var n=this;e&&e.set&&e.set('active',0);var r=t.getConfig(),o=t.Modal,a=r.stylePrefix;if(this.cm=t.CodeManager||null,!this.$editors){var s=this.buildEditor('htmlmixed','hopscotch','HTML'),c=this.buildEditor('css','hopscotch','CSS');this.htmlEditor=s.el,this.cssEditor=c.el;var l=i("
"));l.append(s.$el).append(c.$el),this.$editors=l}o.open({title:r.textViewCode,content:this.$editors}).getModel().once('change:open',(function(){return t.stopCommand(n.id)})),this.htmlEditor.setContent(t.getHtml()),this.cssEditor.setContent(t.getCss())},stop:function(t){var e=t.Modal;e&&e.close()},buildEditor:function(t,e,n){var r=document.createElement('textarea');!this.codeMirror&&(this.codeMirror=this.cm.getViewer('CodeMirror'));var i=this.codeMirror.clone().set({label:n,codeName:t,theme:e,input:r}),o=new this.cm.EditorView({model:i,config:this.cm.getConfig()}).render().$el;return i.init(r),{el:i,$el:o}}}},function(t,e,n){"use strict";n.r(e);var r=n(0);e["default"]={isEnabled:function(){var t=document;return t.fullscreenElement||t.webkitFullscreenElement||t.mozFullScreenElement?1:0},enable:function(t){var e='';return t.requestFullscreen?t.requestFullscreen():t.webkitRequestFullscreen?(e='webkit',t.webkitRequestFullscreen()):t.mozRequestFullScreen?(e='moz',t.mozRequestFullScreen()):t.msRequestFullscreen?t.msRequestFullscreen():console.warn('Fullscreen not supported'),e},disable:function(){var t=document;this.isEnabled()&&(t.exitFullscreen?t.exitFullscreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.msExitFullscreen&&t.msExitFullscreen())},fsChanged:function(t,e){document;var n=(t||'')+'fullscreenchange';this.isEnabled()||(this.stop(null,this.sender),document.removeEventListener(n,this.fsChanged))},run:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.sender=e;var i=n.target,o=Object(r["isElement"])(i)?i:document.querySelector(i),a=this.enable(o||t.getContainer());this.fsChanged=this.fsChanged.bind(this,a),document.addEventListener(a+'fullscreenchange',this.fsChanged),t.trigger('change:canvasOffset')},stop:function(t,e){e&&e.set&&e.set('active',!1),this.disable(),t&&t.trigger('change:canvasOffset')}}},function(t,e,n){"use strict";n.r(e);var r=n(0),i=n(3),o=n.n(i),a=n(1),s=n(23),c=n(35),l=o.a.$;e["default"]=Object(r["extend"])({},c["default"],s["default"],{init:function(t){s["default"].init.apply(this,arguments),Object(r["bindAll"])(this,'initSorter','rollback','onEndMove'),this.opt=t,this.hoverClass=this.ppfx+'highlighter-warning',this.badgeClass=this.ppfx+'badge-warning',this.noSelClass=this.ppfx+'no-select'},enable:function(){for(var t=arguments.length,e=new Array(t),n=0;n2&&void 0!==arguments[2]?arguments[2]:{},r=t.AssetManager,o=r.getConfig(),a=n.types,s=void 0===a?[]:a,c=n.accept,l=n.select;if(this.title=n.modalTitle||t.t('assetManager.modalTitle')||'',this.editor=t,this.config=o,this.am=r,r.setTarget(n.target),r.onClick(n.onClick),r.onDblClick(n.onDblClick),r.onSelect(n.onSelect),r.__behaviour({select:l,types:s,options:n}),o.custom)this.rendered=this.rendered||Object(i["f"])('div'),this.rendered.className="".concat(o.stylePrefix,"custom-wrp"),r.__behaviour({container:this.rendered}),r.__trgCustom();else{if(!this.rendered||s){var u=r.getAll().filter((function(t){return t}));s&&s.length&&(u=u.filter((function(t){return-1!==s.indexOf(t.get('type'))}))),r.render(u),this.rendered=r.getContainer()}if(c){var f=this.rendered.querySelector("input#".concat(o.stylePrefix,"uploadFile"));f&&f.setAttribute('accept',c)}}return this.open(this.rendered),this},stop:function(t){this.editor=t,this.close(this.rendered)}}},function(t,e,n){"use strict";n.r(e);var r=n(0),i=n(13);e["default"]={open:function(){var t=this.container,e=this.editor,n=this.bm,i=this.config,o=i.custom,a=i.appendTo;if(Object(r["isFunction"])(o.open))return o.open(n.__customData());if(this.firstRender&&!a){var s='views-container',c=e.Panels;(c.getPanel(s)||c.addPanel({id:s})).set('appendContent',t).trigger('change:appendContent'),o||t.appendChild(n.render())}t&&(t.style.display='block')},close:function(){var t=this.container,e=this.config.custom;if(Object(r["isFunction"])(e.close))return e.close(this.bm.__customData());t&&(t.style.display='none')},run:function(t){var e=t.Blocks;this.config=e.getConfig(),this.firstRender=!this.container,this.container=this.container||Object(i["f"])('div'),this.editor=t,this.bm=e;var n=this.container;e.__behaviour({container:n}),this.config.custom&&e.__trgCustom(),this.open()},stop:function(){this.close()}}},function(t,e,n){"use strict";n.r(e),e["default"]={run:function(t){var e=t.LayerManager,n=t.Panels;if(!e.getConfig().appendTo){if(!this.layers){var r='views-container',i=document.createElement('div'),o=n.getPanel(r)||n.addPanel({id:r});i.appendChild(e.render()),o.set('appendContent',i).trigger('change:appendContent'),this.layers=i}this.layers.style.display='block'}},stop:function(){var t=this.layers;t&&(t.style.display='none')}}},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n.n(r).a.$;e["default"]={run:function(t,e){if(this.sender=e,!this.$cn){var n=t.getConfig(),r=t.Panels,o='change:appendContent';this.$cn=i('
'),this.$cn2=i('
'),this.$cn.append(this.$cn2);var a=t.DeviceManager;if(a&&n.showDevices){var s=r.addPanel({id:'devices-c'}),c=a.render();s.set('appendContent',c).trigger(o)}var l=t.SelectorManager;this.slm=l;var u=l.getConfig();u.custom?l.__trgCustom({container:this.$cn2.get(0)}):u.appendTo||this.$cn2.append(l.render([]));var f=t.StyleManager;this.sm=f;var h=f.getConfig(),d=h.stylePrefix;this.$header=i("
").concat(t.t('styleManager.empty'),"
")),this.$cn.append(this.$header),h.custom?f.__trgCustom({container:this.$cn2.get(0)}):h.appendTo||this.$cn2.append(f.render());var p='views-container';this.panel=r.getPanel(p),this.panel||(this.panel=r.addPanel({id:p})),this.panel.set('appendContent',this.$cn).trigger(o),this.em=t.getModel(),this.listenTo(this.em,f.events.target,this.toggleSm)}this.toggleSm()},toggleSm:function(){var t,e,n,r,i=this.sender,o=this.sm;i&&i.get&&!i.get('active')||!o||(o.getSelected()?(null===(t=this.$cn2)||void 0===t||t.show(),null===(e=this.$header)||void 0===e||e.hide()):(null===(n=this.$cn2)||void 0===n||n.hide(),null===(r=this.$header)||void 0===r||r.show()))},stop:function(){var t,e;null===(t=this.$cn2)||void 0===t||t.hide(),null===(e=this.$header)||void 0===e||e.hide()}}},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n.n(r).a.$;e["default"]={run:function(t,e){this.sender=e;var n=t.getModel(),r=t.Config.stylePrefix,o=t.TraitManager,a=o.getConfig();if(!a.appendTo){if(!this.$cn){this.$cn=i('
'),this.$cn2=i('
'),this.$cn.append(this.$cn2),this.$header=i('
').append("
").concat(n.t('traitManager.empty'),"
")),this.$cn.append(this.$header),this.$cn2.append("
").concat(n.t('traitManager.label'),"
")),this.$cn2.append(o.render());var s=t.Panels;(s.getPanel('views-container')?s.getPanel('views-container'):s.addPanel({id:'views-container'})).set('appendContent',this.$cn.get(0)).trigger('change:appendContent'),this.target=t.getModel(),this.listenTo(this.target,'component:toggled',this.toggleTm)}this.toggleTm()}},toggleTm:function(){var t=this.sender;t&&t.get&&!t.get('active')||(1===this.target.getSelectedAll().length?(this.$cn2.show(),this.$header.hide()):(this.$cn2.hide(),this.$header.show()))},stop:function(){this.$cn2&&this.$cn2.hide(),this.$header&&this.$header.hide()}}},function(t,e,n){"use strict";n.r(e);var r=n(0);e["default"]={run:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=t.getModel(),o=i.get('clipboard'),a=t.getSelected();o&&a&&(t.getSelectedAll().forEach((function(e){if(e){var i=e.collection;if(i){var a,s={at:i.indexOf(e)+1,action:n.action||'paste-component'},c=o.filter((function(t){return t.get('copyable')}));a=Object(r["contains"])(o,e)&&e.get('copyable')?i.add(e.clone(),s):i.add(c.map((function(t){return t.clone()})),s),(a=Object(r["isArray"])(a)?a:[a]).forEach((function(e){return t.trigger('component:paste',e)}))}}})),a.emitUpdate())}}},function(t,e,n){"use strict";n.r(e);var r=n(11),i=n.n(r),o=n(0),a='sw-visibility';e["default"]={getPanels:function(t){return this.panels||(this.panels=t.Panels.getPanels()),this.panels},preventDrag:function(t){t.abort=1},tglEffects:function(t){var e=this.em,n=t?'on':'off';if(e){var r=e.get('Canvas'),i=r.getBody(),a=r.getToolbarEl();a&&(a.style.display=t?'none':'');var s=i.querySelectorAll(".".concat(this.ppfx,"no-pointer"));Object(o["each"])(s,(function(e){return e.style.pointerEvents=t?'all':''})),e[n]('run:tlb-move:before',this.preventDrag)}},run:function(t,e){var n=this;this.sender=e,this.selected=i()(t.getSelectedAll()),t.select(),this.shouldRunSwVisibility||(this.shouldRunSwVisibility=t.Commands.isActive(a)),this.shouldRunSwVisibility&&t.stopCommand(a),t.getModel().stopDefault();var r=this.getPanels(t),o=t.Canvas.getElement(),s=t.getEl(),c=t.Config.stylePrefix;if(!this.helper){var l=document.createElement('span');l.className="".concat(c,"off-prv fa fa-eye-slash"),s.appendChild(l),l.onclick=function(){return n.stopCommand()},this.helper=l}this.helper.style.display='inline-block',r.forEach((function(t){return t.set('visible',!1)}));var u=o.style;u.width='100%',u.height='100%',u.top='0',u.left='0',u.padding='0',u.margin='0',t.refresh(),this.tglEffects(1)},stop:function(t){var e=this.sender,n=void 0===e?{}:e,r=this.selected;n.set&&n.set('active',0);var i=this.getPanels(t);this.shouldRunSwVisibility&&(t.runCommand(a),this.shouldRunSwVisibility=!1),t.getModel().runDefault(),i.forEach((function(t){return t.set('visible',!0)})),t.Canvas.getElement().setAttribute('style',''),r&&t.select(r),delete this.selected,this.helper&&(this.helper.style.display='none'),t.refresh(),this.tglEffects()}}},function(t,e,n){"use strict";n.r(e);var r=n(2),i=n.n(r);function o(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}e["default"]={run:function(t,e,n){var r=n||{},a=t.Canvas,s=a.getCanvasView(),c=function(t){for(var e=1;e")).get(0),D=u("
")).get(0),M=v+T+'-el',A="".concat(v+_+'-el'," ").concat(v+_),L="".concat(M," ").concat(v+T);b=u("
")).get(0),w=u("
")).get(0),O=u("
")).get(0),x=u("
")).get(0),C=u("
")).get(0),k=u("
")).get(0),S=u("
")).get(0),j=u("
")).get(0),this['marginT'+o]=b,this['marginB'+o]=w,this['marginL'+o]=O,this['marginR'+o]=x,this['padT'+o]=C,this['padB'+o]=k,this['padL'+o]=S,this['padR'+o]=j,E.appendChild(b),E.appendChild(w),E.appendChild(O),E.appendChild(x),D.appendChild(C),D.appendChild(k),D.appendChild(S),D.appendChild(j),y.appendChild(E),y.appendChild(D),this[m]='1'}var R='px',N=parseFloat(g.marginLeft.replace(R,''))*f,I=parseFloat(g.marginRight.replace(R,''))*f,F=parseFloat(g.marginTop.replace(R,''))*f,V=parseFloat(g.marginBottom.replace(R,''))*f,B=b.style,H=w.style,z=O.style,U=x.style,W=C.style,$=k.style,q=S.style,G=j.style,K=parseFloat(p.left),Y=parseFloat(g.width)*f+R;B.height=F+R,B.width=Y,B.top=p.top-F+R,B.left=K+R,H.height=V+R,H.width=Y,H.top=p.top+p.height+R,H.left=K+R;var J=p.height+F+V+R,X=p.top-F+R;z.height=J,z.width=N+R,z.top=X,z.left=K-N+R,U.height=J,U.width=I+R,U.top=X,U.left=K+p.width+R;var Z=parseFloat(g.paddingTop)*f;W.height=Z+R;var Q=parseFloat(g.paddingBottom)*f;$.height=Q+R;var tt=p.height-Q-Z+R,et=p.top+Z+R;q.height=tt,q.width=parseFloat(g.paddingLeft)*f+R,q.top=et;var nt=parseFloat(g.paddingRight)*f;G.height=tt,G.width=nt+R,G.top=et}},stop:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n||{},i=r.state||'',o=this.getOffsetMethod(i),a=t.Canvas,s=a[o](n.view);s.style.opacity=0}}},function(t,e,n){"use strict";n.r(e);var r=n(0);e["default"]={init:function(){Object(r["bindAll"])(this,'_onFramesChange')},run:function(t){this.toggleVis(t)},stop:function(t){this.toggleVis(t,0)},toggleVis:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if(!t.Commands.isActive('preview')){var r=t.Canvas,i=n?'on':'off';r.getFrames().forEach((function(t){return e._upFrame(t,n)})),r.getModel()[i]('change:frames',this._onFramesChange)}},_onFramesChange:function(t,e){var n=this;e.forEach((function(t){return n._upFrame(t,1)}))},_upFrame:function(t,e){var n=e?'add':'remove';t.view.getBody().classList[n]("".concat(this.ppfx,"dashed"))}}},function(t,e,n){var r,i,o;1&&(i=[n(0),n(3)],void 0===(o='function'==typeof(r=function(t,e){var n=Array.prototype.slice;function r(t,e,n){return n.length<=4?t.call(e,n[0],n[1],n[2],n[3]):t.apply(e,n)}function i(t,e){return n.call(t,e)}function o(e,n){return null!=e&&(t.isArray(n)||(n=i(arguments,1)),t.all(n,(function(t){return t in e})))}var a,s,c=(a=!1,s=-1,function(){return a||(s++,a=!0,t.defer((function(){a=!1}))),s});function l(){this.registeredObjects=[],this.cidIndexes=[]}function u(e,n,r,i){for(var o,a=0,s=n.length;at.maximumStackLength&&(t.shift(),t.pointer--)}}}l.prototype={isRegistered:function(e){return e&&e.cid?this.registeredObjects[e.cid]:t.contains(this.registeredObjects,e)},register:function(t){return!this.isRegistered(t)&&(t&&t.cid?(this.registeredObjects[t.cid]=t,this.cidIndexes.push(t.cid)):this.registeredObjects.push(t),!0)},unregister:function(e){if(this.isRegistered(e)){if(e&&e.cid)delete this.registeredObjects[e.cid],this.cidIndexes.splice(t.indexOf(this.cidIndexes,e.cid),1);else{var n=t.indexOf(this.registeredObjects,e);this.registeredObjects.splice(n,1)}return!0}return!1},get:function(){return t.map(this.cidIndexes,(function(t){return this.registeredObjects[t]}),this).concat(this.registeredObjects)}};var p={add:{undo:function(t,e,n,r){t.remove(n,r)},redo:function(t,e,n,r){r.index&&(r.at=r.index),t.add(n,r)},on:function(e,n,r){return{object:n,before:void 0,after:e,options:t.clone(r)}}},remove:{undo:function(t,e,n,r){"index"in r&&(r.at=r.index),t.add(e,r)},redo:function(t,e,n,r){t.remove(e,r)},on:function(e,n,r){return{object:n,before:e,after:void 0,options:t.clone(r)}}},change:{undo:function(e,n,r,i){t.isEmpty(n)?t.each(t.keys(r),e.unset,e):(e.set(n),i&&i.unsetData&&i.unsetData.before&&i.unsetData.before.length&&t.each(i.unsetData.before,e.unset,e))},redo:function(e,n,r,i){t.isEmpty(r)?t.each(t.keys(n),e.unset,e):(e.set(r),i&&i.unsetData&&i.unsetData.after&&i.unsetData.after.length&&t.each(i.unsetData.after,e.unset,e))},on:function(e,n){var r=e.changedAttributes(),i=t.keys(r),o=t.pick(e.previousAttributes(),i),a=t.keys(o),s=(n||(n={})).unsetData={after:[],before:[]};return i.length!=a.length&&(i.length>a.length?t.each(i,(function(t){t in o||s.before.push(t)}),this):t.each(a,(function(t){t in r||s.after.push(t)}))),{object:e,before:o,after:r,options:t.clone(n)}}},reset:{undo:function(t,e,n){t.reset(e)},redo:function(t,e,n){t.reset(n)},on:function(e,n){return{object:e,before:n.previousModels,after:t.clone(e.models)}}}};function g(){}function v(e,n,r,i){if("object"==typeof n)return t.each(n,(function(t,n){2===e?v(e,t,r,i):v(e,n,t,r)}));switch(e){case 0:o(r,"undo","redo","on")&&t.all(t.pick(r,"undo","redo","on"),t.isFunction)&&(i[n]=r);break;case 1:i[n]&&t.isObject(r)&&(i[n]=t.extend({},i[n],r));break;case 2:delete i[n]}return this}g.prototype=p;var m=e.Model.extend({defaults:{type:null,object:null,before:null,after:null,magicFusionIndex:null},undo:function(t){f("undo",this.attributes)},redo:function(t){f("redo",this.attributes)}}),y=e.Collection.extend({model:m,pointer:-1,track:!1,isCurrentlyUndoRedoing:!1,maximumStackLength:1/0,setMaxLength:function(t){this.maximumStackLength=t}}),b=e.Model.extend({defaults:{maximumStackLength:1/0,track:!1},initialize:function(e){this.stack=new y,this.objectRegistry=new l,this.undoTypes=new g,this.stack.setMaxLength(this.get("maximumStackLength")),this.on("change:maximumStackLength",(function(t,e){this.stack.setMaxLength(e)}),this),e&&e.track&&this.startTracking(),e&&e.register&&(t.isArray(e.register)||t.isArguments(e.register)?r(this.register,this,e.register):this.register(e.register))},startTracking:function(){this.set("track",!0),this.stack.track=!0},stopTracking:function(){this.set("track",!1),this.stack.track=!1},isTracking:function(){return this.get("track")},_addToStack:function(t){d(this.stack,t,i(arguments,1),this.undoTypes)},register:function(){u("on",arguments,this._addToStack,this)},unregister:function(){u("off",arguments,this._addToStack,this)},unregisterAll:function(){r(this.unregister,this,this.objectRegistry.get())},undo:function(t){h("undo",this,this.stack,t)},undoAll:function(){h("undo",this,this.stack,!1,!0)},redo:function(t){h("redo",this,this.stack,t)},redoAll:function(){h("redo",this,this.stack,!1,!0)},isAvailable:function(t){var e=this.stack,n=e.length;switch(t){case"undo":return n>0&&e.pointer>-1;case"redo":return n>0&&e.pointer=0||(i[n]=t[n]);return i},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e){function n(e,r){return t.exports=n=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t},t.exports["default"]=t.exports,t.exports.__esModule=!0,n(e,r)}t.exports=n,t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e){t.exports=function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t},t.exports["default"]=t.exports,t.exports.__esModule=!0},function(t,e,n){"use strict";n.r(e);var r=n(11),i=n.n(r),o=n(2),a=n.n(o),s=n(75),c=n.n(s),l=n(0);function u(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function f(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{};n=f(f({},o),h),t=n.em,this.em=t,n._disable&&(n=f(f({},n),{},{maximumStackLength:0}));var d=!0;return(e=new c.a(f({track:!0,register:[]},n))).changeUndoType('change',{condition:function(t){var e=t.get('_undo');if(e){var n=t.get('_undoexc');if(Object(l["isArray"])(n)&&s(t).some((function(t){return n.indexOf(t)>=0})))return!1;if(Object(l["isBoolean"])(e))return!0;if(Object(l["isArray"])(e)&&s(t).some((function(t){return e.indexOf(t)>=0})))return!0}return!1},on:function(t,e,n){!r&&(r=t.previousAttributes());var i=n||e||{};if(i.noUndo&&setTimeout((function(){r=null})),!a(i)){var o=t.toJSON({fromUndo:d}),s={object:t,before:r,after:o};if(r=null,!Object(l["isEmpty"])(o))return s}}}),e.changeUndoType('add',{on:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!a(n)&&u.isRegistered(e))return{object:e,before:void 0,after:t,options:f(f({},n),{},{fromUndo:d})}}}),e.changeUndoType('remove',{on:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!a(n)&&u.isRegistered(e))return{object:e,before:t,after:void 0,options:f(f({},n),{},{fromUndo:d})}}}),e.changeUndoType('reset',{undo:function(t,e){t.reset(e,{fromUndo:d})},redo:function(t,e,n){t.reset(n,{fromUndo:d})},on:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!a(e)&&u.isRegistered(t))return{object:t,before:e.previousModels,after:i()(t.models),options:f(f({},e),{},{fromUndo:d})}}}),e.on('undo redo',(function(){t.trigger('change:canvasOffset'),t.getSelectedAll().map((function(t){return t.trigger('rerender:layer')}))})),['undo','redo'].forEach((function(n){return e.on(n,(function(){return t.trigger(n)}))})),this},postLoad:function(){n.trackSelection&&t&&this.add(t.get('selected'))},getConfig:function(){return n},add:function(t){return e.register(t),this},remove:function(t){return e.unregister(t),this},removeAll:function(){return e.unregisterAll(),this},start:function(){return e.startTracking(),this},stop:function(){return e.stopTracking(),this},undo:function(){var n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return!t.isEditing()&&e.undo(n),this},undoAll:function(){return e.undoAll(),this},redo:function(){var n=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return!t.isEditing()&&e.redo(n),this},redoAll:function(){return e.redoAll(),this},hasUndo:function(){return e.isAvailable('undo')},hasRedo:function(){return e.isAvailable('redo')},isRegistered:function(t){return!!this.getInstance().objectRegistry.isRegistered(t)},getStack:function(){return e.stack},getStackGroup:function(){var t=[],e=[];return this.getStack().forEach((function(n){var r=n.get('magicFusionIndex');e.indexOf(r)<0&&(e.push(r),t.push(n))})),t},skip:function(t){this.stop(),t(),this.start()},getGroupedStack:function(){var t={},e=this.getStack();return e.forEach((function(e,n){var r=e.get('magicFusionIndex'),i=function(t,e){var n=t.attributes,r=n.type,i=n.after,o=n.before,a=n.object,s=n.options;return{index:e,type:r,after:i,before:o,object:a,options:void 0===s?{}:s}}(e,n);t[r]?t[r].push(i):t[r]=[i]})),Object.keys(t).map((function(e){var n=t[e];return{index:n[n.length-1].index,actions:n,labels:Object(l["unique"])(n.reduce((function(t,e){var n,r=null===(n=e.options)||void 0===n?void 0:n.action;return r&&t.push(r),t}),[]))}}))},goToGroup:function(t){var e=this;if(t){var n=this.getPointer(),r=t.index-n;Object(l["times"])(Math.abs(r),(function(){e[r<0?'undo':'redo'](!1)}))}},getPointer:function(){return this.getStack().pointer},clear:function(){return e.clear(),this},getInstance:function(){return e},destroy:function(){this.clear().removeAll(),[t,e,n,r].forEach((function(t){return{}})),this.em={}}}}},function(t,e,n){(function(t){var r=void 0!==t&&t||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new o(i.call(setTimeout,r,arguments),clearTimeout)},e.setInterval=function(){return new o(i.call(setInterval,r,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(r,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout((function(){t._onTimeout&&t._onTimeout()}),e))},n(86),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,n(33))},function(t,e,n){(function(t,e){!function(t,n){"use strict";if(!t.setImmediate){var r,i,o,a,s,c=1,l={},u=!1,f=t.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(t);h=h&&h.setTimeout?h:t,"[object process]"==={}.toString.call(t.process)?r=function(t){e.nextTick((function(){p(t)}))}:!function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?t.MessageChannel?((o=new MessageChannel).port1.onmessage=function(t){p(t.data)},r=function(t){o.port2.postMessage(t)}):f&&"onreadystatechange"in f.createElement("script")?(i=f.documentElement,r=function(t){var e=f.createElement("script");e.onreadystatechange=function(){p(t),e.onreadystatechange=null,i.removeChild(e),e=null},i.appendChild(e)}):r=function(t){setTimeout(p,0,t)}:(a="setImmediate$"+Math.random()+"$",s=function(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(a)&&p(+e.data.slice(a.length))},t.addEventListener?t.addEventListener("message",s,!1):t.attachEvent("onmessage",s),r=function(e){t.postMessage(a+e,"*")}),h.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n1)for(var n=1;n","i")}function o(t,e){for(var n in t)for(var r=e[n]||(e[n]=[]),i=t[n],o=i.length-1;o>=0;o--)r.unshift(i[o])}t.defineMode("htmlmixed",(function(n,a){var s=t.getMode(n,{name:"xml",htmlMode:!0,multilineTagIndentFactor:a.multilineTagIndentFactor,multilineTagIndentPastTag:a.multilineTagIndentPastTag,allowMissingTagName:a.allowMissingTagName}),c={},l=a&&a.tags,u=a&&a.scriptTypes;if(o(e,c),l&&o(l,c),u)for(var f=u.length-1;f>=0;f--)c.script.unshift(["type",u[f].matches,u[f].mode]);function h(e,o){var a,l=s.token(e,o.htmlState),u=/\btag\b/.test(l);if(u&&!/[<>\s\/]/.test(e.current())&&(a=o.htmlState.tagName&&o.htmlState.tagName.toLowerCase())&&c.hasOwnProperty(a))o.inTag=a+" ";else if(o.inTag&&u&&/>$/.test(e.current())){var f=/^([\S]+) (.*)/.exec(o.inTag);o.inTag=null;var d=">"==e.current()&&function(t,e){for(var n=0;n-1?t.backUp(r.length-i):r.match(/<\/?$/)&&(t.backUp(r.length),t.match(e,!1)||t.match(r)),n}(t,v,e.localMode.token(t,e.localState))},o.localMode=p,o.localState=t.startState(p,s.indent(o.htmlState,"",""))}else o.inTag&&(o.inTag+=e.current(),e.eol()&&(o.inTag+=" "));return l}return{startState:function(){return{token:h,inTag:null,localMode:null,localState:null,htmlState:t.startState(s)}},copyState:function(e){var n;return e.localState&&(n=t.copyState(e.localMode,e.localState)),{token:e.token,inTag:e.inTag,localMode:e.localMode,localState:n,htmlState:t.copyState(s,e.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(e,n,r){return!e.localMode||/^\s*<\//.test(n)?s.indent(e.htmlState,n,r):e.localMode.indent?e.localMode.indent(e.localState,n,r):t.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||s}}}}),"xml","javascript","css"),t.defineMIME("text/html","htmlmixed")}(n(28),n(92),n(93),n(50))},function(t,e,n){1&&function(t){"use strict";var e={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},n={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,allowMissingTagName:!1,caseFold:!1};t.defineMode("xml",(function(r,i){var o,a,s=r.indentUnit,c={},l=i.htmlMode?e:n;for(var u in l)c[u]=l[u];for(var u in i)c[u]=i[u];function f(t,e){function n(n){return e.tokenize=n,n(t,e)}var r=t.next();return"<"==r?t.eat("!")?t.eat("[")?t.match("CDATA[")?n(d("atom","]]>")):null:t.match("--")?n(d("comment","--\x3e")):t.match("DOCTYPE",!0,!0)?(t.eatWhile(/[\w\._\-]/),n(function t(e){return function(n,r){for(var i;null!=(i=n.next());){if("<"==i)return r.tokenize=t(e+1),r.tokenize(n,r);if(">"==i){if(1==e){r.tokenize=f;break}return r.tokenize=t(e-1),r.tokenize(n,r)}}return"meta"}}(1))):null:t.eat("?")?(t.eatWhile(/[\w\._\-]/),e.tokenize=d("meta","?>"),"meta"):(o=t.eat("/")?"closeTag":"openTag",e.tokenize=h,"tag bracket"):"&"==r?(t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";"))?"atom":"error":(t.eatWhile(/[^&<]/),null)}function h(t,e){var n,r,i=t.next();if(">"==i||"/"==i&&t.eat(">"))return e.tokenize=f,o=">"==i?"endTag":"selfcloseTag","tag bracket";if("="==i)return o="equals",null;if("<"==i){e.tokenize=f,e.state=y,e.tagName=e.tagStart=null;var a=e.tokenize(t,e);return a?a+" tag error":"tag error"}return/[\'\"]/.test(i)?(e.tokenize=(n=i,(r=function(t,e){for(;!t.eol();)if(t.next()==n){e.tokenize=h;break}return"string"}).isInAttribute=!0,r),e.stringStartCol=t.column(),e.tokenize(t,e)):(t.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function d(t,e){return function(n,r){for(;!n.eol();){if(n.match(e)){r.tokenize=f;break}n.next()}return t}}function p(t){return t&&t.toLowerCase()}function g(t,e,n){this.prev=t.context,this.tagName=e||"",this.indent=t.indented,this.startOfLine=n,(c.doNotIndent.hasOwnProperty(e)||t.context&&t.context.noIndent)&&(this.noIndent=!0)}function v(t){t.context&&(t.context=t.context.prev)}function m(t,e){for(var n;1;){if(!t.context)return;if(n=t.context.tagName,!c.contextGrabbers.hasOwnProperty(p(n))||!c.contextGrabbers[p(n)].hasOwnProperty(p(e)))return;v(t)}}function y(t,e,n){return"openTag"==t?(n.tagStart=e.column(),b):"closeTag"==t?w:y}function b(t,e,n){return"word"==t?(n.tagName=e.current(),a="tag",C):c.allowMissingTagName&&"endTag"==t?(a="tag bracket",C(t,0,n)):(a="error",b)}function w(t,e,n){if("word"==t){var r=e.current();return n.context&&n.context.tagName!=r&&c.implicitlyClosed.hasOwnProperty(p(n.context.tagName))&&v(n),n.context&&n.context.tagName==r||!1===c.matchClosing?(a="tag",O):(a="tag error",x)}return c.allowMissingTagName&&"endTag"==t?(a="tag bracket",O(t,0,n)):(a="error",x)}function O(t,e,n){return"endTag"!=t?(a="error",O):(v(n),y)}function x(t,e,n){return a="error",O(t,0,n)}function C(t,e,n){if("word"==t)return a="attribute",k;if("endTag"==t||"selfcloseTag"==t){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==t||c.autoSelfClosers.hasOwnProperty(p(r))?m(n,r):(m(n,r),n.context=new g(n,r,i==n.indented)),y}return a="error",C}function k(t,e,n){return"equals"==t?S:(c.allowMissing||(a="error"),C(t,0,n))}function S(t,e,n){return"string"==t?j:"word"==t&&c.allowUnquoted?(a="string",C):(a="error",C(t,0,n))}function j(t,e,n){return"string"==t?j:C(t,0,n)}return f.isInText=!0,{startState:function(t){var e={tokenize:f,state:y,indented:t||0,tagName:null,tagStart:null,context:null};return null!=t&&(e.baseIndent=t),e},token:function(t,e){if(!e.tagName&&t.sol()&&(e.indented=t.indentation()),t.eatSpace())return null;o=null;var n=e.tokenize(t,e);return(n||o)&&"comment"!=n&&(a=null,e.state=e.state(o||n,t,e),a&&(n="error"==a?n+" error":a)),n},indent:function(e,n,r){var i=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+s;if(i&&i.noIndent)return t.Pass;if(e.tokenize!=h&&e.tokenize!=f)return r?r.match(/^(\s*)/)[0].length:0;if(e.tagName)return!1!==c.multilineTagIndentPastTag?e.tagStart+e.tagName.length+2:e.tagStart+s*(c.multilineTagIndentFactor||1);if(c.alignCDATA&&/$/,blockCommentStart:"\x3c!--",blockCommentEnd:"--\x3e",configuration:c.htmlMode?"html":"xml",helperType:c.htmlMode?"html":"xml",skipAttribute:function(t){t.state==S&&(t.state=C)},xmlCurrentTag:function(t){return t.tagName?{name:t.tagName,close:"closeTag"==t.type}:null},xmlCurrentContext:function(t){for(var e=[],n=t.context;n;n=n.prev)e.push(n.tagName);return e.reverse()}}})),t.defineMIME("text/xml","xml"),t.defineMIME("application/xml","xml"),t.mimeModes.hasOwnProperty("text/html")||t.defineMIME("text/html",{name:"xml",htmlMode:!0})}(n(28))},function(t,e,n){1&&function(t){"use strict";t.defineMode("javascript",(function(e,n){var r,i,o=e.indentUnit,a=n.statementIndent,s=n.jsonld,c=n.json||s,l=!1!==n.trackScope,u=n.typescript,f=n.wordCharacters||/[\w$\xa1-\uffff]/,h=function(){function t(t){return{type:t,style:"keyword"}}var e=t("keyword a"),n=t("keyword b"),r=t("keyword c"),i=t("keyword d"),o=t("operator"),a={type:"atom",style:"atom"};return{if:t("if"),while:e,with:e,else:n,do:n,try:n,finally:n,return:i,break:i,continue:i,new:t("new"),delete:r,void:r,throw:r,debugger:t("debugger"),var:t("var"),const:t("var"),let:t("var"),function:t("function"),catch:t("catch"),for:t("for"),switch:t("switch"),case:t("case"),default:t("default"),in:o,typeof:o,instanceof:o,true:a,false:a,null:a,undefined:a,NaN:a,Infinity:a,this:t("this"),class:t("class"),super:t("atom"),yield:r,export:t("export"),import:t("import"),extends:r,await:r}}(),d=/[+\-*&%=<>!?|~^@]/,p=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function g(t,e,n){return r=t,i=n,e}function v(t,e){var n,r=t.next();if('"'==r||"'"==r)return e.tokenize=(n=r,function(t,e){var r,i=!1;if(s&&"@"==t.peek()&&t.match(p))return e.tokenize=v,g("jsonld-keyword","meta");for(;null!=(r=t.next())&&(r!=n||i);)i=!i&&"\\"==r;return i||(e.tokenize=v),g("string","string")}),e.tokenize(t,e);if("."==r&&t.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return g("number","number");if("."==r&&t.match(".."))return g("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return g(r);if("="==r&&t.eat(">"))return g("=>","operator");if("0"==r&&t.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return g("number","number");if(/\d/.test(r))return t.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),g("number","number");if("/"==r)return t.eat("*")?(e.tokenize=m,m(t,e)):t.eat("/")?(t.skipToEnd(),g("comment","comment")):Qt(t,e,1)?(function(t){for(var e,n=!1,r=!1;null!=(e=t.next());){if(!n){if("/"==e&&!r)return;"["==e?r=!0:r&&"]"==e&&(r=!1)}n=!n&&"\\"==e}}(t),t.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),g("regexp","string-2")):(t.eat("="),g("operator","operator",t.current()));if("`"==r)return e.tokenize=y,y(t,e);if("#"==r&&"!"==t.peek())return t.skipToEnd(),g("meta","meta");if("#"==r&&t.eatWhile(f))return g("variable","property");if("<"==r&&t.match("!--")||"-"==r&&t.match("->")&&!/\S/.test(t.string.slice(0,t.start)))return t.skipToEnd(),g("comment","comment");if(d.test(r))return">"==r&&e.lexical&&">"==e.lexical.type||(t.eat("=")?"!"!=r&&"="!=r||t.eat("="):/[<>*+\-|&?]/.test(r)&&(t.eat(r),">"==r&&t.eat(r))),"?"==r&&t.eat(".")?g("."):g("operator","operator",t.current());if(f.test(r)){t.eatWhile(f);var i=t.current();if("."!=e.lastType){if(h.propertyIsEnumerable(i)){var o=h[i];return g(o.type,o.style,i)}if("async"==i&&t.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return g("async","keyword",i)}return g("variable","variable",i)}}function m(t,e){for(var n,r=!1;n=t.next();){if("/"==n&&r){e.tokenize=v;break}r="*"==n}return g("comment","comment")}function y(t,e){for(var n,r=!1;null!=(n=t.next());){if(!r&&("`"==n||"$"==n&&t.eat("{"))){e.tokenize=v;break}r=!r&&"\\"==n}return g("quasi","string-2",t.current())}var b="([{}])";function w(t,e){e.fatArrowAt&&(e.fatArrowAt=null);var n=t.string.indexOf("=>",t.start);if(!(n<0)){if(u){var r=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(t.string.slice(t.start,n));r&&(n=r.index)}for(var i=0,o=!1,a=n-1;a>=0;--a){var s=t.string.charAt(a),c=b.indexOf(s);if(c>=0&&c<3){if(!i){++a;break}if(0==--i){"("==s&&(o=!0);break}}else if(c>=3&&c<6)++i;else if(f.test(s))o=!0;else if(/["'\/`]/.test(s))for(;;--a){if(0==a)return;if(t.string.charAt(a-1)==s&&"\\"!=t.string.charAt(a-2)){a--;break}}else if(o&&!i){++a;break}}o&&!i&&(e.fatArrowAt=a)}}var O={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,import:!0,"jsonld-keyword":!0};function x(t,e,n,r,i,o){this.indented=t,this.column=e,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function C(t,e){if(!l)return!1;for(var n=t.localVars;n;n=n.next)if(n.name==e)return!0;for(var r=t.context;r;r=r.prev)for(n=r.vars;n;n=n.next)if(n.name==e)return!0}function k(t,e,n,r,i){var o=t.cc;for(S.state=t,S.stream=i,S.marked=null,S.cc=o,S.style=e,t.lexical.hasOwnProperty("align")||(t.lexical.align=!0);1;)if((o.length?o.pop():c?z:B)(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return S.marked?S.marked:"variable"==n&&C(t,r)?"variable-2":e}}var S={state:null,column:null,marked:null,cc:null};function j(){for(var t=arguments.length-1;t>=0;t--)S.cc.push(arguments[t])}function P(){return j.apply(null,arguments),!0}function _(t,e){for(var n=e;n;n=n.next)if(n.name==t)return!0;return!1}function T(t){var e=S.state;if(S.marked="def",l){if(e.context)if("var"==e.lexical.info&&e.context&&e.context.block){var r=function t(e,n){if(n){if(n.block){var r=t(e,n.prev);return r?r==n.prev?n:new D(r,n.vars,!0):null}return _(e,n.vars)?n:new D(n.prev,new M(e,n.vars),!1)}return null}(t,e.context);if(null!=r)return void(e.context=r)}else if(!_(t,e.localVars))return void(e.localVars=new M(t,e.localVars));n.globalVars&&!_(t,e.globalVars)&&(e.globalVars=new M(t,e.globalVars))}}function E(t){return"public"==t||"private"==t||"protected"==t||"abstract"==t||"readonly"==t}function D(t,e,n){this.prev=t,this.vars=e,this.block=n}function M(t,e){this.name=t,this.next=e}var A=new M("this",new M("arguments",null));function L(){S.state.context=new D(S.state.context,S.state.localVars,!1),S.state.localVars=A}function R(){S.state.context=new D(S.state.context,S.state.localVars,!0),S.state.localVars=null}function N(){S.state.localVars=S.state.context.vars,S.state.context=S.state.context.prev}function I(t,e){var n=function(){var n=S.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new x(r,S.stream.column(),t,null,n.lexical,e)};return n.lex=!0,n}function F(){var t=S.state;t.lexical.prev&&(")"==t.lexical.type&&(t.indented=t.lexical.indented),t.lexical=t.lexical.prev)}function V(t){return function e(n){return n==t?P():";"==t||"}"==n||")"==n||"]"==n?j():P(e)}}function B(t,e){return"var"==t?P(I("vardef",e),kt,V(";"),F):"keyword a"==t?P(I("form"),W,B,F):"keyword b"==t?P(I("form"),B,F):"keyword d"==t?S.stream.match(/^\s*$/,!1)?P():P(I("stat"),q,V(";"),F):"debugger"==t?P(V(";")):"{"==t?P(I("}"),R,ct,F,N):";"==t?P():"if"==t?("else"==S.state.lexical.info&&S.state.cc[S.state.cc.length-1]==F&&S.state.cc.pop()(),P(I("form"),W,B,F,Et)):"function"==t?P(Lt):"for"==t?P(I("form"),R,Dt,B,N,F):"class"==t||u&&"interface"==e?(S.marked="keyword",P(I("form","class"==t?t:e),Vt,F)):"variable"==t?u&&"declare"==e?(S.marked="keyword",P(B)):u&&("module"==e||"enum"==e||"type"==e)&&S.stream.match(/^\s*\w/,!1)?(S.marked="keyword","enum"==e?P(Xt):"type"==e?P(Nt,V("operator"),dt,V(";")):P(I("form"),St,V("{"),I("}"),ct,F,F)):u&&"namespace"==e?(S.marked="keyword",P(I("form"),z,B,F)):u&&"abstract"==e?(S.marked="keyword",P(B)):P(I("stat"),et):"switch"==t?P(I("form"),W,V("{"),I("}","switch"),R,ct,F,F,N):"case"==t?P(z,V(":")):"default"==t?P(V(":")):"catch"==t?P(I("form"),L,H,B,F,N):"export"==t?P(I("stat"),Ut,F):"import"==t?P(I("stat"),$t,F):"async"==t?P(B):"@"==e?P(z,B):j(I("stat"),z,V(";"),F)}function H(t){if("("==t)return P(It,V(")"))}function z(t,e){return $(t,e,!1)}function U(t,e){return $(t,e,!0)}function W(t){return"("!=t?j():P(I(")"),q,V(")"),F)}function $(t,e,n){if(S.state.fatArrowAt==S.stream.start){var r=n?Z:X;if("("==t)return P(L,I(")"),at(It,")"),F,V("=>"),r,N);if("variable"==t)return j(L,St,V("=>"),r,N)}var i=n?K:G;return O.hasOwnProperty(t)?P(i):"function"==t?P(Lt,i):"class"==t||u&&"interface"==e?(S.marked="keyword",P(I("form"),Ft,F)):"keyword c"==t||"async"==t?P(n?U:z):"("==t?P(I(")"),q,V(")"),F,i):"operator"==t||"spread"==t?P(n?U:z):"["==t?P(I("]"),Jt,F,i):"{"==t?st(rt,"}",null,i):"quasi"==t?j(Y,i):"new"==t?P(function(t){return function(e){return"."==e?P(t?tt:Q):"variable"==e&&u?P(Ot,t?K:G):j(t?U:z)}}(n)):P()}function q(t){return t.match(/[;\}\)\],]/)?j():j(z)}function G(t,e){return","==t?P(q):K(t,e,!1)}function K(t,e,n){var r=0==n?G:K,i=0==n?z:U;return"=>"==t?P(L,n?Z:X,N):"operator"==t?/\+\+|--/.test(e)||u&&"!"==e?P(r):u&&"<"==e&&S.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?P(I(">"),at(dt,">"),F,r):"?"==e?P(z,V(":"),i):P(i):"quasi"==t?j(Y,r):";"!=t?"("==t?st(U,")","call",r):"."==t?P(nt,r):"["==t?P(I("]"),q,V("]"),F,r):u&&"as"==e?(S.marked="keyword",P(dt,r)):"regexp"==t?(S.state.lastType=S.marked="operator",S.stream.backUp(S.stream.pos-S.stream.start-1),P(i)):void 0:void 0}function Y(t,e){return"quasi"!=t?j():"${"!=e.slice(e.length-2)?P(Y):P(q,J)}function J(t){if("}"==t)return S.marked="string-2",S.state.tokenize=y,P(Y)}function X(t){return w(S.stream,S.state),j("{"==t?B:z)}function Z(t){return w(S.stream,S.state),j("{"==t?B:U)}function Q(t,e){if("target"==e)return S.marked="keyword",P(G)}function tt(t,e){if("target"==e)return S.marked="keyword",P(K)}function et(t){return":"==t?P(F,B):j(G,V(";"),F)}function nt(t){if("variable"==t)return S.marked="property",P()}function rt(t,e){return"async"==t?(S.marked="property",P(rt)):"variable"==t||"keyword"==S.style?(S.marked="property","get"==e||"set"==e?P(it):(u&&S.state.fatArrowAt==S.stream.start&&(n=S.stream.match(/^\s*:\s*/,!1))&&(S.state.fatArrowAt=S.stream.pos+n[0].length),P(ot))):"number"==t||"string"==t?(S.marked=s?"property":S.style+" property",P(ot)):"jsonld-keyword"==t?P(ot):u&&E(e)?(S.marked="keyword",P(rt)):"["==t?P(z,lt,V("]"),ot):"spread"==t?P(U,ot):"*"==e?(S.marked="keyword",P(rt)):":"==t?j(ot):void 0;var n}function it(t){return"variable"!=t?j(ot):(S.marked="property",P(Lt))}function ot(t){return":"==t?P(U):"("==t?j(Lt):void 0}function at(t,e,n){function r(i,o){if(n?n.indexOf(i)>-1:","==i){var a=S.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),P((function(n,r){return n==e||r==e?j():j(t)}),r)}return i==e||o==e?P():n&&n.indexOf(";")>-1?j(t):P(V(e))}return function(n,i){return n==e||i==e?P():j(t,r)}}function st(t,e,n){for(var r=3;r"),dt):"quasi"==t?j(mt,wt):void 0}function pt(t){if("=>"==t)return P(dt)}function gt(t){return t.match(/[\}\)\]]/)?P():","==t||";"==t?P(gt):j(vt,gt)}function vt(t,e){return"variable"==t||"keyword"==S.style?(S.marked="property",P(vt)):"?"==e||"number"==t||"string"==t?P(vt):":"==t?P(dt):"["==t?P(V("variable"),ut,V("]"),vt):"("==t?j(Rt,vt):t.match(/[;\}\)\],]/)?void 0:P()}function mt(t,e){return"quasi"!=t?j():"${"!=e.slice(e.length-2)?P(mt):P(dt,yt)}function yt(t){if("}"==t)return S.marked="string-2",S.state.tokenize=y,P(mt)}function bt(t,e){return"variable"==t&&S.stream.match(/^\s*[?:]/,!1)||"?"==e?P(bt):":"==t?P(dt):"spread"==t?P(bt):j(dt)}function wt(t,e){return"<"==e?P(I(">"),at(dt,">"),F,wt):"|"==e||"."==t||"&"==e?P(dt):"["==t?P(dt,V("]"),wt):"extends"==e||"implements"==e?(S.marked="keyword",P(dt)):"?"==e?P(dt,V(":"),dt):void 0}function Ot(t,e){if("<"==e)return P(I(">"),at(dt,">"),F,wt)}function xt(){return j(dt,Ct)}function Ct(t,e){if("="==e)return P(dt)}function kt(t,e){return"enum"==e?(S.marked="keyword",P(Xt)):j(St,lt,_t,Tt)}function St(t,e){return u&&E(e)?(S.marked="keyword",P(St)):"variable"==t?(T(e),P()):"spread"==t?P(St):"["==t?st(Pt,"]"):"{"==t?st(jt,"}"):void 0}function jt(t,e){return"variable"!=t||S.stream.match(/^\s*:/,!1)?("variable"==t&&(S.marked="property"),"spread"==t?P(St):"}"==t?j():"["==t?P(z,V(']'),V(':'),jt):P(V(":"),St,_t)):(T(e),P(_t))}function Pt(){return j(St,_t)}function _t(t,e){if("="==e)return P(U)}function Tt(t){if(","==t)return P(kt)}function Et(t,e){if("keyword b"==t&&"else"==e)return P(I("form","else"),B,F)}function Dt(t,e){return"await"==e?P(Dt):"("==t?P(I(")"),Mt,F):void 0}function Mt(t){return"var"==t?P(kt,At):"variable"==t?P(At):j(At)}function At(t,e){return")"==t?P():";"==t?P(At):"in"==e||"of"==e?(S.marked="keyword",P(z,At)):j(z,At)}function Lt(t,e){return"*"==e?(S.marked="keyword",P(Lt)):"variable"==t?(T(e),P(Lt)):"("==t?P(L,I(")"),at(It,")"),F,ft,B,N):u&&"<"==e?P(I(">"),at(xt,">"),F,Lt):void 0}function Rt(t,e){return"*"==e?(S.marked="keyword",P(Rt)):"variable"==t?(T(e),P(Rt)):"("==t?P(L,I(")"),at(It,")"),F,ft,N):u&&"<"==e?P(I(">"),at(xt,">"),F,Rt):void 0}function Nt(t,e){return"keyword"==t||"variable"==t?(S.marked="type",P(Nt)):"<"==e?P(I(">"),at(xt,">"),F):void 0}function It(t,e){return"@"==e&&P(z,It),"spread"==t?P(It):u&&E(e)?(S.marked="keyword",P(It)):u&&"this"==t?P(lt,_t):j(St,lt,_t)}function Ft(t,e){return"variable"==t?Vt(t,e):Bt(t,e)}function Vt(t,e){if("variable"==t)return T(e),P(Bt)}function Bt(t,e){return"<"==e?P(I(">"),at(xt,">"),F,Bt):"extends"==e||"implements"==e||u&&","==t?("implements"==e&&(S.marked="keyword"),P(u?dt:z,Bt)):"{"==t?P(I("}"),Ht,F):void 0}function Ht(t,e){return"async"==t||"variable"==t&&("static"==e||"get"==e||"set"==e||u&&E(e))&&S.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(S.marked="keyword",P(Ht)):"variable"==t||"keyword"==S.style?(S.marked="property",P(zt,Ht)):"number"==t||"string"==t?P(zt,Ht):"["==t?P(z,lt,V("]"),zt,Ht):"*"==e?(S.marked="keyword",P(Ht)):u&&"("==t?j(Rt,Ht):";"==t||","==t?P(Ht):"}"==t?P():"@"==e?P(z,Ht):void 0}function zt(t,e){if("!"==e)return P(zt);if("?"==e)return P(zt);if(":"==t)return P(dt,_t);if("="==e)return P(U);var n=S.state.lexical.prev;return j(n&&"interface"==n.info?Rt:Lt)}function Ut(t,e){return"*"==e?(S.marked="keyword",P(Yt,V(";"))):"default"==e?(S.marked="keyword",P(z,V(";"))):"{"==t?P(at(Wt,"}"),Yt,V(";")):j(B)}function Wt(t,e){return"as"==e?(S.marked="keyword",P(V("variable"))):"variable"==t?j(U,Wt):void 0}function $t(t){return"string"==t?P():"("==t?j(z):"."==t?j(G):j(qt,Gt,Yt)}function qt(t,e){return"{"==t?st(qt,"}"):("variable"==t&&T(e),"*"==e&&(S.marked="keyword"),P(Kt))}function Gt(t){if(","==t)return P(qt,Gt)}function Kt(t,e){if("as"==e)return S.marked="keyword",P(qt)}function Yt(t,e){if("from"==e)return S.marked="keyword",P(z)}function Jt(t){return"]"==t?P():j(at(U,"]"))}function Xt(){return j(I("form"),St,V("{"),I("}"),at(Zt,"}"),F,F)}function Zt(){return j(St,_t)}function Qt(t,e,n){return e.tokenize==v&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(e.lastType)||"quasi"==e.lastType&&/\{\s*$/.test(t.string.slice(0,t.pos-(n||0)))}return N.lex=!0,F.lex=!0,{startState:function(t){var e={tokenize:v,lastType:"sof",cc:[],lexical:new x((t||0)-o,0,"block",!1),localVars:n.localVars,context:n.localVars&&new D(null,null,!1),indented:t||0};return n.globalVars&&"object"==typeof n.globalVars&&(e.globalVars=n.globalVars),e},token:function(t,e){if(t.sol()&&(e.lexical.hasOwnProperty("align")||(e.lexical.align=!1),e.indented=t.indentation(),w(t,e)),e.tokenize!=m&&t.eatSpace())return null;var n=e.tokenize(t,e);return"comment"==r?n:(e.lastType="operator"!=r||"++"!=i&&"--"!=i?r:"incdec",k(e,n,r,i,t))},indent:function(e,r){if(e.tokenize==m||e.tokenize==y)return t.Pass;if(e.tokenize!=v)return 0;var i,s=r&&r.charAt(0),c=e.lexical;if(!/^\s*else\b/.test(r))for(var l=e.cc.length-1;l>=0;--l){var u=e.cc[l];if(u==F)c=c.prev;else if(u!=Et&&u!=N)break}for(;("stat"==c.type||"form"==c.type)&&("}"==s||(i=e.cc[e.cc.length-1])&&(i==G||i==K)&&!/^[,\.=+\-*:?[\(]/.test(r));)c=c.prev;a&&")"==c.type&&"stat"==c.prev.type&&(c=c.prev);var f=c.type,h=s==f;return"vardef"==f?c.indented+("operator"==e.lastType||","==e.lastType?c.info.length+1:0):"form"==f&&"{"==s?c.indented:"form"==f?c.indented+o:"stat"==f?c.indented+(function(t,e){return"operator"==t.lastType||","==t.lastType||d.test(e.charAt(0))||/[,.]/.test(e.charAt(0))}(e,r)?a||o:0):"switch"!=c.info||h||0==n.doubleIndentSwitch?c.align?c.column+(h?0:1):c.indented+(h?0:o):c.indented+(/^(?:case|default)\b/.test(r)?o:2*o)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:c?null:"/*",blockCommentEnd:c?null:"*/",blockCommentContinue:c?null:" * ",lineComment:c?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:c?"json":"javascript",jsonldMode:s,jsonMode:c,expressionAllowed:Qt,skipExpression:function(e){k(e,"atom","atom","true",new t.StringStream("",2,null))}}})),t.registerHelper("wordChars","javascript",/[\w$]/),t.defineMIME("text/javascript","javascript"),t.defineMIME("text/ecmascript","javascript"),t.defineMIME("application/javascript","javascript"),t.defineMIME("application/x-javascript","javascript"),t.defineMIME("application/ecmascript","javascript"),t.defineMIME("application/json",{name:"javascript",json:!0}),t.defineMIME("application/x-json",{name:"javascript",json:!0}),t.defineMIME("application/manifest+json",{name:"javascript",json:!0}),t.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),t.defineMIME("text/typescript",{name:"javascript",typescript:!0}),t.defineMIME("application/typescript",{name:"javascript",typescript:!0})}(n(28))},function(t,e,n){1&&function(t){t.extendMode("css",{commentStart:"/*",commentEnd:"*/",newlineAfterToken:function(t,e){return/^[;{}]$/.test(e)}}),t.extendMode("javascript",{commentStart:"/*",commentEnd:"*/",newlineAfterToken:function(t,e,n,r){return this.jsonMode?/^[\[,{]$/.test(e)||/^}/.test(n):(";"!=e||!r.lexical||")"!=r.lexical.type)&&/^[;{}]$/.test(e)&&!/^;/.test(n)}});var e=/^(a|abbr|acronym|area|base|bdo|big|br|button|caption|cite|code|col|colgroup|dd|del|dfn|em|frame|hr|iframe|img|input|ins|kbd|label|legend|link|map|object|optgroup|option|param|q|samp|script|select|small|span|strong|sub|sup|textarea|tt|var)$/;t.extendMode("xml",{commentStart:"\x3c!--",commentEnd:"--\x3e",newlineAfterToken:function(t,n,r,i){var o=!1;return"html"==this.configuration&&(o=!!i.context&&e.test(i.context.tagName)),!o&&("tag"==t&&/>$/.test(n)&&i.context||/^-1&&s>-1&&s>a&&(t=t.substr(0,a)+t.substring(a+o.commentStart.length,s)+t.substr(s+o.commentEnd.length)),i.replaceRange(t,n,r)}}))})),t.defineExtension("autoIndentRange",(function(t,e){var n=this;this.operation((function(){for(var r=t.line;r<=e.line;r++)n.indentLine(r,"smart")}))})),t.defineExtension("autoFormatRange",(function(e,n){var r=this,i=r.getMode(),o=r.getRange(e,n).split("\n"),a=t.copyState(i,r.getTokenAt(e).state),s=r.getOption("tabSize"),c="",l=0,u=0===e.ch;function f(){c+="\n",u=!0,++l}for(var h=0;h=0;--o){var a=this.tryEntries[o],s=a.completion;if("root"===a.tryLoc)return i("end");if(a.tryLoc<=this.prev){var c=r.call(a,"catchLoc"),l=r.call(a,"finallyLoc");if(c&&l){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,"finallyLoc")&&this.prev=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),P(n),g}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;P(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,n,r){return this.delegate={iterator:T(t),resultName:n,nextLoc:r},"next"===this.method&&(this.arg=e),g}},t}(1?t.exports:void 0);try{regeneratorRuntime=r}catch(t){Function("r","regeneratorRuntime = r")(r)}},function(t,e,n){"use strict";n.r(e);var r=n(3),i=n(10);e["default"]=r["View"].extend({initialize:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.items=[],this.opt=t;var e=t.config||{};this.level=t.level,this.config=e,this.preview=t.preview,this.ppfx=e.pStylePrefix||'',this.pfx=e.stylePrefix||'',this.parent=t.parent,this.parentView=t.parentView;var n=this.pfx,r=this.ppfx,o=this.parent,a=this.collection;this.listenTo(a,'add',this.addTo),this.listenTo(a,'reset resetNavigator',this.render),this.listenTo(a,'remove',this.removeChildren),this.className="".concat(n,"layers");var s=e.em;if(e.sortable&&!this.opt.sorter){var c=s.get('Utils');this.opt.sorter=new c.Sorter({container:e.sortContainer||this.el,containerSel:".".concat(this.className),itemSel:".".concat(n,"layer"),ignoreViewChildren:1,onEndMove:function(t,e,n){var r=e.getSourceModel();s.setSelected(r,{forceChange:1}),s.trigger("".concat(i["b"],":end"),n)},avoidSelectOnEnd:1,nested:1,ppfx:r,pfx:n})}this.sorter=this.opt.sorter||'',this.$el.data('collection',a),o&&this.$el.data('model',o)},removeChildren:function(t){var e=t.viewLayer;e&&(e.remove(),t.viewLayer=0)},addTo:function(t){var e=this.collection.indexOf(t);this.addToCollection(t,null,e)},addToCollection:function(t,e,n){var r=this.level,i=this.parentView,o=this.opt.ItemView,a=e||null,s=new o({ItemView:o,level:r,model:t,parentView:i,config:this.config,sorter:this.sorter,isCountable:this.isCountable,opened:this.opt.opened}),c=s.render().el;if(a)a.appendChild(c);else if(void 0!==n){var l='before';this.$el.children().length==n&&(n--,l='after'),n<0?this.$el.append(c):this.$el.children().eq(n)[l](c)}else this.$el.append(c);return this.items.push(s),c},remove:function(){r["View"].prototype.remove.apply(this,arguments),this.items.map((function(t){return t.remove()}))},isCountable:function(t,e){var n=t.get('type'),r=t.get('tagName');return!(('textnode'==n||'br'==r)&&e||!t.get('layerable'))},render:function(){var t=this,e=document.createDocumentFragment(),n=this.el;return n.innerHTML='',this.collection.each((function(n){return t.addToCollection(n,e)})),n.appendChild(e),n.className=this.className,this}})},function(t,e,n){var r={"./CanvasClear":51,"./CanvasClear.js":51,"./CanvasMove":52,"./CanvasMove.js":52,"./CommandAbstract":31,"./CommandAbstract.js":31,"./ComponentDelete":53,"./ComponentDelete.js":53,"./ComponentDrag":54,"./ComponentDrag.js":54,"./ComponentEnter":55,"./ComponentEnter.js":55,"./ComponentExit":56,"./ComponentExit.js":56,"./ComponentNext":57,"./ComponentNext.js":57,"./ComponentPrev":58,"./ComponentPrev.js":58,"./ComponentStyleClear":59,"./ComponentStyleClear.js":59,"./CopyComponent":60,"./CopyComponent.js":60,"./DeleteComponent":61,"./DeleteComponent.js":61,"./ExportTemplate":62,"./ExportTemplate.js":62,"./Fullscreen":63,"./Fullscreen.js":63,"./MoveComponent":64,"./MoveComponent.js":64,"./OpenAssets":65,"./OpenAssets.js":65,"./OpenBlocks":66,"./OpenBlocks.js":66,"./OpenLayers":67,"./OpenLayers.js":67,"./OpenStyleManager":68,"./OpenStyleManager.js":68,"./OpenTraitManager":69,"./OpenTraitManager.js":69,"./PasteComponent":70,"./PasteComponent.js":70,"./Preview":71,"./Preview.js":71,"./Resize":72,"./Resize.js":72,"./SelectComponent":23,"./SelectComponent.js":23,"./SelectPosition":35,"./SelectPosition.js":35,"./ShowOffset":73,"./ShowOffset.js":73,"./SwitchVisibility":74,"./SwitchVisibility.js":74};function i(t){var e=o(t);return n(e)}function o(t){if(!n.o(r,t)){var e=new Error("Cannot find module '"+t+"'");throw e.code='MODULE_NOT_FOUND',e}return r[t]}i.keys=function(){return Object.keys(r)},i.resolve=o,t.exports=i,i.id=97},function(t,e,n){"use strict";n.r(e);var r=n(2),i=n.n(r),o=n(14),a=n.n(o),s=n(0),c={stylePrefix:'comp-',components:[],draggableComponents:1,storeWrapper:0,processor:0,voidElements:['area','base','br','col','embed','hr','img','input','keygen','link','menuitem','meta','param','source','track','wbr']},l=n(10),u=n(27),f=n(12),h=n(40),d=n(1);function p(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function g(t){for(var e=1;e=0}}),m=f["default"].extend({});function y(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function b(t){for(var e=1;e\n \n "),fallback:"\n \n "),file:''}),initialize:function(t,e){l["a"].prototype.initialize.apply(this,arguments);var n=this.get('attributes'),r=n.src;r&&this.set('src',r,{silent:1})},initToolbar:function(){for(var t=arguments.length,e=new Array(t),n=0;n0&&void 0!==arguments[0]?arguments[0]:{},e=this.get(t.fallback?'fallback':'src')||'',n=e;return e&&'2&&void 0!==arguments[2]?arguments[2]:{};!n.fromDisable&&this.disableEditing()},canActivate:function(){var t,e=this.model,n=this.rteEnabled,r=this.em,i=(null==r?void 0:r.getEditing())===e,o=!0,a=!1;if((n||!e.get('editable')||i||(a=e.isChildOf('text')))&&(o=!1,a&&!e.get('textable'))){for(var s=e.parent();s&&!s.isInstanceOf('text');)s=s.parent();t=s}return{result:o,delegate:t}},onActive:function(t){var e=this;return pt()(vt.a.mark((function n(){var r,i,o,a,s,c;return vt.a.wrap((function(n){for(;1;)switch(n.prev=n.next){case 0:if(i=e.rte,o=e.em,a=e.canActivate(),s=a.result,c=a.delegate,s){n.next=5;break}return c&&(o.setSelected(c),c.trigger('active',t)),n.abrupt("return");case 5:if(null==t||null===(r=t.stopPropagation)||void 0===r||r.call(t),e.lastContent=e.getContent(),!i){n.next=17;break}return n.prev=8,n.next=11,i.enable(e,e.activeRte,{event:t});case 11:e.activeRte=n.sent,n.next=17;break;case 14:n.prev=14,n.t0=n["catch"](8),o.logError(n.t0);case 17:e.toggleEvents(1);case 18:case"end":return n.stop()}}),n,null,[[8,14]])})))()},onDisable:function(){this.disableEditing()},disableEditing:function(){var t=arguments,e=this;return pt()(vt.a.mark((function n(){var r,i,o,a,s,c;return vt.a.wrap((function(n){for(;1;)switch(n.prev=n.next){case 0:if(r=t.length>0&&void 0!==t[0]?t[0]:{},i=e.model,o=e.rte,a=e.activeRte,s=e.em,c=i&&i.get('editable'),!o){n.next=13;break}return n.prev=4,n.next=7,o.disable(e,a);case 7:n.next=12;break;case 9:n.prev=9,n.t0=n["catch"](4),s.logError(n.t0);case 12:c&&e.getContent()!==e.lastContent&&(e.syncContent(r),e.lastContent='');case 13:e.toggleEvents();case 14:case"end":return n.stop()}}),n,null,[[4,9]])})))()},getContent:function(){var t=this.activeRte;return t&&'function'==typeof t.getContent?t.getContent():this.getChildrenContainer().innerHTML},syncContent:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.model,n=this.rte,r=this.rteEnabled;if(r||t.force){var i=this.getContent(),o=e.components(),a=yt({fromDisable:1},t);e.set('content','',a),n.customRte?(o.length&&o.reset(null,t),e.set('content',i,a)):o.resetFromString(i,t)}},insertComponent:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.model,r=this.el,i=r.ownerDocument,o=i.getSelection();if(null!=o&&o.rangeCount){var a,s=o.getRangeAt(0),c=s.startContainer,l=s.startOffset,u=Object(d["getModel"])(c),f=[];if(u&&null!==(a=u.is)&&void 0!==a&&a.call(u,'textnode')){var h=u.collection;h.forEach((function(e){if(e===u){var n='textnode',r=e.get('content');f.push({type:n,content:r.slice(0,l)}),f.push(t),f.push({type:n,content:r.slice(l)})}else f.push(e)}));var p=f.filter(Boolean),g=p.indexOf(t);return h.reset(p,e),h.at(g)}}return n.append(t,e)},onInput:function(){var t=this.em,e='component',n=["".concat(e,":update"),"".concat(e,":input")].join(' ');t&&t.trigger(n,this.model)},disablePropagation:function(t){t.stopPropagation()},toggleEvents:function(t){var e=this.em,n=this.model,r=this.$el,i={on:d["on"],off:d["off"]},o=t?'on':'off';e.setEditing(t?this:0),this.rteEnabled=!!t;var a=[this.el.ownerDocument,document];if(i.off(a,'mousedown',this.onDisable),i[o](a,'mousedown',this.onDisable),e[o]('toolbar:run:before',this.onDisable),n&&(n[o]('removed',this.onDisable),n.trigger("rte:".concat(t?'enable':'disable'))),r&&r.off('mousedown',this.disablePropagation),r&&r[o]('mousedown',this.disablePropagation),this.config.draggableComponents)for(var s=this.el;s;)s.draggable=!t,(s=s.parentNode)&&'BODY'==s.tagName&&(s=0)}}),Ot=wt.extend({render:function(){for(var t=arguments.length,e=new Array(t),n=0;n1&&void 0!==arguments[1]?arguments[1]:{};return!!e.inSvg}}),Gt=f["default"].extend({_createElement:function(t){return document.createElementNS('http://www.w3.org/2000/svg',t)}});function Kt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Yt(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:'',e=this.em,n='';!t&&r.stm&&(t=r.em.getCacheLoad());var i=t,o=i.components,a=i.html;if(o)if(Object(s["isObject"])(o)||Object(s["isArray"])(o))n=o;else try{n=JSON.parse(o)}catch(t){e&&e.logError(t)}else a&&(n=a);var c=n&&n.constructor===Object;return(n&&n.length||c)&&(this.clear(),c?this.getWrapper().set(n):this.getComponents().add(n)),n},store:function(t){if(!r.stm||this.em.get('hasPages'))return{};var e={},n=this.storageKey();if(n.indexOf('html')>=0&&(e.html=r.em.getHtml()),n.indexOf('components')>=0){var i=r.storeWrapper?this.getWrapper():this.getComponents();e.components=JSON.stringify(i)}return t||r.stm.store(e),e},getComponent:function(){var t=this.em.get('PageManager').getSelected(),e=t&&t.getMainFrame();return e&&e.getComponent()},getWrapper:function(){return this.getComponent()},getComponents:function(){var t=this.getWrapper();return t&&t.get('components')},addComponent:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.getComponents().add(t,e)},render:function(){return n.render().el},clear:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.getComponents().map((function(t){return t})).forEach((function(e){return e.remove(t)})),this},setComponents:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.clear(e).addComponent(t,e)},addType:function(t,e){var n=this.em,r=e.model,i=void 0===r?{}:r,c=e.view,l=void 0===c?{}:c,u=e.isComponent,f=e.extend,h=e.extendView,d=e.extendFn,p=void 0===d?[]:d,g=e.extendFnView,v=void 0===g?[]:g,m=this.getType(t),y=this.getType(f),b=this.getType(h),w=y||(m||this.getType('default')),O=w.model,x=b?b.view:w.view,C=function(t,e,n){return t.reduce((function(t,r){var i=e[r],o=n.prototype[r];return i&&o&&(t[r]=function(){o.bind(this).apply(void 0,arguments),i.bind(this).apply(void 0,arguments)}),t}),{})};'object'===a()(i)&&(e.model=O.extend(fe(fe(fe({},i),C(p,i,O)),{},{defaults:fe(fe({},Object(s["result"])(O.prototype,'defaults')||{}),Object(s["result"])(i,'defaults')||{})}),{isComponent:!m||y||u?u||function(){return 0}:O.isComponent})),'object'===a()(l)&&(e.view=x.extend(fe(fe({},l),C(v,l,x)))),m?(m.model=e.model,m.view=e.view):(e.id=t,o.unshift(e));var k="component:type:".concat(m?'update':'add');return n&&n.trigger(k,m||e),this},getType:function(t){for(var e=o,n=0;n1&&void 0!==arguments[1]?arguments[1]:{};t&&(t.set({status:'selected'}),['component:selected','component:toggled'].forEach((function(r){return e.em.trigger(r,t,n)})))},selectRemove:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t){this.em;t.set({status:'',state:''}),['component:deselected','component:toggled'].forEach((function(r){return e.em.trigger(r,t,n)}))}},componentHovered:function(){var t=r.em,e=t.get('componentHovered'),n=t.previous('componentHovered'),i='hovered';n&&n.get('status')==i&&n.set({status:'',state:''}),e&&Object(s["isEmpty"])(e.get('status'))&&e.set('status',i)},getShallowWrapper:function(){var t=this.shallow,e=this.em;if(!t&&e){var n=e.get('shallow');if(!n)return;var r=n.get('DomComponents');if(r.componentTypes=this.componentTypes,t=r.getWrapper()){var i=[l["c"],l["d"]].join(' ');t.on(i,Object(s["debounce"])((function(){return t.components('')}),100))}this.shallow=t}return t},canMove:function(t,e,n){var r=n||0===n?n:null,i={result:!1,reason:0,target:t,source:null};if(!e)return i;var o=null!=e&&e.toHTML?e:null;if(!o){var a=this.getShallowWrapper();o=null==a?void 0:a.append(e)[0]}if(i.source=o,!o)return i;var c=o.get('draggable');if(Object(s["isFunction"])(c))c=!!c(o,t,r);else{var l=t.getEl();c=Object(s["isArray"])(c)?c.join(','):c,c=Object(s["isString"])(c)?null==l?void 0:l.matches(c):c}if(!c)return fe(fe({},i),{},{reason:1});var u=t.get('droppable');if(Object(s["isFunction"])(u))u=!!u(o,t,r);else if(!1===u&&t.isInstanceOf('text')&&o.get('textable'))u=!0;else{var f=o.getEl();u=Object(s["isArray"])(u)?u.join(','):u,u=Object(s["isString"])(u)?null==f?void 0:f.matches(u):u}return fe(fe({},i),{},u?{result:!0}:{reason:2})},allById:function(){return i},getById:function(t){return i[t]||null},destroy:function(){var o=this.allById();Object.keys(o).forEach((function(t){return o[t]&&o[t].remove()})),n&&n.remove(),[r,t,i,e,n].forEach((function(t){return{}})),this.em={}}}}},function(t,e,n){"use strict";n.r(e),n.d(e,"evAll",(function(){return Ce})),n.d(e,"evPfx",(function(){return ke})),n.d(e,"evSector",(function(){return Se})),n.d(e,"evSectorAdd",(function(){return je})),n.d(e,"evSectorRemove",(function(){return Pe})),n.d(e,"evSectorUpdate",(function(){return _e})),n.d(e,"evProp",(function(){return Te})),n.d(e,"evPropAdd",(function(){return Ee})),n.d(e,"evPropRemove",(function(){return De})),n.d(e,"evPropUp",(function(){return Me})),n.d(e,"evLayerSelect",(function(){return Ae})),n.d(e,"evTarget",(function(){return Le})),n.d(e,"evCustom",(function(){return Re}));var r=n(11),i=n.n(r),o=n(2),a=n.n(o),s=n(0),c=n(1),l=n(22),u=n(3),f=n.n(u),h={sectors:[{name:'General',open:!1,properties:['display','float','position','top','right','left','bottom']},{name:'Flex',open:!1,properties:['flex-direction','flex-wrap','justify-content','align-items','align-content','order','flex-basis','flex-grow','flex-shrink','align-self']},{name:'Dimension',open:!1,properties:['width','height','max-width','min-height','margin','padding']},{name:'Typography',open:!1,properties:['font-family','font-size','font-weight','letter-spacing','color','line-height','text-align','text-shadow']},{name:'Decorations',open:!1,properties:['background-color','border-radius','border','box-shadow','background']},{name:'Extra',open:!1,properties:['opacity','transition']}],appendTo:'',stylePrefix:'sm-',custom:!1,hideNotStylable:!0,highlightChanged:!0,highlightComputed:!0,showComputed:!0,clearProperties:!0,avoidComputed:['width','height']},d=n(18),p=n.n(d),g=n(5),v=n.n(g),m=n(6),y=n.n(m),b=n(7),w=n.n(b),O=n(8),x=n.n(O),C=n(4),k=n.n(C),S=n(37),j=["partial"];function P(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function _(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.em=e.em;var r=this.get('id')||'',i=this.get('name')||this.get('label')||'';!this.get('property')&&this.set('property',(i||r).replace(/ /g,'-'));var o=this.get('property');!this.get('id')&&this.set('id',o),!i&&this.set('name',Object(c["capitalize"])(o).replace(/-/g,' ')),this.on('change',this.__upTargets),n.callInit(this,t,e)}},{key:"__getParentProp",value:function(){var t,e;return null===(t=this.collection)||void 0===t||null===(e=t.opts)||void 0===e?void 0:e.parentProp}},{key:"__upTargets",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,o=r.get('StyleManager'),c=this.getName(),l=n.__clear,u=l?'':this.__getFullValue(n),f=this.__getParentProp(),h=this.changedAttributes(),d=Object(s["keys"])(h).reduce((function(t,n){return t[n]=e.previous(n),t}),{}),p=[].concat(i()(Object(s["keys"])(this.__getClearProps())),['__p']),g=Object(s["keys"])(h),v=!n.__up&&!f&&(l||p.some((function(t){return g.indexOf(t)>=0}))),m=this.get('onChange'),y={property:this,from:d,to:h,value:u,opts:n};o.__trgEv(o.events.propertyUpdate,y),m&&m(y),v&&this.__upTargetsStyle(a()({},c,u),n)}},{key:"__upTargetsStyle",value:function(t,e){var n,r=null===(n=this.em)||void 0===n?void 0:n.get('StyleManager');null==r||r.addStyleTargets(_(_({},t),{},{__p:!!e.avoidStore}),e)}},{key:"_up",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e.noTarget&&(e.__up=!0);var n=e.partial,r=p()(e,j);return t.__p=!(!r.avoidStore&&!n),this.set(t,_(_({},r),{},{avoidStore:t.__p}))}},{key:"up",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.set(t,_(_({},e),{},{__up:!0}))}},{key:"init",value:function(){}},{key:"getId",value:function(){return this.get('id')}},{key:"getType",value:function(){return this.get('type')}},{key:"getName",value:function(){return this.get('property')}},{key:"getLabel",value:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.locale,r=void 0===n||n,i=this.getId(),o=this.get('name')||this.get('label');return r&&(null===(t=this.em)||void 0===t?void 0:t.t("styleManager.properties.".concat(i)))||o}},{key:"getValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.noDefault,n=this.get('value');return this.hasValue()||e?n:this.getDefaultValue()}},{key:"hasValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.noParent,n=e&&this.getParentTarget(),r=this.get('value');return!Object(s["isUndefined"])(r)&&''!==r&&!n}},{key:"hasValueParent",value:function(){return this.hasValue()&&!this.hasValue({noParent:!0})}},{key:"getStyle",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.getName(),n=t.camelCase?Object(c["camelCase"])(e):e;return a()({},n,this.__getFullValue(t))}},{key:"getDefaultValue",value:function(){var t=this.get('default');return"".concat(Object(s["isUndefined"])(t)?this.get('defaults'):t)}},{key:"upValue",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null===t||''===t?this.__getClearProps():this.__parseValue(t,e);return this._up(n,e)}},{key:"isVisible",value:function(){return!!this.get('visible')}},{key:"clear",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._up(this.__getClearProps(),_(_({},t),{},{__clear:!0}))}},{key:"canClear",value:function(){var t=this.getParent();return t?t.__canClearProp(this):this.hasValue({noParent:!0})}},{key:"getParent",value:function(){return this.__getParentProp()||null}},{key:"isFull",value:function(){return!!this.get('full')}},{key:"__parseValue",value:function(t,e){return this.parseValue(t,e)}},{key:"__getClearProps",value:function(){return{value:''}}},{key:"setValue",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.parseValue(t),i=!e;!i&&this.set({value:void 0},{avoidStore:i,silent:!0}),this.set(r,_({avoidStore:i},n))}},{key:"setValueFromInput",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.setValue(t,e,_(_({},n),{},{fromInput:1}))}},{key:"parseValue",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={value:t},r='!important';if(Object(s["isString"])(t)&&-1!==t.indexOf(r)&&(n.value=t.replace(r,'').trim(),n.important=1),!this.get('functionName')&&!e.complete)return n;var i=[],o="".concat(n.value),a=o.indexOf('(')+1,c=o.lastIndexOf(')'),l=o.substring(0,a-1);if(l&&(n.functionName=l),i.push(a),c>=0&&i.push(c),n.value=String.prototype.substring.apply(o,i),e.numeric){var u=parseFloat(n.value);n.unit=n.value.replace(u,''),n.value=u}return n}},{key:"__getFullValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.withDefault;return!this.hasValue()&&e?this.getDefaultValue():this.getFullValue()}},{key:"getFullValue",value:function(t){var e=this.get('functionName'),n=this.getDefaultValue(),r=Object(s["isUndefined"])(t)?this.get('value'):t,i=!Object(s["isUndefined"])(r)&&''!==r;if(r&&n&&r===n)return n;if(e&&i){var o='url'===e?"'".concat(r.replace(/'/g,''),"'"):r;r="".concat(e,"(").concat(o,")")}return i&&this.get('important')&&(r="".concat(r," !important")),r||''}},{key:"__setParentTarget",value:function(t){this.__parentTarget=t}},{key:"getParentTarget",value:function(){return this.__parentTarget||null}},{key:"__parseFn",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:'',e=t.indexOf('(')+1,n=t.lastIndexOf(')');return{name:t.substring(0,e-1).trim(),value:String.prototype.substring.apply(t,[e,n>=0?n:void 0]).trim()}}},{key:"__checkVisibility",value:function(t){var e=t.target,n=t.component,r=t.sectors,i=n||e;if(!i)return!1;var o=this.getId(),a=this.getName(),l=this.get('toRequire'),u=this.get('requires'),f=this.get('requiresParent'),h=i.get('unstylable'),d=i.get('stylable-require'),p=i.get('stylable');if(Object(s["isArray"])(p)&&(p=p.indexOf(a)>=0),Object(s["isArray"])(h)&&(p=h.indexOf(a)<0),l&&(p=!e||d&&(d.indexOf(o)>=0||d.indexOf(a)>=0)),r&&u){var g=Object(s["keys"])(u);r.forEach((function(t){t.getProperties().forEach((function(t){if(Object(s["includes"])(g,t.id)){var e=u[t.id];p=p&&Object(s["includes"])(e,t.get('value'))}}))}))}if(f){var v=n&&n.parent(),m=v&&v.getEl();if(m){var y=Object(c["hasWin"])()?window.getComputedStyle(m):{};Object(s["each"])(f,(function(t,e){p=p&&y[e]&&Object(s["includes"])(t,y[e])}))}else p=!1}return!!p}}]),n}(u["Model"]);function D(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function M(t){for(var e=1;e3&&void 0!==arguments[3]?arguments[3]:{};t.prototype.initialize.apply(e,[n,_(_({},r),{},{skipInit:1})])},E.callInit=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!n.skipInit&&t.init(e,n)},E.getDefaults=function(){return Object(s["result"])(this.prototype,'defaults')},E.prototype.defaults={name:'',property:'',type:'',defaults:'',info:'',value:'',icon:'',functionName:'',status:'',visible:!0,fixedValues:['initial','inherit'],onChange:null,full:0,important:0,toRequire:0,requires:null,requiresParent:null};var L=function(t){return'integer'===t||'number'===t},R=function(t){w()(n,t);var e=A(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"defaults",value:function(){return M(M({},E.getDefaults()),{},{detached:!1,properties:[],separator:' ',join:null,fromStyle:null,toStyle:null,full:!0})}},{key:"initialize",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E.callParentInit(E,this,t,e);var n=this.em,r=new Jt(this.get('properties')||[],{em:n,parentProp:this});this.set('properties',r,{silent:1}),this.listenTo(r,'change',this.__upProperties),E.callInit(this,t,e)}},{key:"getProperties",value:function(){return i()(this.get('properties').models)}},{key:"getProperty",value:function(t){return this.get('properties').filter((function(e){return e.getId()===t||e.getName()===t}))[0]||null}},{key:"getPropertyAt",value:function(t){return this.get('properties').at(t)}},{key:"isDetached",value:function(){return!!this.get('detached')}},{key:"getValues",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.byName;return this.getProperties().reduce((function(t,n){return t[e?n.getName():n.getId()]="".concat(n.__getFullValue()),t}),{})}},{key:"getSeparator",value:function(){return this.getSplitSeparator()}},{key:"getJoin",value:function(){return this.__getJoin()}},{key:"getStyleFromProps",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.getName(),n=this.__getJoin(),r=this.get('toStyle'),i=this.getValues(),o={};if(r)o=r(i,{join:n,name:e,property:this});else if(i=this.getValues({byName:!0}),this.isDetached())o=i;else{var s=this.getProperties().map((function(t){return t.__getFullValue({withDefault:1})})).filter(Boolean).join(n);o=a()({},e,s)}return this.isDetached()?o[e]='':(o[e]=o[e]||'',o=M(M({},o),this.getProperties().reduce((function(t,e){return t[e.getName()]='',t}),{}))),t.camelCase?Object.keys(o).reduce((function(t,e){return t[camelCase(e)]=o[e],t}),{}):o}},{key:"getSplitSeparator",value:function(){return new RegExp("".concat(this.get('separator'),"(?![^\\(]*\\))"))}},{key:"__upProperties",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e.__up&&!e.__clearIn){var n=this.__getParentProp();if(n)return n.__upProperties(this,e);this.__upTargetsStyleProps(e,t)}}},{key:"__upTargetsStyleProps",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0,n=this.getStyleFromProps();if(this.isDetached()&&e){var r=e.getName();n=a()({},r,n[r])}this.__upTargetsStyle(n,t)}},{key:"_up",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.__setProperties(this.__getSplitValue(t.value),e),E.prototype._up.call(this,t,e)}},{key:"getStyle",value:function(t){return this.getStyleFromProps(t)}},{key:"__getFullValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.isDetached()||t.__clear?'':this.getStyleFromProps()[this.getName()]||''}},{key:"__getJoin",value:function(){var t=this.get('join');return Object(s["isString"])(t)?t:this.get('separator')}},{key:"__styleHasProps",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.getName(),n=this.getProperties(),r=n.map((function(t){return t.getName()})),o=[e].concat(i()(r));return o.some((function(e){return!Object(s["isUndefined"])(t[e])&&''!==t[e]}))}},{key:"__splitValue",value:function(t,e){return t.split(e).map((function(t){return t.trim()})).filter(Boolean)}},{key:"__splitStyleName",value:function(t,e,n){return this.__splitValue(t[e]||'',n)}},{key:"__getSplitValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:'',e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.byName,r=this.getProperties(),i=4===r.length&&r.every((function(t){return L(t.getType())})),o=this.__splitValue(t,this.getSplitSeparator()),a={};return r.forEach((function(t,e){var r=o[e],c=Object(s["isUndefined"])(r)?'':r;if(i){var l=o.length;c=o[e]||o[e%l+(1!=l&&l%2?1:0)]||c}var u=n?t.getName():t.getId();a[u]=c||''})),a}},{key:"__getPropsFromStyle",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.__styleHasProps(t))return null;var n=e.byName,r=this.getName(),i=this.getProperties(),o=this.getSplitSeparator(),a=this.get('fromStyle'),c=a?a(t,{property:this,name:r,separator:o}):{};return a||(c=this.__getSplitValue(t[r]||'',{byName:n}),i.forEach((function(e){var r=t[e.getName()],i=n?e.getName():e.getId();Object(s["isUndefined"])(r)||''===r||(c[i]=r)}))),c}},{key:"__setProperties",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.getProperties().forEach((function(n){var r=t[n.getId()];n.__getFullValue()!==r&&n.upValue(r,e)}));var n=Object(s["keys"])(t).map((function(e){return t[e]})).join(' ');this.set('value',n,{silent:!0})}},{key:"clear",value:function(){var t=this;return this.getProperties().map((function(e){return e.clear({__clearIn:!t.isDetached()})})),E.prototype.clear.call(this)}},{key:"hasValue",value:function(t){return this.getProperties().some((function(e){return e.hasValue(t)}))}},{key:"getFullValue",value:function(){return this.__getFullValue()}},{key:"__canClearProp",value:function(t){return this.isDetached()&&t.hasValue({noParent:!0})}}]),n}(E);function N(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function I(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=this.get('values');return t.camelCase?Object.keys(e).reduce((function(t,n){return t[Object(c["camelCase"])(n)]=e[n],t}),{}):e}},{key:"getLabel",value:function(){var t;return null===(t=this.prop)||void 0===t?void 0:t.getLayerLabel(this)}},{key:"isSelected",value:function(){var t;return(null===(t=this.prop)||void 0===t?void 0:t.getSelectedLayer())===this}},{key:"select",value:function(){var t;return null===(t=this.prop)||void 0===t?void 0:t.selectLayer(this)}},{key:"remove",value:function(){var t;return null===(t=this.prop)||void 0===t?void 0:t.removeLayer(this)}},{key:"move",value:function(t){var e;return null===(e=this.prop)||void 0===e?void 0:e.moveLayer(this,t)}},{key:"getStylePreview",value:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null===(t=this.prop)||void 0===t?void 0:t.getStylePreview(this,e)}},{key:"hasPreview",value:function(){var t;return!(null===(t=this.prop)||void 0===t||!t.get('preview'))}},{key:"upValues",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.set('values',I(I({},this.getValues()),t))}}]),n}(u["Model"]);function B(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var H=function(t){w()(n,t);var e=B(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"initialize",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prop=e.prop}}]),n}(u["Collection"]);H.prototype.model=V;var z=["__layers"];function U(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function W(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};R.callParentInit(R,this,t,e);var n=this.get('layers'),r=new H(n,{prop:this});r.property=this,r.properties=this.get('properties'),this.set('layers',r,{silent:!0}),this.on('change:selectedLayer',this.__upSelected),this.listenTo(r,'add remove',this.__upLayers),R.callInit(this,t,e)}},{key:"getLayers",value:function(){return this.__getLayers().models}},{key:"__getLayers",value:function(){return this.get('layers')}},{key:"getLayer",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return this.__getLayers().at(t)||null}},{key:"getSelectedLayer",value:function(){var t=this.get('selectedLayer');return t&&t.getIndex()>=0?t:null}},{key:"selectLayer",value:function(t){return this.set('selectedLayer',t,{__select:!0})}},{key:"selectLayerAt",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this.getLayer(t);return e&&this.selectLayer(e)}},{key:"moveLayer",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=t?t.getIndex():-1;n>=0&&Object(s["isNumber"])(e)&&e>=0&&e0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={};this.getProperties().forEach((function(e){var r=e.getId(),i=t[r];n[r]=Object(s["isUndefined"])(i)?e.getDefaultValue():i}));var r=this.get('layers').push({values:n},e);return r}},{key:"removeLayer",value:function(t){return this.get('layers').remove(t)}},{key:"removeLayerAt",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=this.getLayer(t);return e?this.removeLayer(e):null}},{key:"getLayerLabel",value:function(t){var e='';if(t){var n=this.get('layerLabel'),r=t.getValues(),i=t.getIndex();if(n)e=n(t,{index:i,values:r,property:this});else{var o=[];this.getProperties().map((function(t){o.push(r[t.getId()])})),e=o.filter(Boolean).join(' ')}}return e}},{key:"getStyleFromLayer",value:function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.__getJoin(),i=this.__getJoinLayers(),o=this.get('toStyle'),l=this.getName(),u=t.getValues();if(o)e=o(u,{join:r,joinLayers:i,name:l,layer:t,property:this});else{var f=this.getProperties().map((function(t){var e=t.getName(),r=u[t.getId()],i=Object(s["isUndefined"])(r)?t.getDefaultValue():r;if(n.number&&L(t.getType())){var o=t.parseValue(r,n.number);i="".concat(o.value).concat(o.unit)}return{name:e,value:i}}));e=this.isDetached()?f.reduce((function(t,e){return t[e.name]=e.value,t}),{}):a()({},this.getName(),f.map((function(t){return t.value})).join(r))}return n.camelCase?Object.keys(e).reduce((function(t,n){return t[Object(c["camelCase"])(n)]=e[n],t}),{}):e}},{key:"getStylePreview",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={},r=this.get('preview');return r&&(n=this.getStyleFromLayer(t,e)),n}},{key:"getLayerSeparator",value:function(){var t=this.get('layerSeparator');return Object(s["isString"])(t)?new RegExp("".concat(t,"(?![^\\(]*\\))")):t}},{key:"__upProperties",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.getSelectedLayer();n&&(n.upValues(a()({},t.getId(),t.__getFullValue())),e.__up||this.__upTargetsStyleProps(e))}},{key:"__upLayers",value:function(t,e,n){this.__upTargetsStyleProps(n||e)}},{key:"__upTargets",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e.__select)return E.prototype.__upTargets.call(this,t,e)}},{key:"__upTargetsStyleProps",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.__upTargetsStyle(this.getStyleFromLayers(),t)}},{key:"__upTargetsStyle",value:function(t,e){return E.prototype.__upTargetsStyle.call(this,t,e)}},{key:"__upSelected",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.noEvent,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em.get('StyleManager'),i=this.getSelectedLayer(),o=null==i?void 0:i.getValues();o&&this.getProperties().forEach((function(t){var e=o[t.getId()];t.__getFullValue()!==e&&t.upValue(e,W(W({},n),{},{__up:!0}))})),!e&&r.__trgEv(r.events.layerSelect,{property:this})}},{key:"_up",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.__layers,r=void 0===n?[]:n,i=p()(t,z);return!this.isDetached()&&this.__setLayers(r),this.__upSelected({noEvent:!0},e),E.prototype._up.call(this,i,e)}},{key:"__setLayers",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=this.__getLayers(),n=t.map((function(t){return{values:t}}));e.length===n.length?n.map((function(t,n){var r;return null===(r=e.at(n))||void 0===r?void 0:r.upValues(t.values)})):this.__getLayers().reset(n),this.__upSelected({noEvent:!0})}},{key:"__parseValue",value:function(t){var e=this,n=this.parseValue(t);return n.__layers=t.split(q).map((function(t){return t.trim()})).map((function(t){return e.__parseLayer(t)})).filter(Boolean),n}},{key:"__parseLayer",value:function(t){var e=this.get('parseLayer'),n=t.split(G),r=this.getProperties();return e?e({value:t,values:n}):r.reduce((function(t,e,r){var i=n[r];return t[e.getId()]=Object(s["isUndefined"])(i)?e.getDefaultValue():i,t}),{})}},{key:"__getLayersFromStyle",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this.__styleHasProps(e))return null;var n=this.getName(),r=this.getProperties(),i=this.getLayerSeparator(),o=this.get('fromStyle'),c=o?o(e,{property:this,name:n,separatorLayers:i}):[];if(!o){var l=this.__splitStyleName(e,n,i).map((function(e){return e.split(t.getSplitSeparator())})).map((function(t){var e={};return r.forEach((function(n,r){var i=t[r];e[n.getId()]=Object(s["isUndefined"])(i)?n.getDefaultValue():i})),e}));r.forEach((function(n){var r=n.getId();t.__splitStyleName(e,n.getName(),i).map((function(t){return a()({},r,t||n.getDefaultValue())})).forEach((function(t,e){l[e]=l[e]?W(W({},l[e]),t):t}))})),c=l}return Object(s["isArray"])(c)?c:[c]}},{key:"getStyle",value:function(t){return this.getStyleFromLayers(t)}},{key:"getStyleFromLayers",value:function(t){var e=this,n={},r=this.getName(),i=this.getLayers(),o=this.getProperties();if(i.map((function(n){return e.getStyleFromLayer(n,t)})).forEach((function(t){Object(s["keys"])(t).map((function(e){n[e]||(n[e]=[]),n[e].push(t[e])}))})),Object(s["keys"])(n).map((function(t){n[t]=n[t].join(e.__getJoinLayers())})),this.isDetached())n[r]='',!i.length&&o.map((function(t){n[t.getName()]=''}));else{var a=o.reduce((function(t,e){return t[e.getName()]='',t}),{});n[r]=n[r]||'',n=W(W({},n),a)}return n}},{key:"__getJoinLayers",value:function(){var t=this.get('layerJoin'),e=this.get('layerSeparator');return t||(Object(s["isString"])(e)?e:t)}},{key:"__getFullValue",value:function(){return this.get('detached')?'':this.getStyleFromLayers()[this.getName()]}},{key:"hasValue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.noParent,n=e&&this.getParentTarget();return this.getLayers().length>0&&!n}},{key:"clear",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.__getLayers().reset(),this.__upTargetsStyleProps(t),E.prototype.clear.call(this)}},{key:"__canClearProp",value:function(){return!1}}]),n}(R),Y=["complete","partial"];function J(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function X(t){for(var e=1;e
\n
\n ")}},{key:"templateLabel",value:function(t){var e=this.pfx,n=this.em,r=t.parent,i=t.attributes,o=i.icon,a=void 0===o?'':o,s=i.info,c=void 0===s?'':s,l=null==n?void 0:n.getConfig('icons'),u=(null==l?void 0:l.close)||'';return"\n \n ").concat(t.getLabel(),"\n \n ").concat(r?'':"
").concat(u,"
"),"\n ")}},{key:"templateInput",value:function(t){return"\n
\n \n
\n ")}},{key:"initialize",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object(s["bindAll"])(this,'__change','__updateStyle');var e=t.config||{},n=e.em;this.config=e,this.em=n,this.pfx=e.stylePrefix||'',this.ppfx=e.pStylePrefix||'',this.__destroyFn=this.destroy?this.destroy.bind(this):function(){};var r=this.model;r.view=this,this.onValueChange=Object(s["debounce"])(this.onValueChange.bind(this),10),this.updateStatus=Object(s["debounce"])(this.updateStatus.bind(this)),this.listenTo(r,'destroy remove',this.remove),this.listenTo(r,'change:visible',this.updateVisibility),this.listenTo(r,'change:name change:className change:full',this.render),this.listenTo(r,'change:value',this.onValueChange),this.listenTo(n,'change:device',this.onValueChange);var i=this.init&&this.init.bind(this);i&&i()}},{key:"remove",value:function(){var t=this;u["View"].prototype.remove.apply(this,arguments),['em','input','$input','view'].forEach((function(e){return t[e]=null})),this.__destroyFn(this._getClbOpts())}},{key:"updateStatus",value:function(){var t,e=this.model,n=this.pfx,r=this.ppfx,i=this.config,o="".concat(r,"four-color"),a="".concat(r,"color-warn"),s=this.$el.children(".".concat(n,"label")),c=this.getClearEl(),l=c?c.style:{};s.removeClass("".concat(o," ").concat(a)),l.display='none',e.hasValue({noParent:!0})&&i.highlightChanged?(s.addClass(o),i.clearProperties&&(l.display='')):e.hasValue()&&i.highlightComputed&&s.addClass(a),null===(t=this.parent)||void 0===t||t.updateStatus()}},{key:"clear",value:function(t){t&&t.stopPropagation(),this.model.clear()}},{key:"getClearEl",value:function(){return this.clearEl||(this.clearEl=this.el.querySelector("[".concat(Q,"]"))),this.clearEl}},{key:"inputValueChanged",value:function(t){t&&t.stopPropagation(),this.emit||this.model.upValue(t.target.value)}},{key:"onValueChange",value:function(t,e){this.setValue(this.model.getFullValue()),this.updateStatus()}},{key:"setValue",value:function(t){var e=this.model,n=Object(s["isUndefined"])(t)||''===t?e.getDefaultValue():t;if(this.update)return this.__update(n);this.__setValueInput(n)}},{key:"__setValueInput",value:function(t){var e=this.getInputEl();e&&(e.value=t)}},{key:"getInputEl",value:function(){return this.input||(this.input=this.el.querySelector('input')),this.input}},{key:"updateVisibility",value:function(){this.el.style.display=this.model.isVisible()?'':'none'}},{key:"clearCached",value:function(){this.clearEl=null,this.input=null,this.$input=null}},{key:"__unset",value:function(){var t=this.unset&&this.unset.bind(this);t&&t(this._getClbOpts())}},{key:"__update",value:function(t){var e=this.update&&this.update.bind(this);e&&e(X(X({},this._getClbOpts()),{},{value:t}))}},{key:"__change",value:function(){for(var t=this.emit&&this.emit.bind(this),e=arguments.length,n=new Array(e),r=0;r1&&void 0!==arguments[1]?arguments[1]:{},n=e.complete,r=e.partial,i=(p()(e,Y),this.model),o=!1!==n&&!0!==r;Object(c["isObject"])(t)?i.__upTargetsStyle(t,{avoidStore:!o}):i.upValue(t,{partial:!o})}},{key:"_getClbOpts",value:function(){var t=this.model;return{el:this.el,createdEl:this.createdEl,property:t,props:t.attributes,change:this.__change,updateStyle:this.__updateStyle}}},{key:"render",value:function(){this.clearCached();var t=this.pfx,e=this.model,n=this.el,r=this.$el,i=e.getName(),o=e.getType(),a=e.get('className')||'',s="".concat(t,"property"),c='number'===o?"".concat(t).concat(o," ").concat(t,"integer"):"".concat(t).concat(o);this.createdEl&&this.__destroyFn(this._getClbOpts()),r.empty().append(this.template(e)),r.find('[data-sm-label]').append(this.templateLabel(e));var l=this.create&&this.create.bind(this);this.createdEl=l&&l(this._getClbOpts()),r.find('[data-sm-fields]').append(this.createdEl||this.templateInput(e)),n.className="".concat(s," ").concat(c," ").concat(s,"__").concat(i," ").concat(a).trim(),n.className+=e.isFull()?" ".concat(s,"--full"):'';var u=this.onRender&&this.onRender.bind(this);u&&u(),this.setValue(e.getValue())}}]),n}(u["View"]);tt.prototype.events=a()({change:'inputValueChanged'},"click [".concat(Q,"]"),'clear');var et=n(13);function nt(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var rt=function(t){w()(n,t);var e=nt(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"initialize",value:function(t){this.config=t.config||{},this.pfx=this.config.stylePrefix||'',this.properties=[],this.parent=t.parent;var e=this.collection;this.listenTo(e,'add',this.addTo),this.listenTo(e,'reset',this.render)}},{key:"addTo",value:function(t,e,n){this.add(t,null,n)}},{key:"add",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.parent,i=this.config,o=e||this.el,a=new t.typeView({model:t,config:i});r&&(a.parent=r),a.render();var s=a.el;this.properties.push(a),Object(et["b"])(o,s,n.at)}},{key:"remove",value:function(){u["View"].prototype.remove.apply(this,arguments),this.clearItems()}},{key:"clearItems",value:function(){this.properties.forEach((function(t){return t.remove()})),this.properties=[]}},{key:"render",value:function(){var t=this,e=this.$el,n=this.pfx;this.clearItems();var r=document.createDocumentFragment();return this.collection.forEach((function(e){return t.add(e,r)})),e.empty(),e.append(r),e.attr('class',"".concat(n,"properties")),this}}]),n}(u["View"]);function it(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function ot(t){for(var e=1;e\n \n
\n ")}},{key:"remove",value:function(){var t;null===(t=this.props)||void 0===t||t.remove(),tt.prototype.remove.apply(this,arguments)}},{key:"onValueChange",value:function(){}},{key:"onRender",value:function(){var t=this.model,e=this.pfx,n=t.get('properties');if(n.length&&!this.props){var r=t.isDetached(),i=new rt({config:ot(ot({},this.config),{},{highlightComputed:r,highlightChanged:r}),collection:n,parent:this});i.render(),this.$el.find("#".concat(e,"input-holder")).append(i.el),this.props=i}}},{key:"clearCached",value:function(){tt.prototype.clearCached.apply(this,arguments),this.props=null}}]),n}(tt);function ct(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var lt=function(t){w()(n,t);var e=ct(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"events",value:function(){return{click:'select','click [data-close-layer]':'removeItem','mousedown [data-move-layer]':'initSorter','touchstart [data-move-layer]':'initSorter'}}},{key:"template",value:function(){var t=this.pfx,e=this.ppfx,n=this.em,r=null==n?void 0:n.getConfig('icons'),i=(null==r?void 0:r.close)||'',o=(null==r?void 0:r.move)||'';return"\n
\n
\n ").concat(o,"\n
\n
\n
\n
\n
\n
\n ").concat(i,"\n
\n
\n
\n ")}},{key:"initialize",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.model,n=t.config||{};this.em=n.em,this.config=n,this.sorter=t.sorter,this.pfx=n.stylePrefix||'',this.ppfx=n.pStylePrefix||'',this.propertyView=t.propertyView;var r=this.propertyView.model;this.listenTo(e,'destroy remove',this.remove),this.listenTo(e,'change:values',this.updateLabel),this.listenTo(r,'change:selectedLayer',this.updateVisibility),e.view=this,e.set({droppable:0,draggable:1}),this.$el.data('model',e)}},{key:"initSorter",value:function(){var t;null===(t=this.sorter)||void 0===t||t.startSort(this.el)}},{key:"removeItem",value:function(t){t&&t.stopPropagation(),this.model.remove()}},{key:"select",value:function(){this.model.select()}},{key:"getPropertiesWrapper",value:function(){return this.propsWrapEl||(this.propsWrapEl=this.el.querySelector('[data-properties]')),this.propsWrapEl}},{key:"getPreviewEl",value:function(){return this.previewEl||(this.previewEl=this.el.querySelector('[data-preview]')),this.previewEl}},{key:"getLabelEl",value:function(){return this.labelEl||(this.labelEl=this.el.querySelector('[data-label]')),this.labelEl}},{key:"updateLabel",value:function(){var t=this.model,e=t.getLabel();if(this.getLabelEl().innerHTML=e,t.hasPreview()){var n=this.getPreviewEl(),r=t.getStylePreview({number:{min:-3,max:3}}),i=Object(s["keys"])(r).map((function(t){return"".concat(t,":").concat(r[t])})).join(';');n.setAttribute('style',i)}}},{key:"updateVisibility",value:function(){var t=this.pfx,e=this.model,n=this.propertyView,r=this.getPropertiesWrapper(),i=e.isSelected();r.style.display=i?'':'none',this.$el[i?'addClass':'removeClass']("".concat(t,"active")),i&&r.appendChild(n.props.el)}},{key:"render",value:function(){var t=this.el,e=this.pfx,n=this.model;return t.innerHTML=this.template(),t.className="".concat(e,"layer"),n.hasPreview()&&(t.querySelector("[data-preview-box]").style.display=''),this.updateLabel(),this.updateVisibility(),this}}]),n}(u["View"]);function ut(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var ft=function(t){w()(n,t);var e=ut(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"initialize",value:function(t){var e=this.collection,n=t.config||{},r=n.em,i=n.stylePrefix||'',o=n.pStylePrefix||'';this.config=n,this.pfx=i,this.ppfx=o,this.propertyView=t.propertyView,this.className="".concat(i,"layers ").concat(o,"field"),this.listenTo(e,'add',this.addTo),this.listenTo(e,'reset',this.reset),this.items=[];var a=r?r.get('Utils'):'';this.sorter=a?new a.Sorter({container:this.el,ignoreViewChildren:1,containerSel:".".concat(i,"layers"),itemSel:".".concat(i,"layer"),pfx:n.pStylePrefix}):'',e.view=this,this.$el.data('model',e),this.$el.data('collection',e)}},{key:"addTo",value:function(t){var e=this.collection.indexOf(t);this.addToCollection(t,null,e)}},{key:"addToCollection",value:function(t,e,n){var r=e||null,i=this.propertyView,o=this.config,a=this.sorter,s=this.$el,c=new lt({model:t,config:o,sorter:a,propertyView:i}),l=c.render().el;if(this.items.push(c),r)r.appendChild(l);else if(void 0!==n){var u='before';s.children().length===n&&(n--,u='after'),n<0?s.append(l):s.children().eq(n)[u](l)}else s.append(l);return l}},{key:"reset",value:function(t,e){this.clearItems(e),this.render()}},{key:"remove",value:function(){this.clearItems(),u["View"].prototype.remove.apply(this,arguments)}},{key:"clearItems",value:function(){this.items.forEach((function(t){return t.remove()})),this.items=[]}},{key:"render",value:function(){var t=this,e=this.$el,n=this.sorter,r=document.createDocumentFragment();return e.empty(),this.collection.forEach((function(e){return t.addToCollection(e,r)})),e.append(r),e.attr('class',this.className),n&&(n.plh=null),this}}]),n}(u["View"]);function ht(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function dt(t){for(var e=1;e\n \n
\n
\n ")}},{key:"init",value:function(){var t=this.model;this.listenTo(t.__getLayers(),'change reset',this.updateStatus)}},{key:"addLayer",value:function(){this.model.addLayer({},{at:0})}},{key:"setValue",value:function(){}},{key:"remove",value:function(){var t;null===(t=this.layersView)||void 0===t||t.remove(),st.prototype.remove.apply(this,arguments)}},{key:"clearCached",value:function(){st.prototype.clearCached.apply(this,arguments),this.layersView=null}},{key:"onRender",value:function(){var t=this.model,e=this.el,n=this.config,r=t.get('properties');if(r.length&&!this.props){var i=new rt({config:dt(dt({},n),{},{highlightComputed:!1,highlightChanged:!1}),collection:r,parent:this});i.render();var o=new ft({collection:t.__getLayers(),config:n,propertyView:this});o.render(),e.querySelector('[data-layers-wrapper]').appendChild(o.el),this.props=i,this.layersView=o}}}]),n}(st);function vt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function mt(t){for(var e=1;e\n
\n
\n \n
\n
\n
\n
\n
\n
").concat(i,"
\n
\n \n ")}},{key:"__setValueInput",value:function(t){var e=this.model,n=this.el,r=e.getDefaultValue(),i=n.querySelector('[data-preview-box]'),o=n.querySelector('[data-preview]');i.style.display=t&&t!==r?'':'none',o.style.backgroundImage=t||e.getDefaultValue()}},{key:"openAssetManager",value:function(){var t,e=this,n=null===(t=this.em)||void 0===t?void 0:t.get('AssetManager');null==n||n.open({select:function(t,r){var i=Object(s["isString"])(t)?t:t.get('src');e.model.upValue(i,{partial:!r}),r&&n.close()},types:['image'],accept:'image/*'})}}]),n}(tt);function wt(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var Ot=function(t){w()(n,t);var e=wt(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"templateInput",value:function(){return''}},{key:"init",value:function(){var t=this.model;this.listenTo(t,'change:unit',this.onValueChange),this.listenTo(t,'change:units',this.render)}},{key:"setValue",value:function(){}},{key:"onRender",value:function(){var t=this.ppfx,e=this.model,n=this.el;if(!this.inputInst){var r=e.input;r.ppfx=t,r.render(),n.querySelector(".".concat(t,"fields")).appendChild(r.el),this.input=r.inputEl.get(0),this.inputInst=r}}},{key:"clearCached",value:function(){tt.prototype.clearCached.apply(this,arguments),this.inputInst=null}}]),n}(tt),xt=n(43);function Ct(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var kt=function(t){w()(n,t);var e=Ct(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"setValue",value:function(t){var e;null===(e=this.inputInst)||void 0===e||e.setValue(t,{fromTarget:1,def:this.model.getDefaultValue()})}},{key:"remove",value:function(){var t=this;Ot.prototype.remove.apply(this,arguments);var e=this.inputInst;e&&e.remove&&e.remove(),['inputInst','$color'].forEach((function(e){return t[e]=null}))}},{key:"__handleChange",value:function(t,e){this.model.upValue(t,{partial:e})}},{key:"onRender",value:function(){if(!this.inputInst){this.__handleChange=this.__handleChange.bind(this);var t=this.ppfx,e=this.model,n=this.em,r=this.el,i=new xt["a"]({target:n,model:e,ppfx:t,onChange:this.__handleChange}).render();r.querySelector(".".concat(t,"fields")).appendChild(i.el),this.input=i.inputEl.get(0),this.inputInst=i}}}]),n}(Ot);function St(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function jt(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:[];return this.set('options',t),this}},{key:"addOption",value:function(t){if(t){var e=this.getOptions();this.setOptions([].concat(i()(e),[t]))}return this}},{key:"getOptionId",value:function(t){return Object(c["isDef"])(t.id)?t.id:t.value}},{key:"getOptionLabel",value:function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.locale,i=void 0===r||r,o=(Object(s["isString"])(t)?this.getOption(t):t)||{},a=this.getOptionId(o),c=o.label||o.name||a,l=this.getId();return i&&(null===(e=this.em)||void 0===e?void 0:e.t("styleManager.options.".concat(l,".").concat(a)))||c}},{key:"initialize",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n\n \n
\n
\n
\n \n ")}},{key:"initialize",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n").concat(i,""))}));var i=this.el.querySelector("#".concat(e,"input-holder"));i.innerHTML=""),this.input=i.firstChild}}},{key:"__setValueInput",value:function(t){var e=this.model,n=this.getInputEl(),r=e.getOptions()[0],i=r?e.getOptionId(r):'';n&&(n.value=t||i)}}]),n}(tt);function Dt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Mt(t){for(var e=1;e")}},{key:"onRender",value:function(){var t=this.pfx,e=this.ppfx,n=this.model,r="".concat(e,"radio-item-label"),i=n.getName(),o=n.getOptions(),a="".concat(t,"radio ").concat(t,"radio-").concat(i),s=n.cid;if(!this.input){var c=[];o.forEach((function(o){var l=o.className?"".concat(o.className," ").concat(t,"icon ").concat(r):'',u=n.getOptionId(o),f="".concat(i,"-").concat(u,"-").concat(s),h=l?'':n.getOptionLabel(u),d=o.title?"title=\"".concat(o.title,"\""):'',p=n.getValue()===u?'checked':'';c.push("\n
\n \n \n
\n "))}));var l=this.el.querySelector(".".concat(e,"field"));l.innerHTML="
").concat(c.join(''),"
"),this.input=l.firstChild}}},{key:"__setValueInput",value:function(t){var e,n=this.model,r=t||n.getDefaultValue(),i=null===(e=this.getInputEl())||void 0===e?void 0:e.querySelector("[value=\"".concat(r,"\"]"));i&&(i.checked=!0)}}]),n}(Et),It=n(38);function Ft(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Vt(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};E.callParentInit(E,this,t,e);var n=this.get('unit'),r=this.get('units');this.input=Object(c["hasWin"])()&&new It["a"]({model:this}),r.length&&!n&&this.set('unit',r[0],{silent:1}),E.callInit(this,t,e)}},{key:"__getClearProps",value:function(){return Vt(Vt({},E.prototype.__getClearProps()),{},{unit:''})}},{key:"parseValue",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=E.prototype.parseValue.apply(this,arguments),r=this.input.validateInputValue(n.value,Vt({deepCheck:1},e)),i=r.value,o=r.unit;return n.value=i,n.unit=o,n}},{key:"getFullValue",value:function(){var t=this.get('value'),e=this.get('unit');return t=Object(s["isUndefined"])(t)?'':t,e=!Object(s["isUndefined"])(e)&&t?e:'',t="".concat(t).concat(e),E.prototype.getFullValue.apply(this,[t])}}]),n}(E);function zt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Ut(t){for(var e=1;e\n \n \n ")}},{key:"getSliderEl",value:function(){return this.slider||(this.slider=this.el.querySelector('input[type=range]')),this.slider}},{key:"inputValueChanged",value:function(){this.model.upValue(this.getSliderEl().value)}},{key:"inputValueChangedSoft",value:function(){this.model.upValue(this.getSliderEl().value,{partial:!0})}},{key:"setValue",value:function(t){var e=this.model,n=e.parseValue(t);this.getSliderEl().value=''===t?e.getDefaultValue():parseFloat(n.value),Ot.prototype.setValue.apply(this,arguments)}},{key:"onRender",value:function(){Ot.prototype.onRender.apply(this,arguments),this.model.get('showInput')||(this.inputInst.el.style.display='none')}},{key:"clearCached",value:function(){Ot.prototype.clearCached.apply(this,arguments),this.slider=null}}]),n}(Ot),Jt=f.a.Collection.extend(S["a"]).extend({extendViewApi:1,init:function(){var t=this.opts,e=this.em,n=t.module||(null==e?void 0:e.get('StyleManager'));n&&(n.__listenAdd(this,n.events.propertyAdd),n.__listenRemove(this,n.events.propertyRemove))},types:[{id:'stack',model:K,view:gt,isType:function(t){if(t&&'stack'==t.type)return t}},{id:'composite',model:R,view:st,isType:function(t){if(t&&'composite'==t.type)return t}},{id:'file',model:E,view:bt,isType:function(t){if(t&&'file'==t.type)return t}},{id:'color',model:E,view:kt,isType:function(t){if(t&&'color'==t.type)return t}},{id:'select',model:_t,view:Et,isType:function(t){if(t&&'select'==t.type)return t}},{id:'radio',model:Lt,view:Nt,isType:function(t){if(t&&'radio'==t.type)return t}},{id:'slider',model:$t,view:Yt,isType:function(t){if(t&&'slider'==t.type)return t}},{id:'integer',model:Ht,view:Ot,isType:function(t){if(t&&'integer'==t.type)return t}},{id:'number',model:Ht,view:Ot,isType:function(t){if(t&&'number'==t.type)return t}},{id:'base',model:E,view:tt,isType:function(t){return t.type='base',t}}]}),Xt=["extend"];function Zt(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function Qt(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},r=n.em;this.em=r;var i=t||{},o=this.buildProperties(i.buildProps),a=this.get('name')||'',c=[];!this.get('id')&&this.set('id',a.replace(/ /g,'_').toLowerCase()),c=(c=o?this.extendProperties(o):this.get('properties').map((function(t){return Object(s["isString"])(t)?e.buildProperties(t)[0]:t})).filter(Boolean)).map((function(t){return e.checkExtend(t)}));var l=new Jt(c,{em:r});l.sector=this,this.set('properties',l)}},{key:"getId",value:function(){return this.get('id')}},{key:"getName",value:function(){var t,e=this.getId();return(null===(t=this.em)||void 0===t?void 0:t.t("styleManager.sectors.".concat(e)))||this.get('name')}},{key:"setName",value:function(t){return this.set('name',t)}},{key:"isOpen",value:function(){return!!this.get('open')}},{key:"setOpen",value:function(t){return this.set('open',t)}},{key:"isVisible",value:function(){return!!this.get('visible')}},{key:"getProperties",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.get('properties'),n=e.models?i()(e.models):e;return n.filter((function(e){var n=!0;(t.withValue&&(n=e.hasValue({noParent:!0})),t.withParentValue)&&(n=!e.hasValue({noParent:!0})&&e.hasValue());return n}))}},{key:"getProperty",value:function(t){return this.getProperties().filter((function(e){return e.get('id')===t}))[0]||null}},{key:"addProperty",value:function(t,e){return this.get('properties').add(this.checkExtend(t),e)}},{key:"extendProperties",value:function(t,e,n){for(var r=t.length,i=e||this.get('properties'),o=this.get('extendBuilded'),a=[],c=0,l=i.length;c1&&void 0!==arguments[1]?arguments[1]:{},n=e.module,r=e.em;this.em=r,this.module=n,this.listenTo(this,'reset',this.onReset)}},{key:"model",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.collection.em;return new ee(t,re(re({},e),{},{em:n}))}},{key:"onReset",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.previousModels||[];n.forEach((function(t){return t.get('properties').reset()}))}}]),n}(u["Collection"]),ae=n(29),se=n.n(ae),ce=["extend"];function le(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function ue(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.from||'',i=this.props[r||t]||{},o=ue(ue({},i),{},{property:t},e);return o.properties&&Object(s["isFunction"])(o.properties)&&(o.properties=o.properties()),this.props[t]=o,o}},{key:"get",value:function(t){return this.props[t]||null}},{key:"build",value:function(t){var e=this,n=[];return(Object(s["isString"])(t)?[t]:t).forEach((function(t){n.push(e.get(t)||{property:t})})),n}}]),t}(),pe=n(17),ge=n.n(pe),ve=n(16);function me(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var ye=function(t){w()(n,t);var e=me(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"template",value:function(t){var e,n=t.pfx,r=t.label,i=null===(e=this.em)||void 0===e?void 0:e.getConfig('icons'),o=(null==i?void 0:i.caret)||'',a="".concat(n,"sector-");return Object(ve["a"])(fe||(fe=ge()(["\n
\n
$","
\n
","
\n
\n "])),a,a,o,a,r)}},{key:"events",value:function(){return{'click [data-sector-title]':'toggle'}}},{key:"initialize",value:function(t){var e=t.config||{},n=this.model,r=e.em;this.config=e,this.em=r,this.pfx=e.stylePrefix||'',this.listenTo(n,'destroy remove',this.remove),this.listenTo(n,'change:open',this.updateOpen),this.listenTo(n,'change:visible',this.updateVisibility)}},{key:"updateOpen",value:function(){var t=this.$el,e=this.model,n=this.pfx,r=e.isOpen();t[r?'addClass':'removeClass']("".concat(n,"open")),this.getPropertiesEl().style.display=r?'':'none'}},{key:"updateVisibility",value:function(){this.el.style.display=this.model.isVisible()?'':'none'}},{key:"getPropertiesEl",value:function(){var t=this.$el,e=this.pfx;return t.find(".".concat(e,"properties")).get(0)}},{key:"toggle",value:function(){var t=this.model;t.setOpen(!t.get('open'))}},{key:"renderProperties",value:function(){var t=this.model,e=this.config,n=t.get('properties');if(n){var r=new rt({collection:n,config:e});this.$el.append(r.render().el)}}},{key:"render",value:function(){var t=this.pfx,e=this.model,n=this.$el,r=e.getId(),i=e.getName();return n.html(this.template({pfx:t,label:i})),this.renderProperties(),n.attr('class',"".concat(t,"sector ").concat(t,"sector__").concat(r," no-select")),this.updateOpen(),this}}]),n}(u["View"]);function be(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=k()(t);if(e){var i=k()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return x()(this,n)}}var we=function(t){w()(n,t);var e=be(n);function n(){return v()(this,n),e.apply(this,arguments)}return y()(n,[{key:"initialize",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.module,n=t.config,r=void 0===n?{}:n,i=this.collection;this.pfx=r.stylePrefix||'',this.ppfx=r.pStylePrefix||'',this.config=r,this.module=e,this.listenTo(i,'add',this.addTo),this.listenTo(i,'reset',this.render)}},{key:"remove",value:function(){var t=this;u["View"].prototype.remove.apply(this,arguments),['config','module','em'].forEach((function(e){return t[e]={}}))}},{key:"addTo",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.addToCollection(t,null,n)}},{key:"addToCollection",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.config,i=this.el,o=e||i,a=new ye({model:t,config:r}).render().el;return Object(et["b"])(o,a,n.at),a}},{key:"render",value:function(){var t=this,e=this.$el,n=this.pfx,r=this.ppfx;e.empty();var i=document.createDocumentFragment();return this.collection.each((function(e){return t.addToCollection(e,i)})),e.append(i),e.addClass("".concat(n,"sectors ").concat(r,"one-bg ").concat(r,"two-color")),this}}]),n}(u["View"]);function Oe(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function xe(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{};this.__initConfig(h,r);var i=this.config,o=i.em,a=i.pStylePrefix;a&&(i.stylePrefix=a+i.stylePrefix),this.builtIn=new de,t=new Jt([],{em:o,module:this}),e=new oe([],xe(xe({},i),{},{module:this}));var c=new u["Model"]({targets:[]});this.model=c,this.__listenAdd(e,je),this.__listenRemove(e,Pe),this.__listenUpdate(e,_e);var l='component:toggled component:update:classes change:state change:device frame:resized selector:type',f=Object(s["debounce"])((function(){return n.__upSel()}));c.listenTo(o,l,f);var d=Object(s["debounce"])((function(){n.__upProps(),n.__trgCustom()}));c.listenTo(o,'styleable:change undo redo',d);var p=Object(s["debounce"])((function(){return n.__trgCustom()}));return c.listenTo(o,"".concat(Ae," ").concat(Le),p),c.on('change:lastTarget',(function(){return o.trigger(Le,n.getSelected())})),this},__upSel:function(){this.select(this.em.getSelectedAll())},__trgCustom:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.__ctn=this.__ctn||t.container,this.em.trigger(this.events.custom,{container:this.__ctn})},__trgEv:function(t){for(var e,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i2&&void 0!==arguments[2]?arguments[2]:{},i=this.getSector(t);return i||(n.id=t,i=e.add(n,r)),i},getSector:function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=e.where({id:t})[0];return!r&&n.warn&&this._logNoSector(t),r||null},getSectors:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e&&e.models?t.array?i()(e.models):e:[];return t.visible?n.filter((function(t){return t.isVisible()})):n},removeSector:function(t){return this.getSectors().remove(this.getSector(t,{warn:1}))},addProperty:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=this.getSector(t,{warn:1}),i=null;return r&&(i=r.addProperty(e,n)),i},getProperty:function(t,e){var n,r=this.getSector(t,{warn:1});return r&&(n=r.get('properties').filter((function(t){return t.get('property')===e||t.get('id')===e}))[0]),n||null},getProperties:function(t){var e=null,n=this.getSector(t,{warn:1});return n&&(e=n.get('properties')),e},removeProperty:function(t,e){var n=this.getProperties(t);return n?n.remove(this.getProperty(t,e)):null},select:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,i=Object(s["isArray"])(t)?t:[t],o=n.stylable,a=r.get('CssComposer'),l=[];i.filter(Boolean).forEach((function(t){var e=t;if(Object(s["isString"])(t)){var n=a.getRule(t)||a.setRule(t);!Object(s["isUndefined"])(o)&&n.set({stylable:o}),e=n}l.push(e)}));var u=n.component||l.filter((function(t){return Object(c["isComponent"])(t)})).reverse()[0];l=l.map((function(t){return e.getModelToStyle(t)}));var f=r.getState(),h=l.slice().reverse()[0],d=this.getParentRules(h,{state:f,component:u}),p=this.__getStateTarget();return r.skip((function(){var t;if(f&&null!=h&&null!==(t=h.getState)&&void 0!==t&&t.call(h)){var e=h.getStyle();p?p.setStyle(e):p=a.getAll().add({selectors:'gjs-selected',style:e,important:!0})}else p&&(a.remove(p),p=null)})),this.model.set({targets:l,lastTarget:h,lastTargetParents:d,stateTarget:p,component:u}),this.__upProps(n),l},getSelected:function(){return this.model.get('lastTarget')||null},getSelectedAll:function(){return this.model.get('targets')},getSelectedParents:function(){return this.model.get('lastTargetParents')||[]},__getStateTarget:function(){return this.model.get('stateTarget')||null},addStyleTargets:function(t,e){this.getSelectedAll().map((function(n){return n.addStyle(t,e)}));var n=this.getSelected(),r=this.__getStateTarget();n&&(null==r||r.setStyle(n.getStyle(),e))},getBuiltIn:function(t){return this.builtIn.get(t)},getBuiltInAll:function(){return this.builtIn.props},addBuiltIn:function(t,e){return this.builtIn.add(t,e)},getModelToStyle:function(t){var e,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=this.em,i=n.skipAdd;if(r&&null!==(e=t)&&void 0!==e&&e.toHTML){var o,a=r.getConfig(),s=r.get('UndoManager'),c=r.get('CssComposer'),l=r.get('SelectorManager'),u=l?l.getConfig():{},f=a.devicePreviewMode?'':r.get('state'),h=t.get('classes'),d=h.getStyleable(),p=d.length,g=!u.componentFirst||n.useClasses,v={noCount:1},m={state:f,addOpts:v};if(s.stop(),p&&g){var y=r.getCurrentMedia();(o=c.get(d,f,y))||i||(o=c.add(d,f,y,{},v))}else if(a.avoidInlineStyle){var b=t.getId();!(o=c.getIdRule(b,m))&&!i&&(o=c.setIdRule(b,{},m)),t.is('wrapper')&&o.set('wrapper',1,v)}o&&(t=o),s.start()}return t},getParentRules:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.state,r=e.component,i=this.em,o=[];if(i&&t){var a=r,c=i.get('CssComposer'),l=i.get('CodeManager').getGenerator('css'),u=t.toHTML?t:t.getComponent(),f={combination:!0,array:!0},h=[],d=[],p=[];u?(h=c.getRules("#".concat(u.getId())),p=(d=a?c.getRules(a.getSelectors().getFullName(f)):[]).concat(h)):(h=a?c.getRules("#".concat(a.getId())):[],d=c.getRules(t.getSelectors().getFullName(f)),p=h.concat(d));var g=p.filter((function(t){return Object(s["isUndefined"])(n)?1:t.get('state')===n})).sort(l.sortRules).reverse();o=g.slice(g.indexOf(t)+1)}return o},addType:function(e,n){t.addType(e,n)},getType:function(e){return t.getType(e)},getTypes:function(){return t.getTypes()},createType:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.model,r=void 0===n?{}:n,i=e.view,o=void 0===i?{}:i,a=this.config,s=this.getType(t);if(s)return new s.view(xe({model:new s.model(r),config:a},o))},render:function(){var t=this.config,r=this.em,i=n&&n.el;return(n=new we({el:i,em:r,config:t,collection:e,module:this})).render().el},_logNoSector:function(t){var e=this.em;e&&e.logWarning("'".concat(t,"' sector not found"))},__upProps:function(t){var n=this,r=this.getSelected();if(r){var i=this.model.get('component'),o=this.getSelectedParents(),a=r.getStyle(),s=o.map((function(t){return{target:t,style:t.getStyle()}}));e.map((function(e){e.getProperties().map((function(e){n.__upProp(e,a,s,t)}))})),e.forEach((function(t){var n=t.getProperties();n.forEach((function(t){var n=t.__checkVisibility({target:r,component:i,sectors:e});t.set('visible',n)}));var o=n.some((function(t){return t.isVisible()}));t.set('visible',o)}))}},__upProp:function(t,e,n,r){var i=this,o=t.getName(),a=e[o],s=Ne(a),c='stack'===t.getType(),l='composite'===t.getType(),u=xe(xe({},r),{},{__up:!0}),f=!l&&!c,h=c?t.__getLayersFromStyle(e):[],d=l?t.__getPropsFromStyle(e):{},p=s?a:null,g=null;if(c&&null===h||l&&null===d){var v=c?'__getLayersFromStyle':'__getPropsFromStyle',m=n.filter((function(e){return null!==t[v](e.style)}))[0];if(m){p=m.style[o],g=m.target;var y=t[v](m.style);c?h=y:d=y}}else if(!s){p=null;var b=n.filter((function(t){return Ne(t.style[o])}))[0];b&&(p=b.style[o],g=b.target)}if(t.__setParentTarget(g),f&&t.__getFullValue()!==p&&t.upValue(p,u),c&&t.__setLayers(h||[]),l){var w=t.getProperties();if(t.isDetached()){var O=t.__getPropsFromStyle(e,{byName:!0})||{},x=n.map((function(e){return xe(xe({},e),{},{style:t.__getPropsFromStyle(e.style,{byName:!0})||{}})}));w.map((function(t){return i.__upProp(t,O,x,r)}))}else t.__setProperties(d||{},u),t.getProperties().map((function(t){return t.__setParentTarget(g)}))}},destroy:function(){[t,e].forEach((function(t){t.reset(),t.stopListening()})),n&&n.remove(),[t,e,n].forEach((function(t){return{}})),this.em={},this.config={},this.builtIn={},this.model={}}})}},function(t,e,n){"use strict";n.r(e);var r=n(2),i=n.n(r),o=n(0),a=n(21),s={stylePrefix:'gjs-',components:'',style:'',fromElement:0,noticeOnUnload:!0,showOffsets:!1,showOffsetsSelected:!1,forceClass:!0,height:'900px',width:'100%',log:['warning','error'],baseCss:"\n * {\n box-sizing: border-box;\n }\n html, body, [data-gjs-type=wrapper] {\n min-height: 100%;\n }\n body {\n margin: 0;\n height: 100%;\n background-color: #fff\n }\n [data-gjs-type=wrapper] {\n overflow: auto;\n overflow-x: hidden;\n }\n\n * ::-webkit-scrollbar-track {\n background: rgba(0, 0, 0, 0.1)\n }\n\n * ::-webkit-scrollbar-thumb {\n background: rgba(255, 255, 255, 0.2)\n }\n\n * ::-webkit-scrollbar {\n width: 10px\n }\n ",protectedCss:'* { box-sizing: border-box; } body {margin: 0;}',canvasCss:'',defaultCommand:'select-comp',showToolbar:1,showDevices:1,devicePreviewMode:0,mediaCondition:'max-width',tagVarStart:'{[ ',tagVarEnd:' ]}',keepEmptyTextNodes:0,jsInHtml:!0,nativeDnD:1,multipleSelection:1,exportWrapper:0,wrapperIsBody:1,optsHtml:{},optsCss:{},avoidInlineStyle:1,avoidDefaults:1,clearStyles:0,dragMode:0,listenToEl:[],cssIcons:'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css',icons:{close:'',move:'',plus:'',caret:''},el:'',i18n:{},undoManager:{},assetManager:{},canvas:{},layers:{},storageManager:{},richTextEditor:{},domComponents:{},modal:{},codeManager:{},panels:{},commands:{},cssComposer:{},selectorManager:{},deviceManager:{},styleManager:{},blockManager:{},traitManager:{},textViewCode:'Code',keepUnusedStyles:0,multiFrames:0,customUI:!1},c=n(18),l=n.n(c),u=n(5),f=n.n(u),h=n(6),d=n.n(h),p=n(7),g=n.n(p),v=n(8),m=n.n(v),y=n(4),b=n.n(y),w=n(3),O=n.n(w),x=n(1);function C(t){var e=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var n,r=b()(t);if(e){var i=b()(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return m()(this,n)}}var k=function(t){g()(n,t);var e=C(n);function n(){return f()(this,n),e.apply(this,arguments)}return n}(w["Model"]),S=function(t){g()(n,t);var e=C(n);function n(){return f()(this,n),e.apply(this,arguments)}return d()(n,[{key:"getByComponent",value:function(t){var e=this;return this.filter((function(n){return e.getComponent(n)===t}))[0]}},{key:"addComponent",value:function(t,e){var n=this,r=(Object(o["isArray"])(t)?t:[t]).filter((function(t){return!n.hasComponent(t)})).map((function(t){return{component:t}}));return this.push(r,e)}},{key:"getComponent",value:function(t){return t.get('component')}},{key:"hasComponent",value:function(t){var e=this.getByComponent(t);return e&&this.contains(e)}},{key:"lastComponent",value:function(){var t=this.last();return t&&this.getComponent(t)}},{key:"allComponents",value:function(){var t=this;return this.map((function(e){return t.getComponent(e)})).filter((function(t){return t}))}},{key:"removeComponent",value:function(t,e){var n=this,r=(Object(o["isArray"])(t)?t:[t]).map((function(t){return n.getByComponent(t)}));return this.remove(r,e)}}]),n}(w["Collection"]);S.prototype.model=k;var j=["unset"];function P(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function _(t){for(var e=1;e0&&void 0!==arguments[0]?arguments[0]:{};this.config=e,this.set('Config',e),this.set('modules',[]),this.set('toLoad',[]),this.set('storables',[]),this.set('selected',new S),this.set('dmode',e.dragMode),this.set('hasPages',!!e.pageManager);var n=e.el,r=e.log,i=!0===r?Object(o["keys"])(A):Object(o["isArray"])(r)?r:[];Object(o["bindAll"])(this,'initBaseColorPicker'),n&&e.fromElement&&(this.config.components=n.innerHTML),this.attrsOrig=n?Object(o["toArray"])(n.attributes).reduce((function(t,e){return t[e.nodeName]=e.nodeValue,t}),{}):'',M.forEach((function(e){return t.loadModule(e)})),this.on('change:componentHovered',this.componentHovered,this),this.on('change:changesCount',this.updateChanges,this),this.on('change:readyLoad change:readyCanvas',this._checkReady,this),i.forEach((function(e){return t.listenLog(e)})),[{from:'change:selectedComponent',to:'component:toggled'}].forEach((function(e){var n=e.from,r=e.to;t.listenTo(t,n,(function(){for(var e=arguments.length,i=new Array(e),o=0;o0&&void 0!==arguments[0]?arguments[0]:null,r=this.get('StorageManager');this.get('toLoad').forEach((function(t){return t.onLoad()}));var i=function(){t.get('modules').forEach((function(e){return e.postLoad&&e.postLoad(t)})),t.set('readyLoad',1),e&&e()};r&&r.canAutoload()?this.load(i):setTimeout(i);var o=new n({noticeOnUnload:!1,storageManager:!1,undoManager:!1});['PageManager','Canvas'].forEach((function(t){return o.get(t).onLoad()})),this.set('shallow',o)}},{key:"updateChanges",value:function(){var t=this,e=this.get('StorageManager'),n=this.get('changesCount');D&&clearTimeout(D),D=setTimeout((function(){return t.trigger('update')})),this.config.noticeOnUnload&&(window.onbeforeunload=n?function(t){return 1}:null),e.isAutosave()&&n>=e.getStepsBeforeSave()&&this.store()}},{key:"loadModule",value:function(t){var e=this.config,n=new(t.default||t),r=n.name.charAt(0).toLowerCase()+n.name.slice(1),i=Object(o["isUndefined"])(e[r])?e[n.name]:e[r],a=!0===i?{}:i||{},s=this.get('StorageManager');if(a.pStylePrefix=e.pStylePrefix||'',Object(o["isUndefined"])(i)||i||(a._disable=1),n.storageKey&&n.store&&n.load&&s){a.stm=s;var c='domComponents'==r?'unshift':'push';this.get('storables')[c](n)}return a.em=this,n.init(_({},a)),!n.private&&this.set(n.name,n),n.onLoad&&this.get('toLoad').push(n),this.get('modules').push(n),this}},{key:"init",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.destroyed&&(this.initialize(e),this.destroyed=0),this.set('Editor',t)}},{key:"getEditor",value:function(){return this.get('Editor')}},{key:"handleUpdates",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.__skip||r.temporary||r.noCount||r.avoidStore||!this.get('ready')||(E&&clearTimeout(E),E=setTimeout((function(){var t=n.get('changesCount')||0,e=(r.unset,l()(r,j));n.set('changesCount',t+1,e)}),0))}},{key:"changesUp",value:function(t){this.handleUpdates(0,0,t)}},{key:"componentHovered",value:function(t,e,n){var r=this.previous('componentHovered');r&&this.trigger('component:unhovered',r,n),e&&this.trigger('component:hovered',e,n)}},{key:"getSelected",value:function(){return this.get('selected').lastComponent()}},{key:"getSelectedAll",value:function(){return this.get('selected').allComponents()}},{key:"setSelected",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.event,i=r&&(r.ctrlKey||r.metaKey),s=r||{},c=s.shiftKey,l=Object(o["isArray"])(t),u=(l?t:[t]).map((function(t){return Object(x["getModel"])(t,a["default"])})),f=this.getSelectedAll(),h=this.getConfig('multipleSelection');l&&this.removeSelected(f.filter((function(t){return!Object(o["contains"])(u,t)}))),u.forEach((function(t){var r=Object(x["getModel"])(t);if(r&&(e.trigger('component:select:before',r,n),!r.get('selectable')||n.abort)){if(!n.useValid)return;for(var a=r.parent();a&&!a.get('selectable');)a=a.parent();r=a}if(i&&h)return e.toggleSelected(r);if(c&&h){e.clearSelection(e.get('Canvas').getWindow());var s,u,d=r.collection,p=r.index();if(e.getSelectedAll().forEach((function(t){var e=t.collection,n=t.index();e===d&&(np&&(u=Object(o["isUndefined"])(u)?n:Math.min(u,n)))})),!Object(o["isUndefined"])(s))for(;s!==p;)e.addSelected(d.at(s)),s++;if(!Object(o["isUndefined"])(u))for(;u!==p;)e.addSelected(d.at(u)),u--;return e.addSelected(r)}!l&&e.removeSelected(f.filter((function(t){return t!==r}))),e.addSelected(r,n),r}))}},{key:"addSelected",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Object(x["getModel"])(t,a["default"]),i=Object(o["isArray"])(r)?r:[r];i.forEach((function(t){if(!t||t.get('selectable')){var r=e.get('selected');n.forceChange&&e.removeSelected(t,n),r.addComponent(t,n),t&&e.trigger('component:select',t,n)}}))}},{key:"removeSelected",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.get('selected').removeComponent(Object(x["getModel"])(t,a["default"]),e)}},{key:"toggleSelected",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Object(x["getModel"])(t,a["default"]),i=Object(o["isArray"])(r)?r:[r];i.forEach((function(t){e.get('selected').hasComponent(t)?e.removeSelected(t,n):e.addSelected(t,n)}))}},{key:"setHovered",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!t)return this.set('componentHovered','');var n='component:hover',r=Object(x["getModel"])(t);if(r){if(e.forceChange&&this.set('componentHovered',''),this.trigger("".concat(n,":before"),r,e),!r.get('hoverable')){if(!e.useValid||e.abort)return;for(var i=r&&r.parent();i&&!i.get('hoverable');)i=i.parent();r=i}e.abort||(this.set('componentHovered',r,e),this.trigger(n,r,e))}}},{key:"getHovered",value:function(){return this.get('componentHovered')}},{key:"setComponents",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.get('DomComponents').setComponents(t,e)}},{key:"getComponents",value:function(){var t=this.get('DomComponents'),e=this.get('CodeManager');if(t&&e){var n=t.getComponents();return e.getCode(n,'json')}}},{key:"setStyle",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.get('CssComposer');return n.clear(e),n.getAll().add(t,e),this}},{key:"addStyle",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.getStyle().add(t,e);return Object(o["isArray"])(n)?n:[n]}},{key:"getStyle",value:function(){return this.get('CssComposer').getAll()}},{key:"setState",value:function(t){return this.set('state',t),this}},{key:"getState",value:function(){return this.get('state')||''}},{key:"getHtml",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this.config,n=e.optsHtml,r=e.exportWrapper,i=e.wrapperIsBody,o=e.jsInHtml?this.getJs(t):'',a=t.component||this.get('DomComponents').getComponent(),s=a?this.get('CodeManager').getCode(a,'html',_(_({exportWrapper:r,wrapperIsBody:i},n),t)):'';return s+=o?"` : '';\n return html;\n }\n\n /**\n * Returns CSS built inside canvas\n * @param {Object} [opts={}] Options\n * @returns {string} CSS string\n * @private\n */\n getCss(opts = {}) {\n const config = this.config;\n const { optsCss, wrapperIsBody } = config;\n const avoidProt = opts.avoidProtected;\n const keepUnusedStyles = !isUndefined(opts.keepUnusedStyles) ? opts.keepUnusedStyles : config.keepUnusedStyles;\n const cssc = this.get('CssComposer');\n const wrp = opts.component || this.get('DomComponents').getComponent();\n const protCss = !avoidProt ? config.protectedCss : '';\n const css =\n wrp &&\n this.get('CodeManager').getCode(wrp, 'css', {\n cssc,\n wrapperIsBody,\n keepUnusedStyles,\n ...optsCss,\n ...opts,\n });\n return wrp ? (opts.json ? css : protCss + css) : '';\n }\n\n /**\n * Returns JS of all components\n * @return {string} JS string\n * @private\n */\n getJs(opts = {}) {\n var wrp = opts.component || this.get('DomComponents').getWrapper();\n return wrp ? this.get('CodeManager').getCode(wrp, 'js').trim() : '';\n }\n\n /**\n * Store data to the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n * @private\n */\n store(clb) {\n const sm = this.get('StorageManager');\n if (!sm) return;\n\n const store = this.storeData();\n sm.store(store, res => {\n clb && clb(res, store);\n this.set('changesCount', 0);\n this.trigger('storage:store', store);\n });\n\n return store;\n }\n\n storeData() {\n let result = {};\n // Sync content if there is an active RTE\n const editingCmp = this.getEditing();\n editingCmp && editingCmp.trigger('sync:content', { noCount: true });\n\n this.get('storables').forEach(m => {\n result = { ...result, ...m.store(1) };\n });\n return result;\n }\n\n /**\n * Load data from the current storage\n * @param {Function} clb Callback function\n * @private\n */\n load(clb = null) {\n this.getCacheLoad(1, res => {\n this.loadData(res);\n clb && clb(res);\n });\n }\n\n loadData(data = {}) {\n const sm = this.get('StorageManager');\n const result = sm.__clearKeys(data);\n\n this.get('storables').forEach(module => {\n module.load(result);\n module.postLoad && module.postLoad(this);\n });\n\n return result;\n }\n\n /**\n * Returns cached load\n * @param {Boolean} force Force to reload\n * @param {Function} clb Callback function\n * @return {Object}\n * @private\n */\n getCacheLoad(force, clb) {\n if (this.cacheLoad && !force) return this.cacheLoad;\n const sm = this.get('StorageManager');\n const load = [];\n\n if (!sm) return {};\n\n this.get('storables').forEach(m => {\n let key = m.storageKey;\n key = isFunction(key) ? key() : key;\n const keys = isArray(key) ? key : [key];\n keys.forEach(k => load.push(k));\n });\n\n sm.load(load, res => {\n this.cacheLoad = res;\n clb && clb(res);\n setTimeout(() => this.trigger('storage:load', res));\n });\n }\n\n /**\n * Returns device model by name\n * @return {Device|null}\n * @private\n */\n getDeviceModel() {\n var name = this.get('device');\n return this.get('DeviceManager').get(name);\n }\n\n /**\n * Run default command if setted\n * @param {Object} [opts={}] Options\n * @private\n */\n runDefault(opts = {}) {\n var command = this.get('Commands').get(this.config.defaultCommand);\n if (!command || this.defaultRunning) return;\n command.stop(this, this, opts);\n command.run(this, this, opts);\n this.defaultRunning = 1;\n }\n\n /**\n * Stop default command\n * @param {Object} [opts={}] Options\n * @private\n */\n stopDefault(opts = {}) {\n const commands = this.get('Commands');\n const command = commands.get(this.config.defaultCommand);\n if (!command || !this.defaultRunning) return;\n command.stop(this, this, opts);\n this.defaultRunning = 0;\n }\n\n /**\n * Update canvas dimensions and refresh data useful for tools positioning\n * @private\n */\n refreshCanvas(opts = {}) {\n this.set('canvasOffset', null);\n this.set('canvasOffset', this.get('Canvas').getOffset());\n opts.tools && this.trigger('canvas:updateTools');\n }\n\n /**\n * Clear all selected stuf inside the window, sometimes is useful to call before\n * doing some dragging opearation\n * @param {Window} win If not passed the current one will be used\n * @private\n */\n clearSelection(win) {\n var w = win || window;\n w.getSelection().removeAllRanges();\n }\n\n /**\n * Get the current media text\n * @return {string}\n */\n getCurrentMedia() {\n const config = this.config;\n const device = this.getDeviceModel();\n const condition = config.mediaCondition;\n const preview = config.devicePreviewMode;\n const width = device && device.get('widthMedia');\n return device && width && !preview ? `(${condition}: ${width})` : '';\n }\n\n /**\n * Return the component wrapper\n * @return {Component}\n */\n getWrapper() {\n return this.get('DomComponents').getWrapper();\n }\n\n setCurrentFrame(frameView) {\n return this.set('currentFrame', frameView);\n }\n\n getCurrentFrame() {\n return this.get('currentFrame');\n }\n\n getCurrentFrameModel() {\n return (this.getCurrentFrame() || {}).model;\n }\n\n /**\n * Return the count of changes made to the content and not yet stored.\n * This count resets at any `store()`\n * @return {number}\n */\n getDirtyCount() {\n return this.get('changesCount');\n }\n\n getZoomDecimal() {\n return this.get('Canvas').getZoomDecimal();\n }\n\n getZoomMultiplier() {\n return this.get('Canvas').getZoomMultiplier();\n }\n\n setDragMode(value) {\n return this.set('dmode', value);\n }\n\n t(...args) {\n const i18n = this.get('I18n');\n return i18n?.t(...args);\n }\n\n /**\n * Returns true if the editor is in absolute mode\n * @returns {Boolean}\n */\n inAbsoluteMode() {\n return this.get('dmode') === 'absolute';\n }\n\n /**\n * Destroy editor\n */\n destroyAll() {\n const { config, view } = this;\n const editor = this.getEditor();\n const { editors = [] } = config.grapesjs || {};\n const shallow = this.get('shallow');\n shallow?.destroyAll();\n this.stopListening();\n this.stopDefault();\n this.get('modules')\n .slice()\n .reverse()\n .forEach(mod => mod.destroy());\n view && view.remove();\n this.clear({ silent: true });\n this.destroyed = 1;\n ['config', 'view', '_previousAttributes', '_events', '_listeners'].forEach(i => (this[i] = {}));\n editors.splice(editors.indexOf(editor), 1);\n hasWin() && $(config.el).empty().attr(this.attrsOrig);\n }\n\n getEditing() {\n const res = this.get('editing');\n return (res && res.model) || null;\n }\n\n setEditing(value) {\n this.set('editing', value);\n return this;\n }\n\n isEditing() {\n return !!this.get('editing');\n }\n\n log(msg, opts = {}) {\n const { ns, level = 'debug' } = opts;\n this.trigger('log', msg, opts);\n level && this.trigger(`log:${level}`, msg, opts);\n\n if (ns) {\n const logNs = `log-${ns}`;\n this.trigger(logNs, msg, opts);\n level && this.trigger(`${logNs}:${level}`, msg, opts);\n }\n }\n\n logInfo(msg, opts) {\n this.log(msg, { ...opts, level: 'info' });\n }\n\n logWarning(msg, opts) {\n this.log(msg, { ...opts, level: 'warning' });\n }\n\n logError(msg, opts) {\n this.log(msg, { ...opts, level: 'error' });\n }\n\n initBaseColorPicker(el, opts = {}) {\n const config = this.getConfig();\n const { colorPicker = {} } = config;\n const elToAppend = config.el;\n const ppfx = config.stylePrefix;\n\n return $(el).spectrum({\n containerClassName: `${ppfx}one-bg ${ppfx}two-color`,\n appendTo: elToAppend || 'body',\n maxSelectionSize: 8,\n showPalette: true,\n palette: [],\n showAlpha: true,\n chooseText: 'Ok',\n cancelText: '⨯',\n ...opts,\n ...colorPicker,\n });\n }\n\n /**\n * Execute actions without triggering the storage and undo manager.\n * @param {Function} clb\n * @private\n */\n skip(clb) {\n this.__skip = true;\n const um = this.get('UndoManager');\n um ? um.skip(clb) : clb();\n this.__skip = false;\n }\n\n /**\n * Set/get data from the HTMLElement\n * @param {HTMLElement} el\n * @param {string} name Data name\n * @param {any} value Date value\n * @return {any}\n * @private\n */\n data(el, name, value) {\n const varName = '_gjs-data';\n\n if (!el[varName]) {\n el[varName] = {};\n }\n\n if (isUndefined(value)) {\n return el[varName][name];\n } else {\n el[varName][name] = value;\n }\n }\n}\n","import { isObject, isString, each, isUndefined } from 'underscore';\n\nexport default ({ $ }) => {\n if ($ && $.prototype && $.prototype.constructor.name !== 'jQuery') {\n const fn = $.fn;\n\n // Additional helpers\n\n fn.hide = function() {\n return this.css('display', 'none');\n };\n\n fn.show = function() {\n return this.css('display', 'block');\n };\n\n fn.focus = function() {\n const el = this.get(0);\n el && el.focus();\n return this;\n };\n\n // For SVGs in IE\n // (fn.removeClass = function(c) {\n // if (!arguments.length) {\n // return this.attr('class', '');\n // }\n // const classes = isString(c) && c.match(/\\S+/g);\n // return classes\n // ? this.each(function(el) {\n // each(classes, function(c) {\n // if (el.classList) {\n // el.classList.remove(c);\n // } else {\n // const val = el.className;\n // const bval = el.className.baseVal;\n\n // if (!isUndefined(bval)) {\n // val.baseVal = bval.replace(c, '');\n // } else {\n // el.className = val.replace(c, '');\n // }\n // }\n // });\n // })\n // : this;\n // }),\n // (fn.remove = function() {\n // return this.each(node => {\n // return node.parentNode && node.parentNode.removeChild(node);\n // });\n // }),\n\n // For spectrum compatibility\n\n fn.bind = function(ev, h) {\n return this.on(ev, h);\n };\n\n fn.unbind = function(ev, h) {\n if (isObject(ev)) {\n for (let name in ev) {\n ev.hasOwnProperty(name) && this.off(name, ev[name]);\n }\n\n return this;\n } else {\n return this.off(ev, h);\n }\n };\n\n fn.click = function(h) {\n return h ? this.on('click', h) : this.trigger('click');\n };\n\n fn.change = function(h) {\n return h ? this.on('change', h) : this.trigger('change');\n };\n\n fn.keydown = function(h) {\n return h ? this.on('keydown', h) : this.trigger('keydown');\n };\n\n fn.delegate = function(selector, events, data, handler) {\n if (!handler) {\n handler = data;\n }\n\n return this.on(events, selector, function(e) {\n e.data = data;\n handler(e);\n });\n };\n\n fn.scrollLeft = function() {\n let el = this.get(0);\n el = el.nodeType == 9 ? el.defaultView : el;\n let win = el instanceof Window ? el : null;\n return win ? win.pageXOffset : el.scrollLeft || 0;\n };\n\n fn.scrollTop = function() {\n let el = this.get(0);\n el = el.nodeType == 9 ? el.defaultView : el;\n let win = el instanceof Window ? el : null;\n return win ? win.pageYOffset : el.scrollTop || 0;\n };\n\n const offset = $.prototype.offset;\n fn.offset = function(coords) {\n let top, left;\n\n if (coords) {\n top = coords.top;\n left = coords.left;\n }\n\n if (typeof top != 'undefined') {\n this.css('top', `${top}px`);\n }\n if (typeof left != 'undefined') {\n this.css('left', `${left}px`);\n }\n\n return offset.call(this);\n };\n\n $.map = function(items, clb) {\n const ar = [];\n\n for (var i = 0; i < items.length; i++) {\n ar.push(clb(items[i], i));\n }\n\n return ar;\n };\n\n const indexOf = Array.prototype.indexOf;\n\n $.inArray = function(val, arr, i) {\n return arr == null ? -1 : indexOf.call(arr, val, i);\n };\n\n $.Event = function(src, props) {\n if (!(this instanceof $.Event)) {\n return new $.Event(src, props);\n }\n\n this.type = src;\n this.isDefaultPrevented = () => false;\n };\n }\n};\n","import Backbone from 'backbone';\nimport { View } from 'common';\nimport { appendStyles } from 'utils/mixins';\n\nconst $ = Backbone.$;\n\nexport default class EditorView extends View {\n initialize() {\n const { model } = this;\n model.view = this;\n this.conf = model.config;\n this.pn = model.get('Panels');\n this.cv = model.get('Canvas');\n model.once('change:ready', () => {\n this.pn.active();\n this.pn.disableButtons();\n setTimeout(() => {\n model.trigger('load', model.get('Editor'));\n model.set('changesCount', 0);\n });\n });\n }\n\n render() {\n const { $el, conf, model } = this;\n const pfx = conf.stylePrefix;\n const contEl = $(conf.el || `body ${conf.container}`);\n appendStyles(conf.cssIcons, { unique: 1, prepand: 1 });\n $el.empty();\n\n if (conf.width) contEl.css('width', conf.width);\n if (conf.height) contEl.css('height', conf.height);\n\n $el.append(this.cv.render());\n $el.append(this.pn.render());\n\n // Load shallow editor\n const shallow = model.get('shallow');\n const shallowCanvasEl = shallow.get('Canvas').render();\n shallowCanvasEl.style.display = 'none';\n $el.append(shallowCanvasEl);\n\n $el.attr('class', `${pfx}editor ${pfx}one-bg ${pfx}two-color`);\n contEl.addClass(`${pfx}editor-cont`).empty().append($el);\n\n return this;\n }\n}\n","/**\n * Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins.\n * You get the Editor instance on init method and you can pass options via its [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/editor/config/config.js)\n *\n * ```js\n * const editor = grapesjs.init({\n * // options\n * });\n * ```\n *\n * ## Available Events\n *\n * You can make use of available events in this way\n * ```js\n * editor.on('EVENT-NAME', (some, argument) => {\n * // do something\n * })\n * ```\n *\n * * `update` - The structure of the template is updated (its HTML/CSS)\n * * `undo` - Undo executed\n * * `redo` - Redo executed\n * * `load` - Editor is loaded\n *\n * ### Components\n * Check the [Components](/api/components.html) module.\n * ### Keymaps\n * Check the [Keymaps](/api/keymaps.html) module.\n * ### Style Manager\n * Check the [Style Manager](/api/style_manager.html) module.\n * ### Storage\n * Check the [Storage](/api/storage_manager.html) module.\n * ### Canvas\n * Check the [Canvas](/api/canvas.html) module.\n * ### RTE\n * Check the [Rich Text Editor](/api/rich_text_editor.html) module.\n * ### Commands\n * Check the [Commands](/api/commands.html) module.\n * ### Selectors\n * Check the [Selectors](/api/selector_manager.html) module.\n * ### Blocks\n * Check the [Blocks](/api/block_manager.html) module.\n * ### Assets\n * Check the [Assets](/api/assets.html) module.\n * ### Modal\n * Check the [Modal](/api/modal_dialog.html) module.\n * ### Devices\n * Check the [Devices](/api/device_manager.html) module.\n * ### Parser\n * Check the [Parser](/api/parser.html) module.\n * ### Pages\n * Check the [Pages](/api/pages.html) module.\n *\n * ## Methods\n * @module Editor\n */\nimport defaults from './config/config';\nimport EditorModel from './model/Editor';\nimport EditorView from './view/EditorView';\nimport html from 'utils/html';\n\nexport default (config = {}, opts = {}) => {\n const { $ } = opts;\n let c = {\n ...defaults,\n ...config,\n };\n\n c.pStylePrefix = c.stylePrefix;\n let em = new EditorModel(c);\n let editorView;\n\n return {\n $,\n\n /**\n * @property {EditorModel}\n * @private\n */\n editor: em,\n\n modules: [],\n\n /**\n * Initialize editor model\n * @return {this}\n * @private\n */\n init(opts = {}) {\n em.init(this, { ...c, ...opts });\n\n this.modules = [\n 'I18n',\n 'Utils',\n 'Config',\n 'Commands',\n 'Keymaps',\n 'Modal',\n 'Panels',\n 'Canvas',\n 'Parser',\n 'CodeManager',\n 'UndoManager',\n 'RichTextEditor',\n ['Pages', 'PageManager'],\n 'DomComponents',\n ['Components', 'DomComponents'],\n 'LayerManager',\n ['Layers', 'LayerManager'],\n 'CssComposer',\n ['Css', 'CssComposer'],\n 'StorageManager',\n ['Storage', 'StorageManager'],\n 'AssetManager',\n ['Assets', 'AssetManager'],\n 'BlockManager',\n ['Blocks', 'BlockManager'],\n 'TraitManager',\n ['Traits', 'TraitManager'],\n 'SelectorManager',\n ['Selectors', 'SelectorManager'],\n 'StyleManager',\n ['Styles', 'StyleManager'],\n 'DeviceManager',\n ['Devices', 'DeviceManager'],\n ];\n\n this.modules.forEach(prop => {\n if (Array.isArray(prop)) {\n this[prop[0]] = em.get(prop[1]);\n } else {\n this[prop] = em.get(prop);\n }\n });\n\n // Do post render stuff after the iframe is loaded otherwise it'll\n // be empty during tests\n em.once('change:ready', () => {\n this.UndoManager.clear();\n em.get('modules').forEach(module => {\n module.postRender && module.postRender(editorView);\n });\n });\n\n return this;\n },\n\n /**\n * Returns configuration object\n * @param {string} [prop] Property name\n * @returns {any} Returns the configuration object or\n * the value of the specified property\n */\n getConfig(prop) {\n return em.getConfig(prop);\n },\n\n /**\n * Returns HTML built inside canvas\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Return the HTML of a specific Component\n * @param {Boolean} [opts.cleanId=false] Remove unnecessary IDs (eg. those created automatically)\n * @returns {string} HTML string\n */\n getHtml(opts) {\n return em.getHtml(opts);\n },\n\n /**\n * Returns CSS built inside canvas\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Return the CSS of a specific Component\n * @param {Boolean} [opts.json=false] Return an array of CssRules instead of the CSS string\n * @param {Boolean} [opts.avoidProtected=false] Don't include protected CSS\n * @param {Boolean} [opts.onlyMatched=false] Return only rules matched by the passed component.\n * @param {Boolean} [opts.keepUnusedStyles=false] Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor.\n * @returns {String|Array} CSS string or array of CssRules\n */\n getCss(opts) {\n return em.getCss(opts);\n },\n\n /**\n * Returns JS of all components\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Get the JS of a specific component\n * @returns {String} JS string\n */\n getJs(opts) {\n return em.getJs(opts);\n },\n\n /**\n * Return the complete tree of components. Use `getWrapper` to include also the wrapper\n * @return {Components}\n */\n getComponents() {\n return em.get('DomComponents').getComponents();\n },\n\n /**\n * Return the wrapper and its all components\n * @return {Component}\n */\n getWrapper() {\n return em.get('DomComponents').getWrapper();\n },\n\n /**\n * Set components inside editor's canvas. This method overrides actual components\n * @param {Array|Object|string} components HTML string or components model\n * @param {Object} opt the options object to be used by the [setComponents]{@link em#setComponents} method\n * @return {this}\n * @example\n * editor.setComponents('
New component
');\n * // or\n * editor.setComponents({\n * type: 'text',\n * classes:['cls'],\n * content: 'New component'\n * });\n */\n setComponents(components, opt = {}) {\n em.setComponents(components, opt);\n return this;\n },\n\n /**\n * Add components\n * @param {Array|Object|string} components HTML string or components model\n * @param {Object} opts Options\n * @param {Boolean} [opts.avoidUpdateStyle=false] If the HTML string contains styles,\n * by default, they will be created and, if already exist, updated. When this option\n * is true, styles already created will not be updated.\n * @return {Array}\n * @example\n * editor.addComponents('
New component
');\n * // or\n * editor.addComponents({\n * type: 'text',\n * classes:['cls'],\n * content: 'New component'\n * });\n */\n addComponents(components, opts) {\n return this.getWrapper().append(components, opts);\n },\n\n /**\n * Returns style in JSON format object\n * @return {Object}\n */\n getStyle() {\n return em.get('CssComposer').getAll();\n },\n\n /**\n * Set style inside editor's canvas. This method overrides actual style\n * @param {Array|Object|string} style CSS string or style model\n * @return {this}\n * @example\n * editor.setStyle('.cls{color: red}');\n * //or\n * editor.setStyle({\n * selectors: ['cls'],\n * style: { color: 'red' }\n * });\n */\n setStyle(style, opt = {}) {\n em.setStyle(style, opt);\n return this;\n },\n\n /**\n * Add styles to the editor\n * @param {Array|Object|string} style CSS string or style model\n * @returns {Array} Array of created CssRule instances\n * @example\n * editor.addStyle('.cls{color: red}');\n */\n addStyle(style, opts = {}) {\n return em.addStyle(style, opts);\n },\n\n /**\n * Returns the last selected component, if there is one\n * @return {Model}\n */\n getSelected() {\n return em.getSelected();\n },\n\n /**\n * Returns an array of all selected components\n * @return {Array}\n */\n getSelectedAll() {\n return em.getSelectedAll();\n },\n\n /**\n * Get a stylable entity from the selected component.\n * If you select a component without classes the entity is the Component\n * itself and all changes will go inside its 'style' attribute. Otherwise,\n * if the selected component has one or more classes, the function will\n * return the corresponding CSS Rule\n * @return {Model}\n */\n getSelectedToStyle() {\n let selected = em.getSelected();\n\n if (selected) {\n return this.StyleManager.getModelToStyle(selected);\n }\n },\n\n /**\n * Select a component\n * @param {Component|HTMLElement} el Component to select\n * @param {Object} [opts] Options\n * @param {Boolean} [opts.scroll] Scroll canvas to the selected element\n * @return {this}\n * @example\n * // Select dropped block\n * editor.on('block:drag:stop', function(model) {\n * editor.select(model);\n * });\n */\n select(el, opts) {\n em.setSelected(el, opts);\n return this;\n },\n\n /**\n * Add component to selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectAdd(model);\n */\n selectAdd(el) {\n em.addSelected(el);\n return this;\n },\n\n /**\n * Remove component from selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectRemove(model);\n */\n selectRemove(el) {\n em.removeSelected(el);\n return this;\n },\n\n /**\n * Toggle component selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectToggle(model);\n */\n selectToggle(el) {\n em.toggleSelected(el);\n return this;\n },\n\n /**\n * Returns, if active, the Component enabled in rich text editing mode.\n * @returns {Component|null}\n * @example\n * const textComp = editor.getEditing();\n * if (textComp) {\n * console.log('HTML: ', textComp.toHTML());\n * }\n */\n getEditing() {\n return em.getEditing();\n },\n\n /**\n * Set device to the editor. If the device exists it will\n * change the canvas to the proper width\n * @param {string} name Name of the device\n * @return {this}\n * @example\n * editor.setDevice('Tablet');\n */\n setDevice(name) {\n em.set('device', name);\n return this;\n },\n\n /**\n * Return the actual active device\n * @return {string} Device name\n * @example\n * var device = editor.getDevice();\n * console.log(device);\n * // 'Tablet'\n */\n getDevice() {\n return em.get('device');\n },\n\n /**\n * Execute command\n * @param {string} id Command ID\n * @param {Object} options Custom options\n * @return {*} The return is defined by the command\n * @example\n * editor.runCommand('myCommand', {someValue: 1});\n */\n runCommand(id, options = {}) {\n return em.get('Commands').run(id, options);\n },\n\n /**\n * Stop the command if stop method was provided\n * @param {string} id Command ID\n * @param {Object} options Custom options\n * @return {*} The return is defined by the command\n * @example\n * editor.stopCommand('myCommand', {someValue: 1});\n */\n stopCommand(id, options = {}) {\n return em.get('Commands').stop(id, options);\n },\n\n /**\n * Store data to the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n */\n store(clb) {\n return em.store(clb);\n },\n\n /**\n * Get the JSON data object, which could be stored and loaded back with `editor.loadData(json)`\n * @returns {Object}\n * @example\n * console.log(editor.storeData());\n * // { pages: [...], styles: [...], ... }\n */\n storeData() {\n return em.storeData();\n },\n\n /**\n * Load data from the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n */\n load(clb) {\n return em.load(clb);\n },\n\n /**\n * Load data from the JSON data object\n * @param {Object} data Data to load\n * @return {Object} Loaded object\n * @example\n * editor.loadData({ pages: [...], styles: [...], ... })\n */\n loadData(data) {\n return em.loadData(data);\n },\n\n /**\n * Returns container element. The one which was indicated as 'container'\n * on init method\n * @return {HTMLElement}\n */\n getContainer() {\n return c.el;\n },\n\n /**\n * Return the count of changes made to the content and not yet stored.\n * This count resets at any `store()`\n * @return {number}\n */\n getDirtyCount() {\n return em.getDirtyCount();\n },\n\n /**\n * Update editor dimension offsets\n *\n * This method could be useful when you update, for example, some position\n * of the editor element (eg. canvas, panels, etc.) with CSS, where without\n * refresh you'll get misleading position of tools\n * @param {Object} [options] Options\n * @param {Boolean} [options.tools=false] Update the position of tools (eg. rich text editor, component highlighter, etc.)\n */\n refresh(opts) {\n em.refreshCanvas(opts);\n },\n\n /**\n * Replace the built-in Rich Text Editor with a custom one.\n * @param {Object} obj Custom RTE Interface\n * @example\n * editor.setCustomRte({\n * // Function for enabling custom RTE\n * // el is the HTMLElement of the double clicked Text Component\n * // rte is the same instance you have returned the first time you call\n * // enable(). This is useful if need to check if the RTE is already enabled so\n * // ion this case you'll need to return the RTE and the end of the function\n * enable: function(el, rte) {\n * rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API\n * ...\n * return rte; // return the RTE instance\n * },\n *\n * // Disable the editor, called for example when you unfocus the Text Component\n * disable: function(el, rte) {\n * rte.blur(); // this depends on the Custom RTE API\n * }\n *\n * // Called when the Text Component is focused again. If you returned the RTE instance\n * // from the enable function, the enable won't be called again instead will call focus,\n * // in this case to avoid double binding of the editor\n * focus: function (el, rte) {\n * rte.focus(); // this depends on the Custom RTE API\n * }\n * });\n */\n setCustomRte(obj) {\n this.RichTextEditor.customRte = obj;\n },\n\n /**\n * Replace the default CSS parser with a custom one.\n * The parser function receives a CSS string as a parameter and expects\n * an array of CSSRule objects as a result. If you need to remove the\n * custom parser, pass `null` as the argument\n * @param {Function|null} parser Parser function\n * @return {this}\n * @example\n * editor.setCustomParserCss(css => {\n * const result = [];\n * // ... parse the CSS string\n * result.push({\n * selectors: '.someclass, div .otherclass',\n * style: { color: 'red' }\n * })\n * // ...\n * return result;\n * });\n */\n setCustomParserCss(parser) {\n this.Parser.getConfig().parserCss = parser;\n return this;\n },\n\n /**\n * Change the global drag mode of components.\n * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936\n * @param {String} value Drag mode, options: 'absolute' | 'translate'\n * @returns {this}\n */\n setDragMode(value) {\n em.setDragMode(value);\n return this;\n },\n\n /**\n * Trigger event log message\n * @param {*} msg Message to log\n * @param {Object} [opts={}] Custom options\n * @param {String} [opts.ns=''] Namespace of the log (eg. to use in plugins)\n * @param {String} [opts.level='debug'] Level of the log, `debug`, `info`, `warning`, `error`\n * @return {this}\n * @example\n * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' });\n * // This will trigger following events\n * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info`\n * // Callbacks of those events will always receive the message and\n * // options, as arguments, eg:\n * // editor.on('log:info', (msg, opts) => console.info(msg, opts))\n */\n log(msg, opts = {}) {\n em.log(msg, opts);\n return this;\n },\n\n /**\n * Translate label\n * @param {String} key Label to translate\n * @param {Object} [opts] Options for the translation\n * @param {Object} [opts.params] Params for the translation\n * @param {Boolean} [opts.noWarn] Avoid warnings in case of missing resources\n * @returns {String}\n * @example\n * editor.t('msg');\n * // use params\n * editor.t('msg2', { params: { test: 'hello' } });\n * // custom local\n * editor.t('msg2', { params: { test: 'hello' }, l: 'it' });\n */\n t(...args) {\n return em.t(...args);\n },\n\n /**\n * Attach event\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n on(event, callback) {\n em.on(event, callback);\n return this;\n },\n\n /**\n * Attach event and detach it after the first run\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n once(event, callback) {\n em.once(event, callback);\n return this;\n },\n\n /**\n * Detach event\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n off(event, callback) {\n em.off(event, callback);\n return this;\n },\n\n /**\n * Trigger event\n * @param {string} event Event to trigger\n * @return {this}\n */\n trigger(event) {\n em.trigger.apply(em, arguments);\n return this;\n },\n\n /**\n * Destroy the editor\n */\n destroy() {\n if (!em) return;\n em.destroyAll();\n this.modules.forEach(prop => {\n if (Array.isArray(prop)) {\n this[prop[0]] = 0;\n } else {\n this[prop] = 0;\n }\n });\n this.modules = 0;\n editorView = 0;\n em = 0;\n c = 0;\n },\n\n /**\n * Returns editor element\n * @return {HTMLElement}\n * @private\n */\n getEl() {\n return editorView && editorView.el;\n },\n\n /**\n * Returns editor model\n * @return {Model}\n * @private\n */\n getModel() {\n return em;\n },\n\n /**\n * Render editor\n * @return {HTMLElement}\n */\n render() {\n editorView && editorView.remove();\n editorView = new EditorView({\n model: em,\n config: c,\n });\n return editorView.render().el;\n },\n\n /**\n * Trigger a callback once the editor is loaded and rendered.\n * The callback will be executed immediately if the method is called on the already rendered editor.\n * @param {Function} clb Callback to trigger\n * @example\n * editor.onReady(() => {\n * // perform actions\n * });\n */\n onReady(clb) {\n em.get('ready') ? clb(this) : em.on('load', clb);\n },\n\n /**\n * Print safe HTML by using ES6 tagged template strings.\n * @param {Array} literals\n * @param {Array} substs\n * @returns {String}\n * @example\n * const unsafeStr = '';\n * const safeStr = 'Hello';\n * // Use `$${var}` to avoid escaping\n * const strHtml = editor.html`Escaped ${unsafeStr}, unescaped $${safeStr}`;\n */\n html,\n };\n};\n","export default {\n plugins: []\n};\n","/**\n * File made for IE/Edge support\n * https://github.com/artf/grapesjs/issues/214\n */\nimport { hasWin } from './mixins';\n\nexport default () => {\n /**\n * Check if IE/Edge\n * @return {Boolean}\n */\n const isIE = () => {\n let match;\n const agent = window.navigator.userAgent;\n const rules = [\n ['edge', /Edge\\/([0-9\\._]+)/],\n ['ie', /MSIE\\s(7\\.0)/],\n ['ie', /MSIE\\s([0-9\\.]+);.*Trident\\/[4-7].0/],\n ['ie', /Trident\\/7\\.0.*rv\\:([0-9\\.]+).*\\).*Gecko$/]\n ];\n\n for (let i = 0; i < rules.length; i++) {\n const rule = rules[i];\n match = rule[1].exec(agent);\n if (match) break;\n }\n\n return !!match;\n };\n\n if (hasWin() && isIE()) {\n const originalCreateHTMLDocument =\n DOMImplementation.prototype.createHTMLDocument;\n DOMImplementation.prototype.createHTMLDocument = title => {\n if (!title) title = '';\n return originalCreateHTMLDocument.apply(document.implementation, [title]);\n };\n }\n};\n","import { isElement, isFunction } from 'underscore';\nimport $ from 'utils/cash-dom';\nimport Editor from './editor';\nimport polyfills from 'utils/polyfills';\nimport { getGlobal } from 'utils/mixins';\nimport PluginManager from './plugin_manager';\n\npolyfills();\n\nconst plugins = new PluginManager();\nconst editors = [];\nconst defaultConfig = {\n // If true renders editor on init\n autorender: 1,\n\n // Array of plugins to init\n plugins: [],\n\n // Custom options for plugins\n pluginsOpts: {}\n};\n\nexport default {\n $,\n\n editors,\n\n plugins,\n\n // Will be replaced on build\n version: __GJS_VERSION__,\n\n /**\n * Initialize the editor with passed options\n * @param {Object} config Configuration object\n * @param {string|HTMLElement} config.container Selector which indicates where render the editor\n * @param {Boolean} [config.autorender=true] If true, auto-render the content\n * @param {Array} [config.plugins=[]] Array of plugins to execute on start\n * @param {Object} [config.pluginsOpts={}] Custom options for plugins\n * @param {Boolean} [config.headless=false] Init headless editor\n * @return {Editor} Editor instance\n * @example\n * var editor = grapesjs.init({\n * container: '#myeditor',\n * components: '
Hello world
',\n * style: '.hello{color: red}',\n * })\n */\n init(config = {}) {\n const { headless } = config;\n const els = config.container;\n if (!els && !headless) throw new Error(\"'container' is required\");\n config = { ...defaultConfig, ...config, grapesjs: this };\n config.el =\n !headless && (isElement(els) ? els : document.querySelector(els));\n const editor = new Editor(config, { $ }).init();\n const em = editor.getModel();\n\n // Load plugins\n config.plugins.forEach(pluginId => {\n let plugin = isFunction(pluginId) ? pluginId : plugins.get(pluginId);\n const plgOptions = config.pluginsOpts[pluginId] || {};\n\n // Try to search in global context\n if (!plugin) {\n const wplg = getGlobal()[pluginId];\n plugin = wplg?.default || wplg;\n }\n\n if (plugin) {\n plugin(editor, plgOptions);\n } else if (isFunction(pluginId)) {\n pluginId(editor, plgOptions);\n } else {\n em.logWarning(`Plugin ${pluginId} not found`, {\n context: 'plugins',\n plugin: pluginId\n });\n }\n });\n\n // Execute `onLoad` on modules once all plugins are initialized.\n // A plugin might have extended/added some custom type so this\n // is a good point to load stuff like components, css rules, etc.\n em.loadOnStart();\n config.autorender && !headless && editor.render();\n editors.push(editor);\n\n return editor;\n }\n};\n","import defaults from './config/config';\n\nexport default config => {\n var c = config || {};\n\n // Set default options\n for (var name in defaults) {\n if (!(name in c)) c[name] = defaults[name];\n }\n\n var plugins = {};\n\n return {\n /**\n * Add new plugin. Plugins could not be overwritten\n * @param {string} id Plugin ID\n * @param {Function} plugin Function which contains all plugin logic\n * @return {Function} The plugin function\n * @example\n * PluginManager.add('some-plugin', function(editor){\n * editor.Commands.add('new-command', {\n * run: function(editor, senderBtn){\n * console.log('Executed new-command');\n * }\n * })\n * });\n */\n add(id, plugin) {\n if (plugins[id]) {\n return plugins[id];\n }\n\n plugins[id] = plugin;\n return plugin;\n },\n\n /**\n * Returns plugin by ID\n * @param {string} id Plugin ID\n * @return {Function|undefined} Plugin\n * @example\n * var plugin = PluginManager.get('some-plugin');\n * plugin(editor);\n */\n get(id) {\n return plugins[id];\n },\n\n /**\n * Returns object with all plugins\n * @return {Object}\n */\n getAll() {\n return plugins;\n }\n };\n};\n","export default {\n // Default assets\n // eg. [\n // 'https://...image1.png',\n // 'https://...image2.png',\n // {type: 'image', src: 'https://...image3.png', someOtherCustomProp: 1},\n // ..\n // ]\n assets: [],\n\n // Content to add where there is no assets to show\n // eg. 'No assets here, drag to upload'\n noAssets: '',\n\n // Style prefix\n stylePrefix: 'am-',\n\n // Upload endpoint, set `false` to disable upload\n // upload: 'https://endpoint/upload/assets',\n // upload: false,\n upload: 0,\n\n // The name used in POST to pass uploaded files\n uploadName: 'files',\n\n // Custom headers to pass with the upload request\n headers: {},\n\n // Custom parameters to pass with the upload request, eg. csrf token\n params: {},\n\n // The credentials setting for the upload request, eg. 'include', 'omit'\n credentials: 'include',\n\n // Allow uploading multiple files per request.\n // If disabled filename will not have '[]' appended\n multiUpload: true,\n\n // If true, tries to add automatically uploaded assets.\n // To make it work the server should respond with a JSON containing assets\n // in a data key, eg:\n // {\n // data: [\n // 'https://.../image.png',\n // ...\n // {src: 'https://.../image2.png'},\n // ...\n // ]\n // }\n autoAdd: true,\n\n // To upload your assets, the module uses Fetch API, with this option you\n // overwrite it with something else.\n // It should return a Promise\n // @example\n // customFetch: (url, options) => axios(url, { data: options.body }),\n customFetch: null,\n\n // Custom uploadFile function.\n // Differently from the `customFetch` option, this gives a total control\n // over the uploading process, but you also have to emit all `asset:upload:*` events\n // by yourself (if you need to use them somewhere)\n // @example\n // uploadFile: (e) => {\n // var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;\n // // ...send somewhere\n // }\n uploadFile: null,\n\n // In the absence of 'uploadFile' or 'upload' assets will be embedded as Base64\n embedAsBase64: true,\n\n // Handle the image url submit from the built-in 'Add image' form\n // @example\n // handleAdd: (textFromInput) => {\n // // some check...\n // editor.AssetManager.add(textFromInput);\n // }\n handleAdd: null,\n\n // Method called before upload, on return false upload is canceled.\n // @example\n // beforeUpload: (files) => {\n // // logic...\n // var stopUpload = true;\n // if(stopUpload) return false;\n // }\n beforeUpload: null,\n\n // Toggles visiblity of assets url input\n showUrlInput: true,\n\n // Avoid rendering the default asset manager.\n custom: false,\n\n // WARNING: all the options below are considered DEPRECATED.\n // ---------------------------------------------------------------\n\n // Enable an upload dropzone on the entire editor (not document) when dragging\n // files over it\n // If active the dropzone disable/hide the upload dropzone in asset modal,\n // otherwise you will get double drops (#507)\n dropzone: false,\n\n // Open the asset manager once files are been dropped via the dropzone\n openAssetsOnDrop: 1,\n\n // Any dropzone content to append inside dropzone element\n dropzoneContent: ''\n};\n","import { result } from 'underscore';\nimport { Model } from 'common';\n\n/**\n * @property {String} type Asset type, eg. 'image'.\n * @property {String} src Asset URL, eg. 'https://.../image.png'.\n */\nexport default class Asset extends Model {\n defaults() {\n return {\n type: '',\n src: ''\n };\n }\n\n /**\n * Get asset type.\n * @returns {String}\n * @example\n * // Asset: { src: 'https://.../image.png', type: 'image' }\n * asset.getType(); // -> 'image'\n * */\n getType() {\n return this.get('type');\n }\n\n /**\n * Get asset URL.\n * @returns {String}\n * @example\n * // Asset: { src: 'https://.../image.png' }\n * asset.getSrc(); // -> 'https://.../image.png'\n * */\n getSrc() {\n return this.get('src');\n }\n\n /**\n * Get filename of the asset (based on `src`).\n * @returns {String}\n * @example\n * // Asset: { src: 'https://.../image.png' }\n * asset.getFilename(); // -> 'image.png'\n * // Asset: { src: 'https://.../image' }\n * asset.getFilename(); // -> 'image'\n * */\n getFilename() {\n return this.get('src')\n .split('/')\n .pop()\n .split('?')\n .shift();\n }\n\n /**\n * Get extension of the asset (based on `src`).\n * @returns {String}\n * @example\n * // Asset: { src: 'https://.../image.png' }\n * asset.getExtension(); // -> 'png'\n * // Asset: { src: 'https://.../image' }\n * asset.getExtension(); // -> ''\n * */\n getExtension() {\n return this.getFilename()\n .split('.')\n .pop();\n }\n}\n\nAsset.prototype.idAttribute = 'src';\n\nAsset.getDefaults = function() {\n return result(this.prototype, 'defaults');\n};\n","import Asset from './Asset';\n\nexport default class AssetImage extends Asset {\n defaults() {\n return {\n ...Asset.getDefaults(),\n type: 'image',\n unitDim: 'px',\n height: 0,\n width: 0\n };\n }\n}\n","import Backbone from 'backbone';\nimport { clone } from 'underscore';\n\nexport default Backbone.View.extend({\n initialize(o = {}) {\n this.options = o;\n this.collection = o.collection;\n const config = o.config || {};\n this.config = config;\n this.pfx = config.stylePrefix || '';\n this.ppfx = config.pStylePrefix || '';\n this.em = config.em;\n this.className = this.pfx + 'asset';\n this.listenTo(this.model, 'destroy remove', this.remove);\n this.model.view = this;\n const init = this.init && this.init.bind(this);\n init && init(o);\n },\n\n __getBhv() {\n const { em } = this;\n const am = em && em.get('AssetManager');\n return (am && am.__getBehaviour()) || {};\n },\n\n template() {\n const pfx = this.pfx;\n return `\n
\n ${this.getPreview()}\n
\n
\n ${this.getInfo()}\n
\n
\n ⨯\n
\n `;\n },\n\n /**\n * Update target if exists\n * @param {Model} target\n * @private\n * */\n updateTarget(target) {\n if (target && target.set) {\n target.set('attributes', clone(target.get('attributes')));\n target.set('src', this.model.get('src'));\n }\n },\n\n getPreview() {\n return '';\n },\n\n getInfo() {\n return '';\n },\n\n render() {\n const el = this.el;\n el.innerHTML = this.template(this, this.model);\n el.className = this.className;\n return this;\n }\n});\n","import { isFunction } from 'underscore';\nimport AssetView from './AssetView';\nimport html from 'utils/html';\n\nexport default AssetView.extend({\n events: {\n 'click [data-toggle=asset-remove]': 'onRemove',\n click: 'onClick',\n dblclick: 'onDblClick'\n },\n\n getPreview() {\n const { pfx, ppfx, model } = this;\n const src = model.get('src');\n return html`\n
\n
\n `;\n },\n\n getInfo() {\n const { pfx, model } = this;\n let name = model.get('name');\n let width = model.get('width');\n let height = model.get('height');\n let unit = model.get('unitDim');\n let dim = width && height ? `${width}x${height}${unit}` : '';\n name = name || model.getFilename();\n return html`\n
${name}
\n
${dim}
\n `;\n },\n\n init(o) {\n const pfx = this.pfx;\n this.className += ` ${pfx}asset-image`;\n },\n\n /**\n * Triggered when the asset is clicked\n * @private\n * */\n onClick() {\n const { model, pfx } = this;\n const { select } = this.__getBhv();\n const { onClick } = this.config;\n const coll = this.collection;\n coll.trigger('deselectAll');\n this.$el.addClass(pfx + 'highlight');\n\n if (isFunction(select)) {\n select(model, false);\n } else if (isFunction(onClick)) {\n onClick(model);\n } else {\n this.updateTarget(coll.target);\n }\n },\n\n /**\n * Triggered when the asset is double clicked\n * @private\n * */\n onDblClick() {\n const { em, model } = this;\n const { select } = this.__getBhv();\n const { onDblClick } = this.config;\n const { target, onSelect } = this.collection;\n\n if (isFunction(select)) {\n select(model, true);\n } else if (isFunction(onDblClick)) {\n onDblClick(model);\n } else {\n this.updateTarget(target);\n em && em.get('Modal').close();\n }\n isFunction(onSelect) && onSelect(model);\n },\n\n /**\n * Remove asset from collection\n * @private\n * */\n onRemove(e) {\n e.stopImmediatePropagation();\n this.model.collection.remove(this.model);\n }\n});\n","import Backbone from 'backbone';\nimport AssetImage from './AssetImage';\nimport AssetImageView from './../view/AssetImageView';\nimport TypeableCollection from 'domain_abstract/model/TypeableCollection';\n\nexport default Backbone.Collection.extend(TypeableCollection).extend({\n types: [\n {\n id: 'image',\n model: AssetImage,\n view: AssetImageView,\n isType(value) {\n if (typeof value == 'string') {\n return {\n type: 'image',\n src: value\n };\n }\n return value;\n }\n }\n ]\n});\n","import Backbone from 'backbone';\n\nexport default Backbone.View.extend({\n events: {\n submit: 'handleSubmit'\n },\n\n template({ pfx, ppfx, em, ...view }) {\n let form = '';\n if (this.config.showUrlInput) {\n form = `\n
\n
\n \n
\n \n
\n
\n `;\n }\n\n return `\n
\n
\n ${form}\n
\n
\n
\n
\n `;\n },\n\n initialize(o) {\n this.options = o;\n this.config = o.config;\n this.pfx = this.config.stylePrefix || '';\n this.ppfx = this.config.pStylePrefix || '';\n this.em = this.config.em;\n const coll = this.collection;\n this.listenTo(coll, 'reset', this.renderAssets);\n this.listenTo(coll, 'add', this.addToAsset);\n this.listenTo(coll, 'remove', this.removedAsset);\n this.listenTo(coll, 'deselectAll', this.deselectAll);\n },\n\n /**\n * Add new asset to the collection via string\n * @param {Event} e Event object\n * @return {this}\n * @private\n */\n handleSubmit(e) {\n e.preventDefault();\n const input = this.getAddInput();\n const url = input && input.value.trim();\n const handleAdd = this.config.handleAdd;\n\n if (!url) {\n return;\n }\n\n input.value = '';\n this.getAssetsEl().scrollTop = 0;\n\n if (handleAdd) {\n handleAdd.bind(this)(url);\n } else {\n this.options.globalCollection.add(url, { at: 0 });\n }\n },\n\n /**\n * Returns assets element\n * @return {HTMLElement}\n * @private\n */\n getAssetsEl() {\n //if(!this.assets) // Not able to cache as after the rerender it losses the ref\n return this.el.querySelector(`.${this.pfx}assets`);\n },\n\n /**\n * Returns input url element\n * @return {HTMLElement}\n * @private\n */\n getAddInput() {\n if (!this.inputUrl || !this.inputUrl.value)\n this.inputUrl = this.el.querySelector(`.${this.pfx}add-asset input`);\n return this.inputUrl;\n },\n\n /**\n * Triggered when an asset is removed\n * @param {Asset} model Removed asset\n * @private\n */\n removedAsset(model) {\n if (!this.collection.length) {\n this.toggleNoAssets();\n }\n },\n\n /**\n * Add asset to collection\n * @private\n * */\n addToAsset(model) {\n if (this.collection.length == 1) {\n this.toggleNoAssets(1);\n }\n this.addAsset(model);\n },\n\n /**\n * Add new asset to collection\n * @param Object Model\n * @param Object Fragment collection\n * @return Object Object created\n * @private\n * */\n addAsset(model, fragmentEl = null) {\n const fragment = fragmentEl;\n const collection = this.collection;\n const config = this.config;\n const rendered = new model.typeView({\n model,\n collection,\n config\n }).render().el;\n\n if (fragment) {\n fragment.appendChild(rendered);\n } else {\n const assetsEl = this.getAssetsEl();\n if (assetsEl) {\n assetsEl.insertBefore(rendered, assetsEl.firstChild);\n }\n }\n\n return rendered;\n },\n\n /**\n * Checks if to show noAssets\n * @param {Boolean} hide\n * @private\n */\n toggleNoAssets(hide) {\n const assetsEl = this.$el.find(`.${this.pfx}assets`);\n\n if (hide) {\n assetsEl.empty();\n } else {\n const noAssets = this.config.noAssets;\n noAssets && assetsEl.append(noAssets);\n }\n },\n\n /**\n * Deselect all assets\n * @private\n * */\n deselectAll() {\n const pfx = this.pfx;\n this.$el.find(`.${pfx}highlight`).removeClass(`${pfx}highlight`);\n },\n\n renderAssets() {\n const fragment = document.createDocumentFragment();\n const assets = this.$el.find(`.${this.pfx}assets`);\n assets.empty();\n this.toggleNoAssets(this.collection.length);\n this.collection.each(model => this.addAsset(model, fragment));\n assets.append(fragment);\n },\n\n render() {\n const fuRendered = this.options.fu.render().el;\n this.$el.empty();\n this.$el.append(fuRendered).append(this.template(this));\n this.el.className = `${this.ppfx}asset-manager`;\n this.renderAssets();\n return this;\n }\n});\n","import Backbone from 'backbone';\nimport fetch from 'utils/fetch';\nimport html from 'utils/html';\n\nexport default Backbone.View.extend(\n {\n template({ pfx, title, uploadId, disabled, multiUpload }) {\n return html`\n
\n
${title}
\n \n
\n \n `;\n },\n\n events: {},\n\n initialize(opts = {}) {\n this.options = opts;\n const c = opts.config || {};\n this.module = opts.module;\n this.config = c;\n this.em = this.config.em;\n this.pfx = c.stylePrefix || '';\n this.ppfx = c.pStylePrefix || '';\n this.target = this.options.globalCollection || {};\n this.uploadId = this.pfx + 'uploadFile';\n this.disabled =\n c.disableUpload !== undefined\n ? c.disableUpload\n : !c.upload && !c.embedAsBase64;\n this.multiUpload = c.multiUpload !== undefined ? c.multiUpload : true;\n this.events['change #' + this.uploadId] = 'uploadFile';\n let uploadFile = c.uploadFile;\n\n if (uploadFile) {\n this.uploadFile = uploadFile.bind(this);\n } else if (!c.upload && c.embedAsBase64) {\n this.uploadFile = this.constructor.embedAsBase64;\n }\n\n this.delegateEvents();\n },\n\n /**\n * Triggered before the upload is started\n * @private\n */\n onUploadStart() {\n const { module } = this;\n module && module.__propEv('asset:upload:start');\n },\n\n /**\n * Triggered after the upload is ended\n * @param {Object|string} res End result\n * @private\n */\n onUploadEnd(res) {\n const { $el, module } = this;\n module && module.__propEv('asset:upload:end', res);\n const input = $el.find('input');\n input && input.val('');\n },\n\n /**\n * Triggered on upload error\n * @param {Object} err Error\n * @private\n */\n onUploadError(err) {\n const { module } = this;\n console.error(err);\n this.onUploadEnd(err);\n module && module.__propEv('asset:upload:error', err);\n },\n\n /**\n * Triggered on upload response\n * @param {string} text Response text\n * @private\n */\n onUploadResponse(text, clb) {\n const { module, config, target } = this;\n let json;\n try {\n json = typeof text === 'string' ? JSON.parse(text) : text;\n } catch (e) {\n json = text;\n }\n\n module && module.__propEv('asset:upload:response', json);\n\n if (config.autoAdd && target) {\n target.add(json.data, { at: 0 });\n }\n\n this.onUploadEnd(text);\n clb && clb(json);\n },\n\n /**\n * Upload files\n * @param {Object} e Event\n * @return {Promise}\n * @private\n * */\n uploadFile(e, clb) {\n const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;\n const { config } = this;\n const { beforeUpload } = config;\n\n const beforeUploadResponse = beforeUpload && beforeUpload(files);\n if (beforeUploadResponse === false) return;\n\n const body = new FormData();\n const { params, customFetch } = config;\n\n for (let param in params) {\n body.append(param, params[param]);\n }\n\n if (this.multiUpload) {\n for (let i = 0; i < files.length; i++) {\n body.append(`${config.uploadName}[]`, files[i]);\n }\n } else if (files.length) {\n body.append(config.uploadName, files[0]);\n }\n\n var target = this.target;\n const url = config.upload;\n const headers = config.headers;\n const reqHead = 'X-Requested-With';\n\n if (typeof headers[reqHead] == 'undefined') {\n headers[reqHead] = 'XMLHttpRequest';\n }\n\n if (url) {\n this.onUploadStart();\n const fetchOpts = {\n method: 'post',\n credentials: config.credentials || 'include',\n headers,\n body\n };\n const fetchResult = customFetch\n ? customFetch(url, fetchOpts)\n : fetch(url, fetchOpts).then(res =>\n ((res.status / 200) | 0) == 1\n ? res.text()\n : res.text().then(text => Promise.reject(text))\n );\n return fetchResult\n .then(text => this.onUploadResponse(text, clb))\n .catch(err => this.onUploadError(err));\n }\n },\n\n /**\n * Make input file droppable\n * @private\n * */\n initDrop() {\n var that = this;\n if (!this.uploadForm) {\n this.uploadForm = this.$el.find('form').get(0);\n if ('draggable' in this.uploadForm) {\n var uploadFile = this.uploadFile;\n this.uploadForm.ondragover = function() {\n this.className = that.pfx + 'hover';\n return false;\n };\n this.uploadForm.ondragleave = function() {\n this.className = '';\n return false;\n };\n this.uploadForm.ondrop = function(e) {\n this.className = '';\n e.preventDefault();\n that.uploadFile(e);\n return;\n };\n }\n }\n },\n\n initDropzone(ev) {\n let addedCls = 0;\n const c = this.config;\n const em = ev.model;\n const edEl = ev.el;\n const editor = em.get('Editor');\n const container = em.get('Config').el;\n const frameEl = em.get('Canvas').getBody();\n const ppfx = this.ppfx;\n const updatedCls = `${ppfx}dropzone-active`;\n const dropzoneCls = `${ppfx}dropzone`;\n const cleanEditorElCls = () => {\n edEl.className = edEl.className.replace(updatedCls, '').trim();\n addedCls = 0;\n };\n const onDragOver = () => {\n if (!addedCls) {\n edEl.className += ` ${updatedCls}`;\n addedCls = 1;\n }\n return false;\n };\n const onDragLeave = () => {\n cleanEditorElCls();\n return false;\n };\n const onDrop = e => {\n cleanEditorElCls();\n e.preventDefault();\n e.stopPropagation();\n this.uploadFile(e);\n\n if (c.openAssetsOnDrop && editor) {\n const target = editor.getSelected();\n editor.runCommand('open-assets', {\n target,\n onSelect() {\n editor.Modal.close();\n editor.AssetManager.setTarget(null);\n }\n });\n }\n\n return false;\n };\n\n ev.$el.append(`
${c.dropzoneContent}
`);\n cleanEditorElCls();\n\n if ('draggable' in edEl) {\n [edEl, frameEl].forEach(item => {\n item.ondragover = onDragOver;\n item.ondragleave = onDragLeave;\n item.ondrop = onDrop;\n });\n }\n },\n\n render() {\n const { $el, pfx, em } = this;\n $el.html(\n this.template({\n title: em && em.t('assetManager.uploadTitle'),\n uploadId: this.uploadId,\n disabled: this.disabled,\n multiUpload: this.multiUpload,\n pfx\n })\n );\n this.initDrop();\n $el.attr('class', pfx + 'file-uploader');\n return this;\n }\n },\n {\n embedAsBase64: function(e, clb) {\n // List files dropped\n const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;\n const response = { data: [] };\n\n // Unlikely, widely supported now\n if (!FileReader) {\n this.onUploadError(\n new Error('Unsupported platform, FileReader is not defined')\n );\n return;\n }\n\n const promises = [];\n const mimeTypeMatcher = /^(.+)\\/(.+)$/;\n\n for (const file of files) {\n // For each file a reader (to read the base64 URL)\n // and a promise (to track and merge results and errors)\n const promise = new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.addEventListener('load', event => {\n let type;\n const name = file.name;\n\n // Try to find the MIME type of the file.\n const match = mimeTypeMatcher.exec(file.type);\n if (match) {\n type = match[1]; // The first part in the MIME, \"image\" in image/png\n } else {\n type = file.type;\n }\n\n /*\n // Show local video files, http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/\n var URL = window.URL || window.webkitURL\n var file = this.files[0]\n var type = file.type\n var videoNode = document.createElement('video');\n var canPlay = videoNode.canPlayType(type) // can use also for 'audio' types\n if (canPlay === '') canPlay = 'no'\n var message = 'Can play type \"' + type + '\": ' + canPlay\n var isError = canPlay === 'no'\n displayMessage(message, isError)\n\n if (isError) {\n return\n }\n\n var fileURL = URL.createObjectURL(file)\n videoNode.src = fileURL\n */\n\n // If it's an image, try to find its size\n if (type === 'image') {\n const data = {\n src: reader.result,\n name,\n type,\n height: 0,\n width: 0\n };\n\n const image = new Image();\n image.addEventListener('error', error => {\n reject(error);\n });\n image.addEventListener('load', () => {\n data.height = image.height;\n data.width = image.width;\n resolve(data);\n });\n image.src = data.src;\n } else if (type) {\n // Not an image, but has a type\n resolve({\n src: reader.result,\n name,\n type\n });\n } else {\n // No type found, resolve with the URL only\n resolve(reader.result);\n }\n });\n reader.addEventListener('error', error => {\n reject(error);\n });\n reader.addEventListener('abort', error => {\n reject('Aborted');\n });\n\n reader.readAsDataURL(file);\n });\n\n promises.push(promise);\n }\n\n Promise.all(promises).then(\n data => {\n response.data = data;\n this.onUploadResponse(response, clb);\n },\n error => {\n this.onUploadError(error);\n }\n );\n }\n }\n);\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/asset_manager/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * assetManager: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance\n *\n * ```js\n * const assetManager = editor.AssetManager;\n * ```\n *\n * ## Available Events\n * * `asset:open` - Asset Manager opened.\n * * `asset:close` - Asset Manager closed.\n * * `asset:add` - Asset added. The [Asset] is passed as an argument to the callback.\n * * `asset:remove` - Asset removed. The [Asset] is passed as an argument to the callback.\n * * `asset:update` - Asset updated. The updated [Asset] and the object containing changes are passed as arguments to the callback.\n * * `asset:upload:start` - Before the upload is started.\n * * `asset:upload:end` - After the upload is ended.\n * * `asset:upload:error` - On any error in upload, passes the error as an argument.\n * * `asset:upload:response` - On upload response, passes the result as an argument.\n * * `asset` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.\n * * `asset:custom` - Event for handling custom Asset Manager UI.\n *\n * ## Methods\n * * [open](#open)\n * * [close](#close)\n * * [isOpen](#isopen)\n * * [add](#add)\n * * [get](#get)\n * * [getAll](#getall)\n * * [getAllVisible](#getallvisible)\n * * [remove](#remove)\n * * [store](#store)\n * * [load](#load)\n * * [getContainer](#getcontainer)\n *\n * [Asset]: asset.html\n *\n * @module AssetManager\n */\n\nimport { debounce, isFunction } from 'underscore';\nimport Module from 'common/module';\nimport defaults from './config/config';\nimport Asset from './model/Assets';\nimport Assets from './model/Assets';\nimport AssetsView from './view/AssetsView';\nimport FileUpload from './view/FileUploader';\n\nexport const evAll = 'asset';\nexport const evPfx = `${evAll}:`;\nexport const evSelect = `${evPfx}select`;\nexport const evUpdate = `${evPfx}update`;\nexport const evAdd = `${evPfx}add`;\nexport const evRemove = `${evPfx}remove`;\nexport const evRemoveBefore = `${evRemove}:before`;\nexport const evCustom = `${evPfx}custom`;\nexport const evOpen = `${evPfx}open`;\nexport const evClose = `${evPfx}close`;\nexport const evUpload = `${evPfx}upload`;\nexport const evUploadStart = `${evUpload}:start`;\nexport const evUploadEnd = `${evUpload}:end`;\nexport const evUploadError = `${evUpload}:error`;\nexport const evUploadRes = `${evUpload}:response`;\n\nexport default () => {\n let c = {};\n let assets, assetsVis, am, fu;\n const assetCmd = 'open-assets';\n\n return {\n ...Module,\n\n name: 'AssetManager',\n\n storageKey: 'assets',\n\n Asset,\n\n Assets,\n\n events: {\n all: evAll,\n select: evSelect,\n update: evUpdate,\n add: evAdd,\n remove: evRemove,\n removeBefore: evRemoveBefore,\n custom: evCustom,\n open: evOpen,\n close: evClose,\n uploadStart: evUploadStart,\n uploadEnd: evUploadEnd,\n uploadError: evUploadError,\n uploadResponse: evUploadRes,\n },\n\n init(config = {}) {\n c = { ...defaults, ...config };\n const ppfx = c.pStylePrefix;\n const { em } = c;\n this.config = c;\n this.em = em;\n\n if (ppfx) {\n c.stylePrefix = ppfx + c.stylePrefix;\n }\n\n // Global assets collection\n assets = new Assets([]);\n assetsVis = new Assets([]);\n this.all = assets;\n this.__initListen();\n\n // Setup the sync between the global and public collections\n assets.on('add', model => this.getAllVisible().add(model));\n assets.on('remove', model => this.getAllVisible().remove(model));\n\n return this;\n },\n\n __propEv(ev, ...data) {\n this.em.trigger(ev, ...data);\n this.getAll().trigger(ev, ...data);\n },\n\n __onAllEvent: debounce(function () {\n this.__trgCustom();\n }),\n\n __trgCustom() {\n const bhv = this.__getBehaviour();\n if (!bhv.container && !this.getConfig('custom').open) {\n return;\n }\n this.em.trigger(this.events.custom, this.__customData());\n },\n\n __customData() {\n const bhv = this.__getBehaviour();\n return {\n am: this,\n open: this.isOpen(),\n assets: this.getAll().models,\n types: bhv.types || [],\n container: bhv.container,\n close: () => this.close(),\n remove: (...args) => this.remove(...args),\n select: (asset, complete) => {\n const res = this.add(asset);\n isFunction(bhv.select) && bhv.select(res, complete);\n },\n // extra\n options: bhv.options || {},\n };\n },\n\n /**\n * Open the asset manager.\n * @param {Object} [options] Options for the asset manager.\n * @param {Array} [options.types=['image']] Types of assets to show.\n * @param {Function} [options.select] Type of operation to perform on asset selection. If not specified, nothing will happen.\n * @example\n * assetManager.open({\n * select(asset, complete) {\n * const selected = editor.getSelected();\n * if (selected && selected.is('image')) {\n * selected.addAttributes({ src: asset.getSrc() });\n * // The default AssetManager UI will trigger `select(asset, false)` on asset click\n * // and `select(asset, true)` on double-click\n * complete && assetManager.close();\n * }\n * }\n * });\n * // with your custom types (you should have assets with those types declared)\n * assetManager.open({ types: ['doc'], ... });\n */\n open(options = {}) {\n const cmd = this.em.get('Commands');\n cmd.run(assetCmd, {\n types: ['image'],\n select: () => {},\n ...options,\n });\n },\n\n /**\n * Close the asset manager.\n * @example\n * assetManager.close();\n */\n close() {\n const cmd = this.em.get('Commands');\n cmd.stop(assetCmd);\n },\n\n /**\n * Checks if the asset manager is open\n * @returns {Boolean}\n * @example\n * assetManager.isOpen(); // true | false\n */\n isOpen() {\n const cmd = this.em.get('Commands');\n return !!(cmd && cmd.isActive(assetCmd));\n },\n\n /**\n * Add new asset/s to the collection. URLs are supposed to be unique\n * @param {String|Object|Array|Array} asset URL strings or an objects representing the resource.\n * @param {Object} [opts] Options\n * @returns {[Asset]}\n * @example\n * // As strings\n * assetManager.add('http://img.jpg');\n * assetManager.add(['http://img.jpg', './path/to/img.png']);\n *\n * // Using objects you can indicate the type and other meta informations\n * assetManager.add({\n * // type: 'image',\t// image is default\n * \tsrc: 'http://img.jpg',\n * \theight: 300,\n *\twidth: 200,\n * });\n * assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]);\n */\n add(asset, opts = {}) {\n // Put the model at the beginning\n if (typeof opts.at == 'undefined') {\n opts.at = 0;\n }\n\n return assets.add(asset, opts);\n },\n\n /**\n * Return asset by URL\n * @param {String} src URL of the asset\n * @returns {[Asset]|null}\n * @example\n * const asset = assetManager.get('http://img.jpg');\n */\n get(src) {\n return assets.where({ src })[0] || null;\n },\n\n /**\n * Return the global collection, containing all the assets\n * @returns {Collection<[Asset]>}\n */\n getAll() {\n return assets;\n },\n\n /**\n * Return the visible collection, which contains assets actually rendered\n * @returns {Collection<[Asset]>}\n */\n getAllVisible() {\n return assetsVis;\n },\n\n /**\n * Remove asset\n * @param {String|[Asset]} asset Asset or asset URL\n * @returns {[Asset]} Removed asset\n * @example\n * const removed = assetManager.remove('http://img.jpg');\n * // or by passing the Asset\n * const asset = assetManager.get('http://img.jpg');\n * assetManager.remove(asset);\n */\n remove(asset, opts) {\n return this.__remove(asset, opts);\n },\n\n /**\n * Store assets data to the selected storage\n * @param {Boolean} noStore If true, won't store\n * @returns {Object} Data to store\n * @example\n * var assets = assetManager.store();\n */\n store(noStore) {\n const obj = {};\n const assets = JSON.stringify(this.getAll().toJSON());\n obj[this.storageKey] = assets;\n if (!noStore && c.stm) c.stm.store(obj);\n return obj;\n },\n\n /**\n * Load data from the passed object.\n * The fetched data will be added to the collection.\n * @param {Object} data Object of data to load\n * @returns {Object} Loaded assets\n * @example\n * var assets = assetManager.load({\n * \tassets: [...]\n * })\n *\n */\n load(data = {}) {\n const name = this.storageKey;\n let assets = data[name] || [];\n\n if (typeof assets == 'string') {\n try {\n assets = JSON.parse(data[name]);\n } catch (err) {}\n }\n\n if (assets && assets.length) {\n this.getAll().reset(assets);\n }\n\n return assets;\n },\n\n /**\n * Return the Asset Manager Container\n * @returns {HTMLElement}\n */\n getContainer() {\n const bhv = this.__getBehaviour();\n return bhv.container || (am && am.el);\n },\n\n /**\n * Get assets element container\n * @returns {HTMLElement}\n * @private\n */\n getAssetsEl() {\n return am.el.querySelector('[data-el=assets]');\n },\n\n /**\n * Render assets\n * @param {array} assets Assets to render, without the argument will render all global assets\n * @returns {HTMLElement}\n * @example\n * // Render all assets\n * assetManager.render();\n *\n * // Render some of the assets\n * const assets = assetManager.getAll();\n * assetManager.render(assets.filter(\n * asset => asset.get('category') == 'cats'\n * ));\n */\n render(assts) {\n if (this.getConfig('custom')) return;\n const toRender = assts || this.getAll().models;\n\n if (!am) {\n const obj = this.__viewParams();\n obj.fu = this.FileUploader();\n const el = am && am.el;\n am = new AssetsView({\n el,\n ...obj,\n });\n am.render();\n }\n\n assetsVis.reset(toRender);\n return this.getContainer();\n },\n\n __viewParams() {\n return {\n collection: assetsVis, // Collection visible in asset manager\n globalCollection: assets,\n config: c,\n module: this,\n };\n },\n\n /**\n * Add new type. If you want to get more about type definition we suggest to read the [module's page](/modules/Assets.html)\n * @param {string} id Type ID\n * @param {Object} definition Definition of the type. Each definition contains\n * `model` (business logic), `view` (presentation logic)\n * and `isType` function which recognize the type of the\n * passed entity\n * @private\n * @example\n * assetManager.addType('my-type', {\n * model: {},\n * view: {},\n * isType: (value) => {},\n * })\n */\n addType(id, definition) {\n this.getAll().addType(id, definition);\n },\n\n /**\n * Get type\n * @param {string} id Type ID\n * @returns {Object} Type definition\n * @private\n */\n getType(id) {\n return this.getAll().getType(id);\n },\n\n /**\n * Get types\n * @returns {Array}\n * @private\n */\n getTypes() {\n return this.getAll().getTypes();\n },\n\n //-------\n\n AssetsView() {\n return am;\n },\n\n FileUploader() {\n if (!fu) {\n fu = new FileUpload(this.__viewParams());\n }\n return fu;\n },\n\n onLoad() {\n this.getAll().reset(c.assets);\n const { em, events } = this;\n em.on(`run:${assetCmd}`, () => this.__propEv(events.open));\n em.on(`stop:${assetCmd}`, () => this.__propEv(events.close));\n },\n\n postRender(editorView) {\n c.dropzone && fu && fu.initDropzone(editorView);\n },\n\n /**\n * Set new target\n * @param\t{Object}\tm Model\n * @private\n * */\n setTarget(m) {\n assetsVis.target = m;\n },\n\n /**\n * Set callback after asset was selected\n * @param\t{Object}\tf Callback function\n * @private\n * */\n onSelect(f) {\n assetsVis.onSelect = f;\n },\n\n /**\n * Set callback to fire when the asset is clicked\n * @param {function} func\n * @private\n */\n onClick(func) {\n c.onClick = func;\n },\n\n /**\n * Set callback to fire when the asset is double clicked\n * @param {function} func\n * @private\n */\n onDblClick(func) {\n c.onDblClick = func;\n },\n\n __behaviour(opts = {}) {\n return (this._bhv = {\n ...(this._bhv || {}),\n ...opts,\n });\n },\n\n __getBehaviour(opts = {}) {\n return this._bhv || {};\n },\n\n destroy() {\n assets.stopListening();\n assetsVis.stopListening();\n assets.reset();\n assetsVis.reset();\n fu && fu.remove();\n am && am.remove();\n [assets, assetsVis, am, fu].forEach(i => (i = null));\n this._bhv = {};\n this.all = {};\n c = {};\n },\n };\n};\n","export default {\n stylePrefix: 'trt-',\n\n // Specify the element to use as a container, string (query) or HTMLElement\n // With the empty value, nothing will be rendered\n appendTo: '',\n\n // Default options for the target input\n optionsTarget: [{ value: false }, { value: '_blank' }]\n};\n","import Backbone from 'backbone';\nimport { isUndefined, isString, isFunction } from 'underscore';\nimport { capitalize } from 'utils/mixins';\n\nconst $ = Backbone.$;\n\nexport default Backbone.View.extend({\n events: {},\n eventCapture: ['change'],\n\n appendInput: 1,\n\n attributes() {\n return this.model.get('attributes');\n },\n\n templateLabel() {\n const { ppfx } = this;\n const label = this.getLabel();\n return `
${label}
`;\n },\n\n templateInput() {\n const { clsField } = this;\n return `
`;\n },\n\n initialize(o = {}) {\n const { config = {} } = o;\n const { model, eventCapture } = this;\n const { target } = model;\n const { type } = model.attributes;\n this.config = config;\n this.em = config.em;\n this.pfx = config.stylePrefix || '';\n this.ppfx = config.pStylePrefix || '';\n this.target = target;\n const { ppfx } = this;\n this.clsField = `${ppfx}field ${ppfx}field-${type}`;\n [\n ['change:value', this.onValueChange],\n ['remove', this.removeView]\n ].forEach(([event, clb]) => {\n model.off(event, clb);\n this.listenTo(model, event, clb);\n });\n model.view = this;\n this.listenTo(model, 'change:label', this.render);\n this.listenTo(model, 'change:placeholder', this.rerender);\n this.events = {};\n eventCapture.forEach(event => (this.events[event] = 'onChange'));\n this.delegateEvents();\n this.init();\n },\n\n getClbOpts() {\n return {\n component: this.target,\n trait: this.model,\n elInput: this.getInputElem()\n };\n },\n\n removeView() {\n this.remove();\n this.removed();\n },\n\n init() {},\n removed() {},\n onRender() {},\n onUpdate() {},\n onEvent() {},\n\n /**\n * Fires when the input is changed\n * @private\n */\n onChange(event) {\n const el = this.getInputElem();\n if (el && !isUndefined(el.value)) {\n this.model.set('value', el.value);\n }\n this.onEvent({\n ...this.getClbOpts(),\n event\n });\n },\n\n getValueForTarget() {\n return this.model.get('value');\n },\n\n setInputValue(value) {\n const el = this.getInputElem();\n el && (el.value = value);\n },\n\n /**\n * On change callback\n * @private\n */\n onValueChange(model, value, opts = {}) {\n if (opts.fromTarget) {\n this.setInputValue(model.get('value'));\n this.postUpdate();\n } else {\n const val = this.getValueForTarget();\n model.setTargetValue(val, opts);\n }\n },\n\n /**\n * Render label\n * @private\n */\n renderLabel() {\n const { $el, target } = this;\n const label = this.getLabel();\n let tpl = this.templateLabel(target);\n\n if (this.createLabel) {\n tpl =\n this.createLabel({\n label,\n component: target,\n trait: this\n }) || '';\n }\n\n $el.find('[data-label]').append(tpl);\n },\n\n /**\n * Returns label for the input\n * @return {string}\n * @private\n */\n getLabel() {\n const { em } = this;\n const { label, name } = this.model.attributes;\n return (\n em.t(`traitManager.traits.labels.${name}`) ||\n capitalize(label || name).replace(/-/g, ' ')\n );\n },\n\n /**\n * Returns current target component\n */\n getComponent() {\n return this.target;\n },\n\n /**\n * Returns input element\n * @return {HTMLElement}\n * @private\n */\n getInputEl() {\n if (!this.$input) {\n const { em, model } = this;\n const md = model;\n const { name } = model.attributes;\n const plh = md.get('placeholder') || md.get('default') || '';\n const type = md.get('type') || 'text';\n const min = md.get('min');\n const max = md.get('max');\n const value = this.getModelValue();\n const input = $(``);\n const i18nAttr = em.t(`traitManager.traits.attributes.${name}`) || {};\n input.attr(i18nAttr);\n\n if (!isUndefined(value)) {\n md.set({ value }, { silent: true });\n input.prop('value', value);\n }\n\n if (min) {\n input.prop('min', min);\n }\n\n if (max) {\n input.prop('max', max);\n }\n\n this.$input = input;\n }\n return this.$input.get(0);\n },\n\n getInputElem() {\n const { input, $input } = this;\n return (\n input || ($input && $input.get && $input.get(0)) || this.getElInput()\n );\n },\n\n getModelValue() {\n let value;\n const model = this.model;\n const target = this.target;\n const name = model.get('name');\n\n if (model.get('changeProp')) {\n value = target.get(name);\n } else {\n const attrs = target.get('attributes');\n value = model.get('value') || attrs[name];\n }\n\n return !isUndefined(value) ? value : '';\n },\n\n getElInput() {\n return this.elInput;\n },\n\n /**\n * Renders input\n * @private\n * */\n renderField() {\n const { $el, appendInput, model } = this;\n const inputs = $el.find('[data-input]');\n const el = inputs[inputs.length - 1];\n let tpl = model.el;\n\n if (!tpl) {\n tpl = this.createInput\n ? this.createInput(this.getClbOpts())\n : this.getInputEl();\n }\n\n if (isString(tpl)) {\n el.innerHTML = tpl;\n this.elInput = el.firstChild;\n } else {\n appendInput ? el.appendChild(tpl) : el.insertBefore(tpl, el.firstChild);\n this.elInput = tpl;\n }\n\n model.el = this.elInput;\n },\n\n hasLabel() {\n const { label } = this.model.attributes;\n return !this.noLabel && label !== false;\n },\n\n rerender() {\n this.model.el = null;\n this.render();\n },\n\n postUpdate() {\n this.onUpdate(this.getClbOpts());\n },\n\n render() {\n const { $el, pfx, ppfx, model } = this;\n const { type, id } = model.attributes;\n const hasLabel = this.hasLabel && this.hasLabel();\n const cls = `${pfx}trait`;\n this.$input = null;\n let tmpl = `
\n ${hasLabel ? `
` : ''}\n
\n ${\n this.templateInput\n ? isFunction(this.templateInput)\n ? this.templateInput(this.getClbOpts())\n : this.templateInput\n : ''\n }\n
\n
`;\n $el.empty().append(tmpl);\n hasLabel && this.renderLabel();\n this.renderField();\n this.el.className = `${cls}__wrp ${cls}__wrp-${id}`;\n this.postUpdate();\n this.onRender(this.getClbOpts());\n return this;\n }\n});\n","import DomainViews from 'domain_abstract/view/DomainViews';\nimport TraitView from './TraitView';\n\nexport default DomainViews.extend({\n ns: 'Traits',\n itemView: TraitView,\n reuseView: 1,\n\n initialize(o = {}) {\n const config = o.config || {};\n const pfx = config.stylePrefix || '';\n const em = o.editor;\n this.config = config;\n this.em = em;\n this.pfx = pfx;\n this.ppfx = config.pStylePrefix || '';\n this.className = `${pfx}traits`;\n this.listenTo(em, 'component:toggled', this.updatedCollection);\n },\n\n /**\n * Update view collection\n * @private\n */\n updatedCollection() {\n const { ppfx, className, em } = this;\n const comp = em.getSelected();\n this.el.className = `${className} ${ppfx}one-bg ${ppfx}two-color`;\n this.collection = comp ? comp.get('traits') : [];\n this.render();\n }\n});\n","import Backbone from 'backbone';\nimport { isString, isUndefined } from 'underscore';\nimport TraitView from './TraitView';\n\nconst $ = Backbone.$;\n\nexport default TraitView.extend({\n init() {\n this.listenTo(this.model, 'change:options', this.rerender);\n },\n\n templateInput() {\n const { ppfx, clsField } = this;\n return `
\n
\n
\n
\n
\n
`;\n },\n\n /**\n * Returns input element\n * @return {HTMLElement}\n * @private\n */\n getInputEl() {\n if (!this.$input) {\n const { model, em } = this;\n const propName = model.get('name');\n const opts = model.get('options') || [];\n const values = [];\n let input = '';\n this.$input = $(input);\n const val = model.getTargetValue();\n const valResult = values.indexOf(val) >= 0 ? val : model.get('default');\n !isUndefined(valResult) && this.$input.val(valResult);\n }\n\n return this.$input.get(0);\n }\n});\n","import { isUndefined } from 'underscore';\nimport TraitView from './TraitView';\n\nexport default TraitView.extend({\n appendInput: 0,\n\n templateInput() {\n const { ppfx, clsField } = this;\n return ``;\n },\n\n /**\n * Fires when the input is changed\n * @private\n */\n onChange() {\n const value = this.getInputElem().checked;\n this.model.set('value', this.getCheckedValue(value));\n },\n\n getCheckedValue(checked) {\n let result = checked;\n const { valueTrue, valueFalse } = this.model.attributes;\n\n if (result && !isUndefined(valueTrue)) {\n result = valueTrue;\n }\n\n if (!result && !isUndefined(valueFalse)) {\n result = valueFalse;\n }\n\n return result;\n },\n\n /**\n * Returns input element\n * @return {HTMLElement}\n * @private\n */\n getInputEl(...args) {\n const toInit = !this.$input;\n const el = TraitView.prototype.getInputEl.apply(this, args);\n\n if (toInit) {\n let checked, targetValue;\n const { model, target } = this;\n const { valueTrue, valueFalse } = model.attributes;\n const name = model.get('name');\n\n if (model.get('changeProp')) {\n checked = target.get(name);\n targetValue = checked;\n } else {\n targetValue = target.get('attributes')[name];\n checked = targetValue || targetValue === '' ? !0 : !1;\n }\n\n if (!isUndefined(valueFalse) && targetValue === valueFalse) {\n checked = !1;\n }\n\n el.checked = checked;\n }\n\n return el;\n }\n});\n","import TraitView from './TraitView';\nimport { isUndefined } from 'underscore';\nimport InputNumber from 'domain_abstract/ui/InputNumber';\n\nexport default TraitView.extend({\n getValueForTarget() {\n const { model } = this;\n const { value, unit } = model.attributes;\n return !isUndefined(value) && value !== ''\n ? value + unit\n : model.get('default');\n },\n\n /**\n * Returns input element\n * @return {HTMLElement}\n * @private\n */\n getInputEl() {\n if (!this.input) {\n const { ppfx, model } = this;\n const value = this.getModelValue();\n const inputNumber = new InputNumber({\n contClass: `${ppfx}field-int`,\n type: 'number',\n model: model,\n ppfx\n });\n this.input = inputNumber.render();\n this.$input = this.input.inputEl;\n this.$unit = this.input.unitEl;\n model.set('value', value, { fromTarget: 1 });\n this.$input.val(value);\n this.input = inputNumber.el;\n }\n return this.input;\n }\n});\n","import TraitView from './TraitView';\nimport InputColor from 'domain_abstract/ui/InputColor';\n\nexport default TraitView.extend({\n templateInput: '',\n\n /**\n * Returns input element\n * @return {HTMLElement}\n * @private\n */\n getInputEl() {\n if (!this.input) {\n const model = this.model;\n const value = this.getModelValue();\n const inputColor = new InputColor({\n model,\n target: this.config.em,\n contClass: this.ppfx + 'field-color',\n ppfx: this.ppfx\n });\n const input = inputColor.render();\n input.setValue(value, { fromTarget: 1 });\n this.input = input.el;\n }\n\n return this.input;\n }\n});\n","import { isString } from 'underscore';\nimport TraitView from './TraitView';\n\nexport default TraitView.extend({\n eventCapture: ['click button'],\n\n templateInput: '',\n\n onChange() {\n this.handleClick();\n },\n\n handleClick() {\n const { model, em } = this;\n const command = model.get('command');\n\n if (command) {\n if (isString(command)) {\n em.get('Commands').run(command);\n } else {\n command(em.get('Editor'), model);\n }\n }\n },\n\n renderLabel() {\n if (this.model.get('label')) {\n TraitView.prototype.renderLabel.apply(this, arguments);\n }\n },\n\n getInputEl() {\n const { model, ppfx } = this;\n const { labelButton, text, full } = model.props();\n const label = labelButton || text;\n const className = `${ppfx}btn`;\n const input = ``;\n return input;\n }\n});\n","import { defaults, isElement } from 'underscore';\nimport defaultOpts from './config/config';\nimport TraitsView from './view/TraitsView';\nimport TraitView from './view/TraitView';\nimport TraitSelectView from './view/TraitSelectView';\nimport TraitCheckboxView from './view/TraitCheckboxView';\nimport TraitNumberView from './view/TraitNumberView';\nimport TraitColorView from './view/TraitColorView';\nimport TraitButtonView from './view/TraitButtonView';\n\nexport default () => {\n let c = {};\n let TraitsViewer;\n const typesDef = {\n text: TraitView,\n number: TraitNumberView,\n select: TraitSelectView,\n checkbox: TraitCheckboxView,\n color: TraitColorView,\n button: TraitButtonView\n };\n\n return {\n TraitsView,\n\n /**\n * Name of the module\n * @type {String}\n * @private\n */\n name: 'TraitManager',\n\n /**\n * Get configuration object\n * @return {Object}\n * @private\n */\n getConfig() {\n return c;\n },\n\n /**\n * Initialize module. Automatically called with a new instance of the editor\n * @param {Object} config Configurations\n */\n init(config = {}) {\n c = config;\n defaults(c, defaultOpts);\n const ppfx = c.pStylePrefix;\n this.types = { ...typesDef };\n ppfx && (c.stylePrefix = `${ppfx}${c.stylePrefix}`);\n return this;\n },\n\n postRender() {\n const elTo = this.getConfig().appendTo;\n\n if (elTo) {\n const el = isElement(elTo) ? elTo : document.querySelector(elTo);\n el.appendChild(this.render());\n }\n },\n\n /**\n *\n * Get Traits viewer\n * @private\n */\n getTraitsViewer() {\n return TraitsViewer;\n },\n\n /**\n * Add new trait type\n * @param {string} name Type name\n * @param {Object} methods Object representing the trait\n */\n addType(name, trait) {\n const baseView = this.getType('text');\n this.types[name] = baseView.extend(trait);\n },\n\n /**\n * Get trait type\n * @param {string} name Type name\n * @return {Object}\n */\n getType(name) {\n return this.getTypes()[name];\n },\n\n /**\n * Get all trait types\n * @returns {Object}\n */\n getTypes() {\n return this.types;\n },\n\n render() {\n const el = TraitsViewer && TraitsViewer.el;\n TraitsViewer = new TraitsView({\n el,\n collection: [],\n editor: c.em,\n config: c\n });\n TraitsViewer.itemsView = this.getTypes();\n TraitsViewer.updatedCollection();\n return TraitsViewer.el;\n },\n\n destroy() {\n TraitsViewer && TraitsViewer.remove();\n [c, TraitsViewer].forEach(i => (i = {}));\n }\n };\n};\n","export default {\n // Specify the element to use as a container, string (query) or HTMLElement\n // With the empty value, nothing will be rendered\n appendTo: '',\n\n // Append blocks to canvas on click.\n // With the `true` value, it will try to append the block to the selected component.\n // If there is no selected component, the block will be appened to the wrapper.\n // You can also pass a function to this option, use it as a catch-all for all block\n // clicks and implement a custom logic for each block.\n // appendOnClick: (block, editor) => {\n // if (block.get('id') === 'some-id')\n // editor.getSelected().append(block.get('content'))\n // else\n // editor.getWrapper().append(block.get('content'))\n // }\n appendOnClick: false,\n\n // Default blocks\n blocks: [],\n\n // Avoid rendering the default block manager.\n custom: false\n};\n","import { Model } from 'common';\nimport { isFunction } from 'underscore';\n\n/**\n * @property {String} label Block label, eg. `My block`\n * @property {String|Object} content The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition)\n * @property {String} [media=''] HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content'))`\n * @property {Object} [attributes={}] Block attributes to apply in the view element\n */\nexport default class Block extends Model {\n defaults() {\n return {\n label: '',\n content: '',\n media: '',\n category: '',\n activate: false,\n select: null,\n resetId: false,\n disable: false,\n onClick: null,\n attributes: {}\n };\n }\n\n /**\n * Get block id\n * @returns {String}\n */\n getId() {\n return this.id;\n }\n\n /**\n * Get block label\n * @returns {String}\n */\n getLabel() {\n return this.get('label');\n }\n\n /**\n * Get block media\n * @returns {String}\n */\n getMedia() {\n return this.get('media');\n }\n\n /**\n * Get block content\n * @returns {Object|String|Array} Component definition | HTML string\n */\n getContent() {\n return this.get('content');\n }\n\n /**\n * Get block category label\n * @returns {String}\n */\n getCategoryLabel() {\n const ctg = this.get('category');\n return isFunction(ctg.get) ? ctg.get('label') : ctg.label ? ctg.label : ctg;\n }\n}\n","import { Collection } from 'common';\nimport Block from './Block';\n\nexport default class Blocks extends Collection {}\n\nBlocks.prototype.model = Block;\n","import { Model } from 'common';\n\nexport default class Category extends Model {\n defaults() {\n return {\n id: '',\n label: '',\n open: true,\n attributes: {}\n };\n }\n}\n","import { Collection } from 'common';\nimport Category from './Category';\n\nexport default class Categories extends Collection {}\n\nCategories.prototype.model = Category;\n","import Backbone from 'backbone';\nimport { isFunction } from 'underscore';\nimport { on, off, hasDnd } from 'utils/mixins';\n\nexport default Backbone.View.extend({\n events: {\n click: 'handleClick',\n mousedown: 'startDrag',\n dragstart: 'handleDragStart',\n drag: 'handleDrag',\n dragend: 'handleDragEnd'\n },\n\n initialize(o, config = {}) {\n const { model } = this;\n this.em = config.em;\n this.config = config;\n this.endDrag = this.endDrag.bind(this);\n this.ppfx = config.pStylePrefix || '';\n this.listenTo(model, 'destroy remove', this.remove);\n this.listenTo(model, 'change', this.render);\n },\n\n __getModule() {\n return this.em.get('BlockManager');\n },\n\n handleClick(ev) {\n const { config, model, em } = this;\n const onClick = model.get('onClick') || config.appendOnClick;\n em.trigger('block:click', model, ev);\n if (!onClick) {\n return;\n } else if (isFunction(onClick)) {\n return onClick(model, em.getEditor(), { event: ev });\n }\n const sorter = config.getSorter();\n const content = model.get('content');\n const selected = em.getSelected();\n sorter.setDropContent(content);\n let target, valid;\n\n // If there is a selected component, try first to append\n // the block inside, otherwise, try to place it as a next sibling\n if (selected) {\n valid = sorter.validTarget(selected.getEl(), content);\n\n if (valid.valid) {\n target = selected;\n } else {\n const parent = selected.parent();\n valid = sorter.validTarget(parent.getEl(), content);\n if (valid.valid) target = parent;\n }\n }\n\n // If no target found yet, try to append the block to the wrapper\n if (!target) {\n const wrapper = em.getWrapper();\n valid = sorter.validTarget(wrapper.getEl(), content);\n if (valid.valid) target = wrapper;\n }\n\n const result = target && target.append(content)[0];\n result && em.setSelected(result, { scroll: 1 });\n },\n\n /**\n * Start block dragging\n * @private\n */\n startDrag(e) {\n const { config, em, model } = this;\n const disable = model.get('disable');\n //Right or middel click\n if (e.button !== 0 || !config.getSorter || this.el.draggable || disable)\n return;\n em.refreshCanvas();\n const sorter = config.getSorter();\n sorter.setDragHelper(this.el, e);\n sorter.setDropContent(this.model.get('content'));\n sorter.startSort(this.el);\n on(document, 'mouseup', this.endDrag);\n },\n\n handleDragStart(ev) {\n this.__getModule().__startDrag(this.model, ev);\n },\n\n handleDrag(ev) {\n this.__getModule().__drag(ev);\n },\n\n handleDragEnd() {\n this.__getModule().__endDrag();\n },\n\n /**\n * Drop block\n * @private\n */\n endDrag(e) {\n off(document, 'mouseup', this.endDrag);\n const sorter = this.config.getSorter();\n\n // After dropping the block in the canvas the mouseup event is not yet\n // triggerd on 'this.doc' and so clicking outside, the sorter, tries to move\n // things (throws false positives). As this method just need to drop away\n // the block helper I use the trick of 'moved = 0' to void those errors.\n sorter.moved = 0;\n sorter.endMove();\n },\n\n render() {\n const { em, el, $el, ppfx, model } = this;\n const disable = model.get('disable');\n const attr = model.get('attributes') || {};\n const cls = attr.class || '';\n const className = `${ppfx}block`;\n const label =\n (em && em.t(`blockManager.labels.${model.id}`)) || model.get('label');\n const render = model.get('render');\n const media = model.get('media');\n const clsAdd = disable ? `${className}--disable` : `${ppfx}four-color-h`;\n $el.attr(attr);\n el.className = `${cls} ${className} ${ppfx}one-bg ${clsAdd}`.trim();\n el.innerHTML = `\n ${media ? `
${media}
` : ''}\n
${label}
\n `;\n el.title = attr.title || el.textContent.trim();\n el.setAttribute('draggable', hasDnd(em) && !disable ? true : false);\n const result = render && render({ el, model, className, prefix: ppfx });\n if (result) el.innerHTML = result;\n return this;\n }\n});\n","import { View } from 'backbone';\nimport html from 'utils/html';\n\nexport default class CategoryView extends View {\n template({ pfx, label }) {\n return html`\n
\n \n ${label}\n
\n
\n `;\n }\n\n attributes() {\n return this.model.get('attributes');\n }\n\n initialize(o = {}, config = {}) {\n this.config = config;\n const pfx = config.pStylePrefix || '';\n this.em = config.em;\n this.pfx = pfx;\n this.caretR = 'fa fa-caret-right';\n this.caretD = 'fa fa-caret-down';\n this.iconClass = `${pfx}caret-icon`;\n this.activeClass = `${pfx}open`;\n this.className = `${pfx}block-category`;\n this.events = {};\n this.events[`click .${pfx}title`] = 'toggle';\n this.listenTo(this.model, 'change:open', this.updateVisibility);\n this.delegateEvents();\n this.model.view = this;\n }\n\n updateVisibility() {\n if (this.model.get('open')) this.open();\n else this.close();\n }\n\n open() {\n this.$el.addClass(this.activeClass);\n this.getIconEl().className = `${this.iconClass} ${this.caretD}`;\n this.getBlocksEl().style.display = '';\n }\n\n close() {\n this.$el.removeClass(this.activeClass);\n this.getIconEl().className = `${this.iconClass} ${this.caretR}`;\n this.getBlocksEl().style.display = 'none';\n }\n\n toggle() {\n var model = this.model;\n model.set('open', !model.get('open'));\n }\n\n getIconEl() {\n if (!this.iconEl) {\n this.iconEl = this.el.querySelector('.' + this.iconClass);\n }\n\n return this.iconEl;\n }\n\n getBlocksEl() {\n if (!this.blocksEl) {\n this.blocksEl = this.el.querySelector('.' + this.pfx + 'blocks-c');\n }\n\n return this.blocksEl;\n }\n\n append(el) {\n this.getBlocksEl().appendChild(el);\n }\n\n render() {\n const { em, el, $el, model, pfx } = this;\n const label =\n em.t(`blockManager.categories.${model.id}`) || model.get('label');\n el.innerHTML = this.template({ pfx, label });\n $el.addClass(this.className);\n $el.css({ order: model.get('order') });\n this.updateVisibility();\n\n return this;\n }\n}\n","import Backbone from 'backbone';\nimport { isString, isObject, bindAll } from 'underscore';\nimport BlockView from './BlockView';\nimport CategoryView from './CategoryView';\n\nexport default Backbone.View.extend({\n initialize(opts, config) {\n bindAll(this, 'getSorter', 'onDrag', 'onDrop', 'onMove');\n this.config = config || {};\n this.categories = opts.categories || '';\n this.renderedCategories = [];\n var ppfx = this.config.pStylePrefix || '';\n this.ppfx = ppfx;\n this.noCatClass = `${ppfx}blocks-no-cat`;\n this.blockContClass = `${ppfx}blocks-c`;\n this.catsClass = `${ppfx}block-categories`;\n const coll = this.collection;\n this.listenTo(coll, 'add', this.addTo);\n this.listenTo(coll, 'reset', this.render);\n this.em = this.config.em;\n this.tac = 'test-tac';\n this.grabbingCls = this.ppfx + 'grabbing';\n\n if (this.em) {\n this.config.getSorter = this.getSorter;\n this.canvas = this.em.get('Canvas');\n }\n },\n\n updateConfig(opts = {}) {\n this.config = {\n ...this.config,\n ...opts\n };\n },\n\n /**\n * Get sorter\n * @private\n */\n getSorter() {\n if (!this.em) return;\n if (!this.sorter) {\n var utils = this.em.get('Utils');\n var canvas = this.canvas;\n this.sorter = new utils.Sorter({\n container: canvas.getBody(),\n placer: canvas.getPlacerEl(),\n containerSel: '*',\n itemSel: '*',\n pfx: this.ppfx,\n onStart: this.onDrag,\n onEndMove: this.onDrop,\n onMove: this.onMove,\n document: canvas.getFrameEl().contentDocument,\n direction: 'a',\n wmargin: 1,\n nested: 1,\n em: this.em,\n canvasRelative: 1\n });\n }\n return this.sorter;\n },\n\n /**\n * Callback when block is on drag\n * @private\n */\n onDrag(e) {\n this.em.stopDefault();\n this.em.trigger('block:drag:start', e);\n },\n\n onMove(e) {\n this.em.trigger('block:drag:move', e);\n },\n\n /**\n * Callback when block is dropped\n * @private\n */\n onDrop(model) {\n const { em } = this;\n em.runDefault();\n\n if (model && model.get) {\n const oldActive = 'activeOnRender';\n\n if (model.get(oldActive)) {\n model.trigger('active');\n model.unset(oldActive);\n }\n\n em.trigger('block:drag:stop', model);\n }\n },\n\n /**\n * Add new model to the collection\n * @param {Model} model\n * @private\n * */\n addTo(model) {\n this.add(model);\n },\n\n /**\n * Render new model inside the view\n * @param {Model} model\n * @param {Object} fragment Fragment collection\n * @private\n * */\n add(model, fragment) {\n const { config } = this;\n var frag = fragment || null;\n var view = new BlockView(\n {\n model,\n attributes: model.get('attributes')\n },\n config\n );\n var rendered = view.render().el;\n var category = model.get('category');\n\n // Check for categories\n if (category && this.categories && !config.ignoreCategories) {\n if (isString(category)) {\n category = {\n id: category,\n label: category\n };\n } else if (isObject(category) && !category.id) {\n category.id = category.label;\n }\n\n var catModel = this.categories.add(category);\n var catId = catModel.get('id');\n var catView = this.renderedCategories[catId];\n var categories = this.getCategoriesEl();\n model.set('category', catModel, { silent: true });\n\n if (!catView && categories) {\n catView = new CategoryView(\n {\n model: catModel\n },\n this.config\n ).render();\n this.renderedCategories[catId] = catView;\n categories.appendChild(catView.el);\n }\n\n catView && catView.append(rendered);\n return;\n }\n\n if (frag) frag.appendChild(rendered);\n else this.append(rendered);\n },\n\n getCategoriesEl() {\n if (!this.catsEl) {\n this.catsEl = this.el.querySelector(`.${this.catsClass}`);\n }\n\n return this.catsEl;\n },\n\n getBlocksEl() {\n if (!this.blocksEl) {\n this.blocksEl = this.el.querySelector(\n `.${this.noCatClass} .${this.blockContClass}`\n );\n }\n\n return this.blocksEl;\n },\n\n append(el) {\n let blocks = this.getBlocksEl();\n blocks && blocks.appendChild(el);\n },\n\n render() {\n const ppfx = this.ppfx;\n const frag = document.createDocumentFragment();\n this.catsEl = null;\n this.blocksEl = null;\n this.renderedCategories = [];\n this.el.innerHTML = `\n
\n
\n
\n
\n `;\n\n this.collection.each(model => this.add(model, frag));\n this.append(frag);\n const cls = `${this.blockContClass}s ${ppfx}one-bg ${ppfx}two-color`;\n this.$el.addClass(cls);\n this.rendered = true;\n return this;\n }\n});\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/block_manager/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * blockManager: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.\n *\n * ```js\n * // Listen to events\n * editor.on('block:add', (block) => { ... });\n *\n * // Use the API\n * const blockManager = editor.BlockManager;\n * blockManager.add(...);\n * ```\n *\n * ## Available Events\n * * `block:add` - Block added. The [Block] is passed as an argument to the callback.\n * * `block:remove` - Block removed. The [Block] is passed as an argument to the callback.\n * * `block:update` - Block updated. The [Block] and the object containing changes are passed as arguments to the callback.\n * * `block:drag:start` - Started dragging block, the [Block] is passed as an argument.\n * * `block:drag` - Dragging block, the [Block] is passed as an argument.\n * * `block:drag:stop` - Dragging of the block is stopped. The dropped [Component] (if dropped successfully) and the [Block] are passed as arguments.\n * * `block` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.\n *\n * ## Methods\n * * [add](#add)\n * * [get](#get)\n * * [getAll](#getall)\n * * [getAllVisible](#getallvisible)\n * * [remove](#remove)\n * * [getConfig](#getconfig)\n * * [getCategories](#getcategories)\n * * [getContainer](#getcontainer)\n * * [render](#render)\n *\n * [Block]: block.html\n * [Component]: component.html\n *\n * @module BlockManager\n */\nimport { isElement, isArray } from 'underscore';\nimport Module from 'common/module';\nimport defaults from './config/config';\nimport Block from './model/Block';\nimport Blocks from './model/Blocks';\nimport Category from './model/Category';\nimport Categories from './model/Categories';\nimport BlocksView from './view/BlocksView';\n\nexport const evAll = 'block';\nexport const evPfx = `${evAll}:`;\nexport const evAdd = `${evPfx}add`;\nexport const evUpdate = `${evPfx}update`;\nexport const evRemove = `${evPfx}remove`;\nexport const evRemoveBefore = `${evRemove}:before`;\nexport const evDrag = `${evPfx}drag`;\nexport const evDragStart = `${evDrag}:start`;\nexport const evDragStop = `${evDrag}:stop`;\nexport const evCustom = `${evPfx}custom`;\n\nexport default () => {\n var c = {};\n var blocks, blocksVisible, blocksView;\n var categories = [];\n\n return {\n ...Module,\n\n name: 'BlockManager',\n\n Block,\n\n Blocks,\n\n Category,\n\n Categories,\n\n events: {\n all: evAll,\n update: evUpdate,\n add: evAdd,\n remove: evRemove,\n removeBefore: evRemoveBefore,\n drag: evDrag,\n dragStart: evDragStart,\n dragEnd: evDragStop,\n custom: evCustom,\n },\n\n init(config = {}) {\n c = { ...defaults, ...config };\n const { em } = c;\n this.em = em;\n\n // Global blocks collection\n blocks = new Blocks(c.blocks);\n blocksVisible = new Blocks(blocks.models);\n categories = new Categories();\n this.all = blocks;\n this.__initListen();\n\n // Setup the sync between the global and public collections\n blocks.on('add', model => blocksVisible.add(model));\n blocks.on('remove', model => blocksVisible.remove(model));\n blocks.on('reset', coll => blocksVisible.reset(coll.models));\n\n return this;\n },\n\n __trgCustom() {\n this.em.trigger(this.events.custom, this.__customData());\n },\n\n __customData() {\n const bhv = this.__getBehaviour();\n return {\n bm: this,\n blocks: this.getAll().models,\n container: bhv.container,\n dragStart: (block, ev) => this.startDrag(block, ev),\n drag: ev => this.__drag(ev),\n dragStop: cancel => this.endDrag(cancel),\n };\n },\n\n __startDrag(block, ev) {\n const { em, events } = this;\n const content = block.getContent ? block.getContent() : block;\n this._dragBlock = block;\n em.set({ dragResult: null, dragContent: content });\n [em, blocks].map(i => i.trigger(events.dragStart, block, ev));\n },\n\n __drag(ev) {\n const { em, events } = this;\n const block = this._dragBlock;\n [em, blocks].map(i => i.trigger(events.drag, block, ev));\n },\n\n __endDrag() {\n const { em, events } = this;\n const block = this._dragBlock;\n const cmp = em.get('dragResult');\n this._dragBlock = null;\n\n if (cmp) {\n const oldKey = 'activeOnRender';\n const oldActive = cmp.get && cmp.get(oldKey);\n const toActive = block.get('activate') || oldActive;\n const toSelect = block.get('select');\n const first = isArray(cmp) ? cmp[0] : cmp;\n\n if (toSelect || (toActive && toSelect !== false)) {\n em.setSelected(first);\n }\n\n if (toActive) {\n first.trigger('active');\n oldActive && first.unset(oldKey);\n }\n\n if (block.get('resetId')) {\n first.onAll(block => block.resetId());\n }\n }\n\n em.set({ dragResult: null, dragContent: null });\n [em, blocks].map(i => i.trigger(events.dragEnd, cmp, block));\n },\n\n __getFrameViews() {\n return this.em\n .get('Canvas')\n .getFrames()\n .map(frame => frame.view);\n },\n\n __behaviour(opts = {}) {\n return (this._bhv = {\n ...(this._bhv || {}),\n ...opts,\n });\n },\n\n __getBehaviour() {\n return this._bhv || {};\n },\n\n startDrag(block, ev) {\n this.__startDrag(block, ev);\n this.__getFrameViews().forEach(fv => fv.droppable.startCustom());\n },\n\n endDrag(cancel) {\n this.__getFrameViews().forEach(fv => fv.droppable.endCustom(cancel));\n this.__endDrag();\n },\n\n /**\n * Get configuration object\n * @return {Object}\n */\n getConfig() {\n return c;\n },\n\n postRender() {\n const collection = blocksVisible;\n blocksView = new BlocksView({ collection, categories }, c);\n const elTo = this.getConfig().appendTo;\n\n if (elTo) {\n const el = isElement(elTo) ? elTo : document.querySelector(elTo);\n if (!el) return this.__logWarn('\"appendTo\" element not found');\n el.appendChild(this.render(blocksVisible.models));\n }\n\n this.__trgCustom();\n },\n\n /**\n * Add new block.\n * @param {String} id Block ID\n * @param {[Block]} props Block properties\n * @returns {[Block]} Added block\n * @example\n * blockManager.add('h1-block', {\n * label: 'Heading',\n * content: '

Put your title here

',\n * category: 'Basic',\n * attributes: {\n * title: 'Insert h1 block'\n * }\n * });\n */\n add(id, props, opts = {}) {\n const prp = props || {};\n prp.id = id;\n return blocks.add(prp, opts);\n },\n\n /**\n * Get the block by id.\n * @param {String} id Block id\n * @returns {[Block]}\n * @example\n * const block = blockManager.get('h1-block');\n * console.log(JSON.stringify(block));\n * // {label: 'Heading', content: '

Put your ...', ...}\n */\n get(id) {\n return blocks.get(id);\n },\n\n /**\n * Return all blocks.\n * @returns {Collection<[Block]>}\n * @example\n * const blocks = blockManager.getAll();\n * console.log(JSON.stringify(blocks));\n * // [{label: 'Heading', content: '

Put your ...'}, ...]\n */\n getAll() {\n return blocks;\n },\n\n /**\n * Return the visible collection, which containes blocks actually rendered\n * @returns {Collection<[Block]>}\n */\n getAllVisible() {\n return blocksVisible;\n },\n\n /**\n * Remove block.\n * @param {String|[Block]} block Block or block ID\n * @returns {[Block]} Removed block\n * @example\n * const removed = blockManager.remove('BLOCK_ID');\n * // or by passing the Block\n * const block = blockManager.get('BLOCK_ID');\n * blockManager.remove(block);\n */\n remove(block, opts = {}) {\n return this.__remove(block, opts);\n },\n\n /**\n * Get all available categories.\n * It's possible to add categories only within blocks via 'add()' method\n * @return {Array|Collection}\n */\n getCategories() {\n return categories;\n },\n\n /**\n * Return the Blocks container element\n * @return {HTMLElement}\n */\n getContainer() {\n return blocksView.el;\n },\n\n /**\n * Render blocks\n * @param {Array} blocks Blocks to render, without the argument will render all global blocks\n * @param {Object} [opts={}] Options\n * @param {Boolean} [opts.external] Render blocks in a new container (HTMLElement will be returned)\n * @param {Boolean} [opts.ignoreCategories] Render blocks without categories\n * @return {HTMLElement} Rendered element\n * @example\n * // Render all blocks (inside the global collection)\n * blockManager.render();\n *\n * // Render new set of blocks\n * const blocks = blockManager.getAll();\n * const filtered = blocks.filter(block => block.get('category') == 'sections')\n *\n * blockManager.render(filtered);\n * // Or a new set from an array\n * blockManager.render([\n * {label: 'Label text', content: '
Content
'}\n * ]);\n *\n * // Back to blocks from the global collection\n * blockManager.render();\n *\n * // You can also render your blocks outside of the main block container\n * const newBlocksEl = blockManager.render(filtered, { external: true });\n * document.getElementById('some-id').appendChild(newBlocksEl);\n */\n render(blocks, opts = {}) {\n const toRender = blocks || this.getAll().models;\n\n if (opts.external) {\n const collection = new Blocks(toRender);\n return new BlocksView({ collection, categories }, { ...c, ...opts }).render().el;\n }\n\n if (blocksView) {\n blocksView.updateConfig(opts);\n blocksView.collection.reset(toRender);\n\n if (!blocksView.rendered) {\n blocksView.render();\n blocksView.rendered = 1;\n }\n }\n\n return this.getContainer();\n },\n\n destroy() {\n const colls = [blocks, blocksVisible, categories];\n colls.map(c => c.stopListening());\n colls.map(c => c.reset());\n blocksView && blocksView.remove();\n c = {};\n blocks = {};\n blocksVisible = {};\n blocksView = {};\n categories = [];\n this.all = {};\n },\n };\n};\n","const swv = 'sw-visibility';\nconst expt = 'export-template';\nconst osm = 'open-sm';\nconst otm = 'open-tm';\nconst ola = 'open-layers';\nconst obl = 'open-blocks';\nconst ful = 'fullscreen';\nconst prv = 'preview';\n\nexport default {\n stylePrefix: 'pn-',\n\n // Default panels fa-sliders for features\n defaults: [\n {\n id: 'commands',\n buttons: [{}]\n },\n {\n id: 'options',\n buttons: [\n {\n active: true,\n id: swv,\n className: 'fa fa-square-o',\n command: swv,\n context: swv,\n attributes: { title: 'View components' }\n },\n {\n id: prv,\n className: 'fa fa-eye',\n command: prv,\n context: prv,\n attributes: { title: 'Preview' }\n },\n {\n id: ful,\n className: 'fa fa-arrows-alt',\n command: ful,\n context: ful,\n attributes: { title: 'Fullscreen' }\n },\n {\n id: expt,\n className: 'fa fa-code',\n command: expt,\n attributes: { title: 'View code' }\n }\n ]\n },\n {\n id: 'views',\n buttons: [\n {\n id: osm,\n className: 'fa fa-paint-brush',\n command: osm,\n active: true,\n togglable: 0,\n attributes: { title: 'Open Style Manager' }\n },\n {\n id: otm,\n className: 'fa fa-cog',\n command: otm,\n togglable: 0,\n attributes: { title: 'Settings' }\n },\n {\n id: ola,\n className: 'fa fa-bars',\n command: ola,\n togglable: 0,\n attributes: { title: 'Open Layer Manager' }\n },\n {\n id: obl,\n className: 'fa fa-th-large',\n command: obl,\n togglable: 0,\n attributes: { title: 'Open Blocks' }\n }\n ]\n }\n ],\n\n // Editor model\n em: null,\n\n // Delay before show children buttons (in milliseconds)\n delayBtnsShow: 300\n};\n","import Backbone from 'backbone';\nimport Buttons from './Buttons';\n\nexport default Backbone.Model.extend({\n defaults: {\n id: '',\n content: '',\n visible: true,\n buttons: [],\n attributes: {}\n },\n\n initialize(options) {\n this.btn = this.get('buttons') || [];\n this.buttons = new Buttons(this.btn);\n this.set('buttons', this.buttons);\n }\n});\n","import Backbone from 'backbone';\nimport Panel from './Panel';\n\nexport default Backbone.Collection.extend({\n model: Panel\n});\n","import Backbone from 'backbone';\nimport { isString, isObject, isFunction } from 'underscore';\n\nconst $ = Backbone.$;\n\nexport default Backbone.View.extend({\n tagName() {\n return this.model.get('tagName');\n },\n\n events: {\n click: 'clicked'\n },\n\n initialize(o) {\n const { model } = this;\n const cls = model.get('className');\n const { command, listen } = model.attributes;\n const config = o.config || {};\n const { em } = config;\n this.config = config;\n this.em = em;\n const pfx = this.config.stylePrefix || '';\n const ppfx = this.config.pStylePrefix || '';\n this.pfx = pfx;\n this.ppfx = this.config.pStylePrefix || '';\n this.id = pfx + model.get('id');\n this.activeCls = `${pfx}active ${ppfx}four-color`;\n this.disableCls = `${ppfx}disabled`;\n this.btnsVisCls = `${pfx}visible`;\n this.className = pfx + 'btn' + (cls ? ' ' + cls : '');\n this.listenTo(model, 'change', this.render);\n this.listenTo(model, 'change:active updateActive', this.updateActive);\n this.listenTo(model, 'checkActive', this.checkActive);\n this.listenTo(model, 'change:bntsVis', this.updateBtnsVis);\n this.listenTo(model, 'change:attributes', this.updateAttributes);\n this.listenTo(model, 'change:className', this.updateClassName);\n this.listenTo(model, 'change:disable', this.updateDisable);\n\n if (em && isString(command) && listen) {\n const chnOpt = { fromListen: 1 };\n this.listenTo(em, `run:${command}`, () =>\n model.set('active', true, chnOpt)\n );\n this.listenTo(em, `stop:${command}`, () =>\n model.set('active', false, chnOpt)\n );\n }\n\n if (em && em.get) this.commands = em.get('Commands');\n },\n\n /**\n * Updates class name of the button\n *\n * @return void\n * */\n updateClassName() {\n const { model, pfx } = this;\n const cls = model.get('className');\n const attrCls = model.get('attributes').class;\n const classStr = `${attrCls ? attrCls : ''} ${pfx}btn ${cls ? cls : ''}`;\n this.$el.attr('class', classStr.trim());\n },\n\n /**\n * Updates attributes of the button\n *\n * @return void\n * */\n updateAttributes() {\n const { em, model, $el } = this;\n const attr = model.get('attributes') || {};\n const title = em && em.t && em.t(`panels.buttons.titles.${model.id}`);\n $el.attr(attr);\n title && $el.attr({ title });\n\n this.updateClassName();\n },\n\n /**\n * Updates visibility of children buttons\n *\n * @return void\n * */\n updateBtnsVis() {\n if (!this.$buttons) return;\n\n if (this.model.get('bntsVis')) this.$buttons.addClass(this.btnsVisCls);\n else this.$buttons.removeClass(this.btnsVisCls);\n },\n\n /**\n * Update active status of the button\n *\n * @return void\n * */\n updateActive(m, v, opts = {}) {\n const { model, commands, $el, activeCls } = this;\n const { fromCollection, fromListen } = opts;\n const context = model.get('context');\n const options = model.get('options');\n const commandName = model.get('command');\n let command = {};\n\n if (!commandName) return;\n\n if (commands && isString(commandName)) {\n command = commands.get(commandName) || {};\n } else if (isFunction(commandName)) {\n command = commands.create({ run: commandName });\n } else if (commandName !== null && isObject(commandName)) {\n command = commands.create(commandName);\n }\n\n if (model.get('active')) {\n !fromCollection && model.collection.deactivateAll(context, model);\n model.set('active', true, { silent: true }).trigger('checkActive');\n !fromListen &&\n commands.runCommand(command, { ...options, sender: model });\n\n // Disable button if the command has no stop method\n command.noStop && model.set('active', false);\n } else {\n $el.removeClass(activeCls);\n !fromListen &&\n commands.stopCommand(command, { ...options, sender: model, force: 1 });\n }\n },\n\n updateDisable() {\n const { disableCls, model } = this;\n const disable = model.get('disable');\n this.$el[disable ? 'addClass' : 'removeClass'](disableCls);\n },\n\n /**\n * Update active style status\n *\n * @return void\n * */\n checkActive() {\n const { model, $el, activeCls } = this;\n model.get('active') ? $el.addClass(activeCls) : $el.removeClass(activeCls);\n },\n\n /**\n * Triggered when button is clicked\n * @param {Object} e Event\n *\n * @return void\n * */\n clicked(e) {\n const { model } = this;\n\n if (model.get('bntsVis') || model.get('disable') || !model.get('command'))\n return;\n\n this.toggleActive();\n },\n\n toggleActive() {\n const { model, em } = this;\n const { active, togglable } = model.attributes;\n\n if (active && !togglable) return;\n\n model.set('active', !active);\n\n // If the stop is requested\n if (active) {\n if (model.get('runDefaultCommand')) em.runDefault();\n } else {\n if (model.get('stopDefaultCommand')) em.stopDefault();\n }\n },\n\n render() {\n const { model } = this;\n const label = model.get('label');\n const { $el } = this;\n !model.get('el') && $el.empty();\n this.updateAttributes();\n label && $el.append(label);\n this.checkActive();\n this.updateDisable();\n\n return this;\n }\n});\n","import Backbone from 'backbone';\nimport ButtonView from './ButtonView';\nimport { result } from 'underscore';\n\nexport default Backbone.View.extend({\n initialize(o) {\n this.opt = o || {};\n this.config = this.opt.config || {};\n this.pfx = this.config.stylePrefix || '';\n this.parentM = this.opt.parentM || null;\n this.listenTo(this.collection, 'add', this.addTo);\n this.listenTo(this.collection, 'reset remove', this.render);\n this.className = this.pfx + 'buttons';\n },\n\n /**\n * Add to collection\n * @param Object Model\n *\n * @return Object\n * */\n addTo(model) {\n this.addToCollection(model);\n },\n\n /**\n * Add new object to collection\n * @param Object Model\n * @param Object Fragment collection\n *\n * @return Object Object created\n * */\n addToCollection(model, fragmentEl) {\n const fragment = fragmentEl || null;\n const viewObject = ButtonView;\n const el = model.get('el');\n const view = new viewObject({\n el,\n model,\n config: this.config,\n parentM: this.parentM\n });\n const rendered = view.render().el;\n\n if (fragment) {\n fragment.appendChild(rendered);\n } else {\n this.$el.append(rendered);\n }\n\n return rendered;\n },\n\n render() {\n var fragment = document.createDocumentFragment();\n this.$el.empty();\n\n this.collection.each(function(model) {\n this.addToCollection(model, fragment);\n }, this);\n\n this.$el.append(fragment);\n this.$el.attr('class', result(this, 'className'));\n return this;\n }\n});\n","import Backbone from 'backbone';\nimport ButtonsView from './ButtonsView';\n\nexport default Backbone.View.extend({\n initialize(o) {\n const config = o.config || {};\n const model = this.model;\n this.config = config;\n this.pfx = config.stylePrefix || '';\n this.ppfx = config.pStylePrefix || '';\n this.buttons = model.get('buttons');\n this.className = this.pfx + 'panel';\n this.id = this.pfx + model.get('id');\n this.listenTo(model, 'change:appendContent', this.appendContent);\n this.listenTo(model, 'change:content', this.updateContent);\n this.listenTo(model, 'change:visible', this.toggleVisible);\n model.view = this;\n },\n\n /**\n * Append content of the panel\n * */\n appendContent() {\n this.$el.append(this.model.get('appendContent'));\n },\n\n /**\n * Update content\n * */\n updateContent() {\n this.$el.html(this.model.get('content'));\n },\n\n toggleVisible() {\n if (!this.model.get('visible')) {\n this.$el.addClass(`${this.ppfx}hidden`);\n return;\n }\n this.$el.removeClass(`${this.ppfx}hidden`);\n },\n\n attributes() {\n return this.model.get('attributes');\n },\n\n initResize() {\n const em = this.config.em;\n const editor = em ? em.get('Editor') : '';\n const resizable = this.model.get('resizable');\n\n if (editor && resizable) {\n var resz = resizable === true ? [1, 1, 1, 1] : resizable;\n var resLen = resz.length;\n var tc,\n cr,\n bc,\n cl = 0;\n\n // Choose which sides of the panel are resizable\n if (resLen == 2) {\n tc = resz[0];\n bc = resz[0];\n cr = resz[1];\n cl = resz[1];\n } else if (resLen == 4) {\n tc = resz[0];\n cr = resz[1];\n bc = resz[2];\n cl = resz[3];\n }\n\n var resizer = editor.Utils.Resizer.init({\n tc,\n cr,\n bc,\n cl,\n tl: 0,\n tr: 0,\n bl: 0,\n br: 0,\n appendTo: this.el,\n silentFrames: 1,\n avoidContainerUpdate: 1,\n prefix: editor.getConfig().stylePrefix,\n onEnd() {\n em && em.trigger('change:canvasOffset');\n },\n posFetcher: (el, { target }) => {\n const style = el.style;\n const config = resizer.getConfig();\n const keyWidth = config.keyWidth;\n const keyHeight = config.keyHeight;\n const rect = el.getBoundingClientRect();\n const forContainer = target == 'container';\n const styleWidth = style[keyWidth];\n const styleHeight = style[keyHeight];\n const width =\n styleWidth && !forContainer ? parseFloat(styleWidth) : rect.width;\n const height =\n styleHeight && !forContainer\n ? parseFloat(styleHeight)\n : rect.height;\n return {\n left: 0,\n top: 0,\n width,\n height\n };\n },\n ...resizable\n });\n resizer.blur = () => {};\n resizer.focus(this.el);\n }\n },\n\n render() {\n const $el = this.$el;\n const ppfx = this.ppfx;\n const cls = `${this.className} ${this.id} ${ppfx}one-bg ${ppfx}two-color`;\n $el.addClass(cls);\n\n this.toggleVisible();\n\n if (this.buttons.length) {\n var buttons = new ButtonsView({\n collection: this.buttons,\n config: this.config\n });\n $el.append(buttons.render().el);\n }\n\n $el.append(this.model.get('content'));\n return this;\n }\n});\n","import Backbone from 'backbone';\nimport PanelView from './PanelView';\n\nexport default Backbone.View.extend({\n initialize(o) {\n this.opt = o || {};\n this.config = this.opt.config || {};\n this.pfx = this.config.stylePrefix || '';\n const items = this.collection;\n this.listenTo(items, 'add', this.addTo);\n this.listenTo(items, 'reset', this.render);\n this.listenTo(items, 'remove', this.onRemove);\n this.className = this.pfx + 'panels';\n },\n\n onRemove(model) {\n const view = model.view;\n view && view.remove();\n },\n\n /**\n * Add to collection\n * @param Object Model\n *\n * @return Object\n * @private\n * */\n addTo(model) {\n this.addToCollection(model);\n },\n\n /**\n * Add new object to collection\n * @param Object Model\n * @param Object Fragment collection\n * @param integer Index of append\n *\n * @return Object Object created\n * @private\n * */\n addToCollection(model, fragmentEl) {\n const fragment = fragmentEl || null;\n const config = this.config;\n const el = model.get('el');\n const view = new PanelView({\n el,\n model,\n config\n });\n const rendered = view.render().el;\n const appendTo = model.get('appendTo');\n\n // Do nothing if the panel was requested to be another element\n if (el) {\n } else if (appendTo) {\n var appendEl = document.querySelector(appendTo);\n appendEl.appendChild(rendered);\n } else {\n if (fragment) {\n fragment.appendChild(rendered);\n } else {\n this.$el.append(rendered);\n }\n }\n\n view.initResize();\n return rendered;\n },\n\n render() {\n const $el = this.$el;\n const frag = document.createDocumentFragment();\n $el.empty();\n this.collection.each(model => this.addToCollection(model, frag));\n $el.append(frag);\n $el.attr('class', this.className);\n return this;\n }\n});\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/panels/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * panels: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance\n *\n * ```js\n * const panelManager = editor.Panels;\n * ```\n *\n * * [addPanel](#addpanel)\n * * [addButton](#addbutton)\n * * [getButton](#getbutton)\n * * [getPanel](#getpanel)\n * * [getPanels](#getpanels)\n * * [getPanelsEl](#getpanelsel)\n * * [removePanel](#removepanel)\n * * [removeButton](#removebutton)\n *\n * @module Panels\n */\nimport defaults from './config/config';\nimport Panel from './model/Panel';\nimport Panels from './model/Panels';\nimport PanelsView from './view/PanelsView';\n\nexport default () => {\n var c = {};\n var panels, PanelsViewObj;\n\n return {\n /**\n * Name of the module\n * @type {String}\n * @private\n */\n name: 'Panels',\n\n /**\n * Initialize module. Automatically called with a new instance of the editor\n * @param {Object} config Configurations\n * @private\n */\n init(config) {\n c = config || {};\n for (var name in defaults) {\n if (!(name in c)) c[name] = defaults[name];\n }\n\n var ppfx = c.pStylePrefix;\n if (ppfx) c.stylePrefix = ppfx + c.stylePrefix;\n\n panels = new Panels(c.defaults);\n return this;\n },\n\n /**\n * Returns the collection of panels\n * @return {Collection} Collection of panel\n */\n getPanels() {\n return panels;\n },\n\n /**\n * Returns panels element\n * @return {HTMLElement}\n */\n getPanelsEl() {\n return PanelsViewObj && PanelsViewObj.el;\n },\n\n /**\n * Add new panel to the collection\n * @param {Object|Panel} panel Object with right properties or an instance of Panel\n * @return {Panel} Added panel. Useful in case passed argument was an Object\n * @example\n * var newPanel = panelManager.addPanel({\n * id: 'myNewPanel',\n * visible : true,\n * buttons : [...],\n * });\n */\n addPanel(panel) {\n return panels.add(panel);\n },\n\n /**\n * Remove a panel from the collection\n * @param {Object|Panel|String} panel Object with right properties or an instance of Panel or Painel id\n * @return {Panel} Removed panel. Useful in case passed argument was an Object\n * @example\n * const newPanel = panelManager.removePanel({\n * id: 'myNewPanel',\n * visible : true,\n * buttons : [...],\n * });\n *\n * const newPanel = panelManager.removePanel('myNewPanel');\n *\n */\n removePanel(panel) {\n return panels.remove(panel);\n },\n\n /**\n * Get panel by ID\n * @param {string} id Id string\n * @return {Panel|null}\n * @example\n * var myPanel = panelManager.getPanel('myNewPanel');\n */\n getPanel(id) {\n var res = panels.where({ id });\n return res.length ? res[0] : null;\n },\n\n /**\n * Add button to the panel\n * @param {string} panelId Panel's ID\n * @param {Object|Button} button Button object or instance of Button\n * @return {Button|null} Added button. Useful in case passed button was an Object\n * @example\n * var newButton = panelManager.addButton('myNewPanel',{\n * id: 'myNewButton',\n * className: 'someClass',\n * command: 'someCommand',\n * attributes: { title: 'Some title'},\n * active: false,\n * });\n * // It's also possible to pass the command as an object\n * // with .run and .stop methods\n * ...\n * command: {\n * run: function(editor) {\n * ...\n * },\n * stop: function(editor) {\n * ...\n * }\n * },\n * // Or simply like a function which will be evaluated as a single .run command\n * ...\n * command: function(editor) {\n * ...\n * }\n */\n addButton(panelId, button) {\n var pn = this.getPanel(panelId);\n return pn ? pn.get('buttons').add(button) : null;\n },\n\n /**\n * Remove button from the panel\n * @param {String} panelId Panel's ID\n * @param {String} buttonId Button's ID\n * @return {Button|null} Removed button.\n * @example\n * const removedButton = panelManager.addButton('myNewPanel',{\n * id: 'myNewButton',\n * className: 'someClass',\n * command: 'someCommand',\n * attributes: { title: 'Some title'},\n * active: false,\n * });\n *\n * const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton');\n *\n */\n removeButton(panelId, button) {\n var pn = this.getPanel(panelId);\n return pn && pn.get('buttons').remove(button);\n },\n\n /**\n * Get button from the panel\n * @param {string} panelId Panel's ID\n * @param {string} id Button's ID\n * @return {Button|null}\n * @example\n * var button = panelManager.getButton('myPanel','myButton');\n */\n getButton(panelId, id) {\n var pn = this.getPanel(panelId);\n if (pn) {\n var res = pn.get('buttons').where({ id });\n return res.length ? res[0] : null;\n }\n return null;\n },\n\n /**\n * Render panels and buttons\n * @return {HTMLElement}\n * @private\n */\n render() {\n PanelsViewObj && PanelsViewObj.remove();\n PanelsViewObj = new PanelsView({\n collection: panels,\n config: c\n });\n return PanelsViewObj.render().el;\n },\n\n /**\n * Active activable buttons\n * @private\n */\n active() {\n this.getPanels().each(p => {\n p.get('buttons').each(btn => {\n btn.get('active') && btn.trigger('updateActive');\n });\n });\n },\n\n /**\n * Disable buttons flagged as disabled\n * @private\n */\n disableButtons() {\n this.getPanels().each(p => {\n p.get('buttons').each(btn => {\n if (btn.get('disable')) btn.trigger('change:disable');\n });\n });\n },\n\n destroy() {\n panels.reset();\n panels.stopListening();\n PanelsViewObj && PanelsViewObj.remove();\n [c, panels, PanelsViewObj].forEach(i => (i = {}));\n },\n\n Panel\n };\n};\n","export default {\n stylePrefix: 'cv-',\n\n /*\n * Append external scripts to the `` of the iframe.\n * Be aware that these scripts will not be printed in the export code\n * @example\n * scripts: [ 'https://...1.js', 'https://...2.js' ]\n * * // or passing objects as attributes\n * scripts: [ { src: '/file.js', someattr: 'value' }, ... ]\n */\n scripts: [],\n\n /*\n * Append external styles to the `` of the iframe\n * Be aware that these styles will not be printed in the export code\n * @example\n * styles: [ 'https://...1.css', 'https://...2.css' ]\n * // or passing objects as attributes\n * styles: [ { href: '/style.css', someattr: 'value' }, ... ]\n */\n styles: [],\n\n /**\n * Add custom badge naming strategy\n * @example\n * customBadgeLabel: function(component) {\n * return component.getName();\n * }\n */\n customBadgeLabel: '',\n\n /**\n * Indicate when to start the auto scroll of the canvas on component/block dragging (value in px )\n */\n autoscrollLimit: 50,\n\n // Experimental: external highlighter box\n extHl: 0,\n\n /**\n * When some textable component is selected and focused (eg. input or text component) the editor\n * stops some commands (eg. disables the copy/paste of components with CTRL+C/V to allow the copy/paste of the text).\n * This option allows to customize, by a selector, which element should not be considered textable\n */\n notTextable: ['button', 'a', 'input[type=checkbox]', 'input[type=radio]']\n};\n","import { Model } from 'common';\nimport { evPageSelect } from 'pages';\nimport Frames from './Frames';\n\nexport default class Canvas extends Model {\n defaults() {\n return {\n frame: '',\n frames: '',\n rulers: false,\n zoom: 100,\n x: 0,\n y: 0,\n // Scripts to apply on all frames\n scripts: [],\n // Styles to apply on all frames\n styles: [],\n };\n }\n\n initialize(props, config = {}) {\n const { em } = config;\n this.config = config;\n this.em = em;\n this.set('frames', new Frames());\n this.listenTo(this, 'change:zoom', this.onZoomChange);\n this.listenTo(em, 'change:device', this.updateDevice);\n this.listenTo(em, evPageSelect, this._pageUpdated);\n }\n\n init() {\n const { em } = this;\n const mainPage = em.get('PageManager').getMain();\n const frame = mainPage.getMainFrame();\n this.set('frames', mainPage.getFrames());\n this.updateDevice({ frame });\n }\n\n _pageUpdated(page, prev) {\n const { em } = this;\n em.setSelected();\n em.get('readyCanvas') && em.stopDefault(); // We have to stop before changing current frames\n prev && prev.getFrames().map(frame => frame.disable());\n this.set('frames', page.getFrames());\n }\n\n updateDevice(opts = {}) {\n const { em } = this;\n const device = em.getDeviceModel();\n const model = opts.frame || em.getCurrentFrameModel();\n\n if (model && device) {\n const { width, height } = device.attributes;\n model.set({ width, height }, { noUndo: 1 });\n }\n }\n\n onZoomChange() {\n const zoom = this.get('zoom');\n zoom < 1 && this.set('zoom', 1);\n }\n}\n","/*\n This class makes the canvas droppable\n */\n\nimport { on, off } from 'utils/mixins';\nimport { bindAll, indexOf } from 'underscore';\n\nexport default class Droppable {\n constructor(em, rootEl) {\n this.em = em;\n const el =\n rootEl ||\n em\n .get('Canvas')\n .getFrames()\n .map(frame => frame.getComponent().getEl());\n const els = Array.isArray(el) ? el : [el];\n this.el = el;\n this.counter = 0;\n bindAll(\n this,\n 'handleDragEnter',\n 'handleDragOver',\n 'handleDrop',\n 'handleDragLeave'\n );\n els.forEach(el => this.toggleEffects(el, 1));\n\n return this;\n }\n\n toggleEffects(el, enable) {\n const methods = { on, off };\n const method = enable ? 'on' : 'off';\n methods[method](el, 'dragenter', this.handleDragEnter);\n methods[method](el, 'dragover', this.handleDragOver);\n methods[method](el, 'drop', this.handleDrop);\n methods[method](el, 'dragleave', this.handleDragLeave);\n }\n\n __customTglEff(enable) {\n const method = enable ? on : off;\n const doc = this.el.ownerDocument;\n const frameEl = doc.defaultView.frameElement;\n this.sortOpts = enable\n ? {\n onStart({ sorter }) {\n on(frameEl, 'pointermove', sorter.onMove);\n },\n onEnd({ sorter }) {\n off(frameEl, 'pointermove', sorter.onMove);\n },\n customTarget({ event }) {\n return doc.elementFromPoint(event.clientX, event.clientY);\n }\n }\n : null;\n method(frameEl, 'pointerenter', this.handleDragEnter);\n method(frameEl, 'pointermove', this.handleDragOver);\n method(document, 'pointerup', this.handleDrop);\n method(frameEl, 'pointerout', this.handleDragLeave);\n\n // Test with touche devices (seems like frameEl is not capturing pointer events).\n // on/off(document, 'pointermove', sorter.onMove); // for the sorter\n // enable && this.handleDragEnter({}); // no way to use pointerenter/pointerout\n }\n\n startCustom() {\n this.__customTglEff(true);\n }\n\n endCustom(cancel) {\n this.over ? this.endDrop(cancel) : this.__customTglEff(false);\n }\n\n endDrop(cancel, ev) {\n const { em, dragStop } = this;\n this.counter = 0;\n dragStop && dragStop(cancel);\n this.__customTglEff(false);\n em.trigger('canvas:dragend', ev);\n }\n\n handleDragLeave(ev) {\n this.updateCounter(-1, ev);\n }\n\n updateCounter(value, ev) {\n this.counter += value;\n this.counter === 0 && this.endDrop(1, ev);\n }\n\n handleDragEnter(ev) {\n const { em } = this;\n const dt = ev.dataTransfer;\n this.updateCounter(1, ev);\n if (this.over) return;\n this.over = 1;\n const utils = em.get('Utils');\n const canvas = em.get('Canvas');\n // For security reason I can't read the drag data on dragenter, but\n // as I need it for the Sorter context I will use `dragContent` or just\n // any not empty element\n let content = em.get('dragContent') || '
';\n let dragStop, dragContent;\n em.stopDefault();\n\n // Select the right drag provider\n if (em.inAbsoluteMode()) {\n const wrapper = em.get('DomComponents').getWrapper();\n const target = wrapper.append({})[0];\n const dragger = em.get('Commands').run('core:component-drag', {\n event: ev,\n guidesInfo: 1,\n center: 1,\n target,\n onEnd: (ev, dragger, { cancelled }) => {\n let comp;\n if (!cancelled) {\n comp = wrapper.append(content)[0];\n const { left, top, position } = target.getStyle();\n comp.addStyle({ left, top, position });\n }\n this.handleDragEnd(comp, dt);\n target.remove();\n }\n });\n dragStop = cancel => dragger.stop(ev, { cancel });\n dragContent = cnt => (content = cnt);\n } else {\n const sorter = new utils.Sorter({\n em,\n wmargin: 1,\n nested: 1,\n canvasRelative: 1,\n direction: 'a',\n container: this.el,\n placer: canvas.getPlacerEl(),\n containerSel: '*',\n itemSel: '*',\n pfx: 'gjs-',\n onEndMove: model => this.handleDragEnd(model, dt),\n document: this.el.ownerDocument,\n ...(this.sortOpts || {})\n });\n sorter.setDropContent(content);\n sorter.startSort();\n this.sorter = sorter;\n dragStop = cancel => {\n cancel && (sorter.moved = 0);\n sorter.endMove();\n };\n dragContent = content => sorter.setDropContent(content);\n }\n\n this.dragStop = dragStop;\n this.dragContent = dragContent;\n em.trigger('canvas:dragenter', dt, content);\n }\n\n handleDragEnd(model, dt) {\n const { em } = this;\n this.over = 0;\n if (model) {\n em.set('dragResult', model);\n em.trigger('canvas:drop', dt, model);\n }\n em.runDefault({ preserveSelected: 1 });\n }\n\n /**\n * Always need to have this handler active for enabling the drop\n * @param {Event} ev\n */\n handleDragOver(ev) {\n ev.preventDefault();\n this.em.trigger('canvas:dragover', ev);\n }\n\n /**\n * WARNING: This function might fail to run on drop, for example, when the\n * drop, accidentally, happens on some external element (DOM not inside the iframe)\n */\n handleDrop(ev) {\n ev.preventDefault();\n const { dragContent } = this;\n const dt = ev.dataTransfer;\n const content = this.getContentByData(dt).content;\n ev.target.style.border = '';\n content && dragContent && dragContent(content);\n this.endDrop(!content, ev);\n }\n\n getContentByData(dt) {\n const em = this.em;\n const types = dt && dt.types;\n const files = (dt && dt.files) || [];\n const dragContent = em.get('dragContent');\n let content = dt && dt.getData('text');\n\n if (files.length) {\n content = [];\n for (let i = 0; i < files.length; i++) {\n const file = files[i];\n const type = file.type.split('/')[0];\n\n if (type == 'image') {\n content.push({\n type,\n file,\n attributes: { alt: file.name }\n });\n }\n }\n } else if (dragContent) {\n content = dragContent;\n } else if (indexOf(types, 'text/html') >= 0) {\n content = dt && dt.getData('text/html').replace(/<\\/?meta[^>]*>/g, '');\n } else if (indexOf(types, 'text/uri-list') >= 0) {\n content = {\n type: 'link',\n attributes: { href: content },\n content: content\n };\n } else if (indexOf(types, 'text/json') >= 0) {\n const json = dt && dt.getData('text/json');\n json && (content = JSON.parse(json));\n } else if (types.length === 1 && types[0] === 'text/plain') {\n // Avoid dropping non-selectable and non-editable text nodes inside the editor\n content = `
${content}
`;\n }\n\n const result = { content };\n em.trigger('canvas:dragdata', dt, result);\n\n return result;\n }\n}\n","import Backbone from 'backbone';\nimport { bindAll, isString, debounce, isUndefined } from 'underscore';\nimport CssRulesView from 'css_composer/view/CssRulesView';\nimport Droppable from 'utils/Droppable';\nimport { appendVNodes, append, createEl, createCustomEvent, motionsEv } from 'utils/dom';\nimport { on, off, setViewEl, hasDnd, getPointerEvent } from 'utils/mixins';\n\nexport default Backbone.View.extend({\n tagName: 'iframe',\n\n attributes: {\n allowfullscreen: 'allowfullscreen',\n 'data-frame-el': true,\n },\n\n initialize(o) {\n bindAll(this, 'updateClientY', 'stopAutoscroll', 'autoscroll', '_emitUpdate');\n const { model, el } = this;\n this.tools = {};\n this.config = {\n ...(o.config || {}),\n frameView: this,\n };\n this.ppfx = this.config.pStylePrefix || '';\n this.em = this.config.em;\n const cvModel = this.getCanvasModel();\n this.listenTo(model, 'change:head', this.updateHead);\n this.listenTo(cvModel, 'change:styles', this.renderStyles);\n model.view = this;\n setViewEl(el, this);\n },\n\n /**\n * Update `` content of the frame\n */\n updateHead() {\n const { model } = this;\n const headEl = this.getHead();\n const toRemove = [];\n const toAdd = [];\n const current = model.get('head');\n const prev = model.previous('head');\n const attrStr = (attr = {}) =>\n Object.keys(attr)\n .sort()\n .map(i => `[${i}=\"${attr[i]}\"]`)\n .join('');\n const find = (items, stack, res) => {\n items.forEach(item => {\n const { tag, attributes } = item;\n const has = stack.some(s => s.tag === tag && attrStr(s.attributes) === attrStr(attributes));\n !has && res.push(item);\n });\n };\n find(current, prev, toAdd);\n find(prev, current, toRemove);\n toRemove.forEach(stl => {\n const el = headEl.querySelector(`${stl.tag}${attrStr(stl.attributes)}`);\n el && el.parentNode.removeChild(el);\n });\n appendVNodes(headEl, toAdd);\n },\n\n getEl() {\n return this.el;\n },\n\n getCanvasModel() {\n return this.em.get('Canvas').getModel();\n },\n\n getWindow() {\n return this.getEl().contentWindow;\n },\n\n getDoc() {\n return this.getEl().contentDocument;\n },\n\n getHead() {\n return this.getDoc().querySelector('head');\n },\n\n getBody() {\n return this.getDoc().querySelector('body');\n },\n\n getWrapper() {\n return this.getBody().querySelector('[data-gjs-type=wrapper]');\n },\n\n getJsContainer() {\n if (!this.jsContainer) {\n this.jsContainer = createEl('div', { class: `${this.ppfx}js-cont` });\n }\n\n return this.jsContainer;\n },\n\n getToolsEl() {\n const { frameWrapView } = this.config;\n return frameWrapView && frameWrapView.elTools;\n },\n\n getGlobalToolsEl() {\n return this.em.get('Canvas').getGlobalToolsEl();\n },\n\n getHighlighter() {\n return this._getTool('[data-hl]');\n },\n\n getBadgeEl() {\n return this._getTool('[data-badge]');\n },\n\n getOffsetViewerEl() {\n return this._getTool('[data-offset]');\n },\n\n getRect() {\n if (!this.rect) {\n this.rect = this.el.getBoundingClientRect();\n }\n\n return this.rect;\n },\n\n /**\n * Get rect data, not affected by the canvas zoom\n */\n getOffsetRect() {\n const { el } = this;\n const { scrollTop, scrollLeft } = this.getBody();\n const height = el.offsetHeight;\n const width = el.offsetWidth;\n\n return {\n top: el.offsetTop,\n left: el.offsetLeft,\n height,\n width,\n scrollTop,\n scrollLeft,\n scrollBottom: scrollTop + height,\n scrollRight: scrollLeft + width,\n };\n },\n\n _getTool(name) {\n const { tools } = this;\n const toolsEl = this.getToolsEl();\n\n if (!tools[name]) {\n tools[name] = toolsEl.querySelector(name);\n }\n\n return tools[name];\n },\n\n remove() {\n const wrp = this.wrapper;\n this._toggleEffects();\n this.tools = {};\n wrp && wrp.remove();\n Backbone.View.prototype.remove.apply(this, arguments);\n },\n\n startAutoscroll() {\n this.lastMaxHeight = this.getWrapper().offsetHeight - this.el.offsetHeight;\n\n // By detaching those from the stack avoid browsers lags\n // Noticeable with \"fast\" drag of blocks\n setTimeout(() => {\n this._toggleAutoscrollFx(1);\n requestAnimationFrame(this.autoscroll);\n }, 0);\n },\n\n autoscroll() {\n if (this.dragging) {\n const { lastClientY } = this;\n const canvas = this.em.get('Canvas');\n const win = this.getWindow();\n const body = this.getBody();\n const actualTop = body.scrollTop;\n const clientY = lastClientY || 0;\n const limitTop = canvas.getConfig().autoscrollLimit;\n const limitBottom = this.getRect().height - limitTop;\n let nextTop = actualTop;\n\n if (clientY < limitTop) {\n nextTop -= limitTop - clientY;\n }\n\n if (clientY > limitBottom) {\n nextTop += clientY - limitBottom;\n }\n\n if (\n !isUndefined(lastClientY) && // Fixes #3134\n nextTop !== actualTop &&\n nextTop > 0 &&\n nextTop < this.lastMaxHeight\n ) {\n const toolsEl = this.getGlobalToolsEl();\n toolsEl.style.opacity = 0;\n this.showGlobalTools();\n win.scrollTo(0, nextTop);\n }\n\n requestAnimationFrame(this.autoscroll);\n }\n },\n\n updateClientY(ev) {\n ev.preventDefault();\n this.lastClientY = getPointerEvent(ev).clientY * this.em.getZoomDecimal();\n },\n\n showGlobalTools: debounce(function () {\n this.getGlobalToolsEl().style.opacity = '';\n }, 50),\n\n stopAutoscroll() {\n this.dragging && this._toggleAutoscrollFx();\n },\n\n _toggleAutoscrollFx(enable) {\n this.dragging = enable;\n const win = this.getWindow();\n const method = enable ? 'on' : 'off';\n const mt = { on, off };\n mt[method](win, 'mousemove dragover', this.updateClientY);\n mt[method](win, 'mouseup', this.stopAutoscroll);\n },\n\n render() {\n const { $el, ppfx } = this;\n $el.attr({ class: `${ppfx}frame` });\n this.renderScripts();\n return this;\n },\n\n renderScripts() {\n const { el, model, em } = this;\n const evLoad = 'frame:load';\n const evOpts = { el, model, view: this };\n const canvas = this.getCanvasModel();\n const appendScript = scripts => {\n if (scripts.length > 0) {\n const src = scripts.shift();\n const scriptEl = createEl('script', {\n type: 'text/javascript',\n ...(isString(src) ? { src } : src),\n });\n scriptEl.onerror = scriptEl.onload = appendScript.bind(null, scripts);\n el.contentDocument.head.appendChild(scriptEl);\n } else {\n this.renderBody();\n em && em.trigger(evLoad, evOpts);\n }\n };\n\n el.onload = () => {\n em && em.trigger(`${evLoad}:before`, evOpts);\n appendScript([...canvas.get('scripts')]);\n };\n },\n\n renderStyles(opts = {}) {\n const head = this.getHead();\n const canvas = this.getCanvasModel();\n const normalize = stls =>\n stls.map(href => ({\n tag: 'link',\n attributes: {\n rel: 'stylesheet',\n ...(isString(href) ? { href } : href),\n },\n }));\n const prevStyles = normalize(opts.prev || canvas.previous('styles'));\n const styles = normalize(canvas.get('styles'));\n const toRemove = [];\n const toAdd = [];\n const find = (items, stack, res) => {\n items.forEach(item => {\n const { href } = item.attributes;\n const has = stack.some(s => s.attributes.href === href);\n !has && res.push(item);\n });\n };\n find(styles, prevStyles, toAdd);\n find(prevStyles, styles, toRemove);\n toRemove.forEach(stl => {\n const el = head.querySelector(`link[href=\"${stl.attributes.href}\"]`);\n el && el.parentNode.removeChild(el);\n });\n appendVNodes(head, toAdd);\n },\n\n renderBody() {\n const { config, model, ppfx } = this;\n const { em } = config;\n const doc = this.getDoc();\n const body = this.getBody();\n const win = this.getWindow();\n const conf = em.get('Config');\n win._isEditor = true;\n this.renderStyles({ prev: [] });\n\n const colorWarn = '#ffca6f';\n\n // I need all this styles to make the editor work properly\n // Remove `html { height: 100%;}` from the baseCss as it gives jumpings\n // effects (on ENTER) with RTE like CKEditor (maybe some bug there?!?)\n // With `body {height: auto;}` jumps in CKEditor are removed but in\n // Firefox is impossible to drag stuff in empty canvas, so bring back\n // `body {height: 100%;}`.\n // For the moment I give the priority to Firefox as it might be\n // CKEditor's issue\n append(\n body,\n ``\n );\n const component = model.getComponent();\n const { view } = em.get('DomComponents').getType('wrapper');\n this.wrapper = new view({\n model: component,\n config: {\n ...component.config,\n frameView: this,\n },\n }).render();\n append(body, this.wrapper.el);\n append(\n body,\n new CssRulesView({\n collection: model.getStyles(),\n config: {\n ...em.get('CssComposer').getConfig(),\n frameView: this,\n },\n }).render().el\n );\n append(body, this.getJsContainer());\n // em.trigger('loaded'); // I need to manage only the first one maybe\n //this.updateOffset(); // TOFIX (check if I need it)\n\n // Avoid some default behaviours\n on(body, 'click', ev => ev && ev.target.tagName == 'A' && ev.preventDefault());\n on(body, 'submit', ev => ev && ev.preventDefault());\n\n // When the iframe is focused the event dispatcher is not the same so\n // I need to delegate all events to the parent document\n [\n { event: 'keydown keyup keypress', class: 'KeyboardEvent' },\n { event: 'mousedown mousemove mouseup', class: 'MouseEvent' },\n { event: 'pointerdown pointermove pointerup', class: 'PointerEvent' },\n { event: 'wheel', class: 'WheelEvent' },\n ].forEach(obj =>\n obj.event.split(' ').forEach(event => {\n doc.addEventListener(event, ev => this.el.dispatchEvent(createCustomEvent(ev, obj.class)));\n })\n );\n\n this._toggleEffects(1);\n this.droppable = hasDnd(em) && new Droppable(em, this.wrapper.el);\n model.trigger('loaded');\n },\n\n _toggleEffects(enable) {\n const method = enable ? on : off;\n const win = this.getWindow();\n win && method(win, `${motionsEv} resize`, this._emitUpdate);\n },\n\n _emitUpdate() {\n this.model._emitUpdated();\n },\n});\n","import Backbone from 'backbone';\nimport FrameView from './FrameView';\nimport { bindAll, isNumber, isNull, debounce } from 'underscore';\nimport { createEl, removeEl } from 'utils/dom';\nimport Dragger from 'utils/Dragger';\n\nexport default Backbone.View.extend({\n events: {\n 'click [data-action-remove]': 'remove',\n 'mousedown [data-action-move]': 'startDrag'\n },\n\n initialize(opts = {}, conf = {}) {\n bindAll(\n this,\n 'onScroll',\n 'frameLoaded',\n 'updateOffset',\n 'remove',\n 'startDrag'\n );\n const { model } = this;\n const config = {\n ...(opts.config || conf),\n frameWrapView: this\n };\n const { canvasView, em } = config;\n this.cv = canvasView;\n this.config = config;\n this.em = em;\n this.canvas = em && em.get('Canvas');\n this.ppfx = config.pStylePrefix || '';\n this.frame = new FrameView({ model, config });\n this.classAnim = `${this.ppfx}frame-wrapper--anim`;\n this.updateOffset = debounce(this.updateOffset.bind(this));\n this.updateSize = debounce(this.updateSize.bind(this));\n this.listenTo(model, 'loaded', this.frameLoaded);\n this.listenTo(model, 'change:x change:y', this.updatePos);\n this.listenTo(model, 'change:width change:height', this.updateSize);\n this.listenTo(model, 'destroy remove', this.remove);\n this.updatePos();\n this.setupDragger();\n },\n\n setupDragger() {\n const { canvas, model } = this;\n let dragX, dragY, zoom;\n const toggleEffects = on => {\n canvas.toggleFramesEvents(on);\n };\n\n this.dragger = new Dragger({\n onStart: () => {\n const { x, y } = model.attributes;\n zoom = this.em.getZoomMultiplier();\n dragX = x;\n dragY = y;\n toggleEffects();\n },\n onEnd: () => toggleEffects(1),\n setPosition: posOpts => {\n model.set({\n x: dragX + posOpts.x * zoom,\n y: dragY + posOpts.y * zoom\n });\n }\n });\n },\n\n startDrag(ev) {\n ev && this.dragger.start(ev);\n },\n\n __clear(opts) {\n const { frame } = this;\n frame && frame.remove(opts);\n removeEl(this.elTools);\n },\n\n remove(opts) {\n this.__clear(opts);\n Backbone.View.prototype.remove.apply(this, arguments);\n ['frame', 'dragger', 'cv', 'em', 'canvas', 'elTools'].forEach(\n i => (this[i] = 0)\n );\n return this;\n },\n\n updateOffset() {\n const { em, $el, frame } = this;\n if (!em) return;\n em.runDefault({ preserveSelected: 1 });\n $el.removeClass(this.classAnim);\n frame.model._emitUpdated();\n },\n\n updatePos(md) {\n const { model, el } = this;\n const { x, y } = model.attributes;\n const { style } = el;\n this.frame.rect = 0;\n style.left = isNaN(x) ? x : `${x}px`;\n style.top = isNaN(y) ? y : `${y}px`;\n md && this.updateOffset();\n },\n\n updateSize() {\n this.updateDim();\n },\n\n /**\n * Update dimensions of the frame\n * @private\n */\n updateDim() {\n const { em, el, $el, model, classAnim, frame } = this;\n if (!frame) return;\n frame.rect = 0;\n $el.addClass(classAnim);\n const { noChanges, width, height } = this.__handleSize();\n\n // Set width and height from DOM (should be done only once)\n if (isNull(width) || isNull(height)) {\n model.set(\n {\n ...(!width ? { width: el.offsetWidth } : {}),\n ...(!height ? { height: el.offsetHeight } : {})\n },\n { silent: 1 }\n );\n }\n\n // Prevent fixed highlighting box which appears when on\n // component hover during the animation\n em.stopDefault({ preserveSelected: 1 });\n noChanges ? this.updateOffset() : setTimeout(this.updateOffset, 350);\n },\n\n onScroll() {\n const { frame, em } = this;\n em.trigger('frame:scroll', {\n frame,\n body: frame.getBody(),\n target: frame.getWindow()\n });\n },\n\n frameLoaded() {\n const { frame } = this;\n frame.getWindow().onscroll = this.onScroll;\n this.updateDim();\n },\n\n __handleSize() {\n const un = 'px';\n const { model, el } = this;\n const { style } = el;\n const { width, height } = model.attributes;\n const currW = style.width || '';\n const currH = style.height || '';\n const newW = width || '';\n const newH = height || '';\n const noChanges = currW == newW && currH == newH;\n style.width = isNumber(newW) ? `${newW}${un}` : newW;\n style.height = isNumber(newH) ? `${newH}${un}` : newH;\n return { noChanges, width, height, newW, newH };\n },\n\n render() {\n const { frame, $el, ppfx, cv, model, el } = this;\n const { onRender } = model.attributes;\n this.__clear();\n this.__handleSize();\n frame.render();\n $el\n .empty()\n .attr({ class: `${ppfx}frame-wrapper` })\n .append(\n `\n
\n
\n ${model.get('name') || ''}\n
\n
\n
\n \n
\n
\n
\n
\n
\n
\n `\n )\n .append(frame.el);\n const elTools = createEl(\n 'div',\n {\n class: `${ppfx}tools`,\n style: 'pointer-events:none; display: none'\n },\n `\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n `\n );\n this.elTools = elTools;\n const twrp = cv.toolsWrapper;\n twrp && twrp.appendChild(elTools); // TODO remove on frame remove\n onRender &&\n onRender({\n el,\n elTop: el.querySelector('[data-frame-top]'),\n elRight: el.querySelector('[data-frame-right]'),\n elBottom: el.querySelector('[data-frame-bottom]'),\n elLeft: el.querySelector('[data-frame-left]'),\n frame: model,\n frameWrapperView: this,\n remove: this.remove,\n startDrag: this.startDrag\n });\n return this;\n }\n});\n","import DomainViews from 'domain_abstract/view/DomainViews';\nimport FrameWrapView from './FrameWrapView';\n\nexport default DomainViews.extend({\n itemView: FrameWrapView,\n autoAdd: 1,\n\n init() {\n this.listenTo(this.collection, 'reset', this.render);\n },\n\n onRemoveBefore(items, opts) {\n items.forEach(item => item.remove(opts));\n },\n\n onRender() {\n const { config, $el } = this;\n const { em } = config;\n em && $el.attr({ class: `${em.getConfig('stylePrefix')}frames` });\n }\n});\n","import Backbone from 'backbone';\nimport { bindAll } from 'underscore';\nimport {\n on,\n off,\n getElement,\n getKeyChar,\n isTextNode,\n getElRect,\n getUiClass\n} from 'utils/mixins';\nimport FramesView from './FramesView';\n\nconst $ = Backbone.$;\nlet timerZoom;\n\nexport default Backbone.View.extend({\n events: {\n wheel: 'onWheel'\n },\n\n template() {\n const { pfx } = this;\n return `\n
\n
\n `;\n },\n\n initialize(o) {\n bindAll(this, 'clearOff', 'onKeyPress', 'onCanvasMove');\n const { model } = this;\n this.config = o.config || {};\n this.em = this.config.em || {};\n this.pfx = this.config.stylePrefix || '';\n this.ppfx = this.config.pStylePrefix || '';\n this.className = this.config.stylePrefix + 'canvas';\n const { em } = this;\n this._initFrames();\n this.listenTo(em, 'change:canvasOffset', this.clearOff);\n this.listenTo(em, 'component:selected', this.checkSelected);\n this.listenTo(model, 'change:zoom change:x change:y', this.updateFrames);\n this.listenTo(model, 'change:frames', this._onFramesUpdate);\n this.toggleListeners(1);\n },\n\n _onFramesUpdate() {\n this._initFrames();\n this._renderFrames();\n },\n\n _initFrames() {\n const { frames, model, config, em } = this;\n const collection = model.get('frames');\n em.set('readyCanvas', 0);\n collection.once('loaded:all', () => em.set('readyCanvas', 1));\n frames && frames.remove();\n this.frames = new FramesView({\n collection,\n config: {\n ...config,\n canvasView: this\n }\n });\n },\n\n checkSelected(component, opts = {}) {\n const { scroll } = opts;\n const currFrame = this.em.get('currentFrame');\n\n scroll &&\n component.views.forEach(view => {\n view._getFrame() === currFrame && view.scrollIntoView(scroll);\n });\n },\n\n remove() {\n this.frames.remove();\n this.frames = {};\n Backbone.View.prototype.remove.apply(this, arguments);\n this.toggleListeners();\n },\n\n preventDefault(ev) {\n if (ev) {\n ev.preventDefault();\n ev._parentEvent && ev._parentEvent.preventDefault();\n }\n },\n\n onCanvasMove(ev) {\n // const data = { x: ev.clientX, y: ev.clientY };\n // const data2 = this.em.get('Canvas').getMouseRelativeCanvas(ev);\n // const data3 = this.em.get('Canvas').getMouseRelativePos(ev);\n // this.em.trigger('canvas:over', data, data2, data3);\n },\n\n toggleListeners(enable) {\n const { el } = this;\n const fn = enable ? on : off;\n fn(document, 'keypress', this.onKeyPress);\n fn(window, 'scroll resize', this.clearOff);\n // fn(el, 'mousemove dragover', this.onCanvasMove);\n },\n\n onKeyPress(ev) {\n const { em } = this;\n const key = getKeyChar(ev);\n\n if (\n key === ' ' &&\n em.getZoomDecimal() !== 1 &&\n !em.get('Canvas').isInputFocused()\n ) {\n this.preventDefault(ev);\n em.get('Editor').runCommand('core:canvas-move');\n }\n },\n\n onWheel(ev) {\n if ((ev.ctrlKey || ev.metaKey) && this.em.getConfig('multiFrames')) {\n this.preventDefault(ev);\n const { model } = this;\n const delta = Math.max(-1, Math.min(1, ev.wheelDelta || -ev.detail));\n const zoom = model.get('zoom');\n model.set('zoom', zoom + delta * 2);\n }\n },\n\n updateFrames(ev) {\n const { em, model } = this;\n const { x, y } = model.attributes;\n const zoom = this.getZoom();\n const defOpts = { preserveSelected: 1 };\n const mpl = zoom ? 1 / zoom : 1;\n this.framesArea.style.transform = `scale(${zoom}) translate(${x *\n mpl}px, ${y * mpl}px)`;\n this.clearOff();\n em.stopDefault(defOpts);\n em.trigger('canvas:update', ev);\n timerZoom && clearTimeout(timerZoom);\n timerZoom = setTimeout(() => em.runDefault(defOpts), 300);\n },\n\n getZoom() {\n return this.em.getZoomDecimal();\n },\n\n /**\n * Checks if the element is visible in the canvas's viewport\n * @param {HTMLElement} el\n * @return {Boolean}\n */\n isElInViewport(el) {\n const elem = getElement(el);\n const rect = getElRect(elem);\n const frameRect = this.getFrameOffset(elem);\n const rTop = rect.top;\n const rLeft = rect.left;\n return (\n rTop >= 0 &&\n rLeft >= 0 &&\n rTop <= frameRect.height &&\n rLeft <= frameRect.width\n );\n },\n\n /**\n * Get the offset of the element\n * @param {HTMLElement} el\n * @return {Object}\n */\n offset(el, opts = {}) {\n const rect = getElRect(el);\n const docBody = el.ownerDocument.body;\n const { noScroll } = opts;\n\n return {\n top: rect.top + (noScroll ? 0 : docBody.scrollTop),\n left: rect.left + (noScroll ? 0 : docBody.scrollLeft),\n width: rect.width,\n height: rect.height\n };\n },\n\n /**\n * Cleare cached offsets\n * @private\n */\n clearOff() {\n this.frmOff = null;\n this.cvsOff = null;\n },\n\n /**\n * Return frame offset\n * @return {Object}\n * @private\n */\n getFrameOffset(el) {\n if (!this.frmOff || el) {\n const frame = this.frame.el;\n const winEl = el && el.ownerDocument.defaultView;\n const frEl = winEl ? winEl.frameElement : frame;\n this.frmOff = this.offset(frEl || frame);\n }\n return this.frmOff;\n },\n\n /**\n * Return canvas offset\n * @return {Object}\n * @private\n */\n getCanvasOffset() {\n if (!this.cvsOff) this.cvsOff = this.offset(this.el);\n return this.cvsOff;\n },\n\n /**\n * Returns element's rect info\n * @param {HTMLElement} el\n * @return {Object}\n * @private\n */\n getElementPos(el, opts) {\n const zoom = this.getZoom();\n var opt = opts || {};\n var frmOff = this.getFrameOffset(el);\n var cvsOff = this.getCanvasOffset();\n var eo = this.offset(el, opts);\n\n var frmTop = opt.avoidFrameOffset ? 0 : frmOff.top;\n var frmLeft = opt.avoidFrameOffset ? 0 : frmOff.left;\n\n const top = eo.top * zoom + frmTop - cvsOff.top;\n const left = eo.left * zoom + frmLeft - cvsOff.left;\n const height = eo.height * zoom;\n const width = eo.width * zoom;\n\n return { top, left, height, width, zoom, rect: eo };\n },\n\n /**\n * Returns element's offsets like margins and paddings\n * @param {HTMLElement} el\n * @return {Object}\n * @private\n */\n getElementOffsets(el) {\n if (!el || isTextNode(el)) return {};\n const result = {};\n const styles = window.getComputedStyle(el);\n [\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft'\n ].forEach(offset => {\n result[offset] = parseFloat(styles[offset]) * this.getZoom();\n });\n\n return result;\n },\n\n /**\n * Returns position data of the canvas element\n * @return {Object} obj Position object\n * @private\n */\n getPosition(opts = {}) {\n const doc = this.frame.el.contentDocument;\n if (!doc) return;\n const bEl = doc.body;\n const zoom = this.getZoom();\n const fo = this.getFrameOffset();\n const co = this.getCanvasOffset();\n const { noScroll } = opts;\n\n return {\n top: fo.top + (noScroll ? 0 : bEl.scrollTop) * zoom - co.top,\n left: fo.left + (noScroll ? 0 : bEl.scrollLeft) * zoom - co.left,\n width: co.width,\n height: co.height\n };\n },\n\n /**\n * Update javascript of a specific component passed by its View\n * @param {View} view Component's View\n * @private\n */\n updateScript(view) {\n const model = view.model;\n const id = model.getId();\n\n if (!view.scriptContainer) {\n view.scriptContainer = $(`
`);\n this.getJsContainer().appendChild(view.scriptContainer.get(0));\n }\n\n view.el.id = id;\n view.scriptContainer.html('');\n // In editor, I make use of setTimeout as during the append process of elements\n // those will not be available immediately, therefore 'item' variable\n const script = document.createElement('script');\n const scriptFn = model.getScriptString();\n const scriptFnStr = model.get('script-props')\n ? scriptFn\n : `function(){\\n${scriptFn}\\n;}`;\n const scriptProps = JSON.stringify(model.__getScriptProps());\n script.innerHTML = `\n setTimeout(function() {\n var item = document.getElementById('${id}');\n if (!item) return;\n (${scriptFnStr}.bind(item))(${scriptProps})\n }, 1);`;\n // #873\n // Adding setTimeout will make js components work on init of the editor\n setTimeout(() => {\n const scr = view.scriptContainer;\n scr && scr.get(0).appendChild(script);\n }, 0);\n },\n\n /**\n * Get javascript container\n * @private\n */\n getJsContainer(view) {\n const frameView = this.getFrameView(view);\n return frameView && frameView.getJsContainer();\n },\n\n getFrameView(view) {\n return (view && view._getFrame()) || this.em.get('currentFrame');\n },\n\n _renderFrames() {\n if (!this.ready) return;\n const { model, frames, em, framesArea } = this;\n const frms = model.get('frames');\n frms.listenToLoad();\n frames.render();\n const mainFrame = frms.at(0);\n const currFrame = mainFrame && mainFrame.view;\n em.setCurrentFrame(currFrame);\n framesArea && framesArea.appendChild(frames.el);\n this.frame = currFrame;\n },\n\n render() {\n const { el, $el, ppfx, config, em } = this;\n $el.html(this.template());\n const $frames = $el.find('[data-frames]');\n this.framesArea = $frames.get(0);\n\n const toolsWrp = $el.find('[data-tools]');\n this.toolsWrapper = toolsWrp.get(0);\n toolsWrp.append(`\n
\n
\n
\n
\n
\n
\n ${config.extHl ? `
` : ''}\n
\n
\n
\n
\n
\n
\n
\n `);\n const toolsEl = el.querySelector(`#${ppfx}tools`);\n this.hlEl = el.querySelector(`.${ppfx}highlighter`);\n this.badgeEl = el.querySelector(`.${ppfx}badge`);\n this.placerEl = el.querySelector(`.${ppfx}placeholder`);\n this.ghostEl = el.querySelector(`.${ppfx}ghost`);\n this.toolbarEl = el.querySelector(`.${ppfx}toolbar`);\n this.resizerEl = el.querySelector(`.${ppfx}resizer`);\n this.offsetEl = el.querySelector(`.${ppfx}offset-v`);\n this.fixedOffsetEl = el.querySelector(`.${ppfx}offset-fixed-v`);\n this.toolsGlobEl = el.querySelector(`.${ppfx}tools-gl`);\n this.toolsEl = toolsEl;\n this.el.className = getUiClass(em, this.className);\n this.ready = 1;\n this._renderFrames();\n\n return this;\n }\n});\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/canvas/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * canvas: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.\n *\n * ```js\n * // Listen to events\n * editor.on('canvas:drop', () => { ... });\n *\n * // Use the API\n * const canvas = editor.Canvas;\n * canvas.setCoords(...);\n * ```\n * ## Available Events\n * * `canvas:dragenter` - When something is dragged inside the canvas, `DataTransfer` instance passed as an argument\n * * `canvas:dragover` - When something is dragging on canvas, `DataTransfer` instance passed as an argument\n * * `canvas:drop` - Something is dropped in canvas, `DataTransfer` instance and the dropped model are passed as arguments\n * * `canvas:dragend` - When a drag operation is ended, `DataTransfer` instance passed as an argument\n * * `canvas:dragdata` - On any dataTransfer parse, `DataTransfer` instance and the `result` are passed as arguments.\n * By changing `result.content` you're able to customize what is dropped\n *\n * ## Methods\n * * [getConfig](#getconfig)\n * * [getElement](#getelement)\n * * [getFrameEl](#getframeel)\n * * [getWindow](#getwindow)\n * * [getDocument](#getdocument)\n * * [getBody](#getbody)\n * * [setCustomBadgeLabel](#setcustombadgelabel)\n * * [hasFocus](#hasfocus)\n * * [scrollTo](#scrollto)\n * * [setZoom](#setzoom)\n * * [getZoom](#getzoom)\n * * [getCoords](#getcoords)\n * * [setCoords](#setcoords)\n *\n * [Component]: component.html\n * [Frame]: frame.html\n *\n * @module Canvas\n */\n\nimport { isUndefined } from 'underscore';\nimport { getElement, getViewEl } from 'utils/mixins';\nimport defaults from './config/config';\nimport Canvas from './model/Canvas';\nimport canvasView from './view/CanvasView';\n\nexport default () => {\n let c = {};\n let canvas;\n let CanvasView;\n\n return {\n /**\n * Used inside RTE\n * @private\n */\n getCanvasView() {\n return CanvasView;\n },\n\n name: 'Canvas',\n\n /**\n * Initialize module. Automatically called with a new instance of the editor\n * @param {Object} config Configurations\n * @private\n */\n init(config = {}) {\n c = {\n ...defaults,\n ...config,\n module: this,\n };\n\n this.em = c.em;\n const { scripts, styles } = c;\n const ppfx = c.pStylePrefix;\n if (ppfx) c.stylePrefix = ppfx + c.stylePrefix;\n canvas = new Canvas({ scripts, styles }, config);\n this.model = canvas;\n this.startAutoscroll = this.startAutoscroll.bind(this);\n this.stopAutoscroll = this.stopAutoscroll.bind(this);\n return this;\n },\n\n onLoad() {\n this.model.init();\n },\n\n getModel() {\n return canvas;\n },\n\n /**\n * Get the configuration object\n * @returns {Object} Configuration object\n * @example\n * console.log(canvas.getConfig())\n */\n getConfig() {\n return c;\n },\n\n /**\n * Get the canvas element\n * @returns {HTMLElement}\n */\n getElement() {\n return CanvasView.el;\n },\n\n getFrame(index) {\n return this.getFrames()[index || 0];\n },\n\n /**\n * Get the main frame element of the canvas\n * @returns {HTMLIFrameElement}\n */\n getFrameEl() {\n const { frame } = CanvasView || {};\n return frame && frame.el;\n },\n\n getFramesEl() {\n return CanvasView.framesArea;\n },\n\n /**\n * Get the main frame window instance\n * @returns {Window}\n */\n getWindow() {\n return this.getFrameEl().contentWindow;\n },\n\n /**\n * Get the main frame document element\n * @returns {HTMLDocument}\n */\n getDocument() {\n const frame = this.getFrameEl();\n return frame && frame.contentDocument;\n },\n\n /**\n * Get the main frame body element\n * @return {HTMLBodyElement}\n */\n getBody() {\n const doc = this.getDocument();\n return doc && doc.body;\n },\n\n _getCompFrame(compView) {\n return compView && compView._getFrame();\n },\n\n _getLocalEl(globalEl, compView, method) {\n let result = globalEl;\n const frameView = this._getCompFrame(compView);\n result = frameView ? frameView[method]() : result;\n\n return result;\n },\n\n /**\n * Returns element containing all global canvas tools\n * @returns {HTMLElement}\n * @private\n */\n getGlobalToolsEl() {\n return CanvasView.toolsGlobEl;\n },\n\n /**\n * Returns element containing all canvas tools\n * @returns {HTMLElement}\n * @private\n */\n getToolsEl(compView) {\n return this._getLocalEl(CanvasView.toolsEl, compView, 'getToolsEl');\n },\n\n /**\n * Returns highlighter element\n * @returns {HTMLElement}\n * @private\n */\n getHighlighter(compView) {\n return this._getLocalEl(CanvasView.hlEl, compView, 'getHighlighter');\n },\n\n /**\n * Returns badge element\n * @returns {HTMLElement}\n * @private\n */\n getBadgeEl(compView) {\n return this._getLocalEl(CanvasView.badgeEl, compView, 'getBadgeEl');\n },\n\n /**\n * Returns placer element\n * @returns {HTMLElement}\n * @private\n */\n getPlacerEl() {\n return CanvasView.placerEl;\n },\n\n /**\n * Returns ghost element\n * @returns {HTMLElement}\n * @private\n */\n getGhostEl() {\n return CanvasView.ghostEl;\n },\n\n /**\n * Returns toolbar element\n * @returns {HTMLElement}\n * @private\n */\n getToolbarEl() {\n return CanvasView.toolbarEl;\n },\n\n /**\n * Returns resizer element\n * @returns {HTMLElement}\n * @private\n */\n getResizerEl() {\n return CanvasView.resizerEl;\n },\n\n /**\n * Returns offset viewer element\n * @returns {HTMLElement}\n * @private\n */\n getOffsetViewerEl(compView) {\n return this._getLocalEl(CanvasView.offsetEl, compView, 'getOffsetViewerEl');\n },\n\n /**\n * Returns fixed offset viewer element\n * @returns {HTMLElement}\n * @private\n */\n getFixedOffsetViewerEl() {\n return CanvasView.fixedOffsetEl;\n },\n\n render() {\n CanvasView && CanvasView.remove();\n CanvasView = new canvasView({\n model: canvas,\n config: c,\n });\n return CanvasView.render().el;\n },\n\n /**\n * Get frame position\n * @returns {Object}\n * @private\n */\n getOffset() {\n var frameOff = this.offset(this.getFrameEl());\n var canvasOff = this.offset(this.getElement());\n return {\n top: frameOff.top - canvasOff.top,\n left: frameOff.left - canvasOff.left,\n };\n },\n\n /**\n * Get the offset of the passed component element\n * @param {HTMLElement} el\n * @returns {Object}\n * @private\n */\n offset(el) {\n return CanvasView.offset(el);\n },\n\n /**\n * Set custom badge naming strategy\n * @param {Function} f\n * @example\n * canvas.setCustomBadgeLabel(function(component){\n * return component.getName();\n * });\n */\n setCustomBadgeLabel(f) {\n c.customBadgeLabel = f;\n },\n\n /**\n * Get element position relative to the canvas\n * @param {HTMLElement} el\n * @returns {Object}\n * @private\n */\n getElementPos(el, opts) {\n return CanvasView.getElementPos(el, opts);\n },\n\n /**\n * Returns element's offsets like margins and paddings\n * @param {HTMLElement} el\n * @returns {Object}\n * @private\n */\n getElementOffsets(el) {\n return CanvasView.getElementOffsets(el);\n },\n\n /**\n * Get canvas rectangular data\n * @returns {Object}\n */\n getRect() {\n const { top, left } = CanvasView.getPosition();\n return {\n ...CanvasView.getCanvasOffset(),\n topScroll: top,\n leftScroll: left,\n };\n },\n\n /**\n * This method comes handy when you need to attach something like toolbars\n * to elements inside the canvas, dealing with all relative position,\n * offsets, etc. and returning as result the object with positions which are\n * viewable by the user (when the canvas is scrolled the top edge of the element\n * is not viewable by the user anymore so the new top edge is the one of the canvas)\n *\n * The target should be visible before being passed here as invisible elements\n * return empty string as width\n * @param {HTMLElement} target The target in this case could be the toolbar\n * @param {HTMLElement} element The element on which I'd attach the toolbar\n * @param {Object} options Custom options\n * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right\n * @return {Object}\n * @private\n */\n getTargetToElementDim(target, element, options = {}) {\n var opts = options || {};\n var canvasPos = CanvasView.getPosition();\n if (!canvasPos) return;\n var pos = opts.elPos || CanvasView.getElementPos(element);\n var toRight = options.toRight || 0;\n var targetHeight = opts.targetHeight || target.offsetHeight;\n var targetWidth = opts.targetWidth || target.offsetWidth;\n var eventToTrigger = opts.event || null;\n\n var elTop = pos.top - targetHeight;\n var elLeft = pos.left;\n elLeft += toRight ? pos.width : 0;\n elLeft = toRight ? elLeft - targetWidth : elLeft;\n\n var leftPos = elLeft < canvasPos.left ? canvasPos.left : elLeft;\n var topPos = elTop < canvasPos.top ? canvasPos.top : elTop;\n topPos = topPos > pos.top + pos.height ? pos.top + pos.height : topPos;\n\n var result = {\n top: topPos,\n left: leftPos,\n elementTop: pos.top,\n elementLeft: pos.left,\n elementWidth: pos.width,\n elementHeight: pos.height,\n targetWidth: target.offsetWidth,\n targetHeight: target.offsetHeight,\n canvasTop: canvasPos.top,\n canvasLeft: canvasPos.left,\n canvasWidth: canvasPos.width,\n canvasHeight: canvasPos.height,\n };\n\n // In this way I can catch data and also change the position strategy\n if (eventToTrigger && c.em) {\n c.em.trigger(eventToTrigger, result);\n }\n\n return result;\n },\n\n canvasRectOffset(el, pos, opts = {}) {\n const getFrameElFromDoc = doc => {\n const { defaultView } = doc;\n return defaultView && defaultView.frameElement;\n };\n\n const rectOff = (el, top = 1, pos) => {\n const zoom = this.em.getZoomDecimal();\n const side = top ? 'top' : 'left';\n const doc = el.ownerDocument;\n const { offsetTop = 0, offsetLeft = 0 } = opts.offset ? getFrameElFromDoc(doc) : {};\n const { scrollTop = 0, scrollLeft = 0 } = doc.body || {};\n const scroll = top ? scrollTop : scrollLeft;\n const offset = top ? offsetTop : offsetLeft;\n\n // if (!top) {\n // console.log('LEFT', { posLeft: pos[side], scroll, offset }, el);\n // }\n\n return pos[side] - (scroll - offset) * zoom;\n };\n\n return {\n top: rectOff(el, 1, pos),\n left: rectOff(el, 0, pos),\n };\n },\n\n getTargetToElementFixed(el, elToMove, opts = {}) {\n const pos = opts.pos || this.getElementPos(el);\n const cvOff = opts.canvasOff || this.canvasRectOffset(el, pos);\n const toolbarH = elToMove.offsetHeight || 0;\n const toolbarW = elToMove.offsetWidth || 0;\n const elRight = pos.left + pos.width;\n const cv = this.getCanvasView();\n const frCvOff = cv.getPosition();\n const frameOffset = cv.getFrameOffset(el);\n const { event } = opts;\n\n let top = -toolbarH;\n let left = !isUndefined(opts.left) ? opts.left : pos.width - toolbarW;\n left = pos.left < -left ? -pos.left : left;\n left = elRight > frCvOff.width ? left - (elRight - frCvOff.width) : left;\n\n // Scroll with the window if the top edge is reached and the\n // element is bigger than the canvas\n const fullHeight = pos.height + toolbarH;\n const elIsShort = fullHeight < frameOffset.height;\n\n if (cvOff.top < toolbarH) {\n if (elIsShort) {\n top = top + fullHeight;\n } else {\n top = -cvOff.top < pos.height ? -cvOff.top : pos.height;\n }\n }\n\n const result = {\n top,\n left,\n canvasOffsetTop: cvOff.top,\n canvasOffsetLeft: cvOff.left,\n };\n\n // In this way I can catch data and also change the position strategy\n event && this.em.trigger(event, result);\n\n return result;\n },\n\n /**\n * Instead of simply returning e.clientX and e.clientY this function\n * calculates also the offset based on the canvas. This is helpful when you\n * need to get X and Y position while moving between the editor area and\n * canvas area, which is in the iframe\n * @param {Event} e\n * @return {Object}\n * @private\n */\n getMouseRelativePos(e, options) {\n var opts = options || {};\n var addTop = 0;\n var addLeft = 0;\n var subWinOffset = opts.subWinOffset;\n var doc = e.target.ownerDocument;\n var win = doc.defaultView || doc.parentWindow;\n var frame = win.frameElement;\n var yOffset = subWinOffset ? win.pageYOffset : 0;\n var xOffset = subWinOffset ? win.pageXOffset : 0;\n\n if (frame) {\n var frameRect = frame.getBoundingClientRect();\n addTop = frameRect.top || 0;\n addLeft = frameRect.left || 0;\n }\n\n return {\n y: e.clientY + addTop - yOffset,\n x: e.clientX + addLeft - xOffset,\n };\n },\n\n /**\n * X and Y mouse position relative to the canvas\n * @param {Event} ev\n * @return {Object}\n * @private\n */\n getMouseRelativeCanvas(ev, opts) {\n const zoom = this.getZoomDecimal();\n const { top, left } = CanvasView.getPosition(opts);\n\n return {\n y: ev.clientY * zoom + top,\n x: ev.clientX * zoom + left,\n };\n },\n\n /**\n * Check if the canvas is focused\n * @returns {Boolean}\n */\n hasFocus() {\n return this.getDocument().hasFocus();\n },\n\n /**\n * Detects if some input is focused (input elements, text components, etc.)\n * @return {Boolean}\n * @private\n */\n isInputFocused() {\n const doc = this.getDocument();\n const frame = this.getFrameEl();\n const toIgnore = ['body', ...this.getConfig().notTextable];\n const docActive = frame && document.activeElement === frame;\n const focused = docActive ? doc && doc.activeElement : document.activeElement;\n\n return focused && !toIgnore.some(item => focused.matches(item));\n },\n\n /**\n * Scroll canvas to the element if it's not visible. The scrolling is\n * executed via `scrollIntoView` API and options of this method are\n * passed to it. For instance, you can scroll smoothly by using\n * `{ behavior: 'smooth' }`.\n * @param {HTMLElement|[Component]} el\n * @param {Object} [opts={}] Options, same as options for `scrollIntoView`\n * @param {Boolean} [opts.force=false] Force the scroll, even if the element is already visible\n * @example\n * const selected = editor.getSelected();\n * // Scroll smoothly (this behavior can be polyfilled)\n * canvas.scrollTo(selected, { behavior: 'smooth' });\n * // Force the scroll, even if the element is alredy visible\n * canvas.scrollTo(selected, { force: true });\n */\n scrollTo(el, opts = {}) {\n const elem = getElement(el);\n const view = elem && getViewEl(elem);\n view && view.scrollIntoView(opts);\n },\n\n /**\n * Start autoscroll\n * @private\n */\n startAutoscroll(frame) {\n const fr = (frame && frame.view) || this.em.getCurrentFrame();\n fr && fr.startAutoscroll();\n },\n\n /**\n * Stop autoscroll\n * @private\n */\n stopAutoscroll(frame) {\n const fr = (frame && frame.view) || this.em.getCurrentFrame();\n fr && fr.stopAutoscroll();\n },\n\n /**\n * Set canvas zoom value\n * @param {Number} value The zoom value, from 0 to 100\n * @returns {this}\n * @example\n * canvas.setZoom(50); // set zoom to 50%\n */\n setZoom(value) {\n canvas.set('zoom', parseFloat(value));\n return this;\n },\n\n /**\n * Get canvas zoom value\n * @returns {Number}\n * @example\n * canvas.setZoom(50); // set zoom to 50%\n * const zoom = canvas.getZoom(); // 50\n */\n getZoom() {\n return parseFloat(canvas.get('zoom'));\n },\n\n /**\n * Set canvas position coordinates\n * @param {Number} x Horizontal position\n * @param {Number} y Vertical position\n * @returns {this}\n * @example\n * canvas.setCoords(100, 100);\n */\n setCoords(x, y) {\n canvas.set({ x: parseFloat(x), y: parseFloat(y) });\n return this;\n },\n\n /**\n * Get canvas position coordinates\n * @returns {Object} Object containing coordinates\n * @example\n * canvas.setCoords(100, 100);\n * const coords = canvas.getCoords();\n * // { x: 100, y: 100 }\n */\n getCoords() {\n const { x, y } = canvas.attributes;\n return { x, y };\n },\n\n getZoomDecimal() {\n return this.getZoom() / 100;\n },\n\n getZoomMultiplier() {\n const zoom = this.getZoomDecimal();\n return zoom ? 1 / zoom : 1;\n },\n\n toggleFramesEvents(on) {\n const { style } = this.getFramesEl();\n style.pointerEvents = on ? '' : 'none';\n },\n\n getFrames() {\n return canvas.get('frames').map(item => item);\n },\n\n /**\n * Add new frame to the canvas\n * @param {Object} props Frame properties\n * @returns {[Frame]}\n * @example\n * canvas.addFrame({\n * name: 'Mobile home page',\n * x: 100, // Position in canvas\n * y: 100,\n * width: 500, // Frame dimensions\n * height: 600,\n * // device: 'DEVICE-ID',\n * components: [\n * '

Title frame

',\n * '

Paragraph frame

',\n * ],\n * styles: `\n * .testh { color: red; }\n * .testp { color: blue; }\n * `,\n * });\n */\n addFrame(props = {}, opts = {}) {\n return canvas.get('frames').add(\n {\n ...props,\n },\n {\n ...opts,\n em: this.em,\n }\n );\n },\n\n destroy() {\n canvas.stopListening();\n CanvasView && CanvasView.remove();\n [c, canvas, CanvasView].forEach(i => (i = {}));\n ['em', 'model', 'droppable'].forEach(i => (this[i] = {}));\n },\n };\n};\n","export default {\n // Style prefix\n stylePrefix: 'cm-',\n\n inlineCss: false\n};\n","import { Model } from 'backbone';\n\nexport default class HTMLGenerator extends Model {\n build(model, opts = {}) {\n const models = model.components();\n const htmlOpts = {};\n const { em } = opts;\n\n // Remove unnecessary IDs\n if (opts.cleanId && em) {\n const rules = em.get('CssComposer').getAll();\n const idRules = rules\n .toJSON()\n .map(rule => {\n const sels = rule.selectors;\n const sel = sels && sels.length === 1 && sels.models[0];\n return sel && sel.isId() && sel.get('name');\n })\n .filter(i => i);\n\n htmlOpts.attributes = (mod, attrs) => {\n const { id } = attrs;\n if (\n id &&\n id[0] === 'i' && // all autogenerated IDs start with 'i'\n !mod.get('script') && // if the component has script, we have to leave the ID\n !mod.get('attributes').id && // id is not intentionally in attributes\n idRules.indexOf(id) < 0 // we shouldn't have any rule with this ID\n ) {\n delete attrs.id;\n }\n return attrs;\n };\n }\n\n if (opts.exportWrapper) {\n return model.toHTML({\n ...htmlOpts,\n ...(opts.wrapperIsBody && model.is('wrapper') && { tag: 'body' })\n });\n }\n\n return this.buildModels(models, htmlOpts);\n }\n\n buildModels(models, opts = {}) {\n let code = '';\n models.forEach(mod => (code += mod.toHTML(opts)));\n return code;\n }\n}\n","import { each } from 'underscore';\nimport Backbone from 'backbone';\n\nexport default Backbone.Model.extend({\n /** @inheritdoc */\n build(model) {\n var json = model.toJSON();\n this.beforeEach(json);\n\n each(\n json,\n function(v, attr) {\n var obj = json[attr];\n if (obj instanceof Backbone.Model) {\n json[attr] = this.build(obj);\n } else if (obj instanceof Backbone.Collection) {\n var coll = obj;\n json[attr] = [];\n if (coll.length) {\n coll.each(function(el, index) {\n json[attr][index] = this.build(el);\n }, this);\n }\n }\n },\n this\n );\n\n return json;\n },\n\n /**\n * Execute on each object\n * @param {Object} obj\n */\n beforeEach(obj) {\n delete obj.status;\n }\n});\n","import { extend } from 'underscore';\nimport Backbone from 'backbone';\n\nfunction isFunctionEmpty(fn) {\n const content = fn.toString().match(/\\{([\\s\\S]*)\\}/m)[1]; // content between first and last { }\n return content.replace(/^\\s*\\/\\/.*$/gm, '').trim().length === 0; // remove comments\n}\n\nexport default Backbone.Model.extend({\n mapModel(model) {\n var code = '';\n var script = model.get('script-export') || model.get('script');\n var type = model.get('type');\n var comps = model.get('components');\n var id = model.getId();\n\n if (script) {\n // If the component has scripts we need to expose his ID\n var attr = model.get('attributes');\n attr = extend({}, attr, { id });\n model.set('attributes', attr, { silent: 1 });\n var scrStr = model.getScriptString(script);\n const scrProps = model.get('script-props');\n\n // If the script was updated, I'll put its code in a separate container\n if (model.get('scriptUpdated') && !scrProps) {\n this.mapJs[type + '-' + id] = { ids: [id], code: scrStr };\n } else {\n let props;\n const mapType = this.mapJs[type];\n\n if (scrProps) {\n props = model.__getScriptProps();\n }\n\n if (mapType) {\n mapType.ids.push(id);\n if (props) mapType.props[id] = props;\n } else {\n const res = { ids: [id], code: scrStr };\n if (props) res.props = { [id]: props };\n this.mapJs[type] = res;\n }\n }\n }\n\n comps.each(function (model) {\n code += this.mapModel(model);\n }, this);\n\n return code;\n },\n\n build(model) {\n this.mapJs = {};\n this.mapModel(model);\n let code = '';\n\n for (let type in this.mapJs) {\n const mapType = this.mapJs[type];\n\n if (!mapType.code) {\n continue;\n }\n\n if (mapType.props) {\n if (isFunctionEmpty(mapType.code)) {\n continue;\n }\n\n code += `\n var props = ${JSON.stringify(mapType.props)};\n var ids = Object.keys(props).map(function(id) { return '#'+id }).join(',');\n var els = document.querySelectorAll(ids);\n for (var i = 0, len = els.length; i < len; i++) {\n var el = els[i];\n (${mapType.code}.bind(el))(props[el.id]);\n }`;\n } else {\n // Deprecated\n const ids = '#' + mapType.ids.join(', #');\n code += `\n var items = document.querySelectorAll('${ids}');\n for (var i = 0, len = items.length; i < len; i++) {\n (function(){\\n${mapType.code}\\n}.bind(items[i]))();\n }`;\n }\n }\n\n return code;\n },\n});\n","import { bindAll } from 'underscore';\nimport Backbone from 'backbone';\nimport { hasWin } from 'utils/mixins';\n\nlet CodeMirror;\n\nif (hasWin()) {\n CodeMirror = require('codemirror/lib/codemirror');\n require('codemirror/mode/htmlmixed/htmlmixed');\n require('codemirror/mode/css/css');\n require('codemirror-formatting');\n}\n\nexport default Backbone.Model.extend({\n CodeMirror,\n\n defaults: {\n input: '',\n label: '',\n codeName: '',\n theme: 'hopscotch',\n readOnly: true,\n lineNumbers: true\n },\n\n /** @inheritdoc */\n init(el) {\n bindAll(this, 'onChange');\n this.editor = CodeMirror.fromTextArea(el, {\n dragDrop: false,\n lineWrapping: true,\n mode: this.get('codeName'),\n ...this.attributes\n });\n this.element = el;\n this.editor.on('change', this.onChange);\n\n return this;\n },\n\n onChange() {\n this.trigger('update', this);\n },\n\n getEditor() {\n return this.editor;\n },\n\n /**\n * The element where the viewer is attached\n * @return {HTMLElement}\n */\n getElement() {\n return this.element;\n },\n\n /**\n * Set the element which contains the viewer attached.\n * Generally, it should be just a textarea, but some editor might require\n * a container for it some in that case this method can be used\n * @param {HTMLElement} el\n * @return {self}\n */\n setElement(el) {\n this.element = el;\n return this;\n },\n\n /**\n * Refresh the viewer\n * @return {self}\n */\n refresh() {\n this.getEditor().refresh();\n return this;\n },\n\n /**\n * Focus the viewer\n * @return {self}\n */\n focus() {\n this.getEditor().focus();\n return this;\n },\n\n getContent() {\n const ed = this.getEditor();\n return ed && ed.getValue();\n },\n\n /** @inheritdoc */\n setContent(v, opts = {}) {\n const { editor } = this;\n if (!editor) return;\n editor.setValue(v);\n\n if (editor.autoFormatRange) {\n CodeMirror.commands.selectAll(editor);\n editor.autoFormatRange(editor.getCursor(true), editor.getCursor(false));\n CodeMirror.commands.goDocStart(editor);\n }\n\n !opts.noRefresh && setTimeout(() => this.refresh());\n }\n});\n","import html from 'utils/html';\nimport { View } from 'backbone';\n\nexport default class EditorView extends View {\n template({ pfx, codeName, label }) {\n return html`\n
\n
${label}
\n
\n
\n `;\n }\n\n initialize(o) {\n this.config = o.config || {};\n this.pfx = this.config.stylePrefix;\n }\n\n render() {\n const { model, pfx, $el } = this;\n const obj = model.toJSON();\n obj.pfx = pfx;\n $el.html(this.template(obj));\n $el.attr('class', `${pfx}editor-c`);\n $el.find(`#${pfx}code`).append(model.get('input'));\n return this;\n }\n}\n","/**\n * - [addGenerator](#addgenerator)\n * - [getGenerator](#getgenerator)\n * - [getGenerators](#getgenerators)\n * - [addViewer](#addviewer)\n * - [getViewer](#getviewer)\n * - [getViewers](#getviewers)\n * - [updateViewer](#updateviewer)\n * - [getCode](#getcode)\n *\n *\n * Before using methods you should get first the module from the editor instance, in this way:\n *\n * ```js\n * var codeManager = editor.CodeManager;\n * ```\n *\n * @module CodeManager\n */\nimport { isUndefined } from 'underscore';\nimport defaults from './config/config';\nimport gHtml from './model/HtmlGenerator';\nimport gCss from './model/CssGenerator';\nimport gJson from './model/JsonGenerator';\nimport gJs from './model/JsGenerator';\nimport eCM from './model/CodeMirrorEditor';\nimport editorView from './view/EditorView';\n\nexport default () => {\n var c = {};\n var generators = {},\n defGenerators = {},\n viewers = {},\n defViewers = {};\n\n const defaultViewer = 'CodeMirror';\n\n return {\n getConfig() {\n return c;\n },\n\n config: c,\n\n EditorView: editorView,\n\n /**\n * Name of the module\n * @type {String}\n * @private\n */\n name: 'CodeManager',\n\n /**\n * Initialize module. Automatically called with a new instance of the editor\n * @param {Object} config Configurations\n */\n init(config) {\n c = config || {};\n for (var name in defaults) {\n if (!(name in c)) c[name] = defaults[name];\n }\n\n var ppfx = c.pStylePrefix;\n if (ppfx) c.stylePrefix = ppfx + c.stylePrefix;\n\n defGenerators.html = new gHtml();\n defGenerators.css = new gCss();\n defGenerators.json = new gJson();\n defGenerators.js = new gJs();\n defViewers.CodeMirror = new eCM();\n this.loadDefaultGenerators().loadDefaultViewers();\n\n return this;\n },\n\n /**\n * Add new code generator to the collection\n * @param {string} id Code generator ID\n * @param {Object} generator Code generator wrapper\n * @param {Function} generator.build Function that builds the code\n * @return {this}\n * @example\n * codeManager.addGenerator('html7',{\n * build: function(model){\n * return 'myCode';\n * }\n * });\n * */\n addGenerator(id, generator) {\n generators[id] = generator;\n return this;\n },\n\n /**\n * Get code generator by id\n * @param {string} id Code generator ID\n * @return {Object|null}\n * @example\n * var generator = codeManager.getGenerator('html7');\n * generator.build = function(model){\n * //extend\n * };\n * */\n getGenerator(id) {\n return generators[id] || null;\n },\n\n /**\n * Returns all code generators\n * @return {Array}\n * */\n getGenerators() {\n return generators;\n },\n\n /**\n * Add new code viewer\n * @param {string} id Code viewer ID\n * @param {Object} viewer Code viewer wrapper\n * @param {Function} viewer.init Set element on which viewer will be displayed\n * @param {Function} viewer.setContent Set content to the viewer\n * @return {this}\n * @example\n * codeManager.addViewer('ace',{\n * init: function(el){\n * var ace = require('ace-editor');\n * this.editor = ace.edit(el.id);\n * },\n * setContent: function(code){\n * this.editor.setValue(code);\n * }\n * });\n * */\n addViewer(id, viewer) {\n viewers[id] = viewer;\n return this;\n },\n\n /**\n * Get code viewer by id\n * @param {string} id Code viewer ID\n * @return {Object|null}\n * @example\n * var viewer = codeManager.getViewer('ace');\n * */\n getViewer(id) {\n return viewers[id] || null;\n },\n\n /**\n * Returns all code viewers\n * @return {Array}\n * */\n getViewers() {\n return viewers;\n },\n\n createViewer(opts = {}) {\n const type = !isUndefined(opts.type) ? opts.type : defaultViewer;\n const viewer = this.getViewer(type) && this.getViewer(type).clone();\n const cont = document.createElement('div');\n const txtarea = document.createElement('textarea');\n cont.appendChild(txtarea);\n viewer.set(opts);\n viewer.init(txtarea);\n viewer.setElement(cont);\n\n return viewer;\n },\n\n /**\n * Update code viewer content\n * @param {Object} viewer Viewer instance\n * @param {string} code Code string\n * @example\n * var AceViewer = codeManager.getViewer('ace');\n * // ...\n * var viewer = AceViewer.init(el);\n * // ...\n * codeManager.updateViewer(AceViewer, 'code');\n * */\n updateViewer(viewer, code) {\n viewer.setContent(code);\n },\n\n /**\n * Get code from model\n * @param {Object} model Any kind of model that will be passed to the build method of generator\n * @param {string} genId Code generator id\n * @param {Object} [opt] Options\n * @return {string}\n * @example\n * var codeStr = codeManager.getCode(model, 'html');\n * */\n getCode(model, genId, opt = {}) {\n opt.em = c.em;\n var generator = this.getGenerator(genId);\n return generator ? generator.build(model, opt) : '';\n },\n\n /**\n * Load default code generators\n * @return {this}\n * @private\n * */\n loadDefaultGenerators() {\n for (var id in defGenerators) this.addGenerator(id, defGenerators[id]);\n\n return this;\n },\n\n /**\n * Load default code viewers\n * @return {this}\n * @private\n * */\n loadDefaultViewers() {\n for (var id in defViewers) this.addViewer(id, defViewers[id]);\n\n return this;\n },\n\n destroy() {\n [c, generators, defGenerators, viewers, defViewers].forEach(\n i => (i = {})\n );\n }\n };\n};\n","export default {\n // The device `id` to select on start, if not indicated, the first available from `devices` will be used.\n default: null,\n\n // Default devices\n devices: [\n {\n id: 'desktop',\n name: 'Desktop',\n width: '',\n },\n {\n id: 'tablet',\n name: 'Tablet',\n width: '770px',\n widthMedia: '992px',\n },\n {\n id: 'mobileLandscape',\n name: 'Mobile landscape',\n width: '568px',\n widthMedia: '768px',\n },\n {\n id: 'mobilePortrait',\n name: 'Mobile portrait',\n width: '320px',\n widthMedia: '480px',\n },\n ],\n};\n","import { Model } from 'backbone';\n\n/**\n * @typedef Device\n * @property {String} [name=''] Device type, eg. `Mobile`\n * @property {String} [width] Width to set for the editor iframe, eg. '900px'\n * @property {String} [height=''] Height to set for the editor iframe, eg. '600px'\n * @property {String} [widthMedia=''] The width which will be used in media queries, If empty the width will be used\n * @property {Number} [priority=null] Setup the order of media queries\n */\nexport default class Device extends Model {\n defaults() {\n return {\n name: '',\n width: null,\n height: '',\n widthMedia: null,\n priority: null\n };\n }\n\n initialize() {\n this.get('widthMedia') === null &&\n this.set('widthMedia', this.get('width'));\n this.get('width') === null && this.set('width', this.get('widthMedia'));\n !this.get('priority') &&\n this.set('priority', parseFloat(this.get('widthMedia')) || 0);\n const toCheck = ['width', 'height', 'widthMedia'];\n toCheck.forEach(prop => this.checkUnit(prop));\n }\n\n checkUnit(prop) {\n const pr = this.get(prop) || '';\n const noUnit = (parseFloat(pr) || 0).toString() === pr.toString();\n noUnit && this.set(prop, `${pr}px`);\n }\n\n getName() {\n return this.get('name') || this.get('id');\n }\n\n getWidthMedia() {\n return this.get('widthMedia') || '';\n }\n}\n","import { Collection } from 'backbone';\nimport Device from './Device';\n\nexport default class Devices extends Collection {\n comparator(left, right) {\n const max = Number.MAX_VALUE;\n return (right.get('priority') || max) - (left.get('priority') || max);\n }\n\n getSorted() {\n return this.sort();\n }\n}\n\nDevices.prototype.model = Device;\n","import { View } from 'backbone';\nimport html from 'utils/html';\n\nexport default class DevicesView extends View {\n template({ ppfx, label }) {\n return html`\n
${label}
\n
\n \n \n \n
\n
\n
\n
\n \n `;\n }\n\n events() {\n return {\n change: 'updateDevice'\n };\n }\n\n initialize(o) {\n this.config = o.config || {};\n this.em = this.config.em;\n this.ppfx = this.config.pStylePrefix || '';\n this.events['click .' + this.ppfx + 'add-trasp'] = this.startAdd;\n this.listenTo(this.em, 'change:device', this.updateSelect);\n this.delegateEvents();\n }\n\n /**\n * Start adding new device\n * @return {[type]} [description]\n * @private\n */\n startAdd() {}\n\n /**\n * Update device of the editor\n * @private\n */\n updateDevice() {\n var em = this.em;\n if (em) {\n var devEl = this.devicesEl;\n var val = devEl ? devEl.val() : '';\n em.set('device', val);\n }\n }\n\n /**\n * Update select value on device update\n * @private\n */\n updateSelect() {\n var em = this.em;\n var devEl = this.devicesEl;\n if (em && em.getDeviceModel && devEl) {\n var device = em.getDeviceModel();\n var name = device ? device.get('id') : '';\n devEl.val(name);\n }\n }\n\n /**\n * Return devices options\n * @return {string} String of options\n * @private\n */\n getOptions() {\n const { collection, em } = this;\n let result = '';\n\n collection.each(device => {\n const { name, id } = device.attributes;\n const label = (em && em.t && em.t(`deviceManager.devices.${id}`)) || name;\n result += ``;\n });\n\n return result;\n }\n\n render() {\n const { em, ppfx, $el, el } = this;\n const label = em && em.t && em.t('deviceManager.device');\n $el.html(this.template({ ppfx, label }));\n this.devicesEl = $el.find(`.${ppfx}devices`);\n this.devicesEl.append(this.getOptions());\n this.devicesEl.val(em.get('device'));\n el.className = `${ppfx}devices-c`;\n return this;\n }\n}\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/device_manager/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * deviceManager: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance\n *\n * ```js\n * const deviceManager = editor.Devices;\n * ```\n * ## Available Events\n * * `device:add` - Added new device. The [Device] is passed as an argument to the callback\n * * `device:remove` - Device removed. The [Device] is passed as an argument to the callback\n * * `device:select` - New device selected. The newly selected [Device] and the previous one, are passed as arguments to the callback\n * * `device:update` - Device updated. The updated [Device] and the object containing changes are passed as arguments to the callback\n * * `device` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback\n *\n * ## Methods\n * * [add](#add)\n * * [get](#get)\n * * [getDevices](#getdevices)\n * * [remove](#remove)\n * * [select](#select)\n * * [getSelected](#getselected)\n *\n * [Device]: device.html\n *\n * @module Devices\n */\nimport { isString } from 'underscore';\nimport Module from 'common/module';\nimport defaults from './config/config';\nimport Device from './model/Device';\nimport Devices from './model/Devices';\nimport DevicesView from './view/DevicesView';\n\nexport const evAll = 'device';\nexport const evPfx = `${evAll}:`;\nexport const evSelect = `${evPfx}select`;\nexport const evSelectBefore = `${evSelect}:before`;\nexport const evUpdate = `${evPfx}update`;\nexport const evAdd = `${evPfx}add`;\nexport const evAddBefore = `${evAdd}:before`;\nexport const evRemove = `${evPfx}remove`;\nexport const evRemoveBefore = `${evRemove}:before`;\nconst chnSel = 'change:device';\n\nexport default () => {\n let c = {};\n let devices;\n let view;\n\n return {\n ...Module,\n\n name: 'DeviceManager',\n\n Device,\n\n Devices,\n\n events: {\n all: evAll,\n select: evSelect,\n // selectBefore: evSelectBefore,\n update: evUpdate,\n add: evAdd,\n // addBefore: evAddBefore,\n remove: evRemove,\n removeBefore: evRemoveBefore\n },\n\n init(config = {}) {\n c = { ...defaults, ...config };\n const { em } = c;\n\n devices = new Devices();\n c.devices.forEach(dv => this.add(dv));\n this.em = em;\n this.all = devices;\n this.select(c.default || devices.at(0));\n this.__initListen();\n em.on(chnSel, this._onSelect, this);\n\n return this;\n },\n\n _onSelect(m, deviceId, opts) {\n const { em, events } = this;\n const prevId = m.previous('device');\n const newDevice = this.get(deviceId);\n const ev = events.select;\n em.trigger(ev, newDevice, this.get(prevId));\n this.__catchAllEvent(ev, newDevice, opts);\n },\n\n /**\n * Add new device\n * @param {Object} props Device properties\n * @returns {[Device]} Added device\n * @example\n * const device1 = deviceManager.add({\n * // Without an explicit ID, the `name` will be taken. In case of missing `name`, a random ID will be created.\n * id: 'tablet',\n * name: 'Tablet',\n * width: '900px', // This width will be applied on the canvas frame and for the CSS media\n * });\n * const device2 = deviceManager.add({\n * id: 'tablet2',\n * name: 'Tablet 2',\n * width: '800px', // This width will be applied on the canvas frame\n * widthMedia: '810px', // This width that will be used for the CSS media\n * height: '600px', // Height will be applied on the canvas frame\n * });\n */\n add(props, options = {}) {\n let result;\n let opts = options;\n\n // Support old API\n if (isString(props)) {\n const width = options;\n opts = arguments[2] || {};\n result = {\n ...opts,\n id: props,\n name: opts.name || props,\n width\n };\n } else {\n result = props;\n }\n\n if (!result.id) {\n result.id = result.name || this._createId();\n }\n\n return devices.add(result, opts);\n },\n\n /**\n * Return device by ID\n * @param {String} id ID of the device\n * @returns {[Device]|null}\n * @example\n * const device = deviceManager.get('Tablet');\n * console.log(JSON.stringify(device));\n * // {name: 'Tablet', width: '900px'}\n */\n get(id) {\n // Support old API\n const byName = this.getAll().filter(d => d.get('name') === id)[0];\n return byName || devices.get(id) || null;\n },\n\n /**\n * Remove device\n * @param {String|[Device]} device Device or device id\n * @returns {[Device]} Removed device\n * @example\n * const removed = deviceManager.remove('device-id');\n * // or by passing the Device\n * const device = deviceManager.get('device-id');\n * deviceManager.remove(device);\n */\n remove(device, opts = {}) {\n return this.__remove(device, opts);\n },\n\n /**\n * Return all devices\n * @returns {Array<[Device]>}\n * @example\n * const devices = deviceManager.getDevices();\n * console.log(JSON.stringify(devices));\n * // [{name: 'Desktop', width: ''}, ...]\n */\n getDevices() {\n return devices.models;\n },\n\n /**\n * Change the selected device. This will update the frame in the canvas\n * @param {String|[Device]} device Device or device id\n * @example\n * deviceManager.select('some-id');\n * // or by passing the page\n * const device = deviceManager.get('some-id');\n * deviceManager.select(device);\n */\n select(device, opts = {}) {\n const md = isString(device) ? this.get(device) : device;\n md && this.em.set('device', md.get('id'), opts);\n return this;\n },\n\n /**\n * Get the selected device\n * @returns {[Device]}\n * @example\n * const selected = deviceManager.getSelected();\n */\n getSelected() {\n return this.get(this.em.get('device'));\n },\n\n getAll() {\n return devices;\n },\n\n render() {\n view && view.remove();\n view = new DevicesView({\n collection: devices,\n config: c\n });\n return view.render().el;\n },\n\n destroy() {\n devices.stopListening();\n devices.reset();\n view && view.remove();\n [devices, view].forEach(i => (i = null));\n c = {};\n }\n };\n};\n","export default {\n // Style prefix\n stylePrefix: 'clm-',\n\n // Specify the element to use as a container, string (query) or HTMLElement\n // With the empty value, nothing will be rendered\n appendTo: '',\n\n // Default selectors\n selectors: [],\n\n // Default states\n states: [{ name: 'hover' }, { name: 'active' }, { name: 'nth-of-type(2n)' }],\n\n // Custom selector name escaping strategy, eg.\n // name => name.replace(' ', '_')\n escapeName: 0,\n\n // Custom selected name strategy (the string you see after 'Selected')\n // ({ result, state, target }) => {\n // return `${result} - ID: ${target.getId()}`\n // }\n selectedName: 0,\n\n // Icon used to add new selector\n iconAdd:\n '',\n\n // Icon used to sync styles\n iconSync:\n '',\n\n // Icon to show when the selector is enabled\n iconTagOn:\n '',\n\n // Icon to show when the selector is disabled\n iconTagOff:\n '',\n\n // Icon used to remove the selector\n iconTagRemove:\n '',\n\n /**\n * Custom render function for the Selector Manager\n * @example\n * render: ({ el, labelHead, labelStates, labelInfo, }) => {\n * // You can use the default `el` to extend/edit the current\n * // DOM element of the Selector Manager\n * const someEl = document.createElement('div');\n * // ...\n * el.appendChild(someEl);\n * // no need to return anything from the function\n *\n * // Create and return a new DOM element\n * const newEl = document.createElement('div');\n * // ...\n * return newEl;\n *\n * // Return an HTML string for a completely different layout.\n * // Use `data-*` attributes to make the module recognize some elements:\n * // `data-states` - Where to append state ``;\n })\n .join('');\n\n const statesEl = this.getStates();\n statesEl && statesEl.html(`${options}`);\n this.checkStates();\n },\n\n render() {\n const { em, pfx, ppfx, config, $el, el } = this;\n const { render, iconSync, iconAdd } = config;\n const tmpOpts = {\n iconSync,\n iconAdd,\n labelHead: em.t('selectorManager.label'),\n labelInfo: em.t('selectorManager.selected'),\n ppfx,\n pfx,\n el,\n };\n $el.html(this.template(tmpOpts));\n const renderRes = render && render(tmpOpts);\n renderRes && renderRes !== el && $el.empty().append(renderRes);\n this.$input = $el.find('[data-input]');\n this.$addBtn = $el.find('[data-add]');\n this.$classes = $el.find('#' + pfx + 'tags-c');\n this.$btnSyncEl = $el.find('[data-sync-style]');\n this.$input.hide();\n this.renderStates();\n this.renderClasses();\n $el.attr('class', `${this.className} ${ppfx}one-bg ${ppfx}two-color`);\n return this;\n },\n});\n","/**\n * Selectors in GrapesJS are used in CSS Composer inside Rules and in Components as classes. To illustrate this concept let's take\n * a look at this code:\n *\n * ```css\n * span > #send-btn.btn{\n * ...\n * }\n * ```\n * ```html\n * \n * \n * \n * ```\n *\n * In this scenario we get:\n * * span -> selector of type `tag`\n * * send-btn -> selector of type `id`\n * * btn -> selector of type `class`\n *\n * So, for example, being `btn` the same class entity it'll be easier to refactor and track things.\n *\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/selector_manager/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * selectorManager: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.\n *\n * ```js\n * // Listen to events\n * editor.on('selector:add', (selector) => { ... });\n *\n * // Use the API\n * const sm = editor.Selectors;\n * sm.add(...);\n * ```\n *\n * ## Available Events\n * * `selector:add` - Selector added. The [Selector] is passed as an argument to the callback.\n * * `selector:remove` - Selector removed. The [Selector] is passed as an argument to the callback.\n * * `selector:update` - Selector updated. The [Selector] and the object containing changes are passed as arguments to the callback.\n * * `selector:state` - States changed. An object containing all the available data about the triggered event is passed as an argument to the callback.\n * * `selector` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback.\n *\n * ## Methods\n * * [getConfig](#getconfig)\n * * [add](#add)\n * * [get](#get)\n * * [remove](#remove)\n * * [getAll](#getall)\n * * [setState](#setstate)\n * * [getState](#getstate)\n * * [getStates](#getstates)\n * * [setStates](#setstates)\n * * [getSelected](#getselected)\n * * [addSelected](#addselected)\n * * [removeSelected](#removeselected)\n * * [getSelectedTargets](#getselectedtargets)\n * * [setComponentFirst](#setcomponentfirst)\n * * [getComponentFirst](#getcomponentfirst)\n *\n * [Selector]: selector.html\n * [State]: state.html\n * [Component]: component.html\n * [CssRule]: css_rule.html\n *\n * @module SelectorManager\n */\n\nimport { isString, debounce, isObject, isArray } from 'underscore';\nimport { isComponent, isRule } from 'utils/mixins';\nimport { Model, Collection } from 'common';\nimport Module from 'common/module';\nimport defaults from './config/config';\nimport Selector from './model/Selector';\nimport Selectors from './model/Selectors';\nimport State from './model/State';\nimport ClassTagsView from './view/ClassTagsView';\n\nconst isId = str => isString(str) && str[0] == '#';\nconst isClass = str => isString(str) && str[0] == '.';\n\nexport const evAll = 'selector';\nexport const evPfx = `${evAll}:`;\nexport const evAdd = `${evPfx}add`;\nexport const evUpdate = `${evPfx}update`;\nexport const evRemove = `${evPfx}remove`;\nexport const evRemoveBefore = `${evRemove}:before`;\nexport const evCustom = `${evPfx}custom`;\nexport const evState = `${evPfx}state`;\n\nexport default () => {\n return {\n ...Module,\n\n name: 'SelectorManager',\n\n Selector,\n\n Selectors,\n\n events: {\n all: evAll,\n update: evUpdate,\n add: evAdd,\n remove: evRemove,\n removeBefore: evRemoveBefore,\n state: evState,\n custom: evCustom,\n },\n\n /**\n * Get configuration object\n * @name getConfig\n * @function\n * @return {Object}\n */\n\n init(conf = {}) {\n this.__initConfig(defaults, conf);\n const config = this.getConfig();\n const em = config.em;\n const ppfx = config.pStylePrefix;\n\n if (ppfx) {\n config.stylePrefix = ppfx + config.stylePrefix;\n }\n\n // Global selectors container\n this.all = new Selectors(config.selectors);\n this.selected = new Selectors([], { em, config });\n this.states = new Collection(config.states, { model: State });\n this.model = new Model({ cFirst: config.componentFirst, _undo: true });\n this.__initListen({\n collections: [this.states, this.selected],\n propagate: [{ entity: this.states, event: this.events.state }],\n });\n em.on('change:state', (m, value) => em.trigger(evState, value));\n this.model.on('change:cFirst', (m, value) => em.trigger('selector:type', value));\n const listenTo =\n 'component:toggled component:update:classes change:device styleManager:update selector:state selector:type';\n this.model.listenTo(em, listenTo, () => this.__update());\n\n return this;\n },\n\n __update: debounce(function () {\n this.__trgCustom();\n }),\n\n __trgCustom(opts) {\n this.em.trigger(this.events.custom, this.__customData(opts));\n },\n\n __customData(opts = {}) {\n const { container } = opts;\n return {\n states: this.getStates(),\n selected: this.getSelected(),\n container,\n };\n },\n\n // postLoad() {\n // this.__postLoad();\n // const { em, model } = this;\n // const um = em.get('UndoManager');\n // um && um.add(model);\n // um && um.add(this.pages);\n // },\n\n postRender() {\n this.__appendTo();\n this.__trgCustom();\n },\n\n select(value, opts = {}) {\n const targets = Array.isArray(value) ? value : [value];\n const toSelect = this.em.get('StyleManager').select(targets, opts);\n const selTags = this.selectorTags;\n const res = toSelect\n .filter(i => i)\n .map(sel =>\n isComponent(sel) ? sel : isRule(sel) && !sel.get('selectorsAdd') ? sel : sel.getSelectorsString()\n );\n selTags && selTags.componentChanged({ targets: res });\n return this;\n },\n\n addSelector(name, opts = {}, cOpts = {}) {\n let props = { ...opts };\n\n if (isObject(name)) {\n props = name;\n } else {\n props.name = name;\n }\n\n if (isId(props.name)) {\n props.name = props.name.substr(1);\n props.type = Selector.TYPE_ID;\n } else if (isClass(props.name)) {\n props.name = props.name.substr(1);\n }\n\n if (props.label && !props.name) {\n props.name = this.escapeName(props.label);\n }\n\n const cname = props.name;\n const config = this.getConfig();\n const all = this.getAll();\n const selector = cname ? this.get(cname, props.type) : all.where(props)[0];\n\n if (!selector) {\n return all.add(props, { ...cOpts, config });\n }\n\n return selector;\n },\n\n getSelector(name, type = Selector.TYPE_CLASS) {\n if (isId(name)) {\n name = name.substr(1);\n type = Selector.TYPE_ID;\n } else if (isClass(name)) {\n name = name.substr(1);\n }\n\n return this.getAll().where({ name, type })[0];\n },\n\n /**\n * Add a new selector to the collection if it does not already exist.\n * You can pass selectors properties or string identifiers.\n * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls`\n * @param {Object} [opts] Selector options\n * @return {[Selector]}\n * @example\n * const selector = selectorManager.add({ name: 'my-class', label: 'My class' });\n * console.log(selector.toString()) // `.my-class`\n * // Same as\n * const selector = selectorManager.add('.my-class');\n * console.log(selector.toString()) // `.my-class`\n * */\n add(props, opts = {}) {\n const cOpts = isString(props) ? {} : opts;\n // Keep support for arrays but avoid it in docs\n if (isArray(props)) {\n return props.map(item => this.addSelector(item, opts, cOpts));\n } else {\n return this.addSelector(props, opts, cOpts);\n }\n },\n\n /**\n * Add class selectors\n * @param {Array|string} classes Array or string of classes\n * @return {Array} Array of added selectors\n * @private\n * @example\n * sm.addClass('class1');\n * sm.addClass('class1 class2');\n * sm.addClass(['class1', 'class2']);\n * // -> [SelectorObject, ...]\n */\n addClass(classes) {\n const added = [];\n\n if (isString(classes)) {\n classes = classes.trim().split(' ');\n }\n\n classes.forEach(name => added.push(this.addSelector(name)));\n return added;\n },\n\n /**\n * Get the selector by its name/type\n * @param {String} name Selector name or string identifier\n * @returns {[Selector]|null}\n * @example\n * const selector = selectorManager.get('.my-class');\n * // Get Id\n * const selectorId = selectorManager.get('#my-id');\n * */\n get(name, type) {\n // Keep support for arrays but avoid it in docs\n if (isArray(name)) {\n const result = [];\n const selectors = name.map(item => this.getSelector(item)).filter(item => item);\n selectors.forEach(item => result.indexOf(item) < 0 && result.push(item));\n return result;\n } else {\n return this.getSelector(name, type) || null;\n }\n },\n\n /**\n * Remove Selector.\n * @param {String|[Selector]} selector Selector instance or Selector string identifier\n * @returns {[Selector]} Removed Selector\n * @example\n * const removed = selectorManager.remove('.myclass');\n * // or by passing the Selector\n * selectorManager.remove(selectorManager.get('.myclass'));\n */\n remove(selector, opts) {\n return this.__remove(selector, opts);\n },\n\n /**\n * Change the selector state\n * @param {String} value State value\n * @returns {this}\n * @example\n * selectorManager.setState('hover');\n */\n setState(value) {\n this.em.setState(value);\n return this;\n },\n\n /**\n * Get the current selector state value\n * @returns {String}\n */\n getState() {\n return this.em.getState();\n },\n\n /**\n * Get states\n * @returns {Array<[State]>}\n */\n getStates() {\n return [...this.states.models];\n },\n\n /**\n * Set a new collection of states\n * @param {Array} states Array of new states\n * @returns {Array<[State]>}\n * @example\n * const states = selectorManager.setStates([\n * { name: 'hover', label: 'Hover' },\n * { name: 'nth-of-type(2n)', label: 'Even/Odd' }\n * ]);\n */\n setStates(states, opts) {\n return this.states.reset(states, opts);\n },\n\n /**\n * Get commonly selected selectors, based on all selected components.\n * @returns {Array<[Selector]>}\n * @example\n * const selected = selectorManager.getSelected();\n * console.log(selected.map(s => s.toString()))\n */\n getSelected() {\n return this.__getCommon();\n },\n\n /**\n * Add new selector to all selected components.\n * @param {Object|String} props Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls`\n * @example\n * selectorManager.addSelected('.new-class');\n */\n addSelected(props) {\n const added = this.add(props);\n // TODO: target should be the one from StyleManager\n this.em.getSelectedAll().forEach(target => {\n target.getSelectors().add(added);\n });\n // TODO: update selected collection\n },\n\n /**\n * Remove a common selector from all selected components.\n * @param {String|[Selector]} selector Selector instance or Selector string identifier\n * @example\n * selectorManager.removeSelected('.myclass');\n */\n removeSelected(selector) {\n this.em.getSelectedAll().forEach(trg => {\n !selector.get('protected') && trg && trg.getSelectors().remove(selector);\n });\n },\n\n /**\n * Get the array of currently selected targets.\n * @returns {Array<[Component]|[CssRule]>}\n * @example\n * const targetsToStyle = selectorManager.getSelectedTargets();\n * console.log(targetsToStyle.map(target => target.getSelectorsString()))\n */\n getSelectedTargets() {\n return this.em.get('StyleManager').getSelectedAll();\n },\n\n /**\n * Update component-first option.\n * If the component-first is enabled, all the style changes will be applied on selected components (ID rules) instead\n * of selectors (which would change styles on all components with those classes).\n * @param {Boolean} value\n */\n setComponentFirst(value) {\n this.getConfig().componentFirst = value;\n this.model.set({ cFirst: value });\n },\n\n /**\n * Get the value of component-first option.\n * @return {Boolean}\n */\n getComponentFirst() {\n return this.getConfig().componentFirst;\n },\n\n /**\n * Get all selectors\n * @name getAll\n * @function\n * @return {Collection<[Selector]>}\n * */\n\n /**\n * Return escaped selector name\n * @param {String} name Selector name to escape\n * @returns {String} Escaped name\n * @private\n */\n escapeName(name) {\n const { escapeName } = this.getConfig();\n return escapeName ? escapeName(name) : Selector.escapeName(name);\n },\n\n /**\n * Render class selectors. If an array of selectors is provided a new instance of the collection will be rendered\n * @param {Array} selectors\n * @return {HTMLElement}\n * @private\n */\n render(selectors) {\n const { em, selectorTags } = this;\n const config = this.getConfig();\n const el = selectorTags && selectorTags.el;\n this.selected.reset(selectors);\n this.selectorTags = new ClassTagsView({\n el,\n collection: this.selected,\n module: this,\n config,\n });\n\n return this.selectorTags.render().el;\n },\n\n destroy() {\n const { selectorTags, model } = this;\n model.stopListening();\n this.__destroy();\n selectorTags && selectorTags.remove();\n this.selectorTags = {};\n },\n\n /**\n * Get common selectors from the current selection.\n * @return {Array}\n * @private\n */\n __getCommon() {\n return this.__getCommonSelectors(this.em.getSelectedAll());\n },\n\n __getCommonSelectors(components, opts = {}) {\n const selectors = components.map(cmp => cmp.getSelectors && cmp.getSelectors().getValid(opts)).filter(Boolean);\n return this.__common(...selectors);\n },\n\n __common(...args) {\n if (!args.length) return [];\n if (args.length === 1) return args[0];\n if (args.length === 2) return args[0].filter(item => args[1].indexOf(item) >= 0);\n\n return args.slice(1).reduce((acc, item) => this.__common(acc, item), args[0]);\n },\n };\n};\n","export default {\n // Prefix identifier that will be used inside storing and loading\n id: 'gjs-',\n\n // Enable/Disable autosaving\n autosave: 1,\n\n // Indicates if load data inside editor after init\n autoload: 1,\n\n // Indicates which storage to use. Available: local | remote\n type: 'local',\n\n // If autosave enabled, indicates how many steps (general changes to structure)\n // need to be done before save. Useful with remoteStorage to reduce remote calls\n stepsBeforeSave: 1,\n\n //Enable/Disable components model (JSON format)\n storeComponents: 1,\n\n //Enable/Disable styles model (JSON format)\n storeStyles: 1,\n\n //Enable/Disable saving HTML template\n storeHtml: 1,\n\n //Enable/Disable saving CSS template\n storeCss: 1,\n\n // ONLY FOR LOCAL STORAGE\n // If enabled, checks if browser supports Local Storage\n checkLocal: 1,\n\n // ONLY FOR REMOTE STORAGE\n // Custom parameters to pass with the remote storage request, eg. csrf token\n params: {},\n\n // Custom headers for the remote storage request\n headers: {},\n\n // Endpoint where to save all stuff\n urlStore: '',\n\n // Endpoint where to fetch data\n urlLoad: '',\n\n //Callback before request\n beforeSend(jqXHR, settings) {},\n\n //Callback after request\n onComplete(jqXHR, status) {},\n\n // set contentType paramater of $.ajax\n // true: application/json; charset=utf-8'\n // false: 'x-www-form-urlencoded'\n contentTypeJson: true,\n\n credentials: 'include',\n\n // Pass custom options to fetch API (remote storage)\n // You can pass a simple object: { someOption: 'someValue' }\n // or a function which returns and object to add:\n // currentOpts => {\n // return currentOpts.method === 'post' ? { method: 'patch' } : {};\n // }\n fetchOptions: ''\n};\n","import { Model } from 'backbone';\nimport { hasWin } from 'utils/mixins';\n\nexport default Model.extend({\n defaults: {\n checkLocal: true\n },\n\n /**\n * @private\n */\n store(data, clb = () => {}) {\n if (this.hasLocal()) {\n for (let key in data) localStorage.setItem(key, data[key]);\n }\n\n clb && clb();\n },\n\n /**\n * @private\n */\n load(keys, clb = () => {}) {\n const result = {};\n\n if (this.hasLocal()) {\n for (let i = 0, len = keys.length; i < len; i++) {\n const value = localStorage.getItem(keys[i]);\n if (value) result[keys[i]] = value;\n }\n }\n\n clb && clb(result);\n\n return result;\n },\n\n /**\n * @private\n */\n remove(keys) {\n if (!this.hasLocal()) return;\n\n for (let i = 0, len = keys.length; i < len; i++)\n localStorage.removeItem(keys[i]);\n },\n\n /**\n * Check storage environment\n * @private\n * */\n hasLocal() {\n const win = hasWin();\n\n if (this.get('checkLocal') && (!win || !localStorage)) {\n win && console.warn(\"Your browser doesn't support localStorage\");\n return false;\n }\n\n return true;\n }\n});\n","import Backbone from 'backbone';\nimport fetch from 'utils/fetch';\nimport { isUndefined, isFunction } from 'underscore';\n\nexport default Backbone.Model.extend({\n fetch,\n\n defaults: {\n urlStore: '',\n urlLoad: '',\n params: {},\n beforeSend() {},\n onComplete() {},\n contentTypeJson: false,\n credentials: 'include',\n fetchOptions: ''\n },\n\n /**\n * Triggered before the request is started\n * @private\n */\n onStart() {\n const em = this.get('em');\n const before = this.get('beforeSend');\n before && before();\n },\n\n /**\n * Triggered on request error\n * @param {Object} err Error\n * @param {Function} [clbErr] Error callback\n * @private\n */\n onError(err, clbErr) {\n if (clbErr) {\n clbErr(err);\n } else {\n const em = this.get('em');\n console.error(err);\n em && em.trigger('storage:error', err);\n }\n },\n\n /**\n * Triggered on request response\n * @param {string} text Response text\n * @private\n */\n onResponse(text, clb) {\n const em = this.get('em');\n const complete = this.get('onComplete');\n const typeJson = this.get('contentTypeJson');\n const parsable = text && typeof text === 'string';\n const res = typeJson && parsable ? JSON.parse(text) : text;\n complete && complete(res);\n clb && clb(res);\n em && em.trigger('storage:response', res);\n },\n\n store(data, clb, clbErr) {\n const body = {};\n\n for (let key in data) {\n body[key] = data[key];\n }\n\n this.request(this.get('urlStore'), { body }, clb, clbErr);\n },\n\n load(keys, clb, clbErr) {\n this.request(this.get('urlLoad'), { method: 'get' }, clb, clbErr);\n },\n\n /**\n * Execute remote request\n * @param {string} url Url\n * @param {Object} [opts={}] Options\n * @param {Function} [clb=null] Callback\n * @param {Function} [clbErr=null] Error callback\n * @private\n */\n request(url, opts = {}, clb = null, clbErr = null) {\n const typeJson = this.get('contentTypeJson');\n const headers = this.get('headers') || {};\n const params = this.get('params');\n const reqHead = 'X-Requested-With';\n const typeHead = 'Content-Type';\n const bodyObj = opts.body || {};\n let fetchOptions;\n let body;\n\n for (let param in params) {\n bodyObj[param] = params[param];\n }\n\n if (isUndefined(headers[reqHead])) {\n headers[reqHead] = 'XMLHttpRequest';\n }\n\n // With `fetch`, have to send FormData without any 'Content-Type'\n // https://stackoverflow.com/questions/39280438/fetch-missing-boundary-in-multipart-form-data-post\n\n if (isUndefined(headers[typeHead]) && typeJson) {\n headers[typeHead] = 'application/json; charset=utf-8';\n }\n\n if (typeJson) {\n body = JSON.stringify(bodyObj);\n } else {\n body = new FormData();\n\n for (let bodyKey in bodyObj) {\n body.append(bodyKey, bodyObj[bodyKey]);\n }\n }\n fetchOptions = {\n method: opts.method || 'post',\n credentials: this.get('credentials'),\n headers\n };\n\n // Body should only be included on POST method\n if (fetchOptions.method === 'post') {\n fetchOptions.body = body;\n }\n\n const fetchOpts = this.get('fetchOptions') || {};\n const addOpts = isFunction(fetchOpts)\n ? fetchOpts(fetchOptions)\n : fetchOptions;\n\n this.onStart();\n this.fetch(url, {\n ...fetchOptions,\n ...(addOpts || {})\n })\n .then(res =>\n ((res.status / 200) | 0) == 1\n ? res.text()\n : res.text().then(text => Promise.reject(text))\n )\n .then(text => this.onResponse(text, clb))\n .catch(err => this.onError(err, clbErr));\n }\n});\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/storage_manager/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * storageManager: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance.\n *\n * ```js\n * // Listen to events\n * editor.on('storage:start', () => { ... });\n *\n * // Use the API\n * const storageManager = editor.StorageManager;\n * storageManager.add(...);\n * ```\n *\n * ## Available Events\n * * `storage:start` - Before the storage request is started\n * * `storage:start:store` - Before the store request. The object to store is passed as an argumnet (which you can edit)\n * * `storage:start:load` - Before the load request. Items to load are passed as an argumnet (which you can edit)\n * * `storage:load` - Triggered when something was loaded from the storage, loaded object passed as an argumnet\n * * `storage:store` - Triggered when something is stored to the storage, stored object passed as an argumnet\n * * `storage:end` - After the storage request is ended\n * * `storage:end:store` - After the store request\n * * `storage:end:load` - After the load request\n * * `storage:error` - On any error on storage request, passes the error as an argument\n * * `storage:error:store` - Error on store request, passes the error as an argument\n * * `storage:error:load` - Error on load request, passes the error as an argument\n *\n * ## Methods\n * * [getConfig](#getconfig)\n * * [isAutosave](#isautosave)\n * * [setAutosave](#setautosave)\n * * [getStepsBeforeSave](#getstepsbeforesave)\n * * [setStepsBeforeSave](#setstepsbeforesave)\n * * [setStepsBeforeSave](#setstepsbeforesave)\n * * [getStorages](#getstorages)\n * * [getCurrent](#getcurrent)\n * * [getCurrentStorage](#getcurrentstorage)\n * * [setCurrent](#setcurrent)\n * * [add](#add)\n * * [get](#get)\n * * [store](#store)\n * * [load](#load)\n *\n * @module StorageManager\n */\n\nimport defaults from './config/config';\nimport LocalStorage from './model/LocalStorage';\nimport RemoteStorage from './model/RemoteStorage';\n\nconst eventStart = 'storage:start';\nconst eventAfter = 'storage:after';\nconst eventEnd = 'storage:end';\nconst eventError = 'storage:error';\n\nexport default () => {\n var c = {};\n let em;\n var storages = {};\n var defaultStorages = {};\n\n return {\n /**\n * Name of the module\n * @type {String}\n * @private\n */\n name: 'StorageManager',\n\n /**\n * Initialize module. Automatically called with a new instance of the editor\n * @param {Object} config Configurations\n * @param {string} [config.id='gjs-'] The prefix for the fields, useful to differentiate storing/loading\n * with multiple editors on the same page. For example, in local storage, the item of HTML will be saved like 'gjs-html'\n * @param {Boolean} [config.autosave=true] Indicates if autosave mode is enabled, works in conjunction with stepsBeforeSave\n * @param {number} [config.stepsBeforeSave=1] If autosave enabled, indicates how many steps/changes are necessary\n * before autosave is triggered\n * @param {string} [config.type='local'] Default storage type. Available: 'local' | 'remote' | ''(do not store)\n * @private\n * @example\n * ...\n * {\n * autosave: false,\n * type: 'remote',\n * }\n * ...\n */\n init(config = {}) {\n c = { ...defaults, ...config };\n em = c.em;\n if (c._disable) c.type = 0;\n defaultStorages.remote = new RemoteStorage(c);\n defaultStorages.local = new LocalStorage(c);\n c.currentStorage = c.type;\n this.loadDefaultProviders().setCurrent(c.type);\n return this;\n },\n\n /**\n * Get configuration object\n * @return {Object}\n * */\n getConfig() {\n return c;\n },\n\n /**\n * Checks if autosave is enabled\n * @return {Boolean}\n * */\n isAutosave() {\n return !!c.autosave;\n },\n\n /**\n * Set autosave value\n * @param {Boolean} v\n * @return {this}\n * */\n setAutosave(v) {\n c.autosave = !!v;\n return this;\n },\n\n /**\n * Returns number of steps required before trigger autosave\n * @return {number}\n * */\n getStepsBeforeSave() {\n return c.stepsBeforeSave;\n },\n\n /**\n * Set steps required before trigger autosave\n * @param {number} v\n * @return {this}\n * */\n setStepsBeforeSave(v) {\n c.stepsBeforeSave = v;\n return this;\n },\n\n /**\n * Add new storage\n * @param {string} id Storage ID\n * @param {Object} storage Storage wrapper\n * @param {Function} storage.load Load method\n * @param {Function} storage.store Store method\n * @return {this}\n * @example\n * storageManager.add('local2', {\n * load: function(keys, clb, clbErr) {\n * var res = {};\n * for (var i = 0, len = keys.length; i < len; i++){\n * var v = localStorage.getItem(keys[i]);\n * if(v) res[keys[i]] = v;\n * }\n * clb(res); // might be called inside some async method\n * // In case of errors...\n * // clbErr('Went something wrong');\n * },\n * store: function(data, clb, clbErr) {\n * for(var key in data)\n * localStorage.setItem(key, data[key]);\n * clb(); // might be called inside some async method\n * }\n * });\n * */\n add(id, storage) {\n storages[id] = storage;\n return this;\n },\n\n /**\n * Returns storage by id\n * @param {string} id Storage ID\n * @return {Object|null}\n * */\n get(id) {\n return storages[id] || null;\n },\n\n /**\n * Returns all storages\n * @return {Array}\n * */\n getStorages() {\n return storages;\n },\n\n /**\n * Returns current storage type\n * @return {string}\n * */\n getCurrent() {\n return c.currentStorage;\n },\n\n /**\n * Set current storage type\n * @param {string} id Storage ID\n * @return {this}\n * */\n setCurrent(id) {\n c.currentStorage = id;\n return this;\n },\n\n /**\n * Store key-value resources in the current storage\n * @param {Object} data Data in key-value format, eg. {item1: value1, item2: value2}\n * @param {Function} clb Callback function\n * @return {Object|null}\n * @example\n * storageManager.store({item1: value1, item2: value2});\n * */\n store(data, clb) {\n const st = this.get(this.getCurrent());\n const toStore = {};\n this.onStart('store', data);\n\n for (let key in data) {\n toStore[c.id + key] = data[key];\n }\n\n return st\n ? st.store(\n toStore,\n res => {\n this.onAfter('store', res);\n clb && clb(res);\n this.onEnd('store', res);\n },\n err => {\n this.onError('store', err);\n }\n )\n : null;\n },\n\n /**\n * Load resource from the current storage by keys\n * @param {string|Array} keys Keys to load\n * @param {Function} clb Callback function\n * @example\n * storageManager.load(['item1', 'item2'], res => {\n * // res -> {item1: value1, item2: value2}\n * });\n * storageManager.load('item1', res => {\n * // res -> {item1: value1}\n * });\n * */\n load(keys, clb) {\n const st = this.get(this.getCurrent());\n const keysF = [];\n let result = {};\n\n if (typeof keys === 'string') keys = [keys];\n this.onStart('load', keys);\n\n for (var i = 0, len = keys.length; i < len; i++) {\n keysF.push(c.id + keys[i]);\n }\n\n if (st) {\n st.load(\n keysF,\n res => {\n result = this.__clearKeys(res);\n this.onAfter('load', result);\n clb && clb(result);\n this.onEnd('load', result);\n },\n err => {\n clb && clb(result);\n this.onError('load', err);\n }\n );\n } else {\n clb && clb(result);\n }\n },\n\n /**\n * Restore key names\n * @param {Object} data\n * @returns {Object}\n * @private\n */\n __clearKeys(data = {}) {\n const result = {};\n const reg = new RegExp('^' + c.id + '');\n\n for (let itemKey in data) {\n const itemKeyR = itemKey.replace(reg, '');\n result[itemKeyR] = data[itemKey];\n }\n\n return result;\n },\n\n /**\n * Load default storages\n * @return {this}\n * @private\n * */\n loadDefaultProviders() {\n for (var id in defaultStorages) this.add(id, defaultStorages[id]);\n return this;\n },\n\n /**\n * Get current storage\n * @return {Storage}\n * */\n getCurrentStorage() {\n return this.get(this.getCurrent());\n },\n\n /**\n * On start callback\n * @private\n */\n onStart(ctx, data) {\n if (em) {\n em.trigger(eventStart);\n ctx && em.trigger(`${eventStart}:${ctx}`, data);\n }\n },\n\n /**\n * On after callback (before passing data to the callback)\n * @private\n */\n onAfter(ctx, data) {\n if (em) {\n em.trigger(eventAfter);\n ctx && em.trigger(`${eventAfter}:${ctx}`, data);\n }\n },\n\n /**\n * On end callback\n * @private\n */\n onEnd(ctx, data) {\n if (em) {\n em.trigger(eventEnd);\n ctx && em.trigger(`${eventEnd}:${ctx}`, data);\n }\n },\n\n /**\n * On error callback\n * @private\n */\n onError(ctx, data) {\n if (em) {\n em.trigger(eventError, data);\n ctx && em.trigger(`${eventError}:${ctx}`, data);\n this.onEnd(ctx, data);\n }\n },\n\n /**\n * Check if autoload is possible\n * @return {Boolean}\n * @private\n * */\n canAutoload() {\n const storage = this.getCurrentStorage();\n return storage && this.getConfig().autoload;\n },\n\n destroy() {\n [c, em, storages, defaultStorages].forEach(i => (i = {}));\n },\n };\n};\n","export default {\n textTags: ['br', 'b', 'i', 'u', 'a', 'ul', 'ol'],\n\n // Custom CSS parser\n // @see https://grapesjs.com/docs/guides/Custom-CSS-parser.html\n parserCss: null,\n\n // Custom HTML parser\n // At the moment, the custom HTML parser should rely on DOM Node instance as the result\n // @example\n // The return should be an instance of an Node as the root to traverse\n // https://developer.mozilla.org/en-US/docs/Web/API/Node\n // parserHtml: (input, opts = {}) => (new DOMParser()).parseFromString(input, 'text/xml')\n // Here the result will be XMLDocument, which extends Node\n parserHtml: null,\n\n // Default HTML parser options (used in `parserModule.parseHtml(' tags\n allowScripts: false,\n\n // Allow unsafe HTML attributes (eg. `on*` inline event handlers)\n allowUnsafeAttr: false,\n },\n};\n","import { keys } from 'underscore';\n\n// At-rules\n// https://developer.mozilla.org/it/docs/Web/API/CSSRule#Type_constants\nconst atRules = {\n 4: 'media',\n 5: 'font-face',\n 6: 'page',\n 7: 'keyframes',\n 11: 'counter-style',\n 12: 'supports',\n 13: 'document',\n 14: 'font-feature-values',\n 15: 'viewport'\n};\nconst atRuleKeys = keys(atRules);\nconst singleAtRules = ['5', '6', '11', '15'];\nconst singleAtRulesNames = ['font-face', 'page', 'counter-style', 'viewport'];\n\n/**\n * Parse selector string to array.\n * Only classe based are valid as CSS rules inside editor, not valid\n * selectors will be dropped as additional\n * It's ok with the last part of the string as state (:hover, :active)\n * @param {string} str Selectors string\n * @return {Object}\n * @example\n * var res = parseSelector('.test1, .test1.test2, .test2 .test3');\n * console.log(res);\n * // {\n * //result: [['test1'], ['test1', 'test2']],\n * //add: ['.test2 .test3']\n * //}\n */\nexport const parseSelector = (str = '') => {\n const add = [];\n const result = [];\n const sels = str.split(',');\n\n for (var i = 0, len = sels.length; i < len; i++) {\n var sel = sels[i].trim();\n\n // Will accept only concatenated classes and last\n // class might be with state (eg. :hover), nothing else.\n // Can also accept SINGLE ID selectors, eg. `#myid`, `#myid:hover`\n // Composed are not valid: `#myid.some-class`, `#myid.some-class:hover`\n if (\n /^(\\.{1}[\\w\\-]+)+(:{1,2}[\\w\\-()]+)?$/gi.test(sel) ||\n /^(#{1}[\\w\\-]+){1}(:{1,2}[\\w\\-()]+)?$/gi.test(sel)\n ) {\n var cls = sel.split('.').filter(Boolean);\n result.push(cls);\n } else {\n add.push(sel);\n }\n }\n\n return {\n result,\n add\n };\n};\n\n/**\n * Parse style declarations of the node\n * @param {CSSRule} node\n * @return {Object}\n */\nexport const parseStyle = node => {\n const stl = node.style;\n const style = {};\n\n for (var i = 0, len = stl.length; i < len; i++) {\n const propName = stl[i];\n const propValue = stl.getPropertyValue(propName);\n const important = stl.getPropertyPriority(propName);\n style[propName] = `${propValue}${important ? ` !${important}` : ''}`;\n }\n\n return style;\n};\n\n/**\n * Get the condition when possible\n * @param {CSSRule} node\n * @return {string}\n */\nexport const parseCondition = node => {\n const condition =\n node.conditionText ||\n (node.media && node.media.mediaText) ||\n node.name ||\n node.selectorText ||\n '';\n return condition.trim();\n};\n\n/**\n * Create node for the editor\n * @param {Array} selectors Array containing strings of classes\n * @param {Object} style Key-value object of style declarations\n * @return {Object}\n */\nexport const createNode = (selectors, style = {}, opts = {}) => {\n const node = {};\n const selLen = selectors.length;\n const lastClass = selectors[selLen - 1];\n const stateArr = lastClass ? lastClass.split(/:(.+)/) : [];\n const state = stateArr[1];\n const { atRule, selectorsAdd, mediaText } = opts;\n const singleAtRule = singleAtRulesNames.indexOf(atRule) >= 0;\n singleAtRule && (node.singleAtRule = 1);\n atRule && (node.atRuleType = atRule);\n selectorsAdd && (node.selectorsAdd = selectorsAdd);\n mediaText && (node.mediaText = mediaText);\n\n // Isolate the state from selectors\n if (state) {\n selectors[selLen - 1] = stateArr[0];\n node.state = state;\n stateArr.splice(stateArr.length - 1, 1);\n }\n\n node.selectors = selectors;\n node.style = style;\n\n return node;\n};\n\n/**\n * Fetch data from node\n * @param {StyleSheet|CSSRule} el\n * @return {Array}\n */\nexport const parseNode = el => {\n var result = [];\n var nodes = el.cssRules || [];\n\n for (var i = 0, len = nodes.length; i < len; i++) {\n const node = nodes[i];\n const type = node.type.toString();\n let singleAtRule = 0;\n let atRuleType = '';\n let condition = '';\n // keyText is for CSSKeyframeRule\n let sels = node.selectorText || node.keyText;\n const isSingleAtRule = singleAtRules.indexOf(type) >= 0;\n\n // Check if the node is an at-rule\n if (isSingleAtRule) {\n singleAtRule = 1;\n atRuleType = atRules[type];\n condition = parseCondition(node);\n } else if (atRuleKeys.indexOf(type) >= 0) {\n var subRules = parseNode(node);\n condition = parseCondition(node);\n\n for (var s = 0, lens = subRules.length; s < lens; s++) {\n var subRule = subRules[s];\n condition && (subRule.mediaText = condition);\n subRule.atRuleType = atRules[type];\n }\n result = result.concat(subRules);\n }\n\n if (!sels && !isSingleAtRule) continue;\n const style = parseStyle(node);\n const selsParsed = parseSelector(sels);\n const selsAdd = selsParsed.add;\n sels = selsParsed.result;\n\n let lastRule;\n // For each group of selectors\n for (var k = 0, len3 = sels.length; k < len3; k++) {\n const model = createNode(sels[k], style, {\n atRule: atRules[type]\n });\n result.push(model);\n lastRule = model;\n }\n\n // Need to push somewhere not class-based selectors, if some rule was\n // created will push them there, otherwise will create a new rule\n if (selsAdd.length) {\n var selsAddStr = selsAdd.join(', ');\n if (lastRule) {\n lastRule.selectorsAdd = selsAddStr;\n } else {\n const model = {\n selectors: [],\n selectorsAdd: selsAddStr,\n style\n };\n singleAtRule && (model.singleAtRule = singleAtRule);\n atRuleType && (model.atRuleType = atRuleType);\n condition && (model.mediaText = condition);\n result.push(model);\n }\n }\n }\n\n return result;\n};\n\n/**\n * Parse CSS string and return the array of objects\n * @param {String} str CSS string\n * @return {Array} Array of objects for the definition of CSSRules\n */\nexport default str => {\n const el = document.createElement('style');\n el.innerHTML = str;\n\n // There is no .sheet before adding it to the \n document.head.appendChild(el);\n const sheet = el.sheet;\n document.head.removeChild(el);\n\n return parseNode(sheet);\n};\n","import { isString } from 'underscore';\nimport BrowserCssParser, {\n parseSelector,\n createNode\n} from './BrowserParserCss';\n\nexport default (config = {}) => ({\n /**\n * Parse CSS string to a desired model object\n * @param {String} str CSS string\n * @return {Array}\n */\n parse(str) {\n let result = [];\n const { parserCss, em } = config;\n const editor = em && em.get && em.get('Editor');\n const nodes = parserCss ? parserCss(str, editor) : BrowserCssParser(str);\n nodes.forEach(node => (result = result.concat(this.checkNode(node))));\n em && em.trigger('parse:css', { input: str, output: result });\n\n return result;\n },\n\n /**\n * Check the returned node from a custom parser and transforms it to\n * a valid object for the CSS composer\n * @return {[type]}\n */\n checkNode(node) {\n const { selectors, style } = node;\n\n if (isString(selectors)) {\n const nodes = [];\n const selsParsed = parseSelector(selectors);\n const classSets = selsParsed.result;\n const selectorsAdd = selsParsed.add.join(', ');\n const opts = {\n atRule: node.atRule,\n mediaText: node.params\n };\n\n if (classSets.length) {\n classSets.forEach(classSet => {\n nodes.push(createNode(classSet, style, opts));\n });\n } else {\n nodes.push(createNode([], style, opts));\n }\n\n if (selectorsAdd) {\n const lastNode = nodes[nodes.length - 1];\n lastNode.selectorsAdd = selectorsAdd;\n }\n\n node = nodes;\n }\n\n return node;\n }\n});\n","/**\n * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/parser/config/config.js)\n * ```js\n * const editor = grapesjs.init({\n * parser: {\n * // options\n * }\n * })\n * ```\n *\n * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance\n *\n * ```js\n * const { Parser } = editor;\n * ```\n * ## Available Events\n * * `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument\n * * `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument\n *\n * ## Methods\n * * [getConfig](#getconfig)\n * * [parseHtml](#parsehtml)\n * * [parseCss](#parsecss)\n *\n * @module Parser\n */\nimport defaults from './config/config';\nimport parserCss from './model/ParserCss';\nimport parserHtml from './model/ParserHtml';\n\nexport default () => {\n let conf = {};\n let pHtml, pCss;\n\n return {\n compTypes: '',\n\n parserCss: null,\n\n parserHtml: null,\n\n name: 'Parser',\n\n init(config = {}) {\n conf = { ...defaults, ...config };\n conf.Parser = this;\n pHtml = new parserHtml(conf);\n pCss = new parserCss(conf);\n this.em = conf.em;\n this.parserCss = pCss;\n this.parserHtml = pHtml;\n return this;\n },\n\n /**\n * Get the configuration object\n * @returns {Object} Configuration object\n * @example\n * console.log(Parser.getConfig())\n */\n getConfig() {\n return conf;\n },\n\n /**\n * Parse HTML string and return the object containing the Component Definition\n * @param {String} input HTML string to parse\n * @param {Object} [options] Options\n * @param {String} [options.htmlType] [HTML mime type](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02) to parse\n * @param {Boolean} [options.allowScripts=false] Allow `` : '';\n return html;\n }\n\n /**\n * Returns CSS built inside canvas\n * @param {Object} [opts={}] Options\n * @returns {string} CSS string\n * @private\n */\n getCss(opts = {}) {\n const config = this.config;\n const { optsCss } = config;\n const avoidProt = opts.avoidProtected;\n const keepUnusedStyles = !isUndefined(opts.keepUnusedStyles) ? opts.keepUnusedStyles : config.keepUnusedStyles;\n const cssc = this.get('CssComposer');\n const wrp = opts.component || this.get('DomComponents').getComponent();\n const protCss = !avoidProt ? config.protectedCss : '';\n const css =\n wrp &&\n this.get('CodeManager').getCode(wrp, 'css', {\n cssc,\n keepUnusedStyles,\n ...optsCss,\n ...opts,\n });\n return wrp ? (opts.json ? css : protCss + css) : '';\n }\n\n /**\n * Returns JS of all components\n * @return {string} JS string\n * @private\n */\n getJs(opts = {}) {\n var wrp = opts.component || this.get('DomComponents').getWrapper();\n return wrp ? this.get('CodeManager').getCode(wrp, 'js').trim() : '';\n }\n\n /**\n * Store data to the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n * @private\n */\n store(clb) {\n const sm = this.get('StorageManager');\n if (!sm) return;\n\n const store = this.storeData();\n sm.store(store, res => {\n clb && clb(res, store);\n this.set('changesCount', 0);\n this.trigger('storage:store', store);\n });\n\n return store;\n }\n\n storeData() {\n let result = {};\n // Sync content if there is an active RTE\n const editingCmp = this.getEditing();\n editingCmp && editingCmp.trigger('sync:content', { noCount: true });\n\n this.get('storables').forEach(m => {\n result = { ...result, ...m.store(1) };\n });\n return result;\n }\n\n /**\n * Load data from the current storage\n * @param {Function} clb Callback function\n * @private\n */\n load(clb = null) {\n this.getCacheLoad(1, res => {\n this.loadData(res);\n clb && clb(res);\n });\n }\n\n loadData(data = {}) {\n const sm = this.get('StorageManager');\n const result = sm.__clearKeys(data);\n\n this.get('storables').forEach(module => {\n module.load(result);\n module.postLoad && module.postLoad(this);\n });\n\n return result;\n }\n\n /**\n * Returns cached load\n * @param {Boolean} force Force to reload\n * @param {Function} clb Callback function\n * @return {Object}\n * @private\n */\n getCacheLoad(force, clb) {\n if (this.cacheLoad && !force) return this.cacheLoad;\n const sm = this.get('StorageManager');\n const load = [];\n\n if (!sm) return {};\n\n this.get('storables').forEach(m => {\n let key = m.storageKey;\n key = isFunction(key) ? key() : key;\n const keys = isArray(key) ? key : [key];\n keys.forEach(k => load.push(k));\n });\n\n sm.load(load, res => {\n this.cacheLoad = res;\n clb && clb(res);\n setTimeout(() => this.trigger('storage:load', res));\n });\n }\n\n /**\n * Returns device model by name\n * @return {Device|null}\n * @private\n */\n getDeviceModel() {\n var name = this.get('device');\n return this.get('DeviceManager').get(name);\n }\n\n /**\n * Run default command if setted\n * @param {Object} [opts={}] Options\n * @private\n */\n runDefault(opts = {}) {\n var command = this.get('Commands').get(this.config.defaultCommand);\n if (!command || this.defaultRunning) return;\n command.stop(this, this, opts);\n command.run(this, this, opts);\n this.defaultRunning = 1;\n }\n\n /**\n * Stop default command\n * @param {Object} [opts={}] Options\n * @private\n */\n stopDefault(opts = {}) {\n const commands = this.get('Commands');\n const command = commands.get(this.config.defaultCommand);\n if (!command || !this.defaultRunning) return;\n command.stop(this, this, opts);\n this.defaultRunning = 0;\n }\n\n /**\n * Update canvas dimensions and refresh data useful for tools positioning\n * @private\n */\n refreshCanvas(opts = {}) {\n this.set('canvasOffset', null);\n this.set('canvasOffset', this.get('Canvas').getOffset());\n opts.tools && this.trigger('canvas:updateTools');\n }\n\n /**\n * Clear all selected stuf inside the window, sometimes is useful to call before\n * doing some dragging opearation\n * @param {Window} win If not passed the current one will be used\n * @private\n */\n clearSelection(win) {\n var w = win || window;\n w.getSelection().removeAllRanges();\n }\n\n /**\n * Get the current media text\n * @return {string}\n */\n getCurrentMedia() {\n const config = this.config;\n const device = this.getDeviceModel();\n const condition = config.mediaCondition;\n const preview = config.devicePreviewMode;\n const width = device && device.get('widthMedia');\n return device && width && !preview ? `(${condition}: ${width})` : '';\n }\n\n /**\n * Return the component wrapper\n * @return {Component}\n */\n getWrapper() {\n return this.get('DomComponents').getWrapper();\n }\n\n setCurrentFrame(frameView) {\n return this.set('currentFrame', frameView);\n }\n\n getCurrentFrame() {\n return this.get('currentFrame');\n }\n\n getCurrentFrameModel() {\n return (this.getCurrentFrame() || {}).model;\n }\n\n getIcon(icon) {\n const icons = this.getConfig('icons') || {};\n return icons[icon] || '';\n }\n\n /**\n * Return the count of changes made to the content and not yet stored.\n * This count resets at any `store()`\n * @return {number}\n */\n getDirtyCount() {\n return this.get('changesCount');\n }\n\n getZoomDecimal() {\n return this.get('Canvas').getZoomDecimal();\n }\n\n getZoomMultiplier() {\n return this.get('Canvas').getZoomMultiplier();\n }\n\n setDragMode(value) {\n return this.set('dmode', value);\n }\n\n t(...args) {\n const i18n = this.get('I18n');\n return i18n?.t(...args);\n }\n\n /**\n * Returns true if the editor is in absolute mode\n * @returns {Boolean}\n */\n inAbsoluteMode() {\n return this.get('dmode') === 'absolute';\n }\n\n /**\n * Destroy editor\n */\n destroyAll() {\n const { config, view } = this;\n const editor = this.getEditor();\n const { editors = [] } = config.grapesjs || {};\n const shallow = this.get('shallow');\n shallow?.destroyAll();\n this.stopListening();\n this.stopDefault();\n this.get('modules')\n .slice()\n .reverse()\n .forEach(mod => mod.destroy());\n view && view.remove();\n this.clear({ silent: true });\n this.destroyed = 1;\n ['config', 'view', '_previousAttributes', '_events', '_listeners'].forEach(i => (this[i] = {}));\n editors.splice(editors.indexOf(editor), 1);\n hasWin() && $(config.el).empty().attr(this.attrsOrig);\n }\n\n getEditing() {\n const res = this.get('editing');\n return (res && res.model) || null;\n }\n\n setEditing(value) {\n this.set('editing', value);\n return this;\n }\n\n isEditing() {\n return !!this.get('editing');\n }\n\n log(msg, opts = {}) {\n const { ns, level = 'debug' } = opts;\n this.trigger('log', msg, opts);\n level && this.trigger(`log:${level}`, msg, opts);\n\n if (ns) {\n const logNs = `log-${ns}`;\n this.trigger(logNs, msg, opts);\n level && this.trigger(`${logNs}:${level}`, msg, opts);\n }\n }\n\n logInfo(msg, opts) {\n this.log(msg, { ...opts, level: 'info' });\n }\n\n logWarning(msg, opts) {\n this.log(msg, { ...opts, level: 'warning' });\n }\n\n logError(msg, opts) {\n this.log(msg, { ...opts, level: 'error' });\n }\n\n initBaseColorPicker(el, opts = {}) {\n const config = this.getConfig();\n const { colorPicker = {} } = config;\n const elToAppend = config.el;\n const ppfx = config.stylePrefix;\n\n return $(el).spectrum({\n containerClassName: `${ppfx}one-bg ${ppfx}two-color`,\n appendTo: elToAppend || 'body',\n maxSelectionSize: 8,\n showPalette: true,\n palette: [],\n showAlpha: true,\n chooseText: 'Ok',\n cancelText: '⨯',\n ...opts,\n ...colorPicker,\n });\n }\n\n /**\n * Execute actions without triggering the storage and undo manager.\n * @param {Function} clb\n * @private\n */\n skip(clb) {\n this.__skip = true;\n const um = this.get('UndoManager');\n um ? um.skip(clb) : clb();\n this.__skip = false;\n }\n\n /**\n * Set/get data from the HTMLElement\n * @param {HTMLElement} el\n * @param {string} name Data name\n * @param {any} value Date value\n * @return {any}\n * @private\n */\n data(el, name, value) {\n const varName = '_gjs-data';\n\n if (!el[varName]) {\n el[varName] = {};\n }\n\n if (isUndefined(value)) {\n return el[varName][name];\n } else {\n el[varName][name] = value;\n }\n }\n}\n","import { isObject, isString, each, isUndefined } from 'underscore';\n\nexport default ({ $ }) => {\n if ($ && $.prototype && $.prototype.constructor.name !== 'jQuery') {\n const fn = $.fn;\n\n // Additional helpers\n\n fn.hide = function() {\n return this.css('display', 'none');\n };\n\n fn.show = function() {\n return this.css('display', 'block');\n };\n\n fn.focus = function() {\n const el = this.get(0);\n el && el.focus();\n return this;\n };\n\n // For SVGs in IE\n // (fn.removeClass = function(c) {\n // if (!arguments.length) {\n // return this.attr('class', '');\n // }\n // const classes = isString(c) && c.match(/\\S+/g);\n // return classes\n // ? this.each(function(el) {\n // each(classes, function(c) {\n // if (el.classList) {\n // el.classList.remove(c);\n // } else {\n // const val = el.className;\n // const bval = el.className.baseVal;\n\n // if (!isUndefined(bval)) {\n // val.baseVal = bval.replace(c, '');\n // } else {\n // el.className = val.replace(c, '');\n // }\n // }\n // });\n // })\n // : this;\n // }),\n // (fn.remove = function() {\n // return this.each(node => {\n // return node.parentNode && node.parentNode.removeChild(node);\n // });\n // }),\n\n // For spectrum compatibility\n\n fn.bind = function(ev, h) {\n return this.on(ev, h);\n };\n\n fn.unbind = function(ev, h) {\n if (isObject(ev)) {\n for (let name in ev) {\n ev.hasOwnProperty(name) && this.off(name, ev[name]);\n }\n\n return this;\n } else {\n return this.off(ev, h);\n }\n };\n\n fn.click = function(h) {\n return h ? this.on('click', h) : this.trigger('click');\n };\n\n fn.change = function(h) {\n return h ? this.on('change', h) : this.trigger('change');\n };\n\n fn.keydown = function(h) {\n return h ? this.on('keydown', h) : this.trigger('keydown');\n };\n\n fn.delegate = function(selector, events, data, handler) {\n if (!handler) {\n handler = data;\n }\n\n return this.on(events, selector, function(e) {\n e.data = data;\n handler(e);\n });\n };\n\n fn.scrollLeft = function() {\n let el = this.get(0);\n el = el.nodeType == 9 ? el.defaultView : el;\n let win = el instanceof Window ? el : null;\n return win ? win.pageXOffset : el.scrollLeft || 0;\n };\n\n fn.scrollTop = function() {\n let el = this.get(0);\n el = el.nodeType == 9 ? el.defaultView : el;\n let win = el instanceof Window ? el : null;\n return win ? win.pageYOffset : el.scrollTop || 0;\n };\n\n const offset = $.prototype.offset;\n fn.offset = function(coords) {\n let top, left;\n\n if (coords) {\n top = coords.top;\n left = coords.left;\n }\n\n if (typeof top != 'undefined') {\n this.css('top', `${top}px`);\n }\n if (typeof left != 'undefined') {\n this.css('left', `${left}px`);\n }\n\n return offset.call(this);\n };\n\n $.map = function(items, clb) {\n const ar = [];\n\n for (var i = 0; i < items.length; i++) {\n ar.push(clb(items[i], i));\n }\n\n return ar;\n };\n\n const indexOf = Array.prototype.indexOf;\n\n $.inArray = function(val, arr, i) {\n return arr == null ? -1 : indexOf.call(arr, val, i);\n };\n\n $.Event = function(src, props) {\n if (!(this instanceof $.Event)) {\n return new $.Event(src, props);\n }\n\n this.type = src;\n this.isDefaultPrevented = () => false;\n };\n }\n};\n","import Backbone from 'backbone';\nimport { View } from 'common';\nimport { appendStyles } from 'utils/mixins';\n\nconst $ = Backbone.$;\n\nexport default class EditorView extends View {\n initialize() {\n const { model } = this;\n model.view = this;\n this.conf = model.config;\n this.pn = model.get('Panels');\n this.cv = model.get('Canvas');\n model.once('change:ready', () => {\n this.pn.active();\n this.pn.disableButtons();\n setTimeout(() => {\n model.trigger('load', model.get('Editor'));\n model.set('changesCount', 0);\n });\n });\n }\n\n render() {\n const { $el, conf, model } = this;\n const pfx = conf.stylePrefix;\n const contEl = $(conf.el || `body ${conf.container}`);\n appendStyles(conf.cssIcons, { unique: 1, prepand: 1 });\n $el.empty();\n\n if (conf.width) contEl.css('width', conf.width);\n if (conf.height) contEl.css('height', conf.height);\n\n $el.append(this.cv.render());\n $el.append(this.pn.render());\n\n // Load shallow editor\n const shallow = model.get('shallow');\n const shallowCanvasEl = shallow.get('Canvas').render();\n shallowCanvasEl.style.display = 'none';\n $el.append(shallowCanvasEl);\n\n $el.attr('class', `${pfx}editor ${pfx}one-bg ${pfx}two-color`);\n contEl.addClass(`${pfx}editor-cont`).empty().append($el);\n\n return this;\n }\n}\n","/**\n * Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins.\n * You get the Editor instance on init method and you can pass options via its [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/editor/config/config.js)\n *\n * ```js\n * const editor = grapesjs.init({\n * // options\n * });\n * ```\n *\n * ## Available Events\n *\n * You can make use of available events in this way\n * ```js\n * editor.on('EVENT-NAME', (some, argument) => {\n * // do something\n * })\n * ```\n *\n * * `update` - The structure of the template is updated (its HTML/CSS)\n * * `undo` - Undo executed\n * * `redo` - Redo executed\n * * `load` - Editor is loaded\n *\n * ### Components\n * Check the [Components](/api/components.html) module.\n * ### Keymaps\n * Check the [Keymaps](/api/keymaps.html) module.\n * ### Style Manager\n * Check the [Style Manager](/api/style_manager.html) module.\n * ### Storage\n * Check the [Storage](/api/storage_manager.html) module.\n * ### Canvas\n * Check the [Canvas](/api/canvas.html) module.\n * ### RTE\n * Check the [Rich Text Editor](/api/rich_text_editor.html) module.\n * ### Commands\n * Check the [Commands](/api/commands.html) module.\n * ### Selectors\n * Check the [Selectors](/api/selector_manager.html) module.\n * ### Blocks\n * Check the [Blocks](/api/block_manager.html) module.\n * ### Assets\n * Check the [Assets](/api/assets.html) module.\n * ### Modal\n * Check the [Modal](/api/modal_dialog.html) module.\n * ### Devices\n * Check the [Devices](/api/device_manager.html) module.\n * ### Parser\n * Check the [Parser](/api/parser.html) module.\n * ### Pages\n * Check the [Pages](/api/pages.html) module.\n *\n * ## Methods\n * @module Editor\n */\nimport defaults from './config/config';\nimport EditorModel from './model/Editor';\nimport EditorView from './view/EditorView';\nimport html from 'utils/html';\n\nexport default (config = {}, opts = {}) => {\n const { $ } = opts;\n let c = {\n ...defaults,\n ...config,\n };\n\n c.pStylePrefix = c.stylePrefix;\n let em = new EditorModel(c);\n let editorView;\n\n return {\n $,\n\n /**\n * @property {EditorModel}\n * @private\n */\n editor: em,\n\n modules: [],\n\n /**\n * Initialize editor model\n * @return {this}\n * @private\n */\n init(opts = {}) {\n em.init(this, { ...c, ...opts });\n\n this.modules = [\n 'I18n',\n 'Utils',\n 'Config',\n 'Commands',\n 'Keymaps',\n 'Modal',\n 'Panels',\n 'Canvas',\n 'Parser',\n 'CodeManager',\n 'UndoManager',\n 'RichTextEditor',\n ['Pages', 'PageManager'],\n 'DomComponents',\n ['Components', 'DomComponents'],\n 'LayerManager',\n ['Layers', 'LayerManager'],\n 'CssComposer',\n ['Css', 'CssComposer'],\n 'StorageManager',\n ['Storage', 'StorageManager'],\n 'AssetManager',\n ['Assets', 'AssetManager'],\n 'BlockManager',\n ['Blocks', 'BlockManager'],\n 'TraitManager',\n ['Traits', 'TraitManager'],\n 'SelectorManager',\n ['Selectors', 'SelectorManager'],\n 'StyleManager',\n ['Styles', 'StyleManager'],\n 'DeviceManager',\n ['Devices', 'DeviceManager'],\n ];\n\n this.modules.forEach(prop => {\n if (Array.isArray(prop)) {\n this[prop[0]] = em.get(prop[1]);\n } else {\n this[prop] = em.get(prop);\n }\n });\n\n // Do post render stuff after the iframe is loaded otherwise it'll\n // be empty during tests\n em.once('change:ready', () => {\n this.UndoManager.clear();\n em.get('modules').forEach(module => {\n module.postRender && module.postRender(editorView);\n });\n });\n\n return this;\n },\n\n /**\n * Returns configuration object\n * @param {string} [prop] Property name\n * @returns {any} Returns the configuration object or\n * the value of the specified property\n */\n getConfig(prop) {\n return em.getConfig(prop);\n },\n\n /**\n * Returns HTML built inside canvas\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Return the HTML of a specific Component\n * @param {Boolean} [opts.cleanId=false] Remove unnecessary IDs (eg. those created automatically)\n * @returns {string} HTML string\n */\n getHtml(opts) {\n return em.getHtml(opts);\n },\n\n /**\n * Returns CSS built inside canvas\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Return the CSS of a specific Component\n * @param {Boolean} [opts.json=false] Return an array of CssRules instead of the CSS string\n * @param {Boolean} [opts.avoidProtected=false] Don't include protected CSS\n * @param {Boolean} [opts.onlyMatched=false] Return only rules matched by the passed component.\n * @param {Boolean} [opts.keepUnusedStyles=false] Force keep all defined rules. Toggle on in case output looks different inside/outside of the editor.\n * @returns {String|Array} CSS string or array of CssRules\n */\n getCss(opts) {\n return em.getCss(opts);\n },\n\n /**\n * Returns JS of all components\n * @param {Object} [opts={}] Options\n * @param {Component} [opts.component] Get the JS of a specific component\n * @returns {String} JS string\n */\n getJs(opts) {\n return em.getJs(opts);\n },\n\n /**\n * Return the complete tree of components. Use `getWrapper` to include also the wrapper\n * @return {Components}\n */\n getComponents() {\n return em.get('DomComponents').getComponents();\n },\n\n /**\n * Return the wrapper and its all components\n * @return {Component}\n */\n getWrapper() {\n return em.get('DomComponents').getWrapper();\n },\n\n /**\n * Set components inside editor's canvas. This method overrides actual components\n * @param {Array|Object|string} components HTML string or components model\n * @param {Object} opt the options object to be used by the [setComponents]{@link em#setComponents} method\n * @return {this}\n * @example\n * editor.setComponents('
New component
');\n * // or\n * editor.setComponents({\n * type: 'text',\n * classes:['cls'],\n * content: 'New component'\n * });\n */\n setComponents(components, opt = {}) {\n em.setComponents(components, opt);\n return this;\n },\n\n /**\n * Add components\n * @param {Array|Object|string} components HTML string or components model\n * @param {Object} opts Options\n * @param {Boolean} [opts.avoidUpdateStyle=false] If the HTML string contains styles,\n * by default, they will be created and, if already exist, updated. When this option\n * is true, styles already created will not be updated.\n * @return {Array}\n * @example\n * editor.addComponents('
New component
');\n * // or\n * editor.addComponents({\n * type: 'text',\n * classes:['cls'],\n * content: 'New component'\n * });\n */\n addComponents(components, opts) {\n return this.getWrapper().append(components, opts);\n },\n\n /**\n * Returns style in JSON format object\n * @return {Object}\n */\n getStyle() {\n return em.get('CssComposer').getAll();\n },\n\n /**\n * Set style inside editor's canvas. This method overrides actual style\n * @param {Array|Object|string} style CSS string or style model\n * @return {this}\n * @example\n * editor.setStyle('.cls{color: red}');\n * //or\n * editor.setStyle({\n * selectors: ['cls'],\n * style: { color: 'red' }\n * });\n */\n setStyle(style, opt = {}) {\n em.setStyle(style, opt);\n return this;\n },\n\n /**\n * Add styles to the editor\n * @param {Array|Object|string} style CSS string or style model\n * @returns {Array} Array of created CssRule instances\n * @example\n * editor.addStyle('.cls{color: red}');\n */\n addStyle(style, opts = {}) {\n return em.addStyle(style, opts);\n },\n\n /**\n * Returns the last selected component, if there is one\n * @return {Model}\n */\n getSelected() {\n return em.getSelected();\n },\n\n /**\n * Returns an array of all selected components\n * @return {Array}\n */\n getSelectedAll() {\n return em.getSelectedAll();\n },\n\n /**\n * Get a stylable entity from the selected component.\n * If you select a component without classes the entity is the Component\n * itself and all changes will go inside its 'style' attribute. Otherwise,\n * if the selected component has one or more classes, the function will\n * return the corresponding CSS Rule\n * @return {Model}\n */\n getSelectedToStyle() {\n let selected = em.getSelected();\n\n if (selected) {\n return this.StyleManager.getModelToStyle(selected);\n }\n },\n\n /**\n * Select a component\n * @param {Component|HTMLElement} el Component to select\n * @param {Object} [opts] Options\n * @param {Boolean} [opts.scroll] Scroll canvas to the selected element\n * @return {this}\n * @example\n * // Select dropped block\n * editor.on('block:drag:stop', function(model) {\n * editor.select(model);\n * });\n */\n select(el, opts) {\n em.setSelected(el, opts);\n return this;\n },\n\n /**\n * Add component to selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectAdd(model);\n */\n selectAdd(el) {\n em.addSelected(el);\n return this;\n },\n\n /**\n * Remove component from selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectRemove(model);\n */\n selectRemove(el) {\n em.removeSelected(el);\n return this;\n },\n\n /**\n * Toggle component selection\n * @param {Component|HTMLElement|Array} el Component to select\n * @return {this}\n * @example\n * editor.selectToggle(model);\n */\n selectToggle(el) {\n em.toggleSelected(el);\n return this;\n },\n\n /**\n * Returns, if active, the Component enabled in rich text editing mode.\n * @returns {Component|null}\n * @example\n * const textComp = editor.getEditing();\n * if (textComp) {\n * console.log('HTML: ', textComp.toHTML());\n * }\n */\n getEditing() {\n return em.getEditing();\n },\n\n /**\n * Set device to the editor. If the device exists it will\n * change the canvas to the proper width\n * @param {string} name Name of the device\n * @return {this}\n * @example\n * editor.setDevice('Tablet');\n */\n setDevice(name) {\n em.set('device', name);\n return this;\n },\n\n /**\n * Return the actual active device\n * @return {string} Device name\n * @example\n * var device = editor.getDevice();\n * console.log(device);\n * // 'Tablet'\n */\n getDevice() {\n return em.get('device');\n },\n\n /**\n * Execute command\n * @param {string} id Command ID\n * @param {Object} options Custom options\n * @return {*} The return is defined by the command\n * @example\n * editor.runCommand('myCommand', {someValue: 1});\n */\n runCommand(id, options = {}) {\n return em.get('Commands').run(id, options);\n },\n\n /**\n * Stop the command if stop method was provided\n * @param {string} id Command ID\n * @param {Object} options Custom options\n * @return {*} The return is defined by the command\n * @example\n * editor.stopCommand('myCommand', {someValue: 1});\n */\n stopCommand(id, options = {}) {\n return em.get('Commands').stop(id, options);\n },\n\n /**\n * Store data to the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n */\n store(clb) {\n return em.store(clb);\n },\n\n /**\n * Get the JSON project data, which could be stored and loaded back with `editor.loadProject(json)`\n * @returns {Object}\n * @example\n * console.log(editor.getProject());\n * // { pages: [...], styles: [...], ... }\n */\n getProject() {\n return em.storeData();\n },\n\n storeData() {\n return em.storeData();\n },\n\n /**\n * Load data from the current storage\n * @param {Function} clb Callback function\n * @return {Object} Stored data\n */\n load(clb) {\n return em.load(clb);\n },\n\n /**\n * Load data from the JSON project\n * @param {Object} data Project to load\n * @example\n * editor.loadProject({ pages: [...], styles: [...], ... })\n */\n loadProject(data) {\n return em.loadData(data);\n },\n\n loadData(data) {\n return em.loadData(data);\n },\n\n /**\n * Returns container element. The one which was indicated as 'container'\n * on init method\n * @return {HTMLElement}\n */\n getContainer() {\n return c.el;\n },\n\n /**\n * Return the count of changes made to the content and not yet stored.\n * This count resets at any `store()`\n * @return {number}\n */\n getDirtyCount() {\n return em.getDirtyCount();\n },\n\n /**\n * Update editor dimension offsets\n *\n * This method could be useful when you update, for example, some position\n * of the editor element (eg. canvas, panels, etc.) with CSS, where without\n * refresh you'll get misleading position of tools\n * @param {Object} [options] Options\n * @param {Boolean} [options.tools=false] Update the position of tools (eg. rich text editor, component highlighter, etc.)\n */\n refresh(opts) {\n em.refreshCanvas(opts);\n },\n\n /**\n * Replace the built-in Rich Text Editor with a custom one.\n * @param {Object} obj Custom RTE Interface\n * @example\n * editor.setCustomRte({\n * // Function for enabling custom RTE\n * // el is the HTMLElement of the double clicked Text Component\n * // rte is the same instance you have returned the first time you call\n * // enable(). This is useful if need to check if the RTE is already enabled so\n * // ion this case you'll need to return the RTE and the end of the function\n * enable: function(el, rte) {\n * rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API\n * ...\n * return rte; // return the RTE instance\n * },\n *\n * // Disable the editor, called for example when you unfocus the Text Component\n * disable: function(el, rte) {\n * rte.blur(); // this depends on the Custom RTE API\n * }\n *\n * // Called when the Text Component is focused again. If you returned the RTE instance\n * // from the enable function, the enable won't be called again instead will call focus,\n * // in this case to avoid double binding of the editor\n * focus: function (el, rte) {\n * rte.focus(); // this depends on the Custom RTE API\n * }\n * });\n */\n setCustomRte(obj) {\n this.RichTextEditor.customRte = obj;\n },\n\n /**\n * Replace the default CSS parser with a custom one.\n * The parser function receives a CSS string as a parameter and expects\n * an array of CSSRule objects as a result. If you need to remove the\n * custom parser, pass `null` as the argument\n * @param {Function|null} parser Parser function\n * @return {this}\n * @example\n * editor.setCustomParserCss(css => {\n * const result = [];\n * // ... parse the CSS string\n * result.push({\n * selectors: '.someclass, div .otherclass',\n * style: { color: 'red' }\n * })\n * // ...\n * return result;\n * });\n */\n setCustomParserCss(parser) {\n this.Parser.getConfig().parserCss = parser;\n return this;\n },\n\n /**\n * Change the global drag mode of components.\n * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936\n * @param {String} value Drag mode, options: 'absolute' | 'translate'\n * @returns {this}\n */\n setDragMode(value) {\n em.setDragMode(value);\n return this;\n },\n\n /**\n * Trigger event log message\n * @param {*} msg Message to log\n * @param {Object} [opts={}] Custom options\n * @param {String} [opts.ns=''] Namespace of the log (eg. to use in plugins)\n * @param {String} [opts.level='debug'] Level of the log, `debug`, `info`, `warning`, `error`\n * @return {this}\n * @example\n * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' });\n * // This will trigger following events\n * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info`\n * // Callbacks of those events will always receive the message and\n * // options, as arguments, eg:\n * // editor.on('log:info', (msg, opts) => console.info(msg, opts))\n */\n log(msg, opts = {}) {\n em.log(msg, opts);\n return this;\n },\n\n /**\n * Translate label\n * @param {String} key Label to translate\n * @param {Object} [opts] Options for the translation\n * @param {Object} [opts.params] Params for the translation\n * @param {Boolean} [opts.noWarn] Avoid warnings in case of missing resources\n * @returns {String}\n * @example\n * editor.t('msg');\n * // use params\n * editor.t('msg2', { params: { test: 'hello' } });\n * // custom local\n * editor.t('msg2', { params: { test: 'hello' }, l: 'it' });\n */\n t(...args) {\n return em.t(...args);\n },\n\n /**\n * Attach event\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n on(event, callback) {\n em.on(event, callback);\n return this;\n },\n\n /**\n * Attach event and detach it after the first run\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n once(event, callback) {\n em.once(event, callback);\n return this;\n },\n\n /**\n * Detach event\n * @param {string} event Event name\n * @param {Function} callback Callback function\n * @return {this}\n */\n off(event, callback) {\n em.off(event, callback);\n return this;\n },\n\n /**\n * Trigger event\n * @param {string} event Event to trigger\n * @return {this}\n */\n trigger(event) {\n em.trigger.apply(em, arguments);\n return this;\n },\n\n /**\n * Destroy the editor\n */\n destroy() {\n if (!em) return;\n em.destroyAll();\n this.modules.forEach(prop => {\n if (Array.isArray(prop)) {\n this[prop[0]] = 0;\n } else {\n this[prop] = 0;\n }\n });\n this.modules = 0;\n editorView = 0;\n em = 0;\n c = 0;\n },\n\n /**\n * Returns editor element\n * @return {HTMLElement}\n * @private\n */\n getEl() {\n return editorView && editorView.el;\n },\n\n /**\n * Returns editor model\n * @return {Model}\n * @private\n */\n getModel() {\n return em;\n },\n\n /**\n * Render editor\n * @return {HTMLElement}\n */\n render() {\n editorView && editorView.remove();\n editorView = new EditorView({\n model: em,\n config: c,\n });\n return editorView.render().el;\n },\n\n /**\n * Trigger a callback once the editor is loaded and rendered.\n * The callback will be executed immediately if the method is called on the already rendered editor.\n * @param {Function} clb Callback to trigger\n * @example\n * editor.onReady(() => {\n * // perform actions\n * });\n */\n onReady(clb) {\n em.get('ready') ? clb(this) : em.on('load', clb);\n },\n\n /**\n * Print safe HTML by using ES6 tagged template strings.\n * @param {Array} literals\n * @param {Array} substs\n * @returns {String}\n * @example\n * const unsafeStr = '';\n * const safeStr = 'Hello';\n * // Use `$${var}` to avoid escaping\n * const strHtml = editor.html`Escaped ${unsafeStr}, unescaped $${safeStr}`;\n */\n html,\n };\n};\n","export default {\n plugins: []\n};\n","/**\n * File made for IE/Edge support\n * https://github.com/artf/grapesjs/issues/214\n */\nimport { hasWin } from './mixins';\n\nexport default () => {\n /**\n * Check if IE/Edge\n * @return {Boolean}\n */\n const isIE = () => {\n let match;\n const agent = window.navigator.userAgent;\n const rules = [\n ['edge', /Edge\\/([0-9\\._]+)/],\n ['ie', /MSIE\\s(7\\.0)/],\n ['ie', /MSIE\\s([0-9\\.]+);.*Trident\\/[4-7].0/],\n ['ie', /Trident\\/7\\.0.*rv\\:([0-9\\.]+).*\\).*Gecko$/]\n ];\n\n for (let i = 0; i < rules.length; i++) {\n const rule = rules[i];\n match = rule[1].exec(agent);\n if (match) break;\n }\n\n return !!match;\n };\n\n if (hasWin() && isIE()) {\n const originalCreateHTMLDocument =\n DOMImplementation.prototype.createHTMLDocument;\n DOMImplementation.prototype.createHTMLDocument = title => {\n if (!title) title = '';\n return originalCreateHTMLDocument.apply(document.implementation, [title]);\n };\n }\n};\n","import { isElement, isFunction } from 'underscore';\nimport $ from 'utils/cash-dom';\nimport Editor from './editor';\nimport polyfills from 'utils/polyfills';\nimport { getGlobal } from 'utils/mixins';\nimport PluginManager from './plugin_manager';\n\npolyfills();\n\nconst plugins = new PluginManager();\nconst editors = [];\nconst defaultConfig = {\n // If true renders editor on init\n autorender: 1,\n\n // Array of plugins to init\n plugins: [],\n\n // Custom options for plugins\n pluginsOpts: {}\n};\n\nexport default {\n $,\n\n editors,\n\n plugins,\n\n // Will be replaced on build\n version: __GJS_VERSION__,\n\n /**\n * Initialize the editor with passed options\n * @param {Object} config Configuration object\n * @param {string|HTMLElement} config.container Selector which indicates where render the editor\n * @param {Boolean} [config.autorender=true] If true, auto-render the content\n * @param {Array} [config.plugins=[]] Array of plugins to execute on start\n * @param {Object} [config.pluginsOpts={}] Custom options for plugins\n * @param {Boolean} [config.headless=false] Init headless editor\n * @return {Editor} Editor instance\n * @example\n * var editor = grapesjs.init({\n * container: '#myeditor',\n * components: '
Hello world
',\n * style: '.hello{color: red}',\n * })\n */\n init(config = {}) {\n const { headless } = config;\n const els = config.container;\n if (!els && !headless) throw new Error(\"'container' is required\");\n config = { ...defaultConfig, ...config, grapesjs: this };\n config.el =\n !headless && (isElement(els) ? els : document.querySelector(els));\n const editor = new Editor(config, { $ }).init();\n const em = editor.getModel();\n\n // Load plugins\n config.plugins.forEach(pluginId => {\n let plugin = isFunction(pluginId) ? pluginId : plugins.get(pluginId);\n const plgOptions = config.pluginsOpts[pluginId] || {};\n\n // Try to search in global context\n if (!plugin) {\n const wplg = getGlobal()[pluginId];\n plugin = wplg?.default || wplg;\n }\n\n if (plugin) {\n plugin(editor, plgOptions);\n } else if (isFunction(pluginId)) {\n pluginId(editor, plgOptions);\n } else {\n em.logWarning(`Plugin ${pluginId} not found`, {\n context: 'plugins',\n plugin: pluginId\n });\n }\n });\n\n // Execute `onLoad` on modules once all plugins are initialized.\n // A plugin might have extended/added some custom type so this\n // is a good point to load stuff like components, css rules, etc.\n em.loadOnStart();\n config.autorender && !headless && editor.render();\n editors.push(editor);\n\n return editor;\n }\n};\n","import defaults from './config/config';\n\nexport default config => {\n var c = config || {};\n\n // Set default options\n for (var name in defaults) {\n if (!(name in c)) c[name] = defaults[name];\n }\n\n var plugins = {};\n\n return {\n /**\n * Add new plugin. Plugins could not be overwritten\n * @param {string} id Plugin ID\n * @param {Function} plugin Function which contains all plugin logic\n * @return {Function} The plugin function\n * @example\n * PluginManager.add('some-plugin', function(editor){\n * editor.Commands.add('new-command', {\n * run: function(editor, senderBtn){\n * console.log('Executed new-command');\n * }\n * })\n * });\n */\n add(id, plugin) {\n if (plugins[id]) {\n return plugins[id];\n }\n\n plugins[id] = plugin;\n return plugin;\n },\n\n /**\n * Returns plugin by ID\n * @param {string} id Plugin ID\n * @return {Function|undefined} Plugin\n * @example\n * var plugin = PluginManager.get('some-plugin');\n * plugin(editor);\n */\n get(id) {\n return plugins[id];\n },\n\n /**\n * Returns object with all plugins\n * @return {Object}\n */\n getAll() {\n return plugins;\n }\n };\n};\n"],"names":["root","factory","exports","module","define","amd","globalThis","window","this","_","Backbone","core_slice","Array","prototype","slice","apply","fn","ctx","args","length","call","arr","index","hasKeys","obj","keys","isArray","arguments","all","key","getMagicFusionIndex","callstackWasIndexed","magicFusionIndex","indexCycle","defer","ObjectRegistry","registeredObjects","cidIndexes","onoff","which","objects","i","l","objectRegistry","register","unregister","isFunction","actionUndoRedo","action","type","undoTypes","object","before","after","options","managerUndoRedo","manager","stack","magic","everything","isCurrentlyUndoRedoing","pointer","actions","isUndo","clone","models","at","where","get","pop","shift","trigger","validateUndoActionCreation","undoTypesType","condition","addToStack","track","res","diff","add","maximumStackLength","isRegistered","cid","contains","push","splice","indexOf","map","concat","UndoTypes","collection","ignore","model","remove","undefined","isEmpty","each","unset","set","unsetData","afterAttributes","changedAttributes","keysAfter","previousAttributes","pick","keysPrevious","val","reset","previousModels","OwnedUndoTypes","manipulateUndoType","manipType","undoType","fns","undoTypesInstance","isObject","extend","Action","Model","defaults","undo","attributes","redo","UndoStack","Collection","Infinity","setMaxLength","UndoManager","initialize","attr","on","value","startTracking","isArguments","stopTracking","isTracking","_addToStack","unregisterAll","undoAll","redoAll","isAvailable","s","merge","undoManager","addUndoType","changeUndoType","removeUndoType","clear","defaultAttributes","self","g","global","$","previousBackbone","VERSION","noConflict","emulateHTTP","emulateJSON","addMethod","method","attribute","iteratee","context","cb","defaultVal","unshift","addUnderscoreMethods","Class","methods","instance","_isModel","modelMatcher","isString","attrs","matcher","matches","Events","eventSplitter","eventsApi","events","name","callback","opts","names","test","split","internalOn","listening","_events","onApi","_listeners","id","listenTo","_listenId","uniqueId","listeningTo","_listeningTo","thisId","objId","count","handlers","off","offApi","listeners","stopListening","ids","remaining","j","handler","_callback","once","onceMap","bind","listenToOnce","offer","Math","max","triggerApi","objEvents","allEvents","triggerEvents","ev","a1","a2","a3","unbind","cidPrefix","parse","result","changed","validationError","idAttribute","toJSON","sync","escape","has","_validate","silent","changes","changing","_changing","_previousAttributes","current","prev","isEqual","_pending","hasChanged","old","size","previous","fetch","success","resp","serverAttrs","wrapError","save","wait","validate","isNew","patch","xhr","destroy","url","base","urlError","replace","encodeURIComponent","constructor","isValid","error","values","pairs","invert","omit","chain","comparator","_reset","setOptions","addOptions","array","insert","min","tail","singular","removed","_removeModels","added","merged","toAdd","toMerge","toRemove","modelMap","sort","sortable","sortAttr","existing","_prepareModel","_addReference","orderChanged","some","m","_removeReference","_byId","modelId","first","findWhere","Error","sortBy","pluck","create","callbackOpts","_onModelEvent","event","prevId","forEach","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","any","include","includes","invoke","toArray","head","take","initial","rest","drop","last","without","difference","shuffle","lastIndexOf","sample","partition","groupBy","countBy","indexBy","findIndex","findLastIndex","View","viewOptions","_ensureElement","delegateEventSplitter","tagName","selector","$el","render","_removeElement","setElement","element","undelegateEvents","_setElement","delegateEvents","el","match","delegate","eventName","listener","undelegate","_createElement","document","createElement","className","_setAttributes","methodMap","params","dataType","data","contentType","JSON","stringify","_method","beforeSend","setRequestHeader","processData","textStatus","errorThrown","ajax","Router","routes","_bindRoutes","optionalParam","namedParam","splatParam","escapeRegExp","route","isRegExp","_routeToRegExp","router","history","fragment","_extractParameters","execute","navigate","optional","RegExp","exec","param","decodeURIComponent","History","checkUrl","location","routeStripper","rootStripper","pathStripper","started","interval","atRoot","pathname","getSearch","matchRoot","decodeFragment","decodeURI","href","getHash","getPath","path","charAt","getFragment","_usePushState","_wantsHashChange","start","hashChange","_hasHashChange","documentMode","_useHashChange","_wantsPushState","pushState","_hasPushState","rootPath","iframe","src","style","display","tabIndex","body","iWindow","insertBefore","firstChild","contentWindow","open","close","hash","addEventListener","attachEvent","_checkUrlInterval","setInterval","loadUrl","stop","removeEventListener","detachEvent","removeChild","clearInterval","e","title","assign","_updateHash","protoProps","staticProps","child","parent","__super__","CodeMirror","extendMode","commentStart","commentEnd","newlineAfterToken","_type","content","textAfter","state","jsonMode","lexical","inlineElements","inline","configuration","defineExtension","isComment","from","to","cm","curMode","innerMode","getMode","getTokenAt","mode","operation","replaceRange","line","ch","setCursor","selText","getRange","startIndex","endIndex","substr","substring","cmInstance","indentLine","outer","text","copyState","tabSize","getOption","out","lines","atSol","newline","stream","StringStream","eol","inner","token","cur","pos","string","blankLine","end","setSelection","getCursor","mod","userAgent","navigator","platform","gecko","ie_upto10","ie_11up","edge","ie","ie_version","webkit","qtwebkit","chrome","presto","safari","vendor","mac_geMountainLion","phantom","ios","maxTouchPoints","android","mobile","mac","chromeOS","windows","presto_version","Number","flipCtrlCmd","captureRightClick","classTest","cls","range","rmClass","node","removeChildren","childNodes","removeChildrenAndAdd","appendChild","elt","tag","cssText","createTextNode","eltP","setAttribute","nodeType","parentNode","host","activeElt","activeElement","shadowRoot","addClass","joinClasses","a","b","as","createRange","endNode","r","setEnd","setStart","createTextRange","moveToElementText","collapse","moveEnd","moveStart","selectInput","f","copyObj","target","overwrite","prop","hasOwnProperty","countColumn","startValue","search","n","nextTab","selectionStart","selectionEnd","_e","Delayed","time","onTimeout","Date","setTimeout","ms","clearTimeout","scrollerGap","Pass","toString","sel_dontScroll","scroll","sel_mouse","origin","sel_move","findColumn","goal","col","skipped","spaceStrs","spaceStr","lst","insertSorted","score","priority","nothing","createObj","props","inst","Object","nonASCIISingleCaseWordChar","isWordCharBasic","toUpperCase","toLowerCase","isWordChar","helper","source","extendingChars","isExtendingChar","charCodeAt","skipExtendingChars","str","dir","findFirst","pred","midF","mid","ceil","floor","iterateBidiSections","order","found","part","level","bidiOther","getBidiPartAt","sticky","bidiOrdering","lowTypes","arabicTypes","charType","code","bidiRE","isNeutral","isStrong","countsAsLeft","countsAsNum","BidiSpan","direction","outerType","len","types","i$1","i$2","type$1","i$3","prev$1","type$2","i$4","type$3","i$5","cur$1","type$4","i$6","end$1","replace$1","j$1","i$7","isRTL","j$2","nstart","reverse","getOrder","noHandlers","emitter","_handlers","getHandlers","signal","signalDOMEvent","override","preventDefault","defaultPrevented","e_defaultPrevented","codemirrorIgnore","signalCursorActivity","cursorActivity","curOp","cursorActivityHandlers","hasHandler","eventMixin","ctor","e_preventDefault","returnValue","e_stopPropagation","stopPropagation","cancelBubble","e_stop","e_target","srcElement","e_button","button","ctrlKey","zwspSupported","badBidiRects","dragAndDrop","div","zeroWidthElement","measure","offsetHeight","offsetWidth","hasBadBidiRects","txt","r0","getBoundingClientRect","r1","left","right","splitLinesAuto","nl","rt","hasSelection","getSelection","te","ownerDocument","selection","parentElement","compareEndPoints","hasCopyEvent","oncopy","badZoomedRects","hasBadZoomedRects","normal","fromRange","abs","modes","mimeModes","defineMode","dependencies","defineMIME","mime","spec","resolveMode","mfactory","modeObj","modeExtensions","exts","helperType","modeProps","prop$1","properties","nstate","info","startState","lineOracle","lastColumnPos","lastColumnValue","lineStart","getLine","doc","chunk","children","sz","chunkSize","getBetween","iter","getLines","updateLineHeight","height","lineNo","no","lineAtHeight","h","lh","isLine","lineNumberFor","String","lineNumberFormatter","firstLineNumber","Pos","cmp","equalCursorPos","copyPos","x","maxPos","minPos","clipLine","clipPos","clipToLen","linelen","clipPosArray","sol","peek","next","eat","eatWhile","eatSpace","skipToEnd","skipTo","backUp","column","indentation","pattern","consume","caseInsensitive","cased","hideFirstChars","lookAhead","oracle","baseToken","SavedContext","Context","maxLookAhead","baseTokens","baseTokenPos","highlightLine","forceToEnd","st","modeGen","lineClasses","runMode","loop","o","overlay","overlays","i_end","opaque","styles","classes","bgClass","textClass","getLineStyles","updateFrontier","getContextBefore","resetState","maxHighlightLength","stateAfter","styleClasses","highlightFrontier","modeFrontier","precise","findStartLine","saved","fromSaved","processLine","viewFrom","viewTo","nextLine","startAt","callBlankLine","readToken","copy","Token","takeToken","asArray","tokens","extractLineClasses","output","lineClass","flattenSpans","curStart","curStyle","addModeClass","mName","minindent","minline","lim","indented","retreatFrontier","sawReadOnlySpans","sawCollapsedSpans","seeReadOnlySpans","seeCollapsedSpans","MarkedSpan","marker","getMarkedSpanFor","spans","span","removeMarkedSpan","addMarkedSpan","op","inThisOp","WeakSet","markedSpans","attachLine","markedSpansBefore","startCh","isInsert","nw","inclusiveLeft","insertLeft","endsAfter","inclusiveRight","markedSpansAfter","endCh","startsBefore","stretchSpansOverChange","change","full","oldFirst","oldLast","sameLine","offset","span$1","clearEmptySpans","newMarkers","gapMarkers","gap","clearWhenEmpty","removeReadOnlyRanges","markers","mark","readOnly","parts","mk","p","newParts","dfrom","dto","detachMarkedSpans","detachLine","attachMarkedSpans","extraLeft","extraRight","compareCollapsedMarkers","lenDiff","aPos","bPos","fromCmp","toCmp","collapsedSpanAtSide","sps","sp","collapsed","collapsedSpanAtStart","collapsedSpanAtEnd","collapsedSpanAround","conflictingCollapsedRange","visualLine","visualLineEnd","visualLineContinued","visualLineNo","lineN","vis","visualLineEndNo","lastLine","lineIsHidden","widgetNode","lineIsHiddenInner","heightAtLine","lineObj","lineLength","found$1","findMaxLine","d","maxLine","maxLineLength","maxLineChanged","Line","estimateHeight","updateLine","estHeight","cleanUpLine","styleToClassCache","styleToClassCacheWithMode","interpretTokenStyle","cache","buildLineContent","lineView","builder","pre","trailingSpace","splitSpaces","addToken","buildToken","buildTokenBadBidi","insertLineContent","externalMeasured","maps","caches","lastChild","querySelector","defaultSpecialCharPlaceholder","startStyle","endStyle","css","displayText","special","specialChars","mustWrap","createDocumentFragment","lastIndex","txt$1","tabWidth","specialCharPlaceholder","fullStyle","trailingBefore","spaceBefore","buildCollapsedSpan","ignoreWidget","widget","input","needsContentAttribute","setUneditable","allText","spanStyle","spanEndStyle","spanStartStyle","nextChange","foundBookmarks","endStyles","upto","tokenText","LineView","hidden","buildViewArray","nextPos","view","operationGroup","pushOperation","ops","ownsGroup","delayedCallbacks","fireCallbacksForOps","group","callbacks","cursorActivityCalled","finishOperation","endCb","orphanDelayedCallbacks","signalLater","list","fireOrphanDelayed","delayed","updateLineForChanges","dims","updateLineText","updateLineGutter","updateLineClasses","updateLineWidgets","ensureLineWrapped","replaceChild","zIndex","updateLineBackground","background","wrap","getLineContent","ext","built","wrapClass","gutter","gutterBackground","gutterClass","fixedGutter","fixedPos","gutterTotalWidth","gutterMarkers","lineNumbers","wrap$1","gutterWrap","lineNumber","gutterLeft","k","gutterSpecs","gutterWidth","alignable","isWidget","nextSibling","insertLineWidgets","buildLineElement","insertLineWidgetsFor","allowAbove","widgets","ws","handleMouseEvents","positionLineWidget","above","noHScroll","width","wrapperWidth","coverGutter","paddingLeft","position","marginLeft","widgetHeight","parentStyle","gutters","wrapper","clientWidth","eventInWidget","getAttribute","sizer","mover","paddingTop","lineSpace","offsetTop","paddingVert","paddingH","cachedPaddingH","getComputedStyle","currentStyle","parseInt","paddingRight","isNaN","scrollGap","nativeBarWidth","displayWidth","scroller","barWidth","displayHeight","clientHeight","barHeight","ensureLineHeights","rect","wrapping","lineWrapping","curWidth","heights","rects","getClientRects","bottom","top","mapFromLineView","updateExternalMeasurement","lineMeasure","measureChar","bias","measureCharPrepared","prepareMeasureForLine","findViewForLine","findViewIndex","getDimensions","forceUpdate","hasHeights","prepared","varHeight","measureCharInner","bogus","rtop","rbottom","measureText","nullRect","nodeAndOffsetInLineMap","mStart","mEnd","coverStart","coverEnd","getUsefulRect","place","maybeUpdateRectForZooming","rSpan","charWidth","rbot","bot","singleCursorHeightPerLine","screen","logicalXDPI","deviceXDPI","scaleX","scaleY","logicalYDPI","deviceYDPI","clearLineMeasurementCacheFor","clearLineMeasurementCache","externalMeasure","clearCaches","cachedCharWidth","cachedTextHeight","lineNumChars","pageScrollX","pageXOffset","documentElement","scrollLeft","pageScrollY","marginTop","pageYOffset","scrollTop","widgetTopHeight","intoCoordSystem","includeWidgets","yOff","viewOffset","lOff","xOff","fromCoordSystem","coords","localBox","lineSpaceBox","charCoords","cursorCoords","preparedMeasure","getBidi","partPos","other","estimateCoords","PosWithInfo","outside","xRel","coordsChar","y","coordsCharInner","rangeEnd","wrappedLineExtent","begin","wrappedLineExtentChar","boxIsAfter","box","ltr","coordsBidiPartWrapped","coordsBidiPart","baseX","chAround","boxAround","atLeft","atStart","_lineNo","ref","closestDist","endX","dist","textHeight","anchor","clientLeft","offsetLeft","compensateForHScroll","th","perLine","widgetsHeight","estimateLineHeights","est","posFromMouse","liberal","forRect","space","clientX","clientY","e$1","colDiff","round","regChange","lendiff","updateLineNumbers","viewChanged","resetView","cut","viewCuttingPoint","cut$1","cutTop","cutBot","regLineChange","oldN","newN","adjustView","countDirtyView","dirty","updateSelection","showSelection","prepareSelection","primary","curFragment","cursors","selFragment","sel","ranges","primIndex","empty","showCursorWhenSelecting","drawSelectionCursor","drawSelectionRange","cursor","cursorHeight","getWrapperElement","charPos","otherCursor","cmpCoords","padding","leftSide","rightSide","sizerWidth","docLTR","drawForLine","fromArg","toArg","lineLen","wrapX","side","extent","fromPos","toPos","openStart","openEnd","openRight","topLeft","topRight","botLeft","botRight","sFrom","sTo","fromLine","toLine","singleVLine","leftEnd","rightStart","restartBlink","focused","blinker","cursorDiv","visibility","cursorBlinkRate","hasFocus","onBlur","ensureFocus","focus","onFocus","delayBlurEvent","delayingBlurEvent","draggingText","selForContextMenu","receivedFocus","updateHeightsInViewport","prevBottom","lineDiv","viewTop","oldHeight","mustScroll","updateWidgetHeight","chWidth","w","visibleLines","viewport","ensure","ensureFrom","ensureTo","maybeScrollWindow","doScroll","innerHeight","scrollNode","scrollIntoView","scrollPosIntoView","margin","limit","endCoords","scrollPos","calculateScrollPos","startTop","startLeft","updateScrollTop","setScrollLeft","snapMargin","screentop","docBottom","atTop","atBottom","newTop","gutterSpace","screenleft","screenw","tooWide","addToScrollTop","resolveScrollToPos","ensureCursorVisible","scrollToPos","cursorScrollMargin","scrollToCoords","scrollToRange","scrollToCoordsRange","sPos","updateDisplaySimple","setScrollTop","startWorker","forceScroll","scrollHeight","scrollbars","isScroller","scrollWidth","alignHorizontally","measureForScrollbars","gutterW","docH","viewHeight","viewWidth","barLeft","docHeight","NativeScrollbars","vert","horiz","checkedZeroWidth","minHeight","minWidth","update","needsH","needsV","sWidth","totalHeight","totalWidth","zeroWidthHack","disableHoriz","enableZeroWidthBar","disableVert","pointerEvents","bar","delay","maybeDisable","elementFromPoint","NullScrollbars","updateScrollbars","startWidth","startHeight","updateScrollbarsInner","sizes","paddingBottom","heightForcer","borderBottom","scrollbarFiller","coverGutterNextToScrollbar","gutterFiller","scrollbarModel","initScrollbars","scrollbarStyle","axis","nextOpId","startOperation","updateInput","typing","changeObjs","selectionChanged","updateMaxLine","markArrays","endOperation","endOperations","endOperation_R1","endOperation_W1","endOperation_R2","endOperation_W2","endOperation_finish","maybeClipScrollbars","mustUpdate","DisplayUpdate","updatedDisplay","updateDisplayIfNeeded","barMeasure","adjustWidthTo","maxScrollLeft","preparedSelection","takeFocus","setDocumentHeight","postUpdateDisplay","wheelStartX","wheelStartY","maybeHiddenMarkers","unhidden","maybeUnhiddenMarkers","finish","runInOp","methodOp","docMethodOp","highlight","highlightWorker","workTime","changedLines","oldStyles","highlighted","oldCls","newCls","ischange","workDelay","force","visible","editorIsHidden","wrapperHeight","oldDisplayWidth","scrollbarsClipped","marginBottom","borderRightWidth","selectionSnapshot","active","anchorNode","anchorOffset","focusNode","focusOffset","restoreSelection","snapshot","nodeName","removeAllRanges","addRange","renderedView","maybeUpdateLineNumberWidth","viewportMargin","different","lastWrapHeight","lastWrapWidth","toUpdate","selSnapshot","patchDisplay","selectionDiv","reportedViewFrom","reportedViewTo","updateNumbersFrom","container","rm","currentWheelTarget","updateNumber","updateGutterSpace","alignWidgets","comp","align","innerW","lineGutter","lineNumInnerWidth","lineNumWidth","getGutters","sawLineNumbers","renderGutters","specs","gElt","updateGutters","Display","draggable","wheelDX","wheelDY","activeTouch","init","wheelSamples","wheelPixelsPerUnit","wheelEventDelta","dx","wheelDeltaX","dy","wheelDeltaY","detail","HORIZONTAL_AXIS","VERTICAL_AXIS","wheelDelta","wheelEventPixels","delta","onScrollWheel","canScrollX","canScrollY","pixels","movedX","movedY","Selection","equals","here","there","deepCopy","Range","somethingSelected","normalizeSelection","mayTouch","selectionsMayTouch","prim","inv","simpleSelection","changeEnd","adjustForChange","computeSelAfterChange","offsetPos","computeReplacedSel","hint","oldPrev","newPrev","loadMode","modeOption","resetModeState","isWholeLineUpdate","wholeLineUpdateBefore","updateDoc","spansFor","linesFor","firstLine","lastText","lastSpans","nlines","added$1","added$2","linkedDocs","sharedHistOnly","propagate","skip","sharedHist","linked","rel","shared","attachDoc","setDirectionClass","directionChanged","done","undone","undoDepth","lastModTime","lastSelTime","lastOp","lastSelOp","lastOrigin","lastSelOrigin","generation","maxGeneration","historyChangeFromChange","histChange","attachLocalSpans","clearSelectionEvents","lastChangeEvent","hist","addChangeToHistory","selAfter","opId","historyEventDelay","pushSelectionToHistory","selectionEventCanBeMerged","addSelectionToHistory","clearRedo","dest","removeClearedSpans","explicitlyCleared","getOldSpans","mergeOldSpans","stretched","oldCur","stretchCur","copyHistoryArray","newGroup","instantiateSel","newChanges","extendRange","posBefore","extendSelection","extendSelections","heads","replaceOneSelection","setSimpleSelection","filterSelectionChange","setSelectionReplaceHistory","setSelectionNoUndo","NaN","setSelectionInner","skipAtomicInSelection","reCheckSelection","mayClear","newAnchor","skipAtomic","newHead","skipAtomicInner","oldPos","preventCursorLeft","selectLeft","preventCursorRight","selectRight","atomic","near","movePos","far","cantEdit","selectAll","filterChange","canceled","cancel","makeChange","ignoreReadOnly","suppressEdits","makeChangeInner","makeChangeSingleDoc","rebased","rebaseHist","makeChangeFromHistory","allowSelectionOnly","suppress","antiChanges","returned","v","shiftDoc","distance","makeChangeSingleDocInEditor","recomputeMaxLength","checkWidthStart","changesHandler","changeHandler","splitLines","rebaseHistSelSingle","rebaseHistArray","sub","ok","copied","changeLine","handle","changeType","LeafChunk","BranchChunk","removeInner","insertInner","iterN","leaf","maybeSpill","me","sibling","myIndex","used","LineWidget","opt","adjustScrollWhenAboveVisible","addLineWidget","insertAt","aboveVisible","this$1","oldH","nextMarkerId","TextMarker","markText","markTextShared","replacedWith","addToHistory","curLine","clearOnEnter","clearHistory","withOp","visual","dHeight","SharedTextMarker","cloneNode","isParent","findSharedMarkers","findMarks","copySharedMarkers","mFrom","mTo","subMark","detachSharedMarkers","subMarker","nextDocId","Doc","lineSep","cleanGeneration","getValue","join","lineSeparator","setValue","getLineHandle","getLineNumber","getLineHandleVisualStart","lineCount","listSelections","extendSelectionsBy","setSelections","addSelection","getSelections","replaceSelection","dup","replaceSelections","newSel","undoSelection","redoSelection","setExtending","getExtending","historySize","markClean","changeGeneration","forceSplit","isClean","gen","getHistory","setHistory","histData","setGutterMarker","gutterID","clearGutter","lineInfo","addLineClass","removeLineClass","removeLineWidget","setBookmark","realOpts","findMarksAt","getAllMarks","posFromIndex","sepSize","indexFromPos","copyHistory","linkedDoc","unlinkDoc","splitIds","iterLinkedDocs","getEditor","setDirection","eachLine","lastDrop","onDrop","clearDragCursor","files","dataTransfer","isReadOnly","FileReader","File","read","markAsReadAndPasteIfAllFilesAreRead","t","readTextFromFile","file","allowDropFileTypes","reader","onerror","onload","readAsText","text$1","getData","selected","onDragStart","setData","effectAllowed","setDragImage","img","_top","onDragOver","frag","dragCursor","forEachCodeMirror","getElementsByClassName","byClass","editors","globalsRegistered","ensureGlobalHandlers","registerGlobalHandlers","resizeTimer","onResize","setSize","keyNames","fromCharCode","keyMap","normalizeKeyName","alt","ctrl","cmd","normalizeKeyMap","keymap","keyname","lookupKey","getKeyMap","fallthrough","isModifierKey","keyCode","addModifierNames","noShift","altKey","metaKey","shiftKey","keyName","altGraphKey","deleteNearSelection","compute","kill","toKill","replaced","moveCharLogically","moveLogically","endOfLine","visually","prep","targetTop","moveVisually","bidi","mv","getWrappedLineExtent","moveInStorageOrder","searchInVisualLine","getRes","nextCh","basic","pcDefault","emacsy","macDefault","commands","singleSelection","killLine","deleteLine","delLineLeft","delWrappedLineLeft","delWrappedLineRight","rightPos","goDocStart","goDocEnd","goLineStart","goLineStartSmart","lineStartSmart","goLineEnd","lineEnd","goLineRight","goLineLeft","goLineLeftSmart","goLineUp","moveV","goLineDown","goPageUp","goPageDown","goCharLeft","moveH","goCharRight","goColumnLeft","goColumnRight","goWordLeft","goGroupRight","goGroupLeft","goWordRight","delCharBefore","deleteH","delCharAfter","delWordBefore","delWordAfter","delGroupBefore","delGroupAfter","indentAuto","indentSelection","indentMore","indentLess","insertTab","insertSoftTab","spaces","defaultTab","execCommand","transposeChars","newlineAndIndent","sels","openLine","toggleOverwrite","firstNonWS","inWS","doHandleBinding","bound","dropShift","ensurePolled","prevShift","lookupKeyForEditor","keyMaps","extraKeys","stopSeq","dispatchKey","seq","keySeq","dispatchKeyInner","handleKeyBinding","motion","handleCharBinding","lastStoppedKey","onKeyDown","getField","handled","showCrossHair","up","onKeyUp","onKeyPress","charCode","lastClick","lastDoubleClick","DOUBLECLICK_DELAY","PastClick","clickRepeat","now","compare","onMouseDown","supportsTouch","clickInGutter","repeat","selectingText","handleMappedButton","leftButtonDown","onContextMenu","configureMouse","option","unit","addNew","moveOnDrag","contained","behavior","dragDrop","leftButtonStartDrag","leftButtonSelect","moved","dragEnd","mouseMove","dragStart","preventScroll","e2","rangeForUnit","findWordAt","ourRange","ourIndex","startSel","lastPos","extendTo","startCol","posCol","leftPos","oldRange","ranges$1","bidiSimplify","editorSize","counter","curCount","move","buttons","anchorLine","boundary","headIndex","usePart","gutterEvent","prevent","mX","mY","touches","lineBox","contextMenuInGutter","themeChanged","theme","Init","optionHandlers","defineOptions","deflt","notOnInit","defineOption","newBreaks","refresh","getInputField","spellcheck","autocorrect","autocapitalize","detach","attach","wrappingChanged","integer","blur","readOnlyChanged","screenReaderLabelChanged","dragDropChanged","resetPosition","funcs","dragFunctions","toggle","enter","over","leave","inputStyles","inputStyle","pasteIncoming","cutIncoming","autofocus","registerEventHandlers","finishInit","initHooks","textRendering","word","touchFinished","prevTouch","finishTouch","isMouseLikeTouchEvent","touch","radiusX","radiusY","farAway","pageX","pageY","inp","how","aggressive","indent","curSpace","curSpaceString","indentUnit","indentString","indentWithTabs","pos$1","defineInitHook","lastCopied","setLastCopied","newLastCopied","applyTextInput","inserted","deleted","recent","paste","textLines","multiPaste","pasteLinesPerSelection","lineWise","changeEvent","triggerElectric","handlePaste","pasted","clipboardData","disableInput","electricChars","smartIndent","getModeAt","electricInput","copyableRanges","lineRange","disableBrowserMagic","field","hiddenTextarea","border","addEditorMethods","helpers","setOption","getDoc","addKeyMap","removeKeyMap","addOverlay","modeSpec","removeOverlay","newRanges","getLineTokens","getTokenTypeAt","getHelper","getHelpers","help","_global","getStateAfter","defaultTextHeight","defaultCharWidth","getViewport","addWidget","vspace","hspace","triggerOnKeyDown","triggerOnKeyPress","triggerOnKeyUp","triggerOnMouseDown","findPosH","amount","hitSide","rtlMoveVisually","findPosV","goalColumn","goals","headPos","startChar","check","scrollTo","getScrollInfo","interpret","swapDoc","phrase","phraseText","phrases","getScrollerElement","getGutterElement","registerHelper","registerGlobalHelper","predicate","origDir","lineDir","findNextLine","moveOnce","boundToLine","astral","sawType","pageSize","moveAmount","ContentEditableInput","lastAnchorNode","lastAnchorOffset","lastFocusNode","lastFocusOffset","polling","composing","gracePeriod","readDOMTimeout","posToDOM","isInGutter","scan","badPos","bad","domTextBetween","closing","extraLinebreak","recognizeMarker","addText","walk","cmText","markerID","isBlock","textContent","nodeValue","domToPos","lineNode","locateNodeInLineView","textNode","topNode","curNode","previousSibling","dist$1","belongsToInput","onCopyCut","lineWiseCopyCut","clearData","kludge","hadFocus","showPrimarySelection","contentEditable","updateFromDOM","readFromDOMSoon","forceCompositionEnd","label","removeAttribute","showMultipleSelections","curAnchor","curFocus","rng","rangeCount","getRangeAt","startGracePeriod","rememberSelection","selectionInEditor","commonAncestorContainer","poll","pollSelection","pollInterval","pollContent","fromIndex","fromNode","toNode","toIndex","newText","oldText","cutFront","cutEnd","oldTop","maxCutFront","newBot","oldBot","maxCutEnd","chFrom","chTo","TextareaInput","prevInput","pollingFast","fromTextArea","textarea","tabindex","placeholder","realSubmit","form","leaveSubmitMethodAlone","submit","wrappedSubmit","getTextArea","toTextArea","addLegacyProps","cmpPos","createField","prepareCopyCut","fastPoll","dispatchEvent","Event","_display","moveInputWithCursor","wrapOff","lineOff","teTop","teLeft","drawn","contextMenuPending","slowPoll","missed","same","resetSelectionOnContextMenu","oldScrollY","oldCSS","oldWrapperCSS","wrapperBox","offsetParent","scrollY","rehide","detectingSelectAll","prepareSelectAllHack","mouseup","extval","disabled","dontDelegate","func","defineDocExtension","version","keySet","config","parserConfig","propertyKeywords","tokenHooks","documentTypes","mediaTypes","mediaFeatures","mediaValueKeywords","nonStandardPropertyKeywords","fontProperties","counterDescriptors","colorKeywords","valueKeywords","allowNested","lineComment","supportsAtComponent","highlightNonStandardPropertyKeywords","ret","tp","tokenBase","tokenize","tokenString","tokenParenthesized","quote","escaped","pushContext","popContext","pass","states","popAndPass","wordAsValue","stateArg","_stream","atBlock","cx","blockCommentStart","blockCommentEnd","blockCommentContinue","fold","documentTypes_","mediaTypes_","mediaFeatures_","mediaValueKeywords_","propertyKeywords_","nonStandardPropertyKeywords_","colorKeywords_","valueKeywords_","allWords","tokenCComment","maybeEnd","defaultTags","script","maybeBackup","pat","attrRegexpCache","getAttrRegexp","regexp","getAttrValue","getTagRegexp","anchored","addTags","findMatchingMode","tagInfo","tagText","htmlMode","multilineTagIndentFactor","multilineTagIndentPastTag","allowMissingTagName","tags","configTags","configScript","scriptTypes","html","htmlState","inTag","endTagA","endTag","localState","localMode","local","statementIndent","jsonldMode","jsonld","json","trackScope","isTS","typescript","wordRE","wordCharacters","keywords","kw","A","B","C","D","operator","atom","isOperatorChar","isJsonldKeyword","readRegexp","inSet","cont","tokenComment","expressionAllowed","tokenQuasi","lastType","propertyIsEnumerable","brackets","findFatArrow","fatArrowAt","arrow","depth","sawSomething","bracket","atomicTypes","JSLexical","inScope","varname","localVars","vars","parseJS","cc","marked","expression","statement","lex","inList","block","newContext","registerVarScoped","Var","globalVars","isModifier","defaultVars","pushcontext","pushblockcontext","popcontext","pushlex","poplex","expect","wanted","exp","vardef","parenExpr","maybeexpression","maybeelse","functiondef","forspec","enumdef","typename","typeexpr","maybelabel","maybeCatchBinding","afterExport","afterImport","funarg","expressionInner","expressionNoComma","noComma","arrowBodyNoComma","arrowBody","commasep","maybeop","maybeoperatorNoComma","maybeoperatorComma","classExpression","arrayLiteral","contCommasep","objprop","quasi","maybeTarget","expr","property","continueQuasi","targetNoComma","maybeTypeArgs","getterSetter","afterprop","maybetype","what","sep","proceed","maybetypeOrIn","mayberettype","isKW","afterType","typeprops","typearg","maybeReturnType","quasiType","typeprop","functiondecl","continueQuasiType","typeparam","maybeTypeDefault","maybeAssign","vardefCont","eltpattern","proppattern","forspec1","forspec2","classNameAfter","classBody","classfield","maybeFrom","exportField","importSpec","maybeMoreImports","maybeAs","enummember","isContinuedStatement","basecolumn","firstChar","c","doubleIndentSwitch","closeBrackets","skipExpression","htmlConfig","autoSelfClosers","implicitlyClosed","contextGrabbers","doNotIndent","allowUnquoted","allowMissing","caseFold","xmlConfig","editorConf","config_","setStyle","inText","parser","inBlock","doctype","baseState","tagStart","inAttribute","stringStartCol","closure","isInAttribute","terminator","lower","startOfLine","noIndent","maybePopContext","nextTagName","parentTagName","tagNameState","closeTagNameState","attrState","matchClosing","closeState","closeStateErr","attrEqState","attrValueState","attrContinuedState","isInText","baseIndent","fullLine","alignCDATA","tagAfter","grabbers","skipAttribute","xmlCurrentTag","xmlCurrentContext","assets","noAssets","stylePrefix","upload","uploadName","headers","credentials","multiUpload","autoAdd","customFetch","uploadFile","embedAsBase64","handleAdd","beforeUpload","showUrlInput","custom","dropzone","openAssetsOnDrop","dropzoneContent","Asset","getFilename","getDefaults","AssetImage","unitDim","pfx","ppfx","pStylePrefix","em","__getBhv","am","__getBehaviour","template","getPreview","getInfo","updateTarget","innerHTML","AssetView","click","dblclick","dim","onClick","coll","onDblClick","onSelect","onRemove","stopImmediatePropagation","TypeableCollection","AssetImageView","isType","renderAssets","addToAsset","removedAsset","deselectAll","handleSubmit","getAddInput","trim","getAssetsEl","globalCollection","inputUrl","toggleNoAssets","addAsset","fragmentEl","rendered","typeView","assetsEl","hide","append","removeClass","fuRendered","fu","uploadId","disableUpload","onUploadStart","__propEv","onUploadEnd","onUploadError","err","console","onUploadResponse","clb","FormData","reqHead","fetchOpts","then","status","Promise","catch","initDrop","that","uploadForm","ondragover","ondragleave","ondrop","initDropzone","addedCls","edEl","editor","frameEl","getBody","updatedCls","dropzoneCls","cleanEditorElCls","onDragLeave","getSelected","runCommand","Modal","AssetManager","setTarget","item","response","promises","mimeTypeMatcher","promise","resolve","image","Image","readAsDataURL","evAll","evPfx","evSelect","evUpdate","evAdd","evRemove","evRemoveBefore","evCustom","evOpen","evClose","evUpload","evUploadStart","evUploadEnd","evUploadError","evUploadRes","assetsVis","assetCmd","Module","storageKey","Assets","removeBefore","uploadStart","uploadEnd","uploadError","uploadResponse","__initListen","getAllVisible","getAll","__onAllEvent","debounce","__trgCustom","getConfig","__customData","bhv","isOpen","asset","complete","run","isActive","__remove","store","noStore","stm","load","getContainer","assts","toRender","__viewParams","FileUploader","AssetsView","addType","definition","getType","getTypes","FileUpload","onLoad","postRender","editorView","__behaviour","_bhv","appendTo","appendOnClick","blocks","Block","media","category","activate","resetId","disable","ctg","Blocks","Category","Categories","mousedown","dragstart","drag","dragend","endDrag","__getModule","handleClick","sorter","getSorter","setDropContent","validTarget","getEl","valid","getWrapper","setSelected","startDrag","refreshCanvas","setDragHelper","startSort","handleDragStart","__startDrag","handleDrag","__drag","handleDragEnd","__endDrag","endMove","class","clsAdd","hasDnd","prefix","CategoryView","caretR","caretD","iconClass","activeClass","updateVisibility","getIconEl","getBlocksEl","iconEl","blocksEl","bindAll","categories","renderedCategories","noCatClass","blockContClass","catsClass","addTo","tac","grabbingCls","canvas","updateConfig","utils","Sorter","placer","getPlacerEl","containerSel","itemSel","onStart","onDrag","onEndMove","onMove","getFrameEl","contentDocument","wmargin","nested","canvasRelative","stopDefault","runDefault","oldActive","BlockView","ignoreCategories","catModel","catId","catView","getCategoriesEl","catsEl","evDrag","evDragStart","evDragStop","blocksVisible","blocksView","bm","dragStop","getContent","_dragBlock","dragResult","dragContent","oldKey","toActive","toSelect","onAll","__getFrameViews","getFrames","frame","fv","droppable","startCustom","endCustom","BlocksView","elTo","isElement","__logWarn","prp","getCategories","external","colls","scripts","customBadgeLabel","autoscrollLimit","extHl","notTextable","Canvas","frames","rulers","zoom","Frames","onZoomChange","updateDevice","evPageSelect","_pageUpdated","mainPage","getMain","getMainFrame","page","device","getDeviceModel","getCurrentFrameModel","noUndo","Droppable","rootEl","getComponent","els","toggleEffects","enable","handleDragEnter","handleDragOver","handleDrop","handleDragLeave","defaultView","frameElement","sortOpts","onEnd","customTarget","__customTglEff","endDrop","updateCounter","dt","inAbsoluteMode","dragger","guidesInfo","center","cancelled","getStyle","addStyle","cnt","preserveSelected","getContentByData","allowfullscreen","tools","frameView","cvModel","getCanvasModel","updateHead","renderStyles","setViewEl","headEl","getHead","attrStr","items","stl","appendVNodes","getModel","getWindow","getJsContainer","jsContainer","createEl","getToolsEl","frameWrapView","elTools","getGlobalToolsEl","getHighlighter","_getTool","getBadgeEl","getOffsetViewerEl","getRect","getOffsetRect","scrollBottom","scrollRight","toolsEl","wrp","_toggleEffects","startAutoscroll","lastMaxHeight","_toggleAutoscrollFx","requestAnimationFrame","autoscroll","dragging","lastClientY","win","actualTop","limitTop","limitBottom","nextTop","isUndefined","opacity","showGlobalTools","updateClientY","getPointerEvent","getZoomDecimal","stopAutoscroll","mt","renderScripts","evLoad","evOpts","appendScript","scriptEl","renderBody","normalize","stls","prevStyles","conf","_isEditor","baseCss","canvasCss","protectedCss","component","CssRulesView","getStyles","createCustomEvent","motionsEv","_emitUpdate","_emitUpdated","canvasView","cv","FrameView","classAnim","updateOffset","updateSize","frameLoaded","updatePos","setupDragger","dragX","dragY","toggleFramesEvents","Dragger","getZoomMultiplier","setPosition","posOpts","__clear","removeEl","md","updateDim","__handleSize","noChanges","isNull","onScroll","onscroll","currW","currH","newW","newH","isNumber","onRender","twrp","toolsWrapper","elTop","elRight","elBottom","elLeft","frameWrapperView","DomainViews","itemView","FrameWrapView","onRemoveBefore","timerZoom","wheel","_initFrames","clearOff","checkSelected","updateFrames","_onFramesUpdate","toggleListeners","_renderFrames","FramesView","currFrame","views","_getFrame","_parentEvent","onCanvasMove","getKeyChar","isInputFocused","onWheel","getZoom","defOpts","mpl","framesArea","transform","isElInViewport","elem","getElement","getElRect","frameRect","getFrameOffset","rTop","rLeft","docBody","noScroll","frmOff","cvsOff","winEl","frEl","getCanvasOffset","getElementPos","eo","frmTop","avoidFrameOffset","frmLeft","getElementOffsets","isTextNode","parseFloat","getPosition","bEl","fo","co","updateScript","getId","scriptContainer","scriptFn","getScriptString","scriptFnStr","scriptProps","__getScriptProps","scr","getFrameView","ready","frms","listenToLoad","mainFrame","setCurrentFrame","$frames","toolsWrp","hlEl","badgeEl","placerEl","ghostEl","toolbarEl","resizerEl","offsetEl","fixedOffsetEl","toolsGlobEl","getUiClass","CanvasView","getCanvasView","getFrame","getFramesEl","getDocument","_getCompFrame","compView","_getLocalEl","globalEl","getGhostEl","getToolbarEl","getResizerEl","getFixedOffsetViewerEl","getOffset","frameOff","canvasOff","setCustomBadgeLabel","topScroll","leftScroll","getTargetToElementDim","canvasPos","elPos","toRight","targetHeight","targetWidth","eventToTrigger","topPos","elementTop","elementLeft","elementWidth","elementHeight","canvasTop","canvasLeft","canvasWidth","canvasHeight","canvasRectOffset","getFrameElFromDoc","rectOff","getTargetToElementFixed","elToMove","cvOff","toolbarH","toolbarW","frCvOff","frameOffset","fullHeight","elIsShort","canvasOffsetTop","canvasOffsetLeft","getMouseRelativePos","addTop","addLeft","subWinOffset","parentWindow","yOffset","xOffset","getMouseRelativeCanvas","toIgnore","getViewEl","fr","getCurrentFrame","setZoom","setCoords","getCoords","addFrame","keyAutoW","keyAutoH","Frame","changesCount","_undo","_undoexc","domc","allRules","idMap","modOpts","isComponent","components","Wrapper","idMapKeys","selectors","sSel","idSel","temporary","noCount","avoidStore","setHead","getHeadByAttr","addHeadItem","removeHeadByAttr","sm","smc","fromUndo","storeHtml","getHtml","storeCss","getCss","onReset","loadedItems","itemsToLoad","listenToLoadItems","itemLoaded","inlineCss","HTMLGenerator","htmlOpts","cleanId","rules","idRules","rule","isId","toHTML","build","beforeEach","mapModel","comps","scrStr","scrProps","mapJs","mapType","hasWin","require","codeName","onChange","ed","setContent","autoFormatRange","noRefresh","EditorView","generators","defGenerators","viewers","defViewers","defaultViewer","gHtml","gCss","gJson","js","gJs","eCM","loadDefaultGenerators","loadDefaultViewers","addGenerator","generator","getGenerator","getGenerators","addViewer","viewer","getViewer","getViewers","createViewer","txtarea","updateViewer","getCode","genId","maxValue","MAX_VALUE","getMediaLength","mediaQuery","compCls","buildFromModel","avoidInline","styleToString","getFullName","cssc","codeJson","clearStyles","atRules","dump","onlyMatched","matchedRules","atRule","getAtRule","mRules","buildFromRule","sortMediaObject","rulesStr","ruleStr","selectorStrNoAdd","selectorsToString","skipAdd","selectorsAdd","singleAtRule","keepUnusedStyles","getDeclaration","__cleanSelector","getQueryLength","itemsArr","isMobFirst","mquery","sortRules","getKey","q","strict","commandsDef","defaultCommands","CommandAbstract","sender","selAll","getSelectedAll","nativeDrag","defComOptions","logWarning","hideTlb","altMode","eventDrag","emitUpdate","cmdMove","Commands","onEndMoveFromModel","initSorterFromModels","oldCmd","default","cmdName","loadDefaultCommands","noStop","command","cmdObj","stopCommand","getActive","callRun","abort","callStop","DomComponents","CssComposer","canvasModel","toggleMove","disableDragger","enableDragger","toggleDragger","methodCls","getCanvas","classList","methodEv","methodsEv","editorModel","hoverClass","badgeClass","plhClass","freezClass","onFrameScroll","getCanvasBody","getCanvasTools","Boolean","evName","guidesStatic","guidesTarget","setupGuides","isTran","guidesContainer","getGuidesContainer","getGuidesTarget","getGuidesStatic","drg","toggleDrag","getEventOpts","guides","guide","guidesEl","elInfoX","elInfoY","guideContent","elGuideInfoX","elGuideInfoY","elGuideInfoContentX","elGuideInfoContentY","updateGuides","debug","renderGuide","getElementGuides","lastEl","getGuidePosUpdate","originRect","un","guideSize","numEl","getTranslate","itemStr","setTranslate","en","styleUp","adds","_getDragData","relPos","parentRel","pStyle","offsetP","renderGuideInfo","hideGuidesInfo","rectOrigin","isY","origEdge1","origEdge1Raw","origEdge2","origEdge2Raw","elGuideInfo","elGuideInfoCnt","guideInfoStyle","stat","statEdge2","isEdge1","statEdge1","statEdge1Raw","statEdge2Raw","posFirst","posSecond","pos2","sizeRaw","matched","snd","incr","getChildAt","wrappers","Pages","getAllWrappers","flatten","findType","SelectComponent","mouseover","startDelete","mouseout","stopDelete","onDelete","$this","attachBadge","badge","removeBadge","clean","updateBadgeLabel","getName","modal","CodeManager","$editors","oHtmlEd","buildEditor","oCsslEd","htmlEditor","cssEditor","textViewCode","codeMirror","isEnabled","fullscreenElement","webkitFullscreenElement","mozFullScreenElement","requestFullscreen","webkitRequestFullscreen","mozRequestFullScreen","msRequestFullscreen","warn","exitFullscreen","webkitExitFullscreen","mozCancelFullScreen","msExitFullscreen","fsChanged","targetEl","SelectPosition","noSelClass","getHighlighterEl","wp","$wrapper","initSorter","toggleClipboard","cacheEl","startSelectPosition","stopSelectComponent","getContentWindow","rollback","initSorterFromModel","lastModel","toMove","onMoveClb","$badge","getBadge","$hl","onceClose","accept","modalTitle","uploadEl","firstRender","pn","Panels","getPanel","addPanel","lm","LayerManager","layers","panels","$cn","trgEvCnt","$cn2","dvm","DeviceManager","showDevices","devicePanel","dvEl","slm","SelectorManager","slmConfig","StyleManager","smConfig","$header","pnCnt","panel","toggleSm","show","Config","tm","TraitManager","confTm","toggleTm","clp","addOpts","copyable","cop","cmdVis","getPanels","preventDrag","tglEffects","mthEv","tlb","elP","querySelectorAll","shouldRunSwVisibility","editorEl","onclick","canvasS","posFetcher","mousePosFetcher","canvasResizer","forceNew","Utils","Resizer","calibrated","ToolbarButtonView","ToolbarButton","showOffsets","adjScroll","startSelectComponent","toggleSelectComponent","listenToEl","onFrameUpdated","onContainerChange","onHovered","updateGlobalPos","_upToolbar","updateAttached","onHover","onOut","trg","isDoc","currentDoc","setHovered","useValid","updateLocalPos","updateToolsLocal","elHovered","toggleToolsEl","currentFrame","getView","isVisible","elSelected","updateToolsGlobal","initResize","getElSelected","getElHovered","showElementOffset","hideElementOffset","showFixedElementOffset","hideFixedElementOffset","hideHighlighter","isEditing","isChildOf","updateBadge","posOnly","icon","getIcon","clsBadge","customeLabel","badgeLabel","bStyle","targetToElem","leftOff","showHighlighter","modelToStyle","resizeClass","isTaggableNode","resizable","toggleBodyClass","docs","resizer","keyHeight","keyWidth","currentUnit","keepAutoHeight","keepAutoWidth","getModelToStyle","computedStyle","modelStyle","currentWidth","autoWidth","currentHeight","autoHeight","startDim","unitHeight","getUnitFromValue","unitWidth","selectedHandler","onlyHeight","onlyWidth","bodyw","updateEvent","eventToListen","noEmit","updateToolbar","toolbarStyle","toolbar","showToolbar","Toolbar","toolbarView","ToolbarView","updateToolbarPos","getCanvasPosition","updateTools","isCompSelected","isHoverEn","isNewEl","lastHovered","badgeOpts","topOff","_trgToolUp","lastSelected","hideBadge","cleanPrevious","isPointed","scale","getOffsetDim","stopSelectPosition","posTargetCollection","posIndex","posMethod","cDim","posIsLastEl","posTargetEl","outsideElem","posTargetModel","nearFloat","isLast","getOffsetMethod","showOffsetsSelected","stateVar","offsetViewer","marginT","marginB","marginL","marginR","padT","padB","padL","padR","stateLow","marginName","paddingName","marginV","paddingV","paddingEls","fullMargName","fullPadName","marginLeftSt","marginRightSt","marginRight","marginTopSt","marginBottomSt","mtStyle","mbStyle","mlStyle","mrStyle","ptStyle","pbStyle","plStyle","prStyle","posLeft","widthEl","marginSideH","marginSideT","padTop","padBot","padSideH","padSideT","padRight","toggleVis","mth","_upFrame","_onFramesChange","__getConfig","getAllMap","acc","__initConfig","def","__catchAllEvent","collections","entity","__appendTo","_createId","ln","allMap","createId","__listenAdd","__listenRemove","__listenUpdate","__destroy","onBeforeStyle","CSS","CssRule","mediaText","stylable","atRuleType","important","shallow","ensureSelectors","__onChange","isEmptyObj","changesUp","toListen","getSelectors","Selectors","typeStr","addSelector","selOpts","getFullString","stateStr","skipState","allowEmpty","devices","getDevices","deviceDefault","getWidthMedia","stateValue","getStates","sngl","cmpId","getById","ruleProps","wd","selAdd","a1S","a2S","Styleable","onAdd","parseCss","rulesView","storeStyles","elStyle","CssRules","postLoad","um","getCacheLoad","hasPages","slc","singleSel","parserCss","checkNode","addCollection","sl","newSels","le","selec","modelExists","updateStyle","avoidUpdateStyle","styleUpdate","addRules","setRule","atRuleParams","getRule","getRules","setIdRule","getCurrentMedia","Selector","getIdRule","setClassRule","getClassRule","getComponentRules","getSelectorsString","toCSS","CssRuleView","getBlockId","addToCollection","renderStarted","atRuleEl","styleEl","CssGroupRuleView","appendData","clsName","defaultBlockId","blockId","getMediaWidth","contRules","prs","pr","widthMedia","Device","checkUnit","Devices","DevicesView","startAdd","updateSelect","devEl","devicesEl","getOptions","evSelectBefore","evAddBefore","chnSel","dv","_onSelect","deviceId","newDevice","draggableComponents","storeWrapper","processor","voidElements","ComponentWrapperView","ComponentView","Component","columns","rows","rowsToAdd","columnsToAdd","clm","ComponentTableBody","svgAttrs","void","editable","highlightable","ratioDefault","traits","fallback","initToolbar","hasButtonBool","tb","getAttrToHTML","getSrcResult","btoa","isDefaultSrc","parseUri","uri","query","qrs","pair","hostname","protocol","port","mapUrl","address","frameborder","OComponent","changeProp","parseFromSrc","updateSrc","getMapUrl","addr","qr","z","classEmpty","fetchFile","modelOpt","srcExists","addAttributes","onActive","getSrc","onError","noDrag","renderAttributes","getIframe","ifrm","frameBorder","updateClasses","ComponentText","ComponentLink","textTags","compProt","updateContentText","syncContent","rte","fromDisable","disableEditing","canActivate","rteEnabled","sameInEdit","getEditing","isInnerText","isInstanceOf","lastContent","activeRte","logError","toggleEvents","onDisable","getChildrenContainer","contentOpt","customRte","resetFromString","insertComponent","startContainer","startOffset","textModel","newCmps","is","cmps","onInput","disablePropagation","mixins","setEditing","elDocs","prevDef","ComponentLinkView","yt","vi","ytnc","videoId","provider","ytUrl","ytncUrl","viUrl","poster","muted","autoplay","controls","color","modestbranding","sources","updateTraits","getYoutubeTraits","getVimeoTraits","getSourceTraits","prov","getYoutubeSrc","getYoutubeNoCookieSrc","getVimeoSrc","getProviderTrait","getAutoplayTrait","getLoopTrait","getControlsTrait","isYtProv","isYtncProv","isViProv","isExtProv","OComponentView","updateProvider","updateVideo","renderByProvider","videoEl","renderYoutube","renderYoutubeNoCookie","renderVimeo","renderSource","initVideoEl","layerable","scrCnt","scriptCount","svar","svarNext","svarFn","svarNextFn","__innerHTML","customName","selectable","hoverable","inSvg","createElementNS","updateStatus","updateAttributes","initClasses","initComponents","createComment","ComponentWrapper","removable","__hasUm","attrUp","__getSrc","getAttributes","componentView","componentsById","componentTypes","ComponentTableCell","ComponentTableCellView","ComponentTableRow","ComponentTableRowView","ComponentTable","ComponentTableView","ComponentTableHead","ComponentTableHeadView","ComponentTableBodyView","ComponentTableFoot","ComponentTableFootView","ComponentMap","ComponentMapView","ComponentLabel","ComponentLabelView","ComponentVideo","ComponentVideoView","ComponentImage","ComponentImageView","ComponentScript","ComponentScriptView","ComponentSvgIn","ComponentSvgView","ComponentSvg","ComponentFrame","ComponentFrameView","ComponentComment","ComponentCommentView","ComponentTextNode","ComponentTextNodeView","ComponentTextView","Components","ComponentsView","storeComponents","compTypes","componentHovered","selectAdd","selectRemove","setComponents","isObj","getComponents","toStore","addComponent","extendView","extendFn","extendFnView","compType","extendType","extendViewType","typeToExtend","modelToExt","viewToExt","getExtendedObj","srcToExt","parentFn","df","it","removeType","getShallowWrapper","shallowEm","keyUpdate","keyUpdateInside","canMove","reason","srcModel","allById","Trait","targetEvent","targetUpdated","locale","getTargetValue","valueOpts","partial","setTargetValue","fromTarget","trait","valueToSet","final","toSet","step","Traits","handleReset","tf","objs","optionsTarget","TraitFactory","keySymbols","keySymbol","keySymbolOvrd","parentAttr","newAttr","toPropagate","ccid","initTraits","initScriptProps","scriptUpdated","tagUpdated","attrUpdated","_idUpdated","__emitUpdateTlb","__propToParent","__postAdd","__isSymbolOrInst","__initSymb","recursive","__changesUp","__propSelfToParent","$els","eq","closest","setClass","attrPrev","shallowDiff","setAttributes","noClass","attrArr","compAttr","optsAdd","parseStyle","propOrig","addId","noStyle","TYPE_ID","__getSymbol","__getSymbols","classe","classStr","toUp","symbol","symbols","log","__symbReady","__upSymbProps","__isSymbol","__isSymbolTop","symbTopSelf","__getSymbTop","symbTop","symb","__getAllById","symbs","idx","ovrd","symbEnabled","fromInstance","noPropagate","__isSymbOvrd","__getSymbToUp","__logSymbol","propsChanged","optUp","toUpOpts","isTemp","addedInstances","isMainSymb","addSymb","toAppend","addedInst","addedTop","symbolInv","isSymbNested","__isSymbolNested","toUpFn","symbPrnt","newMods","attrCls","clsArr","normalizeClasses","__upSymbCls","addChild","avoidChildren","__upSymbComps","__loadTraits","getInitValue","prevProps","newProps","prevPropsEv","newPropsEv","__scriptPropsChange","compArr","prevColl","tr","traitsI","getTraits","getTrait","_inner","cloned","newId","rulesToClone","newRule","defName","nameTag","i18nPfx","i18nName","i18nNameTag","i18nDefName","capitalize","customTag","sTag","customAttr","withProps","isBoolean","valueRes","altQuoteAttr","attrString","getInnerHTML","getChangedProps","modelProps","tagVarStart","tagVarEnd","reg","updated","rmOpts","byType","oldId","setId","idS","_getStyleRule","idUpdate","idPrev","getList","_getStyleSelector","ensureInList","nextId","getIncrementId","getNewId","ilen","uid","random","keepIds","dm","checkId","badgable","unstylable","dmode","getComponentIds","getComponentsFromDefs","itms","newComponents","resetChildren","newIds","allByID","parsed","parseString","canRemoveStyle","rulesRemoved","__postRemove","parseHtml","optsToPass","nodes","isMult","processDef","__firstAdd","mdl","modelPr","$$typeof","parserHtml","splitPropsFromAttr","__onAddEnd","getClasses","updateHighlight","updateContent","handleChange","avoidRender","_clbObj","__isDraggable","childrenView","importClasses","renderChildren","chgArr","selectedCls","selectedParentCls","freezedCls","hoveredCls","selCls","noExtHl","actualCls","avoidHover","isTextable","hl","onAttrUpdate","removeAttr","textable","defaultAttr","contenteditable","hasComps","getChildrenSelector","getTemplate","gtop","gleft","assignRect","isInViewport","elDoc","_setData","replaceWith","triggerAdd","sameFrameView","viewObject","parentEl","ParserHtml","extendStyle","propNew","noEvent","removeStyle","imp","propPrv","newStyle","baseType","getBaseType","typeFound","recognizeType","ModelInst","ViewInst","extendViewApi","holderClass","inputClass","handleModelChange","elementUpdated","getInputEl","__onInputChange","fromInput","inputEl","plh","defaultOpts","beforeShow","noop","flat","showInput","showButtons","clickoutFiresChange","showInitial","showPalette","showPaletteOnly","hideAfterPaletteSelect","togglePaletteOnly","showSelectionPalette","localStorageKey","maxSelectionSize","cancelText","chooseText","togglePaletteMoreText","togglePaletteLessText","clearText","noColorSelectedText","preferredFormat","containerClassName","replacerClassName","showAlpha","palette","selectionPalette","spectrums","IE","rgbaSupport","backgroundColor","replaceInput","markup","gradientFix","dataID","spectrum","extra","spect","removeData","loadOpts","inputTypeColorSupport","_cachedResult","colorInput","localization","palettes","processNativeColorInputs","colorInputs","trimLeft","trimRight","tinyCounter","math","mathRound","mathMin","mathMax","mathRandom","tinycolor","rgb","format","named","matchers","rgba","hsl","hsla","hsv","hsva","hex8","convertHexToDecimal","parseIntFromHex","hex6","hex3","stringInputToObject","bound01","convertToPercentage","hsvToRgb","hue2rgb","hslToRgb","boundAlpha","inputToRGB","_originalInput","_r","_g","_b","_a","_roundA","_format","_gradientType","gradientType","_ok","_tc_id","isDark","getBrightness","isLight","getOriginalInput","getFormat","getAlpha","toRgb","setAlpha","toHsv","rgbToHsv","toHsvString","toHsl","rgbToHsl","toHslString","toHex","allow3Char","rgbToHex","toHexString","toHex8","rgbaToHex","toHex8String","toRgbString","toPercentageRgb","toPercentageRgbString","toName","hexNames","toFilter","secondColor","hex8String","secondHex8String","formatSet","formattedString","hasAlpha","_applyModification","lighten","brighten","darken","desaturate","saturate","greyscale","spin","_applyCombination","analogous","complement","monochromatic","splitcomplement","triad","tetrad","fromRatio","newColor","color1","color2","mix","w1","rgb1","rgb2","w2","readability","c1","c2","brightnessA","brightnessB","colorDiff","brightness","isReadable","mostReadable","baseColor","colorList","bestColor","bestScore","bestIsReadable","readable","CSS_UNIT","PERMISSIVE_MATCH3","PERMISSIVE_MATCH4","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","burntsienna","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","flipped","flip","paletteTemplate","tiny","swatchStyle","timeout","callbackContext","instanceOptions","resize","reflow","throttler","isDragging","isDefault","dragWidth","dragHeight","dragHelperHeight","slideHeight","alphaWidth","alphaSlideHelperWidth","slideHelperHeight","currentHue","currentSaturation","currentValue","currentAlpha","paletteArray","paletteLookup","draggingClass","shiftMovementDirection","boundElement","pickerContainer","dragHelper","slider","slideHelper","alphaSliderInner","alphaSlider","alphaSlideHelper","textInput","paletteContainer","initialColorContainer","cancelButton","clearButton","chooseButton","toggleButton","isInput","isInputTypeColor","shouldReplace","replacer","offsetElement","previewElement","initialColor","colorOnShow","currentPreferredFormat","applyOptions","toggleClass","updateSelectionPaletteFromStorage","localStorage","oldPalette","addColorToSelectionPalette","inArray","drawPalette","currentColor","unique","getUniqueSelectionPalette","drawInitial","setFromTextInput","updateOriginalInput","isDefaultPrevented","hideAll","$doc","onkeydown","clickout","updateUI","revert","ignoreFormatChange","newHsv","updateHelperLocations","flatColor","realColor","displayColor","realHex","realRgb","alpha","realAlpha","gradient","alphaX","slideY","fireCallback","picker","extraY","dpWidth","outerWidth","dpHeight","outerHeight","inputHeight","docElem","cW","cH","scL","scT","paletteElementClick","keydown","hasClass","oldDragX","oldDragY","furtherFromX","paletteEvent","optionName","optionValue","coord","onmove","onstart","onstop","maxHeight","maxWidth","hasTouch","duringDragEvents","t0","rightclick","hex","pad2","clamp01","hue","results","slices","modification","isOnePointZero","processPercent","isPercentage","ColorPicker","getColor","cl","Input","colorEl","getColorEl","tc","valueClr","noneColor","previousColor","cpStyle","elToAppend","colorPickerConfig","setValueFromInput","noDefault","contClass","validateInputValue","deepCheck","validObj","handleUnitChange","getUnitEl","handleKeyDown","upArrowClick","downArrowClick","unitEl","units","temp","normalizeValue","downIncrement","moveIncrement","upIncrement","prValue","defValue","stepDecimals","toFixed","limitlessMax","limitlessMin","fixed","regFixed","valCopy","uN","itemsView","itemType","itemViewNotFound","ns","reuseView","typeField","clearItems","traitInputAttr","localeFallback","detectLocale","messages","assetManager","addButton","inputPlh","uploadTitle","blockManager","labels","domComponents","comment","video","link","tfoot","tbody","thead","table","row","cell","deviceManager","desktop","tablet","mobileLandscape","mobilePortrait","titles","preview","fullscreen","selectorManager","emptyState","hover","styleManager","layer","fileButton","sectors","general","layout","typography","decorations","flex","dimension","traitManager","false","_blank","messagesAdd","deepAssign","targValue","srcValue","addMessages","_localLang","setLocale","evObj","valuePrev","getLocale","getMessages","lang","_debug","setMessages","msg","localeFlb","lFlb","_getMsg","_addParams","nav","language","userLanguage","msgSet","_mods","_scope","_MODIFIERS","control","_MAP","backspace","tab","return","esc","down","del","delete","home","pageup","pagedown","_downKeys","compareArray","modifierMap","updateModifierKey","clearModifier","assignKey","resetModifiers","scope","mods","getKeys","getMods","shortcut","getScope","mi","addEvent","setScope","deleteScope","isPressed","getPressedKeyCodes","multipleKeys","modifiersMatch","dispatch","keymaster","configDef","keymaps","defKeys","pk","removeAll","backdrop","ModalView","updateOpen","updateTitle","$collector","$content","$title","getCollector","getTitle","currAttr","updateAttr","triggerEvent","ModalM","enb","_evData","titl","createText","setTitle","onceOpen","getContentEl","hidable","hideTextnode","showWrapper","showHover","scrollCanvas","scrollLayers","highlightHover","onInit","ItemsView","inputProp","styleOpts","isStyleHidden","clsNoEdit","countChildren","clsNoChild","clsTitle","clsTitleC","clsCaret","clsInput","inputNameCls","gut","clsBase","clsCount","clsMove","clsChildren","parentView","checkChildren","updateOpening","updateLayerable","updateName","clsEdit","viewLayer","__render","getInputName","innerText","getVisibilityEl","eyeEl","hClass","toggleVisibility","prevDspKey","prevDisplay","handleEdit","handleEditKey","isEscKey","isEnterKey","handleEditEnd","setName","propName","inputName","opened","chvDown","getCaret","toggleOpening","handleSelect","fromLayers","handleHover","handleHoverOut","freeze","unfreeze","isCountable","caret","setRoot","_rendered","__clearItems","ItemView","componentChanged","getRoot","sortContainer","ignoreViewChildren","created","getSourceModel","forceChange","avoidSelectOnEnd","Page","defFrame","evPageSelectBefore","evPageUpdate","evPageAdd","evPageAddBefore","evPageRemove","evPageRemoveBefore","typeMain","selectBefore","addBefore","cnf","pages","_onPageChange","mainComp","getMainComponent","pg","getAllFrames","pagesMap","swv","expt","osm","otm","ola","obl","ful","prv","togglable","delayBtnsShow","btn","Buttons","Panel","listen","activeCls","disableCls","btnsVisCls","updateActive","checkActive","updateBtnsVis","updateClassName","updateDisable","chnOpt","fromListen","$buttons","fromCollection","commandName","deactivateAll","clicked","toggleActive","parentM","ButtonView","appendContent","toggleVisible","cr","bc","resz","resLen","tl","bl","br","silentFrames","avoidContainerUpdate","forContainer","styleWidth","styleHeight","ButtonsView","PanelView","PanelsViewObj","getPanelsEl","removePanel","panelId","removeButton","getButton","PanelsView","disableButtons","runDefaultCommand","stopDefaultCommand","Button","deactivateAllExceptOne","except","disableAllButtons","disableAllButtonsExceptOne","optionsHtml","htmlType","allowScripts","allowUnsafeAttr","atRuleKeys","singleAtRules","singleAtRulesNames","parseSelector","propValue","getPropertyValue","getPropertyPriority","parseCondition","conditionText","selectorText","createNode","selLen","lastClass","stateArr","parseNode","cssRules","keyText","isSingleAtRule","subRules","lens","subRule","selsParsed","selsAdd","lastRule","len3","selsAddStr","sheet","BrowserCssParser","classSets","classSet","pHtml","pCss","Parser","defaultType","DOMParser","mimeType","strF","parseFromString","hEls","modelAttrStart","modelAttr","valueLen","valStr","lastChar","decls","decl","parseClass","attrsLen","nodePrev","nodeChild","ct","namespaceURI","keepEmptyTextNodes","outerHTML","allTxt","foundTextNode","ci","cType","cf","BrowserParserHtml","__clearUnsafeAttr","styleStr","resHtml","returnArray","btnState","isValidTag","parentAnchor","parentFocus","customElAttr","defActions","bold","italic","underline","strikethrough","insertHTML","RichTextEditor","settings","setEl","updateActiveActions","__onKeydown","__onPaste","acts","actionbar","inactive","actionbarCont","actionbarContainer","addAction","styleWithCSS","getActions","queryCommandSupported","queryCommandState","enabled","__toggleEffects","actionbarEl","syncActions","caretRangeFromPoint","poiner","rangeParent","rangeOffset","textHtml","deleteContents","nd","insertNode","toSel","removeAttributes","adjustToolbar","eventsUp","hideToolbar","initRte","globalRte","updatePosition","rteInst","escapeName","selectedName","iconAdd","iconSync","iconTagOn","iconTagOff","iconTagRemove","componentFirst","State","startEditTag","endEditTag","changeStatus","removeTag","removeSelected","$chk","labelInfo","labelHead","stateInputId","stateInputC","toList","toListCls","__handleStateChange","checkSync","renderClasses","tagRemoved","renderStates","syncStyle","getTarget","cssC","getCommonSelectors","noDisabled","ruleComponents","getTargets","ruleComponent","updateStateVis","addToClasses","startNewTag","$addBtn","$input","endNewTag","onInputKeyUp","addNewTag","checkStates","getState","statesEl","targets","trgs","validSelectors","__getCommonSelectors","_commonSelectors","__common","hasStyle","$btnSyncEl","getStatesC","updateSelector","elSel","__getName","getStyleable","idRes","stateChanged","addSelected","ClassTagView","$states","$statesC","labelStates","getLabel","tmpOpts","renderRes","$classes","isClass","evState","cFirst","__update","selTags","selectorTags","isRule","cOpts","cname","getSelector","setState","setStates","__getCommon","getSelectedTargets","setComponentFirst","getComponentFirst","ClassTagsView","getValid","private","protected","namePreEsc","nameEsc","objLen","TYPE_CLASS","combine","curr","combination","autosave","autoload","stepsBeforeSave","checkLocal","urlStore","urlLoad","jqXHR","onComplete","contentTypeJson","fetchOptions","hasLocal","setItem","getItem","removeItem","clbErr","onResponse","request","typeJson","typeHead","bodyObj","bodyKey","eventStart","eventAfter","eventEnd","eventError","storages","defaultStorages","_disable","remote","RemoteStorage","LocalStorage","currentStorage","loadDefaultProviders","setCurrent","isAutosave","setAutosave","getStepsBeforeSave","setStepsBeforeSave","storage","getStorages","getCurrent","onAfter","keysF","__clearKeys","itemKey","itemKeyR","getCurrentStorage","canAutoload","hideNotStylable","highlightChanged","highlightComputed","showComputed","clearProperties","avoidComputed","Property","__upTargets","callInit","parentProp","isClear","__getFullValue","__getParentProp","kProps","__getClearProps","toProps","applyStyle","__up","__trgEv","propertyUpdate","__upTargetsStyle","addStyleTargets","__p","noTarget","hasValue","getDefaultValue","noParent","parentValue","getParentTarget","camelCase","__parseValue","_up","getParent","__canClearProp","parseValue","valueStr","functionName","numeric","num","withDefault","getFullValue","fnParameter","__parentTarget","toRequire","requires","requiresParent","stylableReq","sector","getProperties","callParentInit","skipInit","fixedValues","isNumberType","PropertyComposite","detached","separator","fromStyle","toStyle","Properties","__upProperties","byName","getSplitSeparator","__getJoin","getValues","isDetached","__clearIn","__upTargetsStyleProps","getStyleFromProps","__setProperties","__getSplitValue","nameProps","allNameProps","__splitValue","props4Nums","__styleHasProps","upValue","valuesStr","Layer","getLayerLabel","getSelectedLayer","selectLayer","removeLayer","moveLayer","getStylePreview","Layers","VALUES_REG","PARTS_REG","PropertyStack","layerSeparator","layerJoin","prepend","layerLabel","selectedLayer","layersColl","__upSelected","__upLayers","__getLayers","getIndex","__select","getLayer","currIndex","getLayers","joinLayers","__getJoinLayers","number","newVal","getStyleFromLayer","upValues","PropertyBase","getStyleFromLayers","layerSelect","__layers","__setLayers","newLayers","layersNew","__parseLayer","parseFn","getLayerSeparator","separatorLayers","__splitStyleName","inLayer","clearProp","icons","iconClose","__destroyFn","onValueChange","_getClbOpts","computedCls","labelEl","clearStyleEl","getClearEl","clearStyle","clearEl","emit","__setValueInput","createdEl","__change","__updateStyle","clearCached","clsType","templateLabel","templateInput","isFull","PropertiesView","appendAtIndex","PropertyCompositeView","PropertyView","propsView","LayerView","iconMove","propertyView","pModel","updateLabel","propsWrapEl","previewEl","getLabelEl","hasPreview","prvEl","getPreviewEl","wrapEl","getPropertiesWrapper","isSelected","LayersView","PropertyStackView","iconPlus","plus","addLayer","layersView","PropertyFileView","valueDef","prvBoxEl","backgroundImage","PropertyNumberView","inputInst","PropertyColorView","__handleChange","InputColor","PropertySelect","getOptionId","isDef","optId","propId","__onOptionChange","PropertySelectView","updateOptions","optionsRes","getOptionLabel","styleAttr","inputH","firstOpt","firstId","PropertyRadio","PropertyRadioView","itemCls","elId","titleAttr","checked","inputHld","inputIn","PropertyNumber","InputNumber","PropertySlider","PropertySliderView","getSliderEl","propertyAdd","propertyRemove","Sector","buildProps","extendBuilded","builded","buildProperties","extendProperties","checkExtend","propsModel","withValue","withParentValue","moProps","ex","pLen","mProps","isolated","mProp","mPProps","buildP","builtIn","Sectors","sect","PropertyFactory","typeNumber","typeColor","typeRadio","typeSelect","typeFile","typeSlider","typeComposite","typeStack","unitsSize","unitsSizeNoPerc","unitsTime","unitsAngle","ss","optsFlex","optsFlexAlign","optsBgSize","optsBgAttach","optsBgRepeat","optsWrap","optsOverflow","optsDir","opstDisplay","optsTransitFn","optsCursor","optsFloat","optsPos","optsTextAlign","optsJustCont","optsAlignCont","optsAlignSelf","optsTransitProp","optsBorderStyle","optsBgPos","optsWeight","optsShadowType","optsFonts","font","fixedFontSizes","fixedLetSpace","requireFlex","__sub","spread","att","fromRes","SectorView","iconCaret","clsPfx","getPropertiesEl","setOpen","renderProperties","SectorsView","evSector","evSectorAdd","evSectorRemove","evSectorUpdate","evProp","evPropAdd","evPropRemove","evPropUp","evLayerSelect","evTarget","propDef","SectView","sectorAdd","sectorRemove","sectorUpdate","upAll","__upSel","__clearStateTarget","upProps","__upProps","trgCustom","__ctn","stateTarget","__getStateTarget","addSector","getSector","_logNoSector","getSectors","removeSector","addProperty","sectorId","getProperty","removeProperty","lastTarget","lastTargetParents","getParentRules","getSelectedParents","targetState","getBuiltIn","getBuiltInAll","addBuiltIn","smConf","devicePreviewMode","hasClasses","useClasses","deviceW","avoidInlineStyle","cssGen","optsSel","cmpRules","otherRules","createType","parentStyles","__upProp","__checkVisibility","sectorVisible","hasVal","isStack","isComposite","canUpdate","__getLayersFromStyle","__getPropsFromStyle","newValue","parentTarget","parentItem","__setParentTarget","newParentStyles","eventCapture","appendInput","clsField","removeView","rerender","getClbOpts","elInput","getInputElem","onUpdate","onEvent","getValueForTarget","setInputValue","postUpdate","renderLabel","tpl","createLabel","getModelValue","i18nAttr","getElInput","renderField","inputs","createInput","hasLabel","noLabel","tmpl","TraitView","updatedCollection","resultName","valResult","getCheckedValue","valueTrue","valueFalse","toInit","targetValue","inputNumber","$unit","labelButton","typesDef","TraitNumberView","TraitSelectView","checkbox","TraitCheckboxView","TraitColorView","TraitButtonView","TraitsView","__onUp","getTraitsViewer","baseView","beforeCache","trackSelection","hasSkip","getChanged","hasUndo","undoExc","chn","hasRedo","getInstance","getStack","getStackGroup","getGroupedStack","createItem","goToGroup","getPointer","goTo","times","snapOffset","getDocumentEl","getContainerEl","getWindowEl","keyHandle","handleScroll","lastScroll","actualScroll","scrollDiff","lastScrollDiff","startPointer","getPointerPos","startPosition","getStartPosition","globScrollDiff","currentPos","glDiff","lockedAxis","detectAxisLock","moveDelta","deltaPre","currentPointer","snapGuides","newDelta","trgX","trgY","axs","trgPoint","statPoint","deltaPoint","trgGuide","isPointIn","trgValue","setGuideLock","lock","ofst","trgName","xPos","yPos","getPos","getPointerPosition","pEv","relX","relY","absX","absY","_Array$prototype","idRe","classRe","htmlRe","tagRe","getElementsByTagName","Cash","__cash","eles","getElementById","parseHTML","cash","ele","camelCaseRe","camelCaseWhitespaceRe","letter","removeProp","guid","webkitMatchesSelector","mozMatchesSelector","msMatchesSelector","oMatchesSelector","isNumeric","isFinite","getCompareFunction","splitValuesRe","getSplitValues","computeStyle","isVariable","computeStyleInt","_value","isForce","cssVariableRe","isCSSVariable","prefixedProps","docEl","vendorsPrefixes","getPrefixedProp","propCC","propUC","prefixedProp","numericProps","animationIterationCount","columnCount","flexGrow","flexShrink","fontWeight","lineHeight","orphans","widows","getSuffixedValue","setProperty","dataNamespace","dataAttributeRe","getDataCache","dataset","getExtraSpace","xAxis","hasNamespaces","ns1","ns2","removeEventListeners","_ref","hasData","_this","boxSizing","includeMargins","getEventsCache","parseEventName","removeEvent","namespaces","eventCache","_ref2","eventFullName","_this2","_parseEventName","_one","_this3","_parseEventName2","finalCallback","namespace","thisArg","one","readyState","evt","_parseEventName3","createEvent","initEvent","selectOneRe","selectMultipleRe","selectedIndex","getValueSelectSingle","getValueSelectMultiple","queryEncodeSpaceRe","skippableRe","checkableRe","serialize","elements","queryEncode","isMultiple","eleValue","containers","fragmentRe","singleTagRe","td","initContainers","$1","insertContent","isStr","insertAdjacentHTML","insertElement","_this4","insertAfter","_this5","_this6","_this7","_this8","_this9","prependTo","_this10","$eles","replaceAll","docEle","clientTop","contents","nextElementSibling","not","parents","previousElementSibling","siblings","KEY_ATTR","oldEl","newEl","total","oEvent","keyCodeVal","defineProperty","vNodes","vNodesArr","vnode","TypeError","setTimeoutFunc","_state","_handled","_deferreds","doResolve","deferred","_immediateFn","onFulfilled","onRejected","finale","_unhandledRejectionFn","Handler","prom","promiseFinally","allSettled","race","setImmediate","rej","req","XMLHttpRequest","withCredentials","statusText","responseText","onProgress","onprogress","send","literals","substs","raw","lit","subst","elT","elL","borderOffset","freezeClass","relative","ignoreModels","offTop","offLeft","$document","dropContent","selectOnEnd","activeTextModel","getScale","getDocuments","dropModel","updateTextViewCursorPosition","targetDoc","setContentEditable","toggleSortCursor","clonedEl","computed","moveDragHelper","posY","posX","dragHelperStyle","useBody","createPlaceholder","ins","prevTarget","sourceEl","clearSelection","getTargetModel","isTextableActive","tempModel","selectTargetModel","targetModel","dsp","eO","rY","rX","mousePos","eventMove","sourceModel","dimsFromTarget","lastDims","findPosition","disableTextable","movePlaceholder","prevTargetDim","$plh","isInFlow","styleInFlow","$parent","overflow","propFloat","trgModel","dragInfo","dropInfo","targetP","validResult","getDim","cacheDimsP","getChildrenDim","cacheDims","nearBorders","targetParent","getTargetFromEl","targetPrev","nearElBorders","getCurrentPos","offsets","getCurrentView","elIndex","indexEl","leftLimit","xLimit","yLimit","xCenter","yCenter","dimDown","trgDim","elDim","marg","pT","pL","dst","modelToDrop","srcEl","warns","targetCollection","srcIndex","sameCollection","errors","onUpdateContainer","minDim","maxDim","getBoundingRect","setup","hdl","createHandler","updateContainer","forceShow","handleMouseDown","getParentEl","attrName","parentRect","handlerAttr","clickedHandler","rectDim","startPos","parentDim","toggleFrames","mouseFetch","calc","updateRect","getSelectedHandler","isHandler","deltaX","deltaY","parentW","parentH","startW","startH","normalizeFloat","ratioActive","ratio","getGlobal","elProt","Element","defCls","customUI","appendStyles","prepand","objOrig","objNew","keysNew","origValue","upFirst","nativeDnD","isCommentNode","__cashData","rectText","selectNode","getKeyCode","__gjsv","chars","runtime","Op","hasOwn","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","enumerable","configurable","writable","innerFn","outerFn","tryLocsList","protoGenerator","Generator","_invoke","GenStateSuspendedStart","arg","GenStateExecuting","GenStateCompleted","doneResult","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","GenStateSuspendedYield","makeInvokeMethod","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","getProto","getPrototypeOf","NativeIteratorPrototype","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","__await","unwrapped","previousPromise","callInvokeWithMethodAndArg","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","iterable","iteratorMethod","displayName","isGeneratorFunction","genFun","setPrototypeOf","__proto__","awrap","async","skipTempReset","rootRecord","rval","exception","loc","caught","hasCatch","hasFinally","finallyEntry","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","Function","webpackContext","webpackContextResolve","__webpack_require__","_arrayLikeToArray","arr2","asyncGeneratorStep","_next","_throw","_asyncToGenerator","_classCallCheck","Constructor","_defineProperties","descriptor","_createClass","_defineProperty","_getPrototypeOf","_setPrototypeOf","_inherits","subClass","superClass","_objectWithoutProperties","excluded","sourceKeys","getOwnPropertySymbols","sourceSymbolKeys","_possibleConstructorReturn","ReferenceError","_slicedToArray","_i","_s","_arr","_n","_d","unsupportedIterableToArray","_taggedTemplateLiteral","strings","defineProperties","_toConsumableArray","arrayLikeToArray","_typeof","_unsupportedIterableToArray","minLen","ArrayProto","ObjProto","SymbolProto","supportsArrayBuffer","ArrayBuffer","supportsDataView","DataView","nativeIsArray","nativeKeys","nativeCreate","nativeIsView","isView","_isNaN","_isFinite","hasEnumBug","nonEnumerableProps","MAX_ARRAY_INDEX","pow","restArguments","tagTester","nodelist","Int8Array","hasStringTagBug","isIE11","Map","isDataView","getInt8","isArrayBuffer","buffer","isSymbol","constant","createSizePropertyCheck","getSizeProperty","sizeProperty","shallowProperty","typedArrayPattern","collectNonEnumProps","emulatedSet","nonEnumIdx","proto","isMatch","_keys","_wrapped","toBufferView","bufferSource","Uint8Array","byteOffset","valueOf","tagDataView","aStack","bStack","deepEq","areArrays","aCtor","bCtor","allKeys","ie11fingerprint","weakMapMethods","forEachName","commonInit","mapTail","mapMethods","setMethods","functions","createAssigner","keysFunc","baseCreate","Ctor","extendOwn","tap","interceptor","toPath","deepGet","defaultValue","identity","optimizeCb","argCount","accumulator","baseIteratee","mapObject","currentKey","propertyOf","accum","getTime","createEscaper","escaper","testRegexp","replaceRegexp","templateSettings","evaluate","interpolate","noMatch","escapes","escapeChar","bareIdentifier","oldSettings","argument","variable","idCounter","_chain","executeBound","sourceFunc","boundFunc","callingContext","boundArgs","callArgs","memoize","hasher","throttle","later","leading","throttled","_now","trailing","immediate","passed","debounced","_args","negate","compose","memo","findKey","createPredicateIndexFinder","sortedIndex","low","high","createIndexFinder","predicateFind","createReduce","reducer","guard","contextPath","lastComputed","rand","criteria","reStrSymbol","keyInObj","compact","otherArrays","uniq","isSorted","seen","arrays","intersection","argsLength","unzip","chainResult","mixin","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","getter","__esModule","fromElement","noticeOnUnload","forceClass","defaultCommand","mediaCondition","jsInHtml","multipleSelection","optsHtml","optsCss","avoidDefaults","dragMode","cssIcons","arrowUp","i18n","storageManager","richTextEditor","codeManager","cssComposer","multiFrames","Selectable","Selected","hasComponent","getByComponent","timedInterval","updateItr","deps","Window","ar","Extender","logs","warning","EditorModel","editing","clipboard","previousModel","storables","modules","toLoad","pageManager","toLog","attrsOrig","loadModule","updateChanges","_checkReady","listenLog","eventFrom","eventTo","onbeforeunload","moduleName","Mod","cfgParent","cfg","destroyed","__skip","handleUpdates","lastComponent","allComponents","multiple","mltSel","toggleSelected","selColl","selIndex","removeComponent","getJs","avoidProt","avoidProtected","protCss","storeData","editingCmp","loadData","cacheLoad","defaultRunning","grapesjs","destroyAll","logNs","colorPicker","varName","contEl","shallowCanvasEl","addComponents","getSelectedToStyle","selectToggle","setDevice","getDevice","getProject","loadProject","getDirtyCount","setCustomRte","setCustomParserCss","setDragMode","onReady","plugins","agent","isIE","originalCreateHTMLDocument","DOMImplementation","createHTMLDocument","implementation","polyfills","plugin","defaultConfig","autorender","pluginsOpts","__GJS_VERSION__","headless","Editor","pluginId","plgOptions","wplg","loadOnStart"],"sourceRoot":""} \ No newline at end of file diff --git a/docs/api/storage_manager.md b/docs/api/storage_manager.md index efb105874..35345c839 100644 --- a/docs/api/storage_manager.md +++ b/docs/api/storage_manager.md @@ -44,7 +44,6 @@ storageManager.add(...); * [setAutosave][4] * [getStepsBeforeSave][5] * [setStepsBeforeSave][6] -* [setStepsBeforeSave][6] * [getStorages][7] * [getCurrent][8] * [getCurrentStorage][9] diff --git a/index.d.ts b/index.d.ts index 22f2748b8..700332f00 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,1830 +1,1825 @@ declare namespace Backbone { - interface ModelProperties {} - - class Model { - constructor(attr?:T, opt?:any) - attributes : T - collection: Collection - cid: string - get(prop:K) : T[K] - set(prop:K , val:T[K]) : void - defaults() : T - on(eventName: string, callback: (...args: any[]) => void) - toJSON(options?: any): any - } - - class Collection> { - models: TModel[]; - length: number; - - add(model: {} | TModel): TModel; - add(models: Array<{} | TModel>): TModel[]; - find(iterator: (item : TModel) => boolean, context?: any): TModel; - remove(model: {} | TModel): TModel; - remove(models: Array<{} | TModel>): TModel[]; - reset(models?: Array<{} | TModel>): TModel[]; - } - - interface GenericModel extends Model<{}> {} + interface ModelProperties {} + + class Model { + constructor(attr?: T, opt?: any); + attributes: T; + collection: Collection; + cid: string; + get(prop: K): T[K]; + set(prop: K, val: T[K]): void; + defaults(): T; + on(eventName: string, callback: (...args: any[]) => void): this; + toJSON(options?: any): any; } - declare module grapesjs { - interface EditorConfig { - /** Selector which indicates where render the editor */ - container?: string | HTMLElement + class Collection> { + models: TModel[]; + length: number; - /** If true, auto-render the content */ - autorender? : boolean + add(model: {} | TModel): TModel; + add(models: Array<{} | TModel>): TModel[]; + find(iterator: (item: TModel) => boolean, context?: any): TModel; + remove(model: {} | TModel): TModel; + remove(models: Array<{} | TModel>): TModel[]; + reset(models?: Array<{} | TModel>): TModel[]; + } - /** Array of plugins to execute on start */ - plugins? : [] + interface GenericModel extends Model<{}> {} +} - /** Custom options for plugins */ - pluginsOpts?: Record +declare module grapesjs { + interface EditorConfig { + /** Selector which indicates where render the editor */ + container?: string | HTMLElement; - /** Init headless editor */ - headless?: boolean + /** If true, auto-render the content */ + autorender?: boolean; - /** Style prefix */ - stylePrefix?: string + /** Array of plugins to execute on start */ + plugins?: any[]; - /** HTML string or object of components */ - components?: string, + /** Custom options for plugins */ + pluginsOpts?: Record; - /** CSS string or object of rules */ - style?: string, + /** Init headless editor */ + headless?: boolean; - /** If true, will fetch HTML and CSS from selected container */ - fromElement?: boolean, + /** Style prefix */ + stylePrefix?: string; - /** Show an alert before unload the page with unsaved changes */ - noticeOnUnload?: number, + /** HTML string or object of components */ + components?: string; - /** Show paddings and margins */ - showOffsets?: boolean, + /** CSS string or object of rules */ + style?: string; - /** Show paddings and margins on selected component */ - showOffsetsSelected?: boolean, + /** If true, will fetch HTML and CSS from selected container */ + fromElement?: boolean; - /** On creation of a new Component (via object), if the 'style' attribute is not - * empty, all those roles will be moved in its new class */ - forceClass?: boolean, + /** Show an alert before unload the page with unsaved changes */ + noticeOnUnload?: number; - /** Height for the editor container */ - height?: string, + /** Show paddings and margins */ + showOffsets?: boolean; - /** Width for the editor container */ - width?: string, + /** Show paddings and margins on selected component */ + showOffsetsSelected?: boolean; - /** Type of logs to print with the logger (by default is used the devtool console). - * Available by default: debug, info, warning, error - * You can use `false` to disable all of them or `true` to print all of them */ - log?: ('debug'|'info'|'warning'|'error')[] + /** On creation of a new Component (via object), if the 'style' attribute is not + * empty, all those roles will be moved in its new class */ + forceClass?: boolean; - /** By default Grapes injects base CSS into the canvas. For example, it sets body margin to 0 - * and sets a default background color of white. This CSS is desired in most cases. - * use this property if you wish to overwrite the base CSS to your own CSS. This is most - * useful if for example your template is not based off a document with 0 as body margin. */ - baseCss?: string, + /** Height for the editor container */ + height?: string; - /** CSS that could only be seen (for instance, inside the code viewer) */ - protectedCss?: string, + /** Width for the editor container */ + width?: string; - /** CSS for the iframe which containing the canvas, useful if you need to custom something inside - * (eg. the style of the selected component) */ - canvasCss?: string, + /** Type of logs to print with the logger (by default is used the devtool console). + * Available by default: debug, info, warning, error + * You can use `false` to disable all of them or `true` to print all of them */ + log?: ("debug" | "info" | "warning" | "error")[]; - /** Default command */ - defaultCommand?: string, + /** By default Grapes injects base CSS into the canvas. For example, it sets body margin to 0 + * and sets a default background color of white. This CSS is desired in most cases. + * use this property if you wish to overwrite the base CSS to your own CSS. This is most + * useful if for example your template is not based off a document with 0 as body margin. */ + baseCss?: string; - /** Show a toolbar when the component is selected */ - showToolbar?: boolean, + /** CSS that could only be seen (for instance, inside the code viewer) */ + protectedCss?: string; - // Allow script tag importing - // @deprecated in favor of `config.parser.optionsHtml.allowScripts` - // allowScripts: 0, + /** CSS for the iframe which containing the canvas, useful if you need to custom something inside + * (eg. the style of the selected component) */ + canvasCss?: string; - /** If true render a select of available devices */ - showDevices?: boolean, + /** Default command */ + defaultCommand?: string; - /** When enabled, on device change media rules won't be created */ - devicePreviewMode?: boolean, + /** Show a toolbar when the component is selected */ + showToolbar?: boolean; - /** The condition to use for media queries, eg. 'max-width' - * Comes handy for mobile-first cases */ - mediaCondition?: string, + // Allow script tag importing + // @deprecated in favor of `config.parser.optionsHtml.allowScripts` + // allowScripts: 0, - /** Starting tag for variable inside scripts in Components */ - tagVarStart?: string, + /** If true render a select of available devices */ + showDevices?: boolean; - /** Ending tag for variable inside scripts in Components */ - tagVarEnd?: string, + /** When enabled, on device change media rules won't be created */ + devicePreviewMode?: boolean; - /** When false, removes empty text nodes when parsed, unless they contain a space */ - keepEmptyTextNodes?: boolean, + /** The condition to use for media queries, eg. 'max-width' + * Comes handy for mobile-first cases */ + mediaCondition?: string; - /** Return JS of components inside HTML from 'editor.getHtml()' */ - jsInHtml?: boolean, + /** Starting tag for variable inside scripts in Components */ + tagVarStart?: string; - /** Enable native HTML5 drag and drop */ - nativeDnD?: boolean, + /** Ending tag for variable inside scripts in Components */ + tagVarEnd?: string; - /** Enable multiple selection */ - multipleSelection?: boolean, + /** When false, removes empty text nodes when parsed, unless they contain a space */ + keepEmptyTextNodes?: boolean; - /** Show the wrapper component in the final code, eg. in editor.getHtml() */ - exportWrapper?: boolean, + /** Return JS of components inside HTML from 'editor.getHtml()' */ + jsInHtml?: boolean; - /** The wrapper, if visible, will be shown as a `` */ - wrapperIsBody?: boolean, + /** Enable native HTML5 drag and drop */ + nativeDnD?: boolean; - /** Pass default available options wherever `editor.getHtml()` is called */ - optsHtml?: Record, + /** Enable multiple selection */ + multipleSelection?: boolean; - /** Pass default available options wherever `editor.getCss()` is called */ - optsCss?: Record, + /** Show the wrapper component in the final code, eg. in editor.getHtml() */ + exportWrapper?: boolean; - /** Usually when you update the `style` of the component this changes the - * element's `style` attribute. Unfortunately, inline styling doesn't allow - * use of media queries (@media) or even pseudo selectors (eg. :hover). - * When `avoidInlineStyle` is true all styles are inserted inside the css rule - * @deprecated Don't use this option, we don't support inline styling anymore */ - avoidInlineStyle?: boolean, + /** The wrapper, if visible, will be shown as a `` */ + wrapperIsBody?: boolean; - /** Avoid default properties from storable JSON data, like `components` and `styles`. - * With this option enabled your data will be smaller (usefull if need to - * save some storage space) */ - avoidDefaults?: boolean, + /** Pass default available options wherever `editor.getHtml()` is called */ + optsHtml?: Record; - /** (experimental) - * The structure of components is always on the screen but it's not the same - * for style rules. When you delete a component you might leave a lot of styles - * which will never be used again, therefore they might be removed. - * With this option set to true, styles not used from the CSS generator (so in - * any case where `CssGenerator.build` is used) will be removed automatically. - * But be careful, not always leaving the style not used mean you wouldn't - * use it later, but this option comes really handy when deal with big templates. */ - clearStyles?: boolean, + /** Pass default available options wherever `editor.getCss()` is called */ + optsCss?: Record; - /** Specify the global drag mode of components. By default, components are moved - * following the HTML flow. Two other options are available: - * 'absolute' - Move components absolutely (design tools way) - * 'translate' - Use translate CSS from transform property - * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 */ - dragMode?: boolean, + /** Usually when you update the `style` of the component this changes the + * element's `style` attribute. Unfortunately, inline styling doesn't allow + * use of media queries (@media) or even pseudo selectors (eg. :hover). + * When `avoidInlineStyle` is true all styles are inserted inside the css rule + * @deprecated Don't use this option, we don't support inline styling anymore */ + avoidInlineStyle?: boolean; - /** When the editor is placed in a scrollable container (eg. modals) this might - * cause elements inside the canvas (eg. floating toolbars) to be misaligned. - * To avoid that, you can specify an array of DOM elements on which their scroll will - * trigger the canvas update. - * Be default, if the array is empty, the first parent element will be appended. - * listenToEl: [document.querySelector('#scrollable-el')], */ - listenToEl?: HTMLElement[], - - /** Import asynchronously CSS to use as icons */ - cssIcons?: string, - - /** Dom element */ - el?: string, - - /** Configurations for I18n */ - i18n?: Record, - - /** Configurations for Undo Manager */ - undoManager?: Record | boolean, - - /** Configurations for Asset Manager */ - assetManager?: AssetManagerConfig | boolean, - - /** Configurations for Canvas */ - canvas?: CanvasConfig | boolean, - - /** Configurations for Layers */ - layers?: Record | boolean, - - /** Configurations for Storage Manager */ - storageManager?: StorageManagerConfig | boolean, - - /** Configurations for Rich Text Editor */ - richTextEditor?: RichTextEditorConfig | boolean, - - /** Configurations for DomComponents */ - domComponents?: DomComponentsConfig | boolean, - - /** Configurations for Modal Dialog */ - modal?: ModalConfig | boolean, - - /** Configurations for Code Manager */ - codeManager?: CodeManagerConfig | boolean, - - /** Configurations for Panels */ - panels?: PanelsConfig | boolean, - - /** Configurations for Commands */ - commands?: CommandsConfig | boolean, - - /** Configurations for Css Composer */ - cssComposer?: CssComposerConfig | boolean, - - /** Configurations for Selector Manager */ - selectorManager?: SelectorManagerConfig | boolean, - - /** Configurations for Device Manager */ - deviceManager?: DeviceManagerConfig | boolean, - - /** Configurations for Style Manager */ - styleManager?: StyleManagerConfig | boolean, - - /** Configurations for Block Manager */ - blockManager?: BlockManagerConfig | boolean, - - /** Configurations for Trait Manager */ - traitManager?: TraitManagerConfig | boolean, - - /** Texts **/ - textViewCode?: string, - - /** Keep unused styles within the editor **/ - keepUnusedStyles?: 0, - } - - interface AssetManagerConfig { - assets?: Array; - noAssets?: string; - stylePrefix?: string; - upload?: boolean; - uploadName?: string; - headers?: object; - params?: object; - credentials?: RequestCredentials; - multiUpload?: boolean; - autoAdd?: boolean; - uploadText?: string; - addBtnText?: string; - customFetch?: Function; - uploadFile?: Function; - embedAsBase64?: boolean; - handleAdd?: Function; - dropzone?: boolean; - openAssetsOnDrop?: number; - dropzoneContent?: string; - modalTitle?: string; - inputPlaceholder?: string; - } - - interface CanvasConfig { - stylePrefix?: string; - scripts?: Array; - styles?: Array; - customBadgeLabel?: Function; - autoscrollLimit?: number; - notTextable?: Array; - } - - interface StyleManagerConfig { - stylePrefix?: string; - sectors?: Array; - appendTo?: HTMLElement | string; - textNoElement?: string; - hideNotStylable?: boolean; - highlightChanged?: boolean; - highlightComputed?: boolean; - showComputed?: boolean; - clearProperties?: boolean; - avoidComputed?: Array; - } - - interface BlockManagerConfig { - appendTo?: HTMLElement | string; - blocks: Array; - } - - interface RichTextEditorConfig { - stylePrefix?: string; - adjustToolbar?: boolean; - actions?: Array; - } - - interface TraitManagerConfig { - stylePrefix?: string; - appendTo?: HTMLElement | string; - labelContainer?: string; - labelPlhText?: string; - labelPlhRef?: string; - optionsTarget?: Array; - textNoElement?: string; - } - - interface StorageManagerConfig { - id?: string; - autosave?: boolean; - autoload?: boolean; - type?: "local" | "remote"; - stepsBeforeSave?: number; - storeComponents?: boolean; - storeStyles?: boolean; - storeHtml?: boolean; - storeCss?: boolean; - checkLocal?: boolean; - params?: object; - headers?: object; - urlStore?: string; - urlLoad?: string; - contentTypeJson?: boolean; - credentials?: RequestCredentials; - - beforeSend(jqXHR: any, settings: object): void; - onComplete(jqXHR: any, status: any): void; - } - - interface DomComponentsConfig { - stylePrefix?: string; - wrapperId?: string; - wrapperName?: string; - wrapper?: DomComponentsWrapperConfig; - components?: Array; - imageCompClass?: string; - oAssetsOnCreate?: boolean; - storeWrapper?: boolean; - voidElements?: Array; - } - - interface DomComponentsWrapperConfig { - removable?: boolean, - copyable?: boolean, - draggable?: boolean, - // TODO: Type custom blocks and components - components?: Array, - traits?: Array, - stylable?: Array - } - - interface ModalConfig { - stylePrefix?: string; - title?: string; - content?: string; - backdrop?: boolean; - } - - interface CodeManagerConfig { - stylePrefix?: string; - inlineCss?: boolean; - } - - interface PanelsConfig { - stylePrefix?: string; - defaults?: Array; - em?: object; - delayBtnsShow?: number; - } - - interface CommandsConfig { - ESCAPE_KEY?: number; - stylePrefix?: string; - defaults?: Array; - em?: object; - firstCentered?: boolean; - newFixedH?: boolean; - minComponentH?: number; - minComponentW?: number; - } - - interface CssComposerConfig { - stylePrefix?: string; - staticRules?: string; - rules?: Array; - } - - interface SelectorManagerConfig { - stylePrefix?: string; - appendTo?: HTMLElement | string; - selectors?: Array; - label?: string; - statesLabel?: string; - selectedLabel?: string; - states?: Array; - } - - interface DeviceManagerConfig { - devices?: Array; - deviceLabel?: string; - } - - function init(config : EditorConfig) : Editor; - - interface Trait extends Backbone.Model { - target : Component - - /** Return all the properties */ - props() : TraitOptions; - targetUpdated() : void; - getValue(): string; - getTargetValue(): string; - setTargetValue(value: any, opts: object) : void - setValueFromInput(value : any, final: boolean, opts: object) : void - /** - * Get the initial value of the trait - */ - getInitValue() : string - } - - type TraitType = 'text' - | 'number' - | 'checkbox' - | 'select' - | string - - interface TraitOptions { - type: TraitType; - label: string, - name: string, - min?: string, - max?: string, - unit?: string, - step?: number, - value?: string, - target?: Component, - default?: string, - placeholder?: string, - changeProp?: number, - options?: SelectOption[] - [key: string]: any - } - - interface PanelOptions { - id: string, - content: string, - visible: boolean, - buttons: Button[], - } + /** Avoid default properties from storable JSON data, like `components` and `styles`. + * With this option enabled your data will be smaller (usefull if need to + * save some storage space) */ + avoidDefaults?: boolean; - interface Panel extends Backbone.Model { + /** (experimental) + * The structure of components is always on the screen but it's not the same + * for style rules. When you delete a component you might leave a lot of styles + * which will never be used again, therefore they might be removed. + * With this option set to true, styles not used from the CSS generator (so in + * any case where `CssGenerator.build` is used) will be removed automatically. + * But be careful, not always leaving the style not used mean you wouldn't + * use it later, but this option comes really handy when deal with big templates. */ + clearStyles?: boolean; - } + /** Specify the global drag mode of components. By default, components are moved + * following the HTML flow. Two other options are available: + * 'absolute' - Move components absolutely (design tools way) + * 'translate' - Use translate CSS from transform property + * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 */ + dragMode?: boolean; - interface Button extends Backbone.Model { + /** When the editor is placed in a scrollable container (eg. modals) this might + * cause elements inside the canvas (eg. floating toolbars) to be misaligned. + * To avoid that, you can specify an array of DOM elements on which their scroll will + * trigger the canvas update. + * Be default, if the array is empty, the first parent element will be appended. + * listenToEl: [document.querySelector('#scrollable-el')], */ + listenToEl?: HTMLElement[]; - } + /** Import asynchronously CSS to use as icons */ + cssIcons?: string; - interface ButtonOptions { - id: string, - label: string, - tagName: 'span', - className: string, - command: string | ((editor : Editor, opts? : any) => void), - context: string, - buttons: any[], - attributes: object, - options: object, - active: boolean, - dragDrop: boolean, - togglable: boolean, - runDefaultCommand: boolean, - stopDefaultCommand: boolean, - disable: boolean - } - - interface ComponentView { - model : Component - - onRender(opts: { - editor?: Editor, - model? : Component, - el? : HTMLElement - }) : void; - } - - interface View {} - - interface LayerManager { - /** - * Set new root for layers - * @param el Component to be set as the root - */ - setRoot(el : HTMLElement|Component|String) : this - /** Get the root of layers */ - getRoot() : Component - /** Return the view of layers */ - getAll() : View - } - - interface TraitView { - noLabel?: boolean - templateInput?: string | ((options: { - trait : Trait - }) => string) - eventCapture? : string[] - - onEvent? : (options: { - elInput : HTMLElement, - component : Component, - event : any - }) => void - onUpdate? : (options: { - elInput : HTMLElement, - component : Component - }) => void - createInput? : (options: { - trait : Trait - }) => HTMLElement - createLabel?: (options: { - label : string - }) => string - } - - interface TraitManager { - /** - * Add new trait type - * @param name Type name - * @param methods Object representing the trait - */ - addType(name : string, trait : TraitView) : void - /** - * Get trait type - * @param name Type name - */ - getType(name : string) : Object - /** - * Get all trait types - */ - getTypes() : Object - } + /** Dom element */ + el?: string; + + /** Configurations for I18n */ + i18n?: Record; + + /** Configurations for Undo Manager */ + undoManager?: Record | boolean; + + /** Configurations for Asset Manager */ + assetManager?: AssetManagerConfig | boolean; + + /** Configurations for Canvas */ + canvas?: CanvasConfig | boolean; + + /** Configurations for Layers */ + layers?: Record | boolean; + + /** Configurations for Storage Manager */ + storageManager?: StorageManagerConfig | boolean; + + /** Configurations for Rich Text Editor */ + richTextEditor?: RichTextEditorConfig | boolean; + + /** Configurations for DomComponents */ + domComponents?: DomComponentsConfig | boolean; + + /** Configurations for Modal Dialog */ + modal?: ModalConfig | boolean; + + /** Configurations for Code Manager */ + codeManager?: CodeManagerConfig | boolean; + + /** Configurations for Panels */ + panels?: PanelsConfig | boolean; + + /** Configurations for Commands */ + commands?: CommandsConfig | boolean; + + /** Configurations for Css Composer */ + cssComposer?: CssComposerConfig | boolean; + + /** Configurations for Selector Manager */ + selectorManager?: SelectorManagerConfig | boolean; + + /** Configurations for Device Manager */ + deviceManager?: DeviceManagerConfig | boolean; + + /** Configurations for Style Manager */ + styleManager?: StyleManagerConfig | boolean; + + /** Configurations for Block Manager */ + blockManager?: BlockManagerConfig | boolean; + + /** Configurations for Trait Manager */ + traitManager?: TraitManagerConfig | boolean; + + /** Texts **/ + textViewCode?: string; + + /** Keep unused styles within the editor **/ + keepUnusedStyles?: 0; + } + + interface AssetManagerConfig { + assets?: Array; + noAssets?: string; + stylePrefix?: string; + upload?: boolean; + uploadName?: string; + headers?: object; + params?: object; + credentials?: RequestCredentials; + multiUpload?: boolean; + autoAdd?: boolean; + uploadText?: string; + addBtnText?: string; + customFetch?: Function; + uploadFile?: Function; + embedAsBase64?: boolean; + handleAdd?: Function; + dropzone?: boolean; + openAssetsOnDrop?: number; + dropzoneContent?: string; + modalTitle?: string; + inputPlaceholder?: string; + } + + interface CanvasConfig { + stylePrefix?: string; + scripts?: Array; + styles?: Array; + customBadgeLabel?: Function; + autoscrollLimit?: number; + notTextable?: Array; + } + + interface StyleManagerConfig { + stylePrefix?: string; + sectors?: Array; + appendTo?: HTMLElement | string; + textNoElement?: string; + hideNotStylable?: boolean; + highlightChanged?: boolean; + highlightComputed?: boolean; + showComputed?: boolean; + clearProperties?: boolean; + avoidComputed?: Array; + } + + interface BlockManagerConfig { + appendTo?: HTMLElement | string; + blocks: Array; + } + + interface RichTextEditorConfig { + stylePrefix?: string; + adjustToolbar?: boolean; + actions?: Array; + } + + interface TraitManagerConfig { + stylePrefix?: string; + appendTo?: HTMLElement | string; + labelContainer?: string; + labelPlhText?: string; + labelPlhRef?: string; + optionsTarget?: Array; + textNoElement?: string; + } + + interface StorageManagerConfig { + id?: string; + autosave?: boolean; + autoload?: boolean; + type?: "local" | "remote"; + stepsBeforeSave?: number; + storeComponents?: boolean; + storeStyles?: boolean; + storeHtml?: boolean; + storeCss?: boolean; + checkLocal?: boolean; + params?: object; + headers?: object; + urlStore?: string; + urlLoad?: string; + contentTypeJson?: boolean; + credentials?: RequestCredentials; + + beforeSend(jqXHR: any, settings: object): void; + onComplete(jqXHR: any, status: any): void; + } + + interface DomComponentsConfig { + stylePrefix?: string; + wrapperId?: string; + wrapperName?: string; + wrapper?: DomComponentsWrapperConfig; + components?: Array; + imageCompClass?: string; + oAssetsOnCreate?: boolean; + storeWrapper?: boolean; + voidElements?: Array; + } + + interface DomComponentsWrapperConfig { + removable?: boolean; + copyable?: boolean; + draggable?: boolean; + // TODO: Type custom blocks and components + components?: Array; + traits?: Array; + stylable?: Array; + } + + interface ModalConfig { + stylePrefix?: string; + title?: string; + content?: string; + backdrop?: boolean; + } + + interface CodeManagerConfig { + stylePrefix?: string; + inlineCss?: boolean; + } + + interface PanelsConfig { + stylePrefix?: string; + defaults?: Array; + em?: object; + delayBtnsShow?: number; + } + + interface CommandsConfig { + ESCAPE_KEY?: number; + stylePrefix?: string; + defaults?: Array; + em?: object; + firstCentered?: boolean; + newFixedH?: boolean; + minComponentH?: number; + minComponentW?: number; + } + + interface CssComposerConfig { + stylePrefix?: string; + staticRules?: string; + rules?: Array; + } + + interface SelectorManagerConfig { + stylePrefix?: string; + appendTo?: HTMLElement | string; + selectors?: Array; + label?: string; + statesLabel?: string; + selectedLabel?: string; + states?: Array; + } + + interface DeviceManagerConfig { + devices?: Array; + deviceLabel?: string; + } + + function init(config: EditorConfig): Editor; + interface Trait extends Backbone.Model { + target: Component; + + /** Return all the properties */ + props(): TraitOptions; + targetUpdated(): void; + getValue(): string; + getTargetValue(): string; + setTargetValue(value: any, opts: object): void; + setValueFromInput(value: any, final: boolean, opts: object): void; /** - * Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins. - * You get the Editor instance on init method and you can pass options via its [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/editor/config/config.js) - * - * ```js - * const editor = grapesjs.init({ - * // options + * Get the initial value of the trait + */ + getInitValue(): string; + } + + type TraitType = "text" | "number" | "checkbox" | "select" | string; + + interface TraitOptions { + type: TraitType; + label: string; + name: string; + min?: string; + max?: string; + unit?: string; + step?: number; + value?: string; + target?: Component; + default?: string; + placeholder?: string; + changeProp?: number; + options?: SelectOption[]; + [key: string]: any; + } + + interface PanelOptions { + id: string; + content: string; + visible: boolean; + buttons: Button[]; + } + + interface Panel extends Backbone.Model {} + + interface Button extends Backbone.Model {} + + interface ButtonOptions { + id: string; + label: string; + tagName: "span"; + className: string; + command: string | ((editor: Editor, opts?: any) => void); + context: string; + buttons: any[]; + attributes: object; + options: object; + active: boolean; + dragDrop: boolean; + togglable: boolean; + runDefaultCommand: boolean; + stopDefaultCommand: boolean; + disable: boolean; + } + + interface ComponentView { + model: Component; + + onRender(opts: { + editor?: Editor; + model?: Component; + el?: HTMLElement; + }): void; + } + + interface View {} + + interface LayerManager { + /** + * Set new root for layers + * @param el Component to be set as the root + */ + setRoot(el: HTMLElement | Component | String): this; + /** Get the root of layers */ + getRoot(): Component; + /** Return the view of layers */ + getAll(): View; + } + + interface TraitView { + noLabel?: boolean; + templateInput?: string | ((options: { trait: Trait }) => string); + eventCapture?: string[]; + + onEvent?: (options: { + elInput: HTMLElement; + component: Component; + event: any; + }) => void; + onUpdate?: (options: { + elInput: HTMLElement; + component: Component; + }) => void; + createInput?: (options: { trait: Trait }) => HTMLElement; + createLabel?: (options: { label: string }) => string; + } + + interface TraitManager { + /** + * Add new trait type + * @param name Type name + * @param methods Object representing the trait + */ + addType(name: string, trait: TraitView): void; + /** + * Get trait type + * @param name Type name + */ + getType(name: string): Object; + /** + * Get all trait types + */ + getTypes(): Object; + } + + /** + * Editor contains the top level API which you'll probably use to customize the editor or extend it with plugins. + * You get the Editor instance on init method and you can pass options via its [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/editor/config/config.js) + * + * ```js + * const editor = grapesjs.init({ + * // options + * }); + * ``` + * + * ## Available Events + * + * You can make use of available events in this way + * ```js + * editor.on('EVENT-NAME', (some, argument) => { + * // do something + * }) + * ``` + * + * * `update` - The structure of the template is updated (its HTML/CSS) + * * `undo` - Undo executed + * * `redo` - Redo executed + * * `load` - Editor is loaded + * + * ### Components + * Check the [Components](/api/components.html) module. + * ### Keymaps + * Check the [Keymaps](/api/keymaps.html) module. + * ### Style Manager + * Check the [Style Manager](/api/style_manager.html) module. + * ### Storage + * Check the [Storage](/api/storage_manager.html) module. + * ### Canvas + * Check the [Canvas](/api/canvas.html) module. + * ### RTE + * Check the [Rich Text Editor](/api/rich_text_editor.html) module. + * ### Commands + * Check the [Commands](/api/commands.html) module. + * ### Selectors + * Check the [Selectors](/api/selector_manager.html) module. + * ### Blocks + * Check the [Blocks](/api/block_manager.html) module. + * ### Assets + * Check the [Assets](/api/assets.html) module. + * ### Modal + * Check the [Modal](/api/modal_dialog.html) module. + * ### Devices + * Check the [Devices](/api/device_manager.html) module. + * ### Parser + * Check the [Parser](/api/parser.html) module. + * ### Pages + * Check the [Pages](/api/pages.html) module. + * + * ## Methods + */ + interface Editor { + DomComponents: Components; + LayerManager: LayerManager; + CssComposer: CssComposer; + StorageManager: StorageManager; + AssetManager: AssetManager; + BlockManager: BlockManager; + TraitManager: TraitManager; + SelectorManager: SelectorManager; + CodeManager: object; + Commands: Commands; + Keymaps: Keymaps; + Modal: Modal; + Panels: Panels; + StyleManager: StyleManager; + Canvas: Canvas; + UndoManager: UndoManager; + DeviceManager: object; + RichTextEditor: RichTextEditor; + Parser: Parser; + Utils: object; + Config: EditorConfig | object; + + /** + * Returns configuration object + * @param [prop] - Property name + * @returns Returns the configuration object or + * the value of the specified property + */ + getConfig(prop?: string): EditorConfig | object; + /** + * Returns HTML built inside canvas + * @param [opts = {}] - Options + * @param [opts.component] - Return the HTML of a specific Component + * @param [opts.cleanId = false] - Remove unnecessary IDs (eg. those created automatically) + * @returns HTML string + */ + getHtml(opts?: { component?: Component; cleanId?: boolean }): string; + /** + * Returns CSS built inside canvas + * @param [opts = {}] - Options + * @param [opts.component] - Return the CSS of a specific Component + * @param [opts.json = false] - Return an array of CssRules instead of the CSS string + * @param [opts.avoidProtected = false] - Don't include protected CSS + * @param [opts.onlyMatched = false] - Return only rules matched by the passed component. + * @returns CSS string or array of CssRules + */ + getCss(opts?: { + component?: Component; + json?: boolean; + avoidProtected?: boolean; + onlyMatched?: boolean; + }): string | CssRule[]; + /** + * Returns JS of all components + * @param [opts = {}] - Options + * @param [opts.component] - Get the JS of a specific component + * @returns JS string + */ + getJs(opts?: { component?: Component }): string; + /** + * Return the complete tree of components. Use `getWrapper` to include also the wrapper + */ + getComponents(): Components; + /** + * Return the wrapper and its all components + */ + getWrapper(): Component; + /** + * Set components inside editor's canvas. This method overrides actual components + * @example + * editor.setComponents('
New component
'); + * // or + * editor.setComponents({ + * type: 'text', + * classes:['cls'], + * content: 'New component' + * }); + * @param components - HTML string or components model + * @param opt - the options object to be used by the [setComponents]{@link em#setComponents} method + */ + setComponents(components: object[] | any | string, opt: any): any; + /** + * Add components + * @example + * editor.addComponents('
New component
'); + * // or + * editor.addComponents({ + * type: 'text', + * classes:['cls'], + * content: 'New component' + * }); + * @param components - HTML string or components model + * @param opts - Options + * @param [opts.avoidUpdateStyle = false] - If the HTML string contains styles, + * by default, they will be created and, if already exist, updated. When this option + * is true, styles already created will not be updated. + */ + addComponents( + components: object[] | any | string, + opts: { + avoidUpdateStyle?: boolean; + } + ): Component[]; + /** + * Returns style in JSON format object + */ + getStyle(): any; + /** + * Set style inside editor's canvas. This method overrides actual style + * @example + * editor.setStyle('.cls{color: red}'); + * //or + * editor.setStyle({ + * selectors: ['cls'], + * style: { color: 'red' } + * }); + * @param style - CSS string or style model + */ + setStyle(style: object[] | any | string): Editor; + /** + * Add styles to the editor + * @example + * editor.addStyle('.cls{color: red}'); + * @param style - CSS string or style model + * @returns Array of created CssRule instances + */ + addStyle(style: object[] | any | string): CssRule[]; + /** + * Returns the last selected component, if there is one + */ + getSelected(): Component | null; + /** + * Returns an array of all selected components + */ + getSelectedAll(): Component[]; + /** + * Get a stylable entity from the selected component. + * If you select a component without classes the entity is the Component + * itself and all changes will go inside its 'style' attribute. Otherwise, + * if the selected component has one or more classes, the function will + * return the corresponding CSS Rule + */ + getSelectedToStyle(): Component; // TODO: | CSSRule + /** + * Select a component + * @example + * // Select dropped block + * editor.on('block:drag:stop', function(model) { + * editor.select(model); * }); - * ``` + * @param el - Component to select + * @param [opts] - Options + * @param [opts.scroll] - Scroll canvas to the selected element + */ + select( + el: Component | HTMLElement, + opts?: { + scroll?: boolean; + } + ): Editor; + /** + * Add component to selection + * @example + * editor.selectAdd(model); + * @param el - Component to select + */ + selectAdd(el: Component | HTMLElement | any[]): Editor; + /** + * Remove component from selection + * @example + * editor.selectRemove(model); + * @param el - Component to select + */ + selectRemove(el: Component | HTMLElement | any[]): Editor; + /** + * Toggle component selection + * @example + * editor.selectToggle(model); + * @param el - Component to select + */ + selectToggle(el: Component | HTMLElement | any[]): Editor; + /** + * Returns, if active, the Component enabled in rich text editing mode. + * @example + * const textComp = editor.getEditing(); + * if (textComp) { + * console.log('HTML: ', textComp.toHTML()); + * } + */ + getEditing(): Component | null; + /** + * Set device to the editor. If the device exists it will + * change the canvas to the proper width + * @example + * editor.setDevice('Tablet'); + * @param name - Name of the device + */ + setDevice(name: string): Editor; + /** + * Return the actual active device + * @example + * var device = editor.getDevice(); + * console.log(device); + * // 'Tablet' + * @returns Device name + */ + getDevice(): string; + /** + * Execute command + * @example + * editor.runCommand('myCommand', {someValue: 1}); + * @param id - Command ID + * @param options - Custom options + * @returns The return is defined by the command + */ + runCommand(id: string, options: any): any; + /** + * Stop the command if stop method was provided + * @example + * editor.stopCommand('myCommand', {someValue: 1}); + * @param id - Command ID + * @param options - Custom options + * @returns The return is defined by the command + */ + stopCommand(id: string, options: any): any; + /** + * Store data to the current storage + * @param clb - Callback function + * @returns Stored data + */ + store(clb: (...params: any[]) => any): any; + /** + * Get the JSON data object, which could be stored and loaded back with `editor.loadData(json)` + * @example + * console.log(editor.storeData()); + * // { pages: [...], styles: [...], ... } + */ + storeData(): any; + /** + * Load data from the current storage + * @param clb - Callback function + * @returns Stored data + */ + load(clb: (...params: any[]) => any): any; + /** + * Load data from the JSON data object + * @example + * editor.loadData({ pages: [...], styles: [...], ... }) + * @param data - Data to load + * @returns Loaded object + */ + loadData(data: any): any; + /** + * Returns container element. The one which was indicated as 'container' + * on init method + */ + getContainer(): HTMLElement; + /** + * Return the count of changes made to the content and not yet stored. + * This count resets at any `store()` + */ + getDirtyCount(): number; + /** + * Update editor dimension offsets + * + * This method could be useful when you update, for example, some position + * of the editor element (eg. canvas, panels, etc.) with CSS, where without + * refresh you'll get misleading position of tools + * @param [options] - Options + * @param [options.tools = false] - Update the position of tools (eg. rich text editor, component highlighter, etc.) + */ + refresh(options?: { tools?: boolean }): void; + /** + * Replace the built-in Rich Text Editor with a custom one. + * @example + * editor.setCustomRte({ + * // Function for enabling custom RTE + * // el is the HTMLElement of the double clicked Text Component + * // rte is the same instance you have returned the first time you call + * // enable(). This is useful if need to check if the RTE is already enabled so + * // ion this case you'll need to return the RTE and the end of the function + * enable: function(el, rte) { + * rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API + * ... + * return rte; // return the RTE instance + * }, + * + * // Disable the editor, called for example when you unfocus the Text Component + * disable: function(el, rte) { + * rte.blur(); // this depends on the Custom RTE API + * } * - * ## Available Events + * // Called when the Text Component is focused again. If you returned the RTE instance + * // from the enable function, the enable won't be called again instead will call focus, + * // in this case to avoid double binding of the editor + * focus: function (el, rte) { + * rte.focus(); // this depends on the Custom RTE API + * } + * }); + * @param obj - Custom RTE Interface + */ + setCustomRte(obj: any): void; + /** + * Replace the default CSS parser with a custom one. + * The parser function receives a CSS string as a parameter and expects + * an array of CSSRule objects as a result. If you need to remove the + * custom parser, pass `null` as the argument + * @example + * editor.setCustomParserCss(css => { + * const result = []; + * // ... parse the CSS string + * result.push({ + * selectors: '.someclass, div .otherclass', + * style: { color: 'red' } + * }) + * // ... + * return result; + * }); + * @param parser - Parser function + */ + setCustomParserCss(parser: ((...params: any[]) => any) | null): Editor; + /** + * Change the global drag mode of components. + * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 + * @param value - Drag mode, options: 'absolute' | 'translate' + */ + setDragMode(value: string): Editor; + /** + * Trigger event log message + * @example + * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' }); + * // This will trigger following events + * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info` + * // Callbacks of those events will always receive the message and + * // options, as arguments, eg: + * // editor.on('log:info', (msg, opts) => console.info(msg, opts)) + * @param msg - Message to log + * @param [opts = {}] - Custom options + * @param [opts.ns = ''] - Namespace of the log (eg. to use in plugins) + * @param [opts.level = 'debug'] - Level of the log, `debug`, `info`, `warning`, `error` + */ + log( + msg: any, + opts?: { + ns?: string; + level?: string; + } + ): Editor; + /** + * Translate label + * @example + * editor.t('msg'); + * // use params + * editor.t('msg2', { params: { test: 'hello' } }); + * // custom local + * editor.t('msg2', { params: { test: 'hello' }, l: 'it' }); + * @param key - Label to translate + * @param [opts] - Options for the translation + * @param [opts.params] - Params for the translation + * @param [opts.noWarn] - Avoid warnings in case of missing resources + */ + t( + key: string, + opts?: { + params?: any; + noWarn?: boolean; + } + ): string; + /** + * Attach event + * @param event - Event name + * @param callback - Callback function + */ + on(event: GrapesEvent, callback: (...params: any[]) => any): Editor; + /** + * Attach event and detach it after the first run + * @param event - Event name + * @param callback - Callback function + */ + once(event: GrapesEvent, callback: (...params: any[]) => any): Editor; + /** + * Detach event + * @param event - Event name + * @param callback - Callback function + */ + off(event: GrapesEvent, callback: (...params: any[]) => any): Editor; + /** + * Trigger event + * @param event - Event to trigger + */ + trigger(event: GrapesEvent): Editor; + /** + * Destroy the editor + */ + destroy(): void; + /** + * Render editor + */ + render(): HTMLElement; + /** + * Trigger a callback once the editor is loaded and rendered. + * The callback will be executed immediately if the method is called on the already rendered editor. + * @example + * editor.onReady(() => { + * // perform actions + * }); + * @param clb - Callback to trigger + */ + onReady(clb: (...params: any[]) => any): void; + /** + * Print safe HTML by using ES6 tagged template strings. + * @example + * const unsafeStr = ''; + * const safeStr = 'Hello'; + * // Use `$${var}` to avoid escaping + * const strHtml = editor.html`Escaped ${unsafeStr}, unescaped $${safeStr}`; + */ + html(literals: string[], substs: string[]): string; + } + + type GrapesEvent = + | ComponentEvent + | BlockEvent + | AssetEvent + | KeymapEvent + | StyleManagerEvent + | StorageEvent + | CanvasEvent + | SelectorEvent + | RichTextEditorEvent + | ModalEvent + | CommandEvent + | GeneralEvent; + + type ComponentEvent = + | "component:create" + | "component:mount" + | "component:add" + | "component:remove" + | "component:remove:before" + | "component:clone" + | "component:update" + | "component:styleUpdate" + | "component:selected" + | "component:deselected" + | "component:toggled" + | "component:type:add" + | "component:type:update" + | "component:drag:start" + | "component:drag" + | "component:drag:end"; + + type BlockEvent = + | "block:add" + | "block:remove" + | "block:drag:start" + | "block:drag" + | "block:drag:stop"; + + type AssetEvent = + | "asset:add" + | "asset:remove" + | "asset:upload:start" + | "asset:upload:end" + | "asset:upload:error" + | "asset:upload:response"; + + type KeymapEvent = + | "keymap:add" + | "keymap:remove" + | "keymap:emit" + | "keymap:emit:{keymapId}"; + + type StyleManagerEvent = + | "styleManager:update:target" + | "styleManager:change" + | "styleManager:change:{propertyName}"; + + type StorageEvent = + | "storage:start" + | "storage:start:store" + | "storage:start:load" + | "storage:load" + | "storage:store" + | "storage:end" + | "storage:end:store" + | "storage:end:load" + | "storage:error" + | "storage:error:store" + | "storage:error:load"; + + type CanvasEvent = + | "canvas:dragenter" + | "canvas:dragover" + | "canvas:drop" + | "canvas:dragend" + | "canvas:dragdata"; + + type SelectorEvent = "selector:add"; + + type RichTextEditorEvent = "rte:enable" | "rte:disable"; + + type ModalEvent = "modal:open" | "modal:close"; + + type CommandEvent = + | "run:{commandName}" + | "stop:{commandName}" + | "run:{commandName}:before" + | "stop:{commandName}:before" + | "abort:{commandName}"; + + type GeneralEvent = "canvasScroll" | "undo" | "redo" | "load"; + + /** + * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/asset_manager/config/config.js) + * ```js + * const editor = grapesjs.init({ + * assetManager: { + * // options + * } + * }) + * ``` + * + * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance + * + * ```js + * const assetManager = editor.AssetManager; + * ``` + * + * ## Available Events + * * `asset:open` - Asset Manager opened. + * * `asset:close` - Asset Manager closed. + * * `asset:add` - Asset added. The [Asset] is passed as an argument to the callback. + * * `asset:remove` - Asset removed. The [Asset] is passed as an argument to the callback. + * * `asset:update` - Asset updated. The updated [Asset] and the object containing changes are passed as arguments to the callback. + * * `asset:upload:start` - Before the upload is started. + * * `asset:upload:end` - After the upload is ended. + * * `asset:upload:error` - On any error in upload, passes the error as an argument. + * * `asset:upload:response` - On upload response, passes the result as an argument. + * * `asset` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. + * * `asset:custom` - Event for handling custom Asset Manager UI. + * + * ## Methods + * * [open](#open) + * * [close](#close) + * * [isOpen](#isopen) + * * [add](#add) + * * [get](#get) + * * [getAll](#getall) + * * [getAllVisible](#getallvisible) + * * [remove](#remove) + * * [store](#store) + * * [load](#load) + * * [getContainer](#getcontainer) + * + * [Asset]: asset.html + */ + interface AssetManager { + /** + * Open the asset manager. + * @example + * assetManager.open({ + * select(asset, complete) { + * const selected = editor.getSelected(); + * if (selected && selected.is('image')) { + * selected.addAttributes({ src: asset.getSrc() }); + * // The default AssetManager UI will trigger `select(asset, false)` on asset click + * // and `select(asset, true)` on double-click + * complete && assetManager.close(); + * } + * } + * }); + * // with your custom types (you should have assets with those types declared) + * assetManager.open({ types: ['doc'], ... }); + * @param [options] - Options for the asset manager. + * @param [options.types = ['image']] - Types of assets to show. + * @param [options.select] - Type of operation to perform on asset selection. If not specified, nothing will happen. + */ + open(options?: { + types?: String[]; + select?: (...params: any[]) => any; + }): void; + /** + * Close the asset manager. + * @example + * assetManager.close(); + */ + close(): void; + /** + * Checks if the asset manager is open + * @example + * assetManager.isOpen(); // true | false + */ + isOpen(): boolean; + /** + * Add new asset/s to the collection. URLs are supposed to be unique + * @example + * // As strings + * assetManager.add('http://img.jpg'); + * assetManager.add(['http://img.jpg', './path/to/img.png']); * - * You can make use of available events in this way - * ```js - * editor.on('EVENT-NAME', (some, argument) => { - * // do something + * // Using objects you can indicate the type and other meta informations + * assetManager.add({ + * // type: 'image', // image is default + * src: 'http://img.jpg', + * height: 300, + * width: 200, + * }); + * assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]); + * @param asset - URL strings or an objects representing the resource. + * @param [opts] - Options + */ + add(asset: string | any | String[] | object[], opts?: any): any; + /** + * Return asset by URL + * @example + * const asset = assetManager.get('http://img.jpg'); + * @param src - URL of the asset + */ + get(src: string): any; + /** + * Return the global collection, containing all the assets + */ + getAll(): any; + /** + * Return the visible collection, which contains assets actually rendered + */ + getAllVisible(): any; + /** + * Remove asset + * @example + * const removed = assetManager.remove('http://img.jpg'); + * // or by passing the Asset + * const asset = assetManager.get('http://img.jpg'); + * assetManager.remove(asset); + */ + remove(): any; + /** + * Store assets data to the selected storage + * @example + * var assets = assetManager.store(); + * @param noStore - If true, won't store + * @returns Data to store + */ + store(noStore: boolean): any; + /** + * Load data from the passed object. + * The fetched data will be added to the collection. + * @example + * var assets = assetManager.load({ + * assets: [...] * }) - * ``` + * @param data - Object of data to load + * @returns Loaded assets + */ + load(data: any): any; + /** + * Return the Asset Manager Container + */ + getContainer(): HTMLElement; + /** + * Render assets + * @example + * // Render all assets + * assetManager.render(); * - * * `update` - The structure of the template is updated (its HTML/CSS) - * * `undo` - Undo executed - * * `redo` - Redo executed - * * `load` - Editor is loaded + * // Render some of the assets + * const assets = assetManager.getAll(); + * assetManager.render(assets.filter( + * asset => asset.get('category') == 'cats' + * )); + * @param assets - Assets to render, without the argument will render all global assets + */ + render(assets: any[]): HTMLElement; + } + + interface AssetOptions { + /** + * Asset type, eg. 'image'. + */ + type: string; + /** + * Asset URL, eg. 'https://.../image.png'. + */ + src: string; + } + + interface Asset extends Backbone.Model { + /** + * Get asset type. + * @example + * // Asset: { src: 'https://.../image.png', type: 'image' } + * asset.getType(); // -> 'image' + */ + getType(): string; + + /** + * Get asset URL. + * @example + * // Asset: { src: 'https://.../image.png' } + * asset.getSrc(); // -> 'https://.../image.png' + */ + getSrc(): string; + + /** + * Get filename of the asset (based on `src`). + * @example + * // Asset: { src: 'https://.../image.png' } + * asset.getFilename(); // -> 'image.png' + * // Asset: { src: 'https://.../image' } + * asset.getFilename(); // -> 'image' + */ + getFilename(): string; + + /** + * Get extension of the asset (based on `src`). + * @example + * // Asset: { src: 'https://.../image.png' } + * asset.getExtension(); // -> 'png' + * // Asset: { src: 'https://.../image' } + * asset.getExtension(); // -> '' + */ + getExtension(): string; + } + + /** + * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/block_manager/config/config.js) + * ```js + * const editor = grapesjs.init({ + * blockManager: { + * // options + * } + * }) + * ``` + * + * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. + * + * ```js + * // Listen to events + * editor.on('block:add', (block) => { ... }); + * + * // Use the API + * const blockManager = editor.BlockManager; + * blockManager.add(...); + * ``` + * + * ## Available Events + * * `block:add` - Block added. The [Block] is passed as an argument to the callback. + * * `block:remove` - Block removed. The [Block] is passed as an argument to the callback. + * * `block:update` - Block updated. The [Block] and the object containing changes are passed as arguments to the callback. + * * `block:drag:start` - Started dragging block, the [Block] is passed as an argument. + * * `block:drag` - Dragging block, the [Block] is passed as an argument. + * * `block:drag:stop` - Dragging of the block is stopped. The dropped [Component] (if dropped successfully) and the [Block] are passed as arguments. + * * `block` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. + * + * ## Methods + * * [add](#add) + * * [get](#get) + * * [getAll](#getall) + * * [getAllVisible](#getallvisible) + * * [remove](#remove) + * * [getConfig](#getconfig) + * * [getCategories](#getcategories) + * * [getContainer](#getcontainer) + * * [render](#render) + * + * [Block]: block.html + * [Component]: component.html + */ + interface BlockManager { + /** + * Get configuration object + */ + getConfig(): BlockManagerConfig; + /** + * Add new block. + * @example + * blockManager.add('h1-block', { + * label: 'Heading', + * content: '

Put your title here

', + * category: 'Basic', + * attributes: { + * title: 'Insert h1 block' + * } + * }); + * @param id - Block ID + */ + add(id: string, block: BlockOptions): any; + /** + * Get the block by id. + * @example + * const block = blockManager.get('h1-block'); + * console.log(JSON.stringify(block)); + * // {label: 'Heading', content: '

Put your ...', ...} + * @param id - Block id + */ + get(id: string): any; + /** + * Return all blocks. + * @example + * const blocks = blockManager.getAll(); + * console.log(JSON.stringify(blocks)); + * // [{label: 'Heading', content: '

Put your ...'}, ...] + */ + getAll(): any; + /** + * Return the visible collection, which containes blocks actually rendered + */ + getAllVisible(): any; + /** + * Remove block. + * @example + * const removed = blockManager.remove('BLOCK_ID'); + * // or by passing the Block + * const block = blockManager.get('BLOCK_ID'); + * blockManager.remove(block); + */ + remove(): any; + /** + * Get all available categories. + * It's possible to add categories only within blocks via 'add()' method + */ + getCategories(): any[] | Backbone.Collection>; + /** + * Return the Blocks container element + */ + getContainer(): HTMLElement; + /** + * Render blocks + * @example + * // Render all blocks (inside the global collection) + * blockManager.render(); * - * ### Components - * Check the [Components](/api/components.html) module. - * ### Keymaps - * Check the [Keymaps](/api/keymaps.html) module. - * ### Style Manager - * Check the [Style Manager](/api/style_manager.html) module. - * ### Storage - * Check the [Storage](/api/storage_manager.html) module. - * ### Canvas - * Check the [Canvas](/api/canvas.html) module. - * ### RTE - * Check the [Rich Text Editor](/api/rich_text_editor.html) module. - * ### Commands - * Check the [Commands](/api/commands.html) module. - * ### Selectors - * Check the [Selectors](/api/selector_manager.html) module. - * ### Blocks - * Check the [Blocks](/api/block_manager.html) module. - * ### Assets - * Check the [Assets](/api/assets.html) module. - * ### Modal - * Check the [Modal](/api/modal_dialog.html) module. - * ### Devices - * Check the [Devices](/api/device_manager.html) module. - * ### Parser - * Check the [Parser](/api/parser.html) module. - * ### Pages - * Check the [Pages](/api/pages.html) module. + * // Render new set of blocks + * const blocks = blockManager.getAll(); + * const filtered = blocks.filter(block => block.get('category') == 'sections') * - * ## Methods - */ - interface Editor { - DomComponents: Components; - LayerManager: LayerManager; - CssComposer: CssComposer; - StorageManager: StorageManager; - AssetManager: AssetManager; - BlockManager: BlockManager; - TraitManager: TraitManager; - SelectorManager: SelectorManager; - CodeManager: object; - Commands: Commands; - Keymaps: Keymaps; - Modal: Modal; - Panels: Panels; - StyleManager: StyleManager; - Canvas: Canvas; - UndoManager: UndoManager; - DeviceManager: object; - RichTextEditor: RichTextEditor; - Parser: Parser; - Utils: object; - Config: EditorConfig | object; - - /** - * Returns configuration object - * @param [prop] - Property name - * @returns Returns the configuration object or - * the value of the specified property - */ - getConfig(prop?: string): EditorConfig | object; - /** - * Returns HTML built inside canvas - * @param [opts = {}] - Options - * @param [opts.component] - Return the HTML of a specific Component - * @param [opts.cleanId = false] - Remove unnecessary IDs (eg. those created automatically) - * @returns HTML string - */ - getHtml(opts?: { - component?: Component; - cleanId?: boolean; - }): string; - /** - * Returns CSS built inside canvas - * @param [opts = {}] - Options - * @param [opts.component] - Return the CSS of a specific Component - * @param [opts.json = false] - Return an array of CssRules instead of the CSS string - * @param [opts.avoidProtected = false] - Don't include protected CSS - * @param [opts.onlyMatched = false] - Return only rules matched by the passed component. - * @returns CSS string or array of CssRules - */ - getCss(opts?: { - component?: Component; - json?: boolean; - avoidProtected?: boolean; - onlyMatched?: boolean; - }): string | CssRule[]; - /** - * Returns JS of all components - * @param [opts = {}] - Options - * @param [opts.component] - Get the JS of a specific component - * @returns JS string - */ - getJs(opts?: { - component?: Component; - }): string; - /** - * Return the complete tree of components. Use `getWrapper` to include also the wrapper - */ - getComponents(): Components; - /** - * Return the wrapper and its all components - */ - getWrapper(): Component; - /** - * Set components inside editor's canvas. This method overrides actual components - * @example - * editor.setComponents('
New component
'); - * // or - * editor.setComponents({ - * type: 'text', - * classes:['cls'], - * content: 'New component' - * }); - * @param components - HTML string or components model - * @param opt - the options object to be used by the [setComponents]{@link em#setComponents} method - */ - setComponents(components: object[] | any | string, opt: any): any; - /** - * Add components - * @example - * editor.addComponents('
New component
'); - * // or - * editor.addComponents({ - * type: 'text', - * classes:['cls'], - * content: 'New component' - * }); - * @param components - HTML string or components model - * @param opts - Options - * @param [opts.avoidUpdateStyle = false] - If the HTML string contains styles, - * by default, they will be created and, if already exist, updated. When this option - * is true, styles already created will not be updated. - */ - addComponents(components: object[] | any | string, opts: { - avoidUpdateStyle?: boolean; - }): Component[]; - /** - * Returns style in JSON format object - */ - getStyle(): any; - /** - * Set style inside editor's canvas. This method overrides actual style - * @example - * editor.setStyle('.cls{color: red}'); - * //or - * editor.setStyle({ - * selectors: ['cls'], - * style: { color: 'red' } - * }); - * @param style - CSS string or style model - */ - setStyle(style: object[] | any | string): Editor; - /** - * Add styles to the editor - * @example - * editor.addStyle('.cls{color: red}'); - * @param style - CSS string or style model - * @returns Array of created CssRule instances - */ - addStyle(style: object[] | any | string): CssRule[]; - /** - * Returns the last selected component, if there is one - */ - getSelected(): Component | null; - /** - * Returns an array of all selected components - */ - getSelectedAll(): Component[]; - /** - * Get a stylable entity from the selected component. - * If you select a component without classes the entity is the Component - * itself and all changes will go inside its 'style' attribute. Otherwise, - * if the selected component has one or more classes, the function will - * return the corresponding CSS Rule - */ - getSelectedToStyle(): Component; // TODO: | CSSRule - /** - * Select a component - * @example - * // Select dropped block - * editor.on('block:drag:stop', function(model) { - * editor.select(model); - * }); - * @param el - Component to select - * @param [opts] - Options - * @param [opts.scroll] - Scroll canvas to the selected element - */ - select(el: Component | HTMLElement, opts?: { - scroll?: boolean; - }): Editor; - /** - * Add component to selection - * @example - * editor.selectAdd(model); - * @param el - Component to select - */ - selectAdd(el: Component | HTMLElement | any[]): Editor; - /** - * Remove component from selection - * @example - * editor.selectRemove(model); - * @param el - Component to select - */ - selectRemove(el: Component | HTMLElement | any[]): Editor; - /** - * Toggle component selection - * @example - * editor.selectToggle(model); - * @param el - Component to select - */ - selectToggle(el: Component | HTMLElement | any[]): Editor; - /** - * Returns, if active, the Component enabled in rich text editing mode. - * @example - * const textComp = editor.getEditing(); - * if (textComp) { - * console.log('HTML: ', textComp.toHTML()); - * } - */ - getEditing(): Component | null; - /** - * Set device to the editor. If the device exists it will - * change the canvas to the proper width - * @example - * editor.setDevice('Tablet'); - * @param name - Name of the device - */ - setDevice(name: string): Editor; - /** - * Return the actual active device - * @example - * var device = editor.getDevice(); - * console.log(device); - * // 'Tablet' - * @returns Device name - */ - getDevice(): string; - /** - * Execute command - * @example - * editor.runCommand('myCommand', {someValue: 1}); - * @param id - Command ID - * @param options - Custom options - * @returns The return is defined by the command - */ - runCommand(id: string, options: any): any; - /** - * Stop the command if stop method was provided - * @example - * editor.stopCommand('myCommand', {someValue: 1}); - * @param id - Command ID - * @param options - Custom options - * @returns The return is defined by the command - */ - stopCommand(id: string, options: any): any; - /** - * Store data to the current storage - * @param clb - Callback function - * @returns Stored data - */ - store(clb: (...params: any[]) => any): any; - /** - * Get the JSON data object, which could be stored and loaded back with `editor.loadData(json)` - * @example - * console.log(editor.storeData()); - * // { pages: [...], styles: [...], ... } - */ - storeData(): any; - /** - * Load data from the current storage - * @param clb - Callback function - * @returns Stored data - */ - load(clb: (...params: any[]) => any): any; - /** - * Load data from the JSON data object - * @example - * editor.loadData({ pages: [...], styles: [...], ... }) - * @param data - Data to load - * @returns Loaded object - */ - loadData(data: any): any; - /** - * Returns container element. The one which was indicated as 'container' - * on init method - */ - getContainer(): HTMLElement; - /** - * Return the count of changes made to the content and not yet stored. - * This count resets at any `store()` - */ - getDirtyCount(): number; - /** - * Update editor dimension offsets - * - * This method could be useful when you update, for example, some position - * of the editor element (eg. canvas, panels, etc.) with CSS, where without - * refresh you'll get misleading position of tools - * @param [options] - Options - * @param [options.tools = false] - Update the position of tools (eg. rich text editor, component highlighter, etc.) - */ - refresh(options?: { - tools?: boolean; - }): void; - /** - * Replace the built-in Rich Text Editor with a custom one. - * @example - * editor.setCustomRte({ - * // Function for enabling custom RTE - * // el is the HTMLElement of the double clicked Text Component - * // rte is the same instance you have returned the first time you call - * // enable(). This is useful if need to check if the RTE is already enabled so - * // ion this case you'll need to return the RTE and the end of the function - * enable: function(el, rte) { - * rte = new MyCustomRte(el, {}); // this depends on the Custom RTE API - * ... - * return rte; // return the RTE instance - * }, - * - * // Disable the editor, called for example when you unfocus the Text Component - * disable: function(el, rte) { - * rte.blur(); // this depends on the Custom RTE API - * } - * - * // Called when the Text Component is focused again. If you returned the RTE instance - * // from the enable function, the enable won't be called again instead will call focus, - * // in this case to avoid double binding of the editor - * focus: function (el, rte) { - * rte.focus(); // this depends on the Custom RTE API - * } - * }); - * @param obj - Custom RTE Interface - */ - setCustomRte(obj: any): void; - /** - * Replace the default CSS parser with a custom one. - * The parser function receives a CSS string as a parameter and expects - * an array of CSSRule objects as a result. If you need to remove the - * custom parser, pass `null` as the argument - * @example - * editor.setCustomParserCss(css => { - * const result = []; - * // ... parse the CSS string - * result.push({ - * selectors: '.someclass, div .otherclass', - * style: { color: 'red' } - * }) - * // ... - * return result; - * }); - * @param parser - Parser function - */ - setCustomParserCss(parser: ((...params: any[]) => any) | null): Editor; - /** - * Change the global drag mode of components. - * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 - * @param value - Drag mode, options: 'absolute' | 'translate' - */ - setDragMode(value: string): Editor; - /** - * Trigger event log message - * @example - * editor.log('Something done!', { ns: 'from-plugin-x', level: 'info' }); - * // This will trigger following events - * // `log`, `log:info`, `log-from-plugin-x`, `log-from-plugin-x:info` - * // Callbacks of those events will always receive the message and - * // options, as arguments, eg: - * // editor.on('log:info', (msg, opts) => console.info(msg, opts)) - * @param msg - Message to log - * @param [opts = {}] - Custom options - * @param [opts.ns = ''] - Namespace of the log (eg. to use in plugins) - * @param [opts.level = 'debug'] - Level of the log, `debug`, `info`, `warning`, `error` - */ - log(msg: any, opts?: { - ns?: string; - level?: string; - }): Editor; - /** - * Translate label - * @example - * editor.t('msg'); - * // use params - * editor.t('msg2', { params: { test: 'hello' } }); - * // custom local - * editor.t('msg2', { params: { test: 'hello' }, l: 'it' }); - * @param key - Label to translate - * @param [opts] - Options for the translation - * @param [opts.params] - Params for the translation - * @param [opts.noWarn] - Avoid warnings in case of missing resources - */ - t(key: string, opts?: { - params?: any; - noWarn?: boolean; - }): string; - /** - * Attach event - * @param event - Event name - * @param callback - Callback function - */ - on(event: GrapesEvent, callback: (...params: any[]) => any): Editor; - /** - * Attach event and detach it after the first run - * @param event - Event name - * @param callback - Callback function - */ - once(event: GrapesEvent, callback: (...params: any[]) => any): Editor; - /** - * Detach event - * @param event - Event name - * @param callback - Callback function - */ - off(event: GrapesEvent, callback: (...params: any[]) => any): Editor; - /** - * Trigger event - * @param event - Event to trigger - */ - trigger(event: GrapesEvent): Editor; - /** - * Destroy the editor - */ - destroy(): void; - /** - * Render editor - */ - render(): HTMLElement; - /** - * Trigger a callback once the editor is loaded and rendered. - * The callback will be executed immediately if the method is called on the already rendered editor. - * @example - * editor.onReady(() => { - * // perform actions - * }); - * @param clb - Callback to trigger - */ - onReady(clb: (...params: any[]) => any): void; - /** - * Print safe HTML by using ES6 tagged template strings. - * @example - * const unsafeStr = ''; - * const safeStr = 'Hello'; - * // Use `$${var}` to avoid escaping - * const strHtml = editor.html`Escaped ${unsafeStr}, unescaped $${safeStr}`; - */ - html(literals: string[], substs: string[]): string; - } - - type GrapesEvent = ComponentEvent - | BlockEvent - | AssetEvent - | KeymapEvent - | StyleManagerEvent - | StorageEvent - | CanvasEvent - | SelectorEvent - | RichTextEditorEvent - | ModalEvent - | CommandEvent - | GeneralEvent; - - type ComponentEvent = - 'component:create' - | 'component:mount' - | 'component:add' - | 'component:remove' - | 'component:remove:before' - | 'component:clone' - | 'component:update' - | 'component:styleUpdate' - | 'component:selected' - | 'component:deselected' - | 'component:toggled' - | 'component:type:add' - | 'component:type:update' - | 'component:drag:start' - | 'component:drag' - | 'component:drag:end'; - - type BlockEvent = - "block:add" - | "block:remove" - | "block:drag:start" - | "block:drag" - | "block:drag:stop"; - - type AssetEvent = - "asset:add" - | "asset:remove" - | "asset:upload:start" - | "asset:upload:end" - | "asset:upload:error" - | "asset:upload:response"; - - type KeymapEvent = - "keymap:add" - | "keymap:remove" - | "keymap:emit" - | "keymap:emit:{keymapId}"; - - type StyleManagerEvent = - "styleManager:update:target" - | "styleManager:change" - | "styleManager:change:{propertyName}"; - - type StorageEvent = - "storage:start" - | "storage:start:store" - | "storage:start:load" - | "storage:load" - | "storage:store" - | "storage:end" - | "storage:end:store" - | "storage:end:load" - | "storage:error" - | "storage:error:store" - | "storage:error:load"; - - type CanvasEvent = - "canvas:dragenter" - | "canvas:dragover" - | "canvas:drop" - | "canvas:dragend" - | "canvas:dragdata"; - - type SelectorEvent = "selector:add"; - - type RichTextEditorEvent = "rte:enable" | "rte:disable"; - - type ModalEvent = "modal:open" | "modal:close"; - - type CommandEvent = - "run:{commandName}" - | "stop:{commandName}" - | "run:{commandName}:before" - | "stop:{commandName}:before" - | "abort:{commandName}"; - - type GeneralEvent = - "canvasScroll" - | "undo" - | "redo" - | "load"; - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/asset_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * assetManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const assetManager = editor.AssetManager; - * ``` - * - * ## Available Events - * * `asset:open` - Asset Manager opened. - * * `asset:close` - Asset Manager closed. - * * `asset:add` - Asset added. The [Asset] is passed as an argument to the callback. - * * `asset:remove` - Asset removed. The [Asset] is passed as an argument to the callback. - * * `asset:update` - Asset updated. The updated [Asset] and the object containing changes are passed as arguments to the callback. - * * `asset:upload:start` - Before the upload is started. - * * `asset:upload:end` - After the upload is ended. - * * `asset:upload:error` - On any error in upload, passes the error as an argument. - * * `asset:upload:response` - On upload response, passes the result as an argument. - * * `asset` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. - * * `asset:custom` - Event for handling custom Asset Manager UI. + * blockManager.render(filtered); + * // Or a new set from an array + * blockManager.render([ + * {label: 'Label text', content: '
Content
'} + * ]); * - * ## Methods - * * [open](#open) - * * [close](#close) - * * [isOpen](#isopen) - * * [add](#add) - * * [get](#get) - * * [getAll](#getall) - * * [getAllVisible](#getallvisible) - * * [remove](#remove) - * * [store](#store) - * * [load](#load) - * * [getContainer](#getcontainer) + * // Back to blocks from the global collection + * blockManager.render(); * - * [Asset]: asset.html - */ - interface AssetManager { - /** - * Open the asset manager. - * @example - * assetManager.open({ - * select(asset, complete) { - * const selected = editor.getSelected(); - * if (selected && selected.is('image')) { - * selected.addAttributes({ src: asset.getSrc() }); - * // The default AssetManager UI will trigger `select(asset, false)` on asset click - * // and `select(asset, true)` on double-click - * complete && assetManager.close(); - * } - * } - * }); - * // with your custom types (you should have assets with those types declared) - * assetManager.open({ types: ['doc'], ... }); - * @param [options] - Options for the asset manager. - * @param [options.types = ['image']] - Types of assets to show. - * @param [options.select] - Type of operation to perform on asset selection. If not specified, nothing will happen. - */ - open(options?: { - types?: String[]; - select?: (...params: any[]) => any; - }): void; - /** - * Close the asset manager. - * @example - * assetManager.close(); - */ - close(): void; - /** - * Checks if the asset manager is open - * @example - * assetManager.isOpen(); // true | false - */ - isOpen(): boolean; - /** - * Add new asset/s to the collection. URLs are supposed to be unique - * @example - * // As strings - * assetManager.add('http://img.jpg'); - * assetManager.add(['http://img.jpg', './path/to/img.png']); - * - * // Using objects you can indicate the type and other meta informations - * assetManager.add({ - * // type: 'image', // image is default - * src: 'http://img.jpg', - * height: 300, - * width: 200, - * }); - * assetManager.add([{ src: 'img2.jpg' }, { src: 'img2.png' }]); - * @param asset - URL strings or an objects representing the resource. - * @param [opts] - Options - */ - add(asset: string | any | String[] | object[], opts?: any): any; - /** - * Return asset by URL - * @example - * const asset = assetManager.get('http://img.jpg'); - * @param src - URL of the asset - */ - get(src: string): any; - /** - * Return the global collection, containing all the assets - */ - getAll(): any; - /** - * Return the visible collection, which contains assets actually rendered - */ - getAllVisible(): any; - /** - * Remove asset - * @example - * const removed = assetManager.remove('http://img.jpg'); - * // or by passing the Asset - * const asset = assetManager.get('http://img.jpg'); - * assetManager.remove(asset); - */ - remove(): any; - /** - * Store assets data to the selected storage - * @example - * var assets = assetManager.store(); - * @param noStore - If true, won't store - * @returns Data to store - */ - store(noStore: boolean): any; - /** - * Load data from the passed object. - * The fetched data will be added to the collection. - * @example - * var assets = assetManager.load({ - * assets: [...] - * }) - * @param data - Object of data to load - * @returns Loaded assets - */ - load(data: any): any; - /** - * Return the Asset Manager Container - */ - getContainer(): HTMLElement; - /** - * Render assets - * @example - * // Render all assets - * assetManager.render(); - * - * // Render some of the assets - * const assets = assetManager.getAll(); - * assetManager.render(assets.filter( - * asset => asset.get('category') == 'cats' - * )); - * @param assets - Assets to render, without the argument will render all global assets - */ - render(assets: any[]): HTMLElement; - } + * // You can also render your blocks outside of the main block container + * const newBlocksEl = blockManager.render(filtered, { external: true }); + * document.getElementById('some-id').appendChild(newBlocksEl); + * @param blocks - Blocks to render, without the argument will render all global blocks + * @param [opts = {}] - Options + * @param [opts.external] - Render blocks in a new container (HTMLElement will be returned) + * @param [opts.ignoreCategories] - Render blocks without categories + * @returns Rendered element + */ + render( + blocks: any[], + opts?: { + external?: boolean; + ignoreCategories?: boolean; + } + ): HTMLElement; + } - interface AssetOptions { - /** - * Asset type, eg. 'image'. - */ - type: string; - /** - * Asset URL, eg. 'https://.../image.png'. - */ - src: string; - } - - interface Asset extends Backbone.Model { - /** - * Get asset type. - * @example - * // Asset: { src: 'https://.../image.png', type: 'image' } - * asset.getType(); // -> 'image' - */ - getType(): string; - - /** - * Get asset URL. - * @example - * // Asset: { src: 'https://.../image.png' } - * asset.getSrc(); // -> 'https://.../image.png' - */ - getSrc(): string; - - /** - * Get filename of the asset (based on `src`). - * @example - * // Asset: { src: 'https://.../image.png' } - * asset.getFilename(); // -> 'image.png' - * // Asset: { src: 'https://.../image' } - * asset.getFilename(); // -> 'image' - */ - getFilename(): string; - - /** - * Get extension of the asset (based on `src`). - * @example - * // Asset: { src: 'https://.../image.png' } - * asset.getExtension(); // -> 'png' - * // Asset: { src: 'https://.../image' } - * asset.getExtension(); // -> '' - */ - getExtension(): string; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/block_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * blockManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('block:add', (block) => { ... }); - * - * // Use the API - * const blockManager = editor.BlockManager; - * blockManager.add(...); - * ``` - * - * ## Available Events - * * `block:add` - Block added. The [Block] is passed as an argument to the callback. - * * `block:remove` - Block removed. The [Block] is passed as an argument to the callback. - * * `block:update` - Block updated. The [Block] and the object containing changes are passed as arguments to the callback. - * * `block:drag:start` - Started dragging block, the [Block] is passed as an argument. - * * `block:drag` - Dragging block, the [Block] is passed as an argument. - * * `block:drag:stop` - Dragging of the block is stopped. The dropped [Component] (if dropped successfully) and the [Block] are passed as arguments. - * * `block` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. - * - * ## Methods - * * [add](#add) - * * [get](#get) - * * [getAll](#getall) - * * [getAllVisible](#getallvisible) - * * [remove](#remove) - * * [getConfig](#getconfig) - * * [getCategories](#getcategories) - * * [getContainer](#getcontainer) - * * [render](#render) - * - * [Block]: block.html - * [Component]: component.html - */ - interface BlockManager { - /** - * Get configuration object - */ - getConfig(): BlockManagerConfig; - /** - * Add new block. - * @example - * blockManager.add('h1-block', { - * label: 'Heading', - * content: '

Put your title here

', - * category: 'Basic', - * attributes: { - * title: 'Insert h1 block' - * } - * }); - * @param id - Block ID - */ - add(id: string, block : BlockOptions): any; - /** - * Get the block by id. - * @example - * const block = blockManager.get('h1-block'); - * console.log(JSON.stringify(block)); - * // {label: 'Heading', content: '

Put your ...', ...} - * @param id - Block id - */ - get(id: string): any; - /** - * Return all blocks. - * @example - * const blocks = blockManager.getAll(); - * console.log(JSON.stringify(blocks)); - * // [{label: 'Heading', content: '

Put your ...'}, ...] - */ - getAll(): any; - /** - * Return the visible collection, which containes blocks actually rendered - */ - getAllVisible(): any; - /** - * Remove block. - * @example - * const removed = blockManager.remove('BLOCK_ID'); - * // or by passing the Block - * const block = blockManager.get('BLOCK_ID'); - * blockManager.remove(block); - */ - remove(): any; - /** - * Get all available categories. - * It's possible to add categories only within blocks via 'add()' method - */ - getCategories(): any[] | Backbone.Collection>; - /** - * Return the Blocks container element - */ - getContainer(): HTMLElement; - /** - * Render blocks - * @example - * // Render all blocks (inside the global collection) - * blockManager.render(); - * - * // Render new set of blocks - * const blocks = blockManager.getAll(); - * const filtered = blocks.filter(block => block.get('category') == 'sections') - * - * blockManager.render(filtered); - * // Or a new set from an array - * blockManager.render([ - * {label: 'Label text', content: '
Content
'} - * ]); - * - * // Back to blocks from the global collection - * blockManager.render(); - * - * // You can also render your blocks outside of the main block container - * const newBlocksEl = blockManager.render(filtered, { external: true }); - * document.getElementById('some-id').appendChild(newBlocksEl); - * @param blocks - Blocks to render, without the argument will render all global blocks - * @param [opts = {}] - Options - * @param [opts.external] - Render blocks in a new container (HTMLElement will be returned) - * @param [opts.ignoreCategories] - Render blocks without categories - * @returns Rendered element - */ - render(blocks: any[], opts?: { - external?: boolean; - ignoreCategories?: boolean; - }): HTMLElement; - } - - interface BlockOptions { - /** - * Block label, eg. `My block` - */ - label: string; - /** - * The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition) - */ - content: string | any; - /** - * HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content'))` - */ - onClick?: (...params: any[]) => any; - } - interface Block extends Backbone.Model { - /** - * Get block id - */ - getId(): string; - - /** - * Get block label - */ - getLabel(): string; - - /** - * Get block media - */ - getMedia(): string; - - /** - * Get block content - * @returns Component definition | HTML string - */ - getContent(): any | string | (object | String)[]; - - /** - * Get block category label - */ - getCategoryLabel(): string; - - self(): Block; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/commands/config/config.js) - * ```js - * const editor = grapesjs.init({ - * commands: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('run', () => { ... }); - * - * // Use the API - * const commands = editor.Commands; - * commands.add(...); - * ``` - * - * * ## Available Events - * * `run:{commandName}` - Triggered when some command is called to run (eg. editor.runCommand('preview')) - * * `stop:{commandName}` - Triggered when some command is called to stop (eg. editor.stopCommand('preview')) - * * `run:{commandName}:before` - Triggered before the command is called - * * `stop:{commandName}:before` - Triggered before the command is called to stop - * * `abort:{commandName}` - Triggered when the command execution is aborted (`editor.on(`run:preview:before`, opts => opts.abort = 1);`) - * * `run` - Triggered on run of any command. The id and the result are passed as arguments to the callback - * * `stop` - Triggered on stop of any command. The id and the result are passed as arguments to the callback - * - * ## Methods - * * [add](#add) - * * [get](#get) - * * [getAll](#getall) - * * [extend](#extend) - * * [has](#has) - * * [run](#run) - * * [stop](#stop) - * * [isActive](#isactive) - * * [getActive](#getactive) - */ - interface Commands { - /** - * Add new command to the collection - * @example - * commands.add('myCommand', { - * run(editor, sender) { - * alert('Hello world!'); - * }, - * stop(editor, sender) { - * }, - * }); - * // As a function - * commands.add('myCommand2', editor => { ... }); - */ - add(id : string, command : (editor : Editor) => void | { - run: (editor: Editor, sender? : any) => void; - stop: (editor: Editor, sender? : any) => void; - }) : void - /** - * Get command by ID - * @example - * var myCommand = commands.get('myCommand'); - * myCommand.run(); - * @param id - Command's ID - * @returns Object representing the command - */ - get(id: string): any; - /** - * Extend the command. The command to extend should be defined as an object - * @example - * commands.extend('old-command', { - * someInnerFunction() { - * // ... - * } - * }); - * @param id - Command's ID - * @param Object - with the new command functions - */ - extend(id: string, Object: any): Commands; - /** - * Check if command exists - * @param id - Command's ID - */ - has(id: string): boolean; - /** - * Get an object containing all the commands - */ - getAll(): any; - /** - * Execute the command - * @example - * commands.run('myCommand', { someOption: 1 }); - * @param id - Command ID - * @param [options = {}] - Options - * @returns The return is defined by the command - */ - run(id: string, options?: any): any; - /** - * Stop the command - * @example - * commands.stop('myCommand', { someOption: 1 }); - * @param id - Command ID - * @param [options = {}] - Options - * @returns The return is defined by the command - */ - stop(id: string, options?: any): any; - /** - * Check if the command is active. You activate commands with `run` - * and disable them with `stop`. If the command was created without `stop` - * method it can't be registered as active - * @example - * const cId = 'some-command'; - * commands.run(cId); - * commands.isActive(cId); - * // -> true - * commands.stop(cId); - * commands.isActive(cId); - * // -> false - * @param id - Command id - */ - isActive(id: string): boolean; - /** - * Get all active commands - * @example - * console.log(commands.getActive()); - * // -> { someCommand: itsLastReturn, anotherOne: ... }; - */ - getActive(): any; - } - - interface AddComponentOptions { - isComponent?: (el : HTMLElement) => boolean | ComponentProperties, - model?: ComponentModelDefinition - view?: ComponentViewDefinition - } - - interface ComponentModelDefinition { - defaults?: ComponentProperties - init?: (this: Component) => void - handlePropChange?: (this: Component) => void - handleAttrChange?: (this: Component) => void - handleTitleChange?: (this: Component) => void - } - - interface ComponentViewDefinition { - tagName : string, - events: Record - init?: (options: {model: Component}) => void - removed?: () => void - onRender?: (options: {el : HTMLElement, model: Component}) => void - } - - /** - * With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/dom_components/config/config.js) - * ```js - * const editor = grapesjs.init({ - * domComponents: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('component:create', () => { ... }); - * - * // Use the API - * const cmp = editor.Components; - * cmp.addType(...); - * ``` - * - * ## Available Events - * * `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method - * * `component:mount` - Component is mounted to an element and rendered in canvas - * * `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback - * * `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback - * * `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback - * * `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback - * * `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback - * * `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback - * * `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback - * * `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback - * * `component:selected` - New component selected, the selected model is passed as an argument to the callback - * * `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback - * * `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback - * * `component:type:add` - New component type added, the new type is passed as an argument to the callback - * * `component:type:update` - Component type updated, the updated type is passed as an argument to the callback - * * `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent) - * * `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer - * * `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer - * - * ## Methods - * * [getWrapper](#getwrapper) - * * [getComponents](#getcomponents) - * * [addComponent](#addcomponent) - * * [clear](#clear) - * * [load](#load) - * * [store](#store) - * * [addType](#addtype) - * * [getType](#gettype) - * * [getTypes](#gettypes) - * * [render](#render) - */ - interface Components { - /** - * Load components from the passed object, if the object is empty will try to fetch them - * autonomously from the selected storage - * The fetched data will be added to the collection - * @param data - Object of data to load - * @returns Loaded data - */ - load(data: any): any; - /** - * Store components on the selected storage - * @param noStore - If true, won't store - * @returns Data to store - */ - store(noStore: boolean): any; - /** - * Returns root component inside the canvas. Something like `` inside HTML page - * The wrapper doesn't differ from the original Component Model - * @example - * // Change background of the wrapper and set some attribute - * var wrapper = cmp.getWrapper(); - * wrapper.set('style', {'background-color': 'red'}); - * wrapper.set('attributes', {'title': 'Hello!'}); - * @returns Root Component - */ - getWrapper(): Component; - /** - * Returns wrapper's children collection. Once you have the collection you can - * add other Components(Models) inside. Each component can have several nested - * components inside and you can nest them as more as you wish. - * @example - * // Let's add some component - * var wrapperChildren = cmp.getComponents(); - * var comp1 = wrapperChildren.add({ - * style: { 'background-color': 'red'} - * }); - * var comp2 = wrapperChildren.add({ - * tagName: 'span', - * attributes: { title: 'Hello!'} - * }); - * // Now let's add an other one inside first component - * // First we have to get the collection inside. Each - * // component has 'components' property - * var comp1Children = comp1.get('components'); - * // Procede as before. You could also add multiple objects - * comp1Children.add([ - * { style: { 'background-color': 'blue'}}, - * { style: { height: '100px', width: '100px'}} - * ]); - * // Remove comp2 - * wrapperChildren.remove(comp2); - * @returns Collection of components - */ - getComponents(): Components; - /** - * Add new components to the wrapper's children. It's the same - * as 'cmp.getComponents().add(...)' - * @example - * // Example of a new component with some extra property - * var comp1 = cmp.addComponent({ - * tagName: 'div', - * removable: true, // Can't remove it - * draggable: true, // Can't move it - * copyable: true, // Disable copy/past - * content: 'Content text', // Text inside component - * style: { color: 'red'}, - * attributes: { title: 'here' } - * }); - * @param component - Component/s to add - * @param [component.tagName = 'div'] - Tag name - * @param [component.type = ''] - Type of the component. Available: ''(default), 'text', 'image' - * @param [component.removable = true] - If component is removable - * @param [component.draggable = true] - If is possible to move the component around the structure - * @param [component.droppable = true] - If is possible to drop inside other components - * @param [component.badgable = true] - If the badge is visible when the component is selected - * @param [component.stylable = true] - If is possible to style component - * @param [component.copyable = true] - If is possible to copy&paste the component - * @param [component.content = ''] - String inside component - * @param [component.style = {}] - Style object - * @param [component.attributes = {}] - Attribute object - * @param opt - the options object to be used by the [Components.add]{@link getComponents} method - * @returns Component/s added - */ - addComponent(component: { + interface BlockOptions { + /** + * Block label, eg. `My block` + */ + label: string; + /** + * The content of the block. Might be an HTML string or a [Component Defintion](/modules/Components.html#component-definition) + */ + content: string | any; + /** + * HTML string for the media/icon of the block, eg. ` editor.getWrapper().append(block.get('content'))` + */ + onClick?: (...params: any[]) => any; + } + interface Block extends Backbone.Model { + /** + * Get block id + */ + getId(): string; + + /** + * Get block label + */ + getLabel(): string; + + /** + * Get block media + */ + getMedia(): string; + + /** + * Get block content + * @returns Component definition | HTML string + */ + getContent(): any | string | (object | String)[]; + + /** + * Get block category label + */ + getCategoryLabel(): string; + + self(): Block; + } + + /** + * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/commands/config/config.js) + * ```js + * const editor = grapesjs.init({ + * commands: { + * // options + * } + * }) + * ``` + * + * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. + * + * ```js + * // Listen to events + * editor.on('run', () => { ... }); + * + * // Use the API + * const commands = editor.Commands; + * commands.add(...); + * ``` + * + * * ## Available Events + * * `run:{commandName}` - Triggered when some command is called to run (eg. editor.runCommand('preview')) + * * `stop:{commandName}` - Triggered when some command is called to stop (eg. editor.stopCommand('preview')) + * * `run:{commandName}:before` - Triggered before the command is called + * * `stop:{commandName}:before` - Triggered before the command is called to stop + * * `abort:{commandName}` - Triggered when the command execution is aborted (`editor.on(`run:preview:before`, opts => opts.abort = 1);`) + * * `run` - Triggered on run of any command. The id and the result are passed as arguments to the callback + * * `stop` - Triggered on stop of any command. The id and the result are passed as arguments to the callback + * + * ## Methods + * * [add](#add) + * * [get](#get) + * * [getAll](#getall) + * * [extend](#extend) + * * [has](#has) + * * [run](#run) + * * [stop](#stop) + * * [isActive](#isactive) + * * [getActive](#getactive) + */ + interface Commands { + /** + * Add new command to the collection + * @example + * commands.add('myCommand', { + * run(editor, sender) { + * alert('Hello world!'); + * }, + * stop(editor, sender) { + * }, + * }); + * // As a function + * commands.add('myCommand2', editor => { ... }); + */ + add( + id: string, + command: (editor: Editor) => void | { + run: (editor: Editor, sender?: any) => void; + stop: (editor: Editor, sender?: any) => void; + } + ): void; + /** + * Get command by ID + * @example + * var myCommand = commands.get('myCommand'); + * myCommand.run(); + * @param id - Command's ID + * @returns Object representing the command + */ + get(id: string): any; + /** + * Extend the command. The command to extend should be defined as an object + * @example + * commands.extend('old-command', { + * someInnerFunction() { + * // ... + * } + * }); + * @param id - Command's ID + * @param Object - with the new command functions + */ + extend(id: string, Object: any): Commands; + /** + * Check if command exists + * @param id - Command's ID + */ + has(id: string): boolean; + /** + * Get an object containing all the commands + */ + getAll(): any; + /** + * Execute the command + * @example + * commands.run('myCommand', { someOption: 1 }); + * @param id - Command ID + * @param [options = {}] - Options + * @returns The return is defined by the command + */ + run(id: string, options?: any): any; + /** + * Stop the command + * @example + * commands.stop('myCommand', { someOption: 1 }); + * @param id - Command ID + * @param [options = {}] - Options + * @returns The return is defined by the command + */ + stop(id: string, options?: any): any; + /** + * Check if the command is active. You activate commands with `run` + * and disable them with `stop`. If the command was created without `stop` + * method it can't be registered as active + * @example + * const cId = 'some-command'; + * commands.run(cId); + * commands.isActive(cId); + * // -> true + * commands.stop(cId); + * commands.isActive(cId); + * // -> false + * @param id - Command id + */ + isActive(id: string): boolean; + /** + * Get all active commands + * @example + * console.log(commands.getActive()); + * // -> { someCommand: itsLastReturn, anotherOne: ... }; + */ + getActive(): any; + } + + interface AddComponentOptions { + isComponent?: (el: HTMLElement) => boolean | ComponentProperties; + model?: ComponentModelDefinition; + view?: ComponentViewDefinition; + } + + interface ComponentModelDefinition { + defaults?: ComponentProperties; + init?: (this: Component) => void; + handlePropChange?: (this: Component) => void; + handleAttrChange?: (this: Component) => void; + handleTitleChange?: (this: Component) => void; + } + + interface ComponentViewDefinition { + tagName: string; + events: Record; + init?: (options: { model: Component }) => void; + removed?: () => void; + onRender?: (options: { el: HTMLElement; model: Component }) => void; + } + + /** + * With this module is possible to manage components inside the canvas. You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/dom_components/config/config.js) + * ```js + * const editor = grapesjs.init({ + * domComponents: { + * // options + * } + * }) + * ``` + * + * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. + * + * ```js + * // Listen to events + * editor.on('component:create', () => { ... }); + * + * // Use the API + * const cmp = editor.Components; + * cmp.addType(...); + * ``` + * + * ## Available Events + * * `component:create` - Component is created (only the model, is not yet mounted in the canvas), called after the init() method + * * `component:mount` - Component is mounted to an element and rendered in canvas + * * `component:add` - Triggered when a new component is added to the editor, the model is passed as an argument to the callback + * * `component:remove` - Triggered when a component is removed, the model is passed as an argument to the callback + * * `component:remove:before` - Triggered before the remove of the component, the model, remove function (if aborted via options, with this function you can complete the remove) and options (use options.abort = true to prevent remove), are passed as arguments to the callback + * * `component:clone` - Triggered when a component is cloned, the new model is passed as an argument to the callback + * * `component:update` - Triggered when a component is updated (moved, styled, etc.), the model is passed as an argument to the callback + * * `component:update:{propertyName}` - Listen any property change, the model is passed as an argument to the callback + * * `component:styleUpdate` - Triggered when the style of the component is updated, the model is passed as an argument to the callback + * * `component:styleUpdate:{propertyName}` - Listen for a specific style property change, the model is passed as an argument to the callback + * * `component:selected` - New component selected, the selected model is passed as an argument to the callback + * * `component:deselected` - Component deselected, the deselected model is passed as an argument to the callback + * * `component:toggled` - Component selection changed, toggled model is passed as an argument to the callback + * * `component:type:add` - New component type added, the new type is passed as an argument to the callback + * * `component:type:update` - Component type updated, the updated type is passed as an argument to the callback + * * `component:drag:start` - Component drag started. Passed an object, to the callback, containing the `target` (component to drag), `parent` (parent of the component) and `index` (component index in the parent) + * * `component:drag` - During component drag. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the current pointer + * * `component:drag:end` - Component drag ended. Passed the same object as in `component:drag:start` event, but in this case, `parent` and `index` are updated by the final pointer + * + * ## Methods + * * [getWrapper](#getwrapper) + * * [getComponents](#getcomponents) + * * [addComponent](#addcomponent) + * * [clear](#clear) + * * [load](#load) + * * [store](#store) + * * [addType](#addtype) + * * [getType](#gettype) + * * [getTypes](#gettypes) + * * [render](#render) + */ + interface Components { + /** + * Load components from the passed object, if the object is empty will try to fetch them + * autonomously from the selected storage + * The fetched data will be added to the collection + * @param data - Object of data to load + * @returns Loaded data + */ + load(data: any): any; + /** + * Store components on the selected storage + * @param noStore - If true, won't store + * @returns Data to store + */ + store(noStore: boolean): any; + /** + * Returns root component inside the canvas. Something like `` inside HTML page + * The wrapper doesn't differ from the original Component Model + * @example + * // Change background of the wrapper and set some attribute + * var wrapper = cmp.getWrapper(); + * wrapper.set('style', {'background-color': 'red'}); + * wrapper.set('attributes', {'title': 'Hello!'}); + * @returns Root Component + */ + getWrapper(): Component; + /** + * Returns wrapper's children collection. Once you have the collection you can + * add other Components(Models) inside. Each component can have several nested + * components inside and you can nest them as more as you wish. + * @example + * // Let's add some component + * var wrapperChildren = cmp.getComponents(); + * var comp1 = wrapperChildren.add({ + * style: { 'background-color': 'red'} + * }); + * var comp2 = wrapperChildren.add({ + * tagName: 'span', + * attributes: { title: 'Hello!'} + * }); + * // Now let's add an other one inside first component + * // First we have to get the collection inside. Each + * // component has 'components' property + * var comp1Children = comp1.get('components'); + * // Procede as before. You could also add multiple objects + * comp1Children.add([ + * { style: { 'background-color': 'blue'}}, + * { style: { height: '100px', width: '100px'}} + * ]); + * // Remove comp2 + * wrapperChildren.remove(comp2); + * @returns Collection of components + */ + getComponents(): Components; + /** + * Add new components to the wrapper's children. It's the same + * as 'cmp.getComponents().add(...)' + * @example + * // Example of a new component with some extra property + * var comp1 = cmp.addComponent({ + * tagName: 'div', + * removable: true, // Can't remove it + * draggable: true, // Can't move it + * copyable: true, // Disable copy/past + * content: 'Content text', // Text inside component + * style: { color: 'red'}, + * attributes: { title: 'here' } + * }); + * @param component - Component/s to add + * @param [component.tagName = 'div'] - Tag name + * @param [component.type = ''] - Type of the component. Available: ''(default), 'text', 'image' + * @param [component.removable = true] - If component is removable + * @param [component.draggable = true] - If is possible to move the component around the structure + * @param [component.droppable = true] - If is possible to drop inside other components + * @param [component.badgable = true] - If the badge is visible when the component is selected + * @param [component.stylable = true] - If is possible to style component + * @param [component.copyable = true] - If is possible to copy&paste the component + * @param [component.content = ''] - String inside component + * @param [component.style = {}] - Style object + * @param [component.attributes = {}] - Attribute object + * @param opt - the options object to be used by the [Components.add]{@link getComponents} method + * @returns Component/s added + */ + addComponent( + component: { tagName?: string; type?: string; removable?: boolean; @@ -1836,3452 +1831,3504 @@ declare namespace Backbone { content?: string; style?: any; attributes?: any; - }, opt: any): Component; - /** - * Render and returns wrapper element with all components inside. - * Once the wrapper is rendered, and it's what happens when you init the editor, - * the all new components will be added automatically and property changes are all - * updated immediately - */ - render(): HTMLElement; - /** - * Remove all components - */ - clear(): Components; - /** - * Add new component type. - * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) - * @param type - Component ID - * @param methods - Component methods - */ - addType(type: string, methods: AddComponentOptions): Components; - /** - * Get component type. - * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) - * @param type - Component ID - * @returns Component type definition, eg. `{ model: ..., view: ... }` - */ - getType(type: string): any; - /** - * Remove component type - * @param type - Component ID - * @returns Removed component type, undefined otherwise - */ - removeType(type: string): any | undefined; - /** - * Return the array of all types - */ - getTypes(): any[]; - } + }, + opt: any + ): Component; + /** + * Render and returns wrapper element with all components inside. + * Once the wrapper is rendered, and it's what happens when you init the editor, + * the all new components will be added automatically and property changes are all + * updated immediately + */ + render(): HTMLElement; + /** + * Remove all components + */ + clear(): Components; + /** + * Add new component type. + * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) + * @param type - Component ID + * @param methods - Component methods + */ + addType(type: string, methods: AddComponentOptions): Components; + /** + * Get component type. + * Read more about this in [Define New Component](https://grapesjs.com/docs/modules/Components.html#define-new-component) + * @param type - Component ID + * @returns Component type definition, eg. `{ model: ..., view: ... }` + */ + getType(type: string): any; + /** + * Remove component type + * @param type - Component ID + * @returns Removed component type, undefined otherwise + */ + removeType(type: string): any | undefined; + /** + * Return the array of all types + */ + getTypes(): any[]; + } - interface ComponentProperties { - /** - * Component type, eg. `text`, `image`, `video`, etc. - * @defaultValue '' - */ - type?: string; - /** - * HTML tag of the component, eg. `span`. Default: `div` - * @defaultValue 'div' - */ - tagName?: string; - /** - * Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` - * @defaultValue {} - */ - attributes?: Record; - /** - * Name of the component. Will be used, for example, in Layers and badges - * @defaultValue '' - */ - name?: string; - /** - * When `true` the component is removable from the canvas, default: `true` - * @defaultValue true - */ - removable?: boolean; - /** + interface ComponentProperties { + /** + * Component type, eg. `text`, `image`, `video`, etc. + * @defaultValue '' + */ + type?: string; + /** + * HTML tag of the component, eg. `span`. Default: `div` + * @defaultValue 'div' + */ + tagName?: string; + /** + * Key-value object of the component's attributes, eg. `{ title: 'Hello' }` Default: `{}` + * @defaultValue {} + */ + attributes?: Record; + /** + * Name of the component. Will be used, for example, in Layers and badges + * @defaultValue '' + */ + name?: string; + /** + * When `true` the component is removable from the canvas, default: `true` + * @defaultValue true + */ + removable?: boolean; + /** * Indicates if it's possible to drag the component inside others. You can also specify a query string to indentify elements, eg. `'.some-class[title=Hello], [data-gjs-type=column]'` means you can drag the component only inside elements containing `some-class` class and `Hello` title, and `column` components. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drag is possible. Default: `true` * @defaultValue true */ - draggable?: boolean | string | ((...params: any[]) => any); - /** + draggable?: boolean | string | ((...params: any[]) => any); + /** * Indicates if it's possible to drop other components inside. You can use a query string as with `draggable`. In the case of a function, target and destination components are passed as arguments, return a Boolean to indicate if the drop is possible. Default: `true` * @defaultValue true */ - droppable?: boolean | string | ((...params: any[]) => any); - /** - * Set to false if you don't want to see the badge (with the name) over the component. Default: `true` - * @defaultValue true - */ - badgable?: boolean; - /** + droppable?: boolean | string | ((...params: any[]) => any); + /** + * Set to false if you don't want to see the badge (with the name) over the component. Default: `true` + * @defaultValue true + */ + badgable?: boolean; + /** * True if it's possible to style the component. You can also indicate an array of CSS properties which is possible to style, eg. `['color', 'width']`, all other properties will be hidden from the style manager. Default: `true` * @defaultValue true */ - stylable?: boolean | String[]; - ///** - // * Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` - // * @defaultValue [] - // */ - //`stylable-require`?: String[]; - /** - * Indicate an array of style properties which should be hidden from the style manager. Default: `[]` + stylable?: boolean | String[]; + ///** + // * Indicate an array of style properties to show up which has been marked as `toRequire`. Default: `[]` + // * @defaultValue [] + // */ + //`stylable-require`?: String[]; + /** + * Indicate an array of style properties which should be hidden from the style manager. Default: `[]` + * @defaultValue [] + */ + unstylable?: String[]; + /** + * It can be highlighted with 'dotted' borders if true. Default: `true` + * @defaultValue true + */ + highlightable?: boolean; + /** + * True if it's possible to clone the component. Default: `true` + * @defaultValue true + */ + copyable?: boolean; + /** + * Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/artf/grapesjs/blob/master/src/utils/Resizer.js). Default: `false` + */ + resizable?: boolean; + /** + * Allow to edit the content of the component (used on Text components). Default: `false` + */ + editable?: boolean; + /** + * Set to `false` if you need to hide the component inside Layers. Default: `true` + * @defaultValue true + */ + layerable?: boolean; + /** + * Allow component to be selected when clicked. Default: `true` + * @defaultValue true + */ + selectable?: boolean; + /** + * Shows a highlight outline when hovering on the element if `true`. Default: `true` + * @defaultValue true + */ + hoverable?: boolean; + /** + * This property is used by the HTML exporter as void elements don't have closing tags, eg. `
`, `
`, etc. Default: `false` + */ + void?: boolean; + /** + * Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` + * @defaultValue {} + */ + style?: any; + /** + * Component related styles, eg. `.my-component-class { color: red }` + * @defaultValue '' + */ + styles?: string; + /** + * Content of the component (not escaped) which will be appended before children rendering. Default: `''` + * @defaultValue '' + */ + content?: string; + /** + * Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default: `''` + * @defaultValue '' + */ + icon?: string; + /** + * Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` + * @defaultValue '' + */ + script?: string | ((...params: any[]) => any); + ///** + // * You can specify javascript available only in export functions (eg. when you get the HTML). + //If this property is defined it will overwrite the `script` one (in export functions). Default: `''` + // * @defaultValue '' + // */ + //script-export?: string | ((...params: any[]) => any); + /** + * Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` + * @defaultValue '' + */ + traits?: TraitOptions[] | String[] | Backbone.Collection; + /** + * Indicates an array of properties which will be inhereted by all NEW appended children. + For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` + and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` * @defaultValue [] */ - unstylable?: String[]; - /** - * It can be highlighted with 'dotted' borders if true. Default: `true` - * @defaultValue true + propagate?: String[]; + /** + * Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). + Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. + By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). */ - highlightable?: boolean; - /** - * True if it's possible to clone the component. Default: `true` - * @defaultValue true - */ - copyable?: boolean; - /** - * Indicates if it's possible to resize the component. It's also possible to pass an object as [options for the Resizer](https://github.com/artf/grapesjs/blob/master/src/utils/Resizer.js). Default: `false` - */ - resizable?: boolean; - /** - * Allow to edit the content of the component (used on Text components). Default: `false` - */ - editable?: boolean; - /** - * Set to `false` if you need to hide the component inside Layers. Default: `true` - * @defaultValue true - */ - layerable?: boolean; - /** - * Allow component to be selected when clicked. Default: `true` - * @defaultValue true - */ - selectable?: boolean; - /** - * Shows a highlight outline when hovering on the element if `true`. Default: `true` - * @defaultValue true - */ - hoverable?: boolean; - /** - * This property is used by the HTML exporter as void elements don't have closing tags, eg. `
`, `
`, etc. Default: `false` - */ - void?: boolean; - /** - * Component default style, eg. `{ width: '100px', height: '100px', 'background-color': 'red' }` - * @defaultValue {} - */ - style?: any; - /** - * Component related styles, eg. `.my-component-class { color: red }` - * @defaultValue '' - */ - styles?: string; - /** - * Content of the component (not escaped) which will be appended before children rendering. Default: `''` - * @defaultValue '' - */ - content?: string; - /** - * Component's icon, this string will be inserted before the name (in Layers and badge), eg. it can be an HTML string ''. Default: `''` - * @defaultValue '' - */ - icon?: string; - /** - * Component's javascript. More about it [here](/modules/Components-js.html). Default: `''` - * @defaultValue '' - */ - script?: string | ((...params: any[]) => any); - ///** - // * You can specify javascript available only in export functions (eg. when you get the HTML). - //If this property is defined it will overwrite the `script` one (in export functions). Default: `''` - // * @defaultValue '' - // */ - //script-export?: string | ((...params: any[]) => any); - /** - * Component's traits. More about it [here](/modules/Traits.html). Default: `['id', 'title']` - * @defaultValue '' - */ - traits?: TraitOptions[] | String[] | Backbone.Collection; - /** - * Indicates an array of properties which will be inhereted by all NEW appended children. - For example if you create a component likes this: `{ removable: false, draggable: false, propagate: ['removable', 'draggable'] }` - and append some new component inside, the new added component will get the exact same properties indicated in the `propagate` array (and the `propagate` property itself). Default: `[]` - * @defaultValue [] - */ - propagate?: String[]; - /** - * Set an array of items to show up inside the toolbar when the component is selected (move, clone, delete). - Eg. `toolbar: [ { attributes: {class: 'fa fa-arrows'}, command: 'tlb-move' }, ... ]`. - By default, when `toolbar` property is falsy the editor will add automatically commands `core:component-exit` (select parent component, added if there is one), `tlb-move` (added if `draggable`) , `tlb-clone` (added if `copyable`), `tlb-delete` (added if `removable`). - */ - toolbar?: object[]; - ///** - // * Children components. Default: `null` - // */ - components?: Backbone.Collection; - [key: string]: any - } - - /** - * The Component object represents a single node of our template structure, so when you update its properties the changes are - * immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all - * the tree of nodes). - * An example on how to update properties: - * ```js - * component.set({ - * tagName: 'span', - * attributes: { ... }, - * removable: false, - * }); - * component.get('tagName'); - * // -> 'span' - * ``` - * - * [Component]: component.html - */ - interface Component extends Backbone.Model { - view?: ComponentView - - /** - * Hook method, called once the model is created - */ - init(): void; - - /** - * Hook method, called when the model has been updated (eg. updated some model's property) - * @param property - Property name, if triggered after some property update - * @param value - Property value, if triggered after some property update - * @param previous - Property previous value, if triggered after some property update - */ - updated(property: string, value: any, previous: any): void; - - /** - * Hook method, called once the model has been removed - */ - removed(): void; - - /** - * Check component's type - * @example - * component.is('image') - * // -> false - * @param type - Component type - */ - is(type: string): boolean; - - /** - * Return all the propeties - */ - props(): ComponentProperties; - - /** - * Get the index of the component in the parent collection. - */ - index(): number; - - /** - * Change the drag mode of the component. - * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 - * @param value - Drag mode, options: 'absolute' | 'translate' - */ - setDragMode(value: string): this; - - /** - * Find inner components by query string. - * **ATTENTION**: this method works only with already rendered component - * @example - * component.find('div > .class'); - * // -> [Component, Component, ...] - * @param query - Query string - * @returns Array of components - */ - find(query: string): Component[]; - - /** - * Find all inner components by component type. - * The advantage of this method over `find` is that you can use it - * also before rendering the component - * @example - * const allImages = component.findType('image'); - * console.log(allImages[0]) // prints the first found component - * @param type - Component type - */ - findType(type: string): Component[]; - - /** - * Find the closest parent component by query string. - * **ATTENTION**: this method works only with already rendered component - * @example - * component.closest('div.some-class'); - * // -> Component - * @param query - Query string - */ - closest(query: string): Component; - - /** - * Find the closest parent component by its type. - * The advantage of this method over `closest` is that you can use it - * also before rendering the component - * @example - * const Section = component.closestType('section'); - * console.log(Section); - * @param type - Component type - * @returns Found component, otherwise `undefined` - */ - closestType(type: string): Component; - - /** - * The method returns a Boolean value indicating whether the passed - * component is a descendant of a given component - * @param component - Component to check - */ - contains(component: Component): boolean; - - /** - * Replace a component with another one - * @example - * component.replaceWith('
Some new content
'); - * // -> Component - * @param el - Component or HTML string - * @returns New added component/s - */ - replaceWith(el: string | Component): Component | Component[]; - - /** - * Update attributes of the component - * @example - * component.setAttributes({ id: 'test', 'data-key': 'value' }); - * @param attrs - Key value attributes - * @param options - Options for the model update - */ - setAttributes(attrs: any, options: any): this; - - /** - * Add attributes to the component - * @example - * component.addAttributes({ 'data-key': 'value' }); - * @param attrs - Key value attributes - * @param options - Options for the model update - */ - addAttributes(attrs: any, options: any): this; - - /** - * Remove attributes from the component - * @example - * component.removeAttributes('some-attr'); - * component.removeAttributes(['some-attr1', 'some-attr2']); - * @param attrs - Array of attributes to remove - * @param options - Options for the model update - */ - removeAttributes(attrs: string | String[], options: any): this; - - /** - * Get the style of the component - */ - getStyle(): any; - - /** - * Set the style on the component - * @example - * component.setStyle({ color: 'red' }); - * @param prop - Key value style object - */ - setStyle(prop: any): any; - - /** - * Return all component's attributes - */ - getAttributes(): Record; - - /** - * Add classes - * @example - * model.addClass('class1'); - * model.addClass('class1 class2'); - * model.addClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - * @param classes - Array or string of classes - * @returns Array of added selectors - */ - addClass(classes: String[] | string): any[]; - - /** - * Set classes (resets current collection) - * @example - * model.setClass('class1'); - * model.setClass('class1 class2'); - * model.setClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - * @param classes - Array or string of classes - * @returns Array of added selectors - */ - setClass(classes: String[] | string): any[]; - - /** - * Remove classes - * @example - * model.removeClass('class1'); - * model.removeClass('class1 class2'); - * model.removeClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - * @param classes - Array or string of classes - * @returns Array of removed selectors - */ - removeClass(classes: String[] | string): any[]; - - /** - * Returns component's classes as an array of strings - */ - getClasses(): any[]; - - /** - * Add new component children - * @example - * someComponent.get('components').length // -> 0 - * const videoComponent = someComponent.append('
')[0]; - * // This will add 2 components (`video` and `div`) to your `someComponent` - * someComponent.get('components').length // -> 2 - * // You can pass components directly - * otherComponent.append(otherComponent2); - * otherComponent.append([otherComponent3, otherComponent4]); - * // append at specific index (eg. at the beginning) - * someComponent.append(otherComponent, { at: 0 }); - * @param components - Component to add - * @param [opts = {}] - Options for the append action - * @returns Array of appended components - */ - append(components: Component | string, opts?: any): any[]; - - /** - * Set new collection if `components` are provided, otherwise the - * current collection is returned - * @example - * // Set new collection - * component.components('
'); - * // Get current collection - * const collection = component.components(); - * console.log(collection.length); - * // -> 2 - * @param [components] - Component Definitions or HTML string - * @param [opts = {}] - Options, same as in `Component.append()` - */ - components(components?: Component | string, opts?: any): Backbone.Collection; - - /** - * If exists, returns the child component at specific index. - * @example - * // Return first child - * component.getChildAt(0); - * // Return second child - * component.getChildAt(1); - * @param index - Index of the component to return - */ - getChildAt(index: number): any; - - /** - * If exists, returns the last child component. - * @example - * const lastChild = component.getLastChild(); - */ - getLastChild(): any; - - /** - * Remove all inner components - * * @return {this} - */ - empty(): void; - - /** - * Get the parent component, if exists - * @example - * component.parent(); - * // -> Component - */ - parent(): Component | null; - - /** - * Get traits. - * @example - * const traits = component.getTraits(); - * console.log(traits); - * // [Trait, Trait, Trait, ...] - */ - getTraits(): Trait[]; - - /** - * Replace current collection of traits with a new one. - * @example - * const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]); - * console.log(traits); - * // [Trait, ...] - * @param traits - Array of trait definitions - */ - setTraits(traits: object[]): Trait[]; - - /** - * Get the trait by id/name. - * @example - * const traitTitle = component.getTrait('title'); - * traitTitle && traitTitle.set('label', 'New label'); - * @param id - The `id` or `name` of the trait - * @returns Trait getModelToStyle - */ - getTrait(id: string): Trait | null; - - /** - * Update a trait. - * @example - * component.updateTrait('title', { - * type: 'select', - * options: [ 'Option 1', 'Option 2' ], - * }); - * @param id - The `id` or `name` of the trait - * @param props - Object with the props to update - */ - updateTrait(id: string, props: any): this; - - /** - * Get the trait position index by id/name. Useful in case you want to - * replace some trait, at runtime, with something else. - * @example - * const traitTitle = component.getTraitIndex('title'); - * console.log(traitTitle); // 1 - * @param id - The `id` or `name` of the trait - * @returns Index position of the current trait - */ - getTraitIndex(id: string): number; - - /** - * Remove trait/s by id/s. - * @example - * component.removeTrait('title'); - * component.removeTrait(['title', 'id']); - * @param id - The `id`/`name` of the trait (or an array) - * @returns Array of removed traits - */ - removeTrait(id: string | String[]): Trait[]; - - /** - * Add new trait/s. - * @example - * component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index) - * component.addTrait({ - * type: 'checkbox', - * name: 'disabled', - * }); - * component.addTrait(['title', {...}, ...]); - * @param trait - Trait to add (or an array of traits) - * @param opts - Options for the add - * @returns Array of added traits - */ - addTrait(trait: string | any | (String | object)[], opts: Record): Trait[]; - - /** - * Get the name of the component - */ - getName(): string; - - /** - * Get the icon string - */ - getIcon(): string; - - /** - * Return HTML string of the component - * @example - * // Simple HTML return - * component.set({ tagName: 'span' }); - * component.setAttributes({ title: 'Hello' }); - * component.toHTML(); - * // -> - * - * // Custom attributes - * component.toHTML({ attributes: { 'data-test': 'Hello' } }); - * // -> - * - * // Custom dynamic attributes - * component.toHTML({ - * attributes(component, attributes) { - * if (component.get('tagName') == 'span') { - * attributes.title = 'Custom attribute'; - * } - * return attributes; - * }, - * }); - * // -> - * @param [opts = {}] - Options - * @param [opts.tag] - Custom tagName - * @param [opts.attributes = null] - You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. - * @param [opts.withProps] - Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. - * @param [opts.altQuoteAttr] - In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). - * @returns HTML string - */ - toHTML(opts?: { - tag?: string; - attributes?: any | ((...params: any[]) => any); - withProps?: boolean; - altQuoteAttr?: boolean; - }): string; - - /** - * Get inner HTML of the component - * @param [opts = {}] - Same options of `toHTML` - * @returns HTML string - */ - getInnerHTML(opts?: any): string; - - /** - * Return an object containing only changed props - */ - getChangedProps(): void; - - /** - * Get block id - */ - getId(): string; - - /** - * Set new id on the component - */ - setId(id: string): this; - - /** - * Get the DOM element of the component. - * This works only if the component is already rendered - * @param frame - Specific frame from which taking the element - */ - getEl(frame?: Frame): HTMLElement; - - /** - * Get the View of the component. - * This works only if the component is already rendered - * @param frame - Get View of a specific frame - */ - getView(frame?: Frame): ComponentView; - - /** - * Execute callback function on itself and all inner components - * @example - * component.onAll(component => { - * // do something with component - * }) - * @param clb - Callback function, the model is passed as an argument - */ - onAll(clb: (...params: any[]) => any): this; - - /** - * Remove the component - */ - remove(): this; - - /** - * Move the component to another destination component - * @example - * // Move the selected component on top of the wrapper - * const dest = editor.getWrapper(); - * editor.getSelected().move(dest, { at: 0 }); - * @param component - Destination component (so the current one will be appended as a child) - * @param opts - Options for the append action - */ - move(component: Component, opts: any): this; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/panels/config/config.js) - * ```js - * const editor = grapesjs.init({ - * panels: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const panelManager = editor.Panels; - * ``` - * - * * [addPanel](#addpanel) - * * [addButton](#addbutton) - * * [getButton](#getbutton) - * * [getPanel](#getpanel) - * * [getPanels](#getpanels) - * * [getPanelsEl](#getpanelsel) - * * [removePanel](#removepanel) - * * [removeButton](#removebutton) - */ - interface Panels { - /** - * Returns the collection of panels - * @returns Collection of panel - */ - getPanels(): Backbone.Collection; - /** - * Returns panels element - */ - getPanelsEl(): HTMLElement; - /** - * Add new panel to the collection - * @example - * var newPanel = panelManager.addPanel({ - * id: 'myNewPanel', - * visible : true, - * buttons : [...], - * }); - * @param panel - Object with right properties or an instance of Panel - * @returns Added panel. Useful in case passed argument was an Object - */ - addPanel(panel: any | Panel): Panel; - /** - * Remove a panel from the collection - * @example - * const newPanel = panelManager.removePanel({ - * id: 'myNewPanel', - * visible : true, - * buttons : [...], - * }); - * - * const newPanel = panelManager.removePanel('myNewPanel'); - * @param panel - Object with right properties or an instance of Panel or Painel id - * @returns Removed panel. Useful in case passed argument was an Object - */ - removePanel(panel: any | Panel | string): Panel; - /** - * Get panel by ID - * @example - * var myPanel = panelManager.getPanel('myNewPanel'); - * @param id - Id string - */ - getPanel(id: string): Panel | null; - /** - * Add button to the panel - * @example - * var newButton = panelManager.addButton('myNewPanel',{ - * id: 'myNewButton', - * className: 'someClass', - * command: 'someCommand', - * attributes: { title: 'Some title'}, - * active: false, - * }); - * // It's also possible to pass the command as an object - * // with .run and .stop methods - * ... - * command: { - * run: function(editor) { - * ... - * }, - * stop: function(editor) { - * ... - * } - * }, - * // Or simply like a which will be evaluated as a single .run command - * ... - * command: function(editor) { - * ... - * } - * @param panelId - Panel's ID - * @param button - Button object or instance of Button - * @returns Added button. Useful in case passed button was an Object - */ - addButton(panelId: string, button: ButtonOptions | Button): Button | null; - /** - * Remove button from the panel - * @example - * const removedButton = panelManager.addButton('myNewPanel',{ - * id: 'myNewButton', - * className: 'someClass', - * command: 'someCommand', - * attributes: { title: 'Some title'}, - * active: false, - * }); - * - * const removedButton = panelManager.removeButton('myNewPanel', 'myNewButton'); - * @param panelId - Panel's ID - * @param buttonId - Button's ID - * @returns Removed button. - */ - removeButton(panelId: string, buttonId: string): Button | null; - /** - * Get button from the panel - * @example - * var button = panelManager.getButton('myPanel','myButton'); - * @param panelId - Panel's ID - * @param id - Button's ID - */ - getButton(panelId: string, id: string): Button | null; - } - - /** - * With Style Manager you build categories (called sectors) of CSS properties which could be used to customize the style of components. - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/style_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * styleManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('style:sector:add', (sector) => { ... }); - * - * // Use the API - * const styleManager = editor.StyleManager; - * styleManager.addSector(...); - * ``` - * ## Available Events - * * `style:sector:add` - Sector added. The [Sector] is passed as an argument to the callback. - * * `style:sector:remove` - Sector removed. The [Sector] is passed as an argument to the callback. - * * `style:sector:update` - Sector updated. The [Sector] and the object containing changes are passed as arguments to the callback. - * * `style:property:add` - Property added. The [Property] is passed as an argument to the callback. - * * `style:property:remove` - Property removed. The [Property] is passed as an argument to the callback. - * * `style:property:update` - Property updated. The [Property] and the object containing changes are passed as arguments to the callback. - * * `style:target` - Target selection changed. The target (or `null` in case the target is deselected) is passed as an argument to the callback. - * - * - * ## Methods - * * [getConfig](#getconfig) - * * [addSector](#addsector) - * * [getSector](#getsector) - * * [getSectors](#getsectors) - * * [removeSector](#removesector) - * * [addProperty](#addproperty) - * * [getProperty](#getproperty) - * * [getProperties](#getproperties) - * * [removeProperty](#removeproperty) - * * [select](#select) - * * [getSelected](#getselected) - * * [getSelectedAll](#getselectedall) - * * [getSelectedParents](#getselectedparents) - * * [addStyleTargets](#addstyletargets) - * * [getBuiltIn](#getbuiltin) - * * [getBuiltInAll](#getbuiltinall) - * * [addBuiltIn](#addbuiltin) - * * [addType](#addtype) - * * [getType](#gettype) - * * [getTypes](#gettypes) - * - * [Sector]: sector.html - * [CssRule]: css_rule.html - * [Component]: component.html - * [Property]: property.html - */ - interface StyleManager { - /** - * Get configuration object - */ - getConfig(): StyleManagerConfig; - /** - * Add new sector. If the sector with the same id already exists, that one will be returned. - * @example - * const sector = styleManager.addSector('mySector',{ - * name: 'My sector', - * open: true, - * properties: [{ name: 'My property'}] - * }, { at: 0 }); - * // With `at: 0` we place the new sector at the beginning of the list - * @param id - Sector id - * @param sector - Sector definition. Check the [available properties](sector.html#properties) - * @param [options = {}] - Options - * @param [options.at] - Position index (by default, will be appended at the end). - */ - addSector(id: string, sector: any, options?: { - at?: number; - }): any; - /** - * Get sector by id. - * @example - * const sector = styleManager.getSector('mySector'); - * @param id - Sector id - */ - getSector(id: string): any; - /** - * Get all sectors. - * @example - * const sectors = styleManager.getSectors(); - * @param [opts = {}] - Options - * @param [opts.visible] - Returns only visible sectors - */ - getSectors(opts?: { - visible?: boolean; - }): any; - /** - * Remove sector by id. - * @example - * const removed = styleManager.removeSector('mySector'); - * @param id - Sector id - */ - removeSector(id: string): any; - /** - * Add new property to the sector. - * @example - * const property = styleManager.addProperty('mySector', { - * label: 'Minimum height', - * property: 'min-height', - * type: 'select', - * default: '100px', - * options: [ - * { id: '100px', label: '100' }, - * { id: '200px', label: '200' }, - * ], - * }, { at: 0 }); - * @param sectorId - Sector id. - * @param property - Property definition. Check the [base available properties](property.html#properties) + others based on the `type` of your property. - * @param [opts = {}] - Options - * @param [opts.at] - Position index (by default, will be appended at the end). - */ - addProperty(sectorId: string, property: any, opts?: { - at?: number; - }): any; - /** - * Get the property. - * @example - * const property = styleManager.getProperty('mySector', 'min-height'); - * @param sectorId - Sector id. - * @param id - Property id. - */ - getProperty(sectorId: string, id: string): any; - /** - * Get all properties of the sector. - * @example - * const properties = styleManager.getProperties('mySector'); - * @param sectorId - Sector id. - */ - getProperties(sectorId: string): any; - /** - * Remove the property. - * @example - * const property = styleManager.removeProperty('mySector', 'min-height'); - * @param sectorId - Sector id. - * @param id - Property id. - */ - removeProperty(sectorId: string, id: string): any; - /** - * Select new target. - * The target could be a Component, CSSRule, or a CSS selector string. - * @example - * // Select the first button in the current page - * const wrapperCmp = editor.Pages.getSelected().getMainComponent(); - * const btnCmp = wrapperCmp.find('button')[0]; - * btnCmp && styleManager.select(btnCmp); - * - * // Set as a target the CSS selector - * styleManager.select('.btn > span'); - */ - select(): any; - /** - * Get the last selected target. - * By default, the Style Manager shows styles of the last selected target. - */ - getSelected(): any; - /** - * Get the array of selected targets. - */ - getSelectedAll(): any; - /** - * Get parent rules of the last selected target. - */ - getSelectedParents(): any; - /** - * Update selected targets with a custom style. - * @example - * styleManager.addStyleTargets({ color: 'red' }); - * @param style - Style object - * @param [opts = {}] - Options - */ - addStyleTargets(style: any, opts?: any): void; - /** - * Return built-in property definition - * @example - * const widthPropDefinition = styleManager.getBuiltIn('width'); - * @param prop - Property name. - * @returns Property definition. - */ - getBuiltIn(prop: string): any | null; - /** - * Get all the available built-in property definitions. - */ - getBuiltInAll(): any; - /** - * Add built-in property definition. - * If the property exists already, it will extend it. - * @example - * const sector = styleManager.addBuiltIn('new-property', { - * type: 'select', - * default: 'value1', - * options: [{ id: 'value1', label: 'Some label' }, ...], - * }) - * @param prop - Property name. - * @param definition - Property definition. - * @returns Added property definition. - */ - addBuiltIn(prop: string, definition: any): any; - /** - * Add new property type - * @example - * styleManager.addType('my-custom-prop', { - * // Create UI - * create({ props, change }) { - * const el = document.createElement('div'); - * el.innerHTML = ''; - * const inputEl = el.querySelector('.my-input'); - * inputEl.addEventListener('change', event => change({ event })); - * inputEl.addEventListener('input', event => change({ event, partial: true })); - * return el; - * }, - * // Propagate UI changes up to the targets - * emit({ props, updateStyle }, { event, partial }) { - * const { value } = event.target; - * updateStyle(`${value}px`, { partial }); - * }, - * // Update UI (eg. when the target is changed) - * update({ value, el }) { - * el.querySelector('.my-input').value = parseInt(value, 10); - * }, - * // Clean the memory from side effects if necessary (eg. global event listeners, etc.) - * destroy() {} - * }) - * @param id - Type ID - * @param definition - Definition of the type. - */ - addType(id: string, definition: any): void; - /** - * Get type - * @param id - Type ID - * @returns Type definition - */ - getType(id: string): any; - /** - * Get all types - */ - getTypes(): any[]; - } + toolbar?: object[]; + ///** + // * Children components. Default: `null` + // */ + components?: Backbone.Collection; + [key: string]: any; + } - interface SectorOptions { - /** - * Sector id, eg. `typography` - */ - id: string; - /** - * Sector name, eg. `Typography` - */ - name: string; - /** - * Indicates the open state. - * @defaultValue true - */ - open?: boolean; - /** - * Indicate an array of Property defintions. - * @defaultValue [] - */ - properties?: AnyProperty[]; - } - - interface Sector extends Backbone.Model { - /** - * Get sector id - */ - getId(): string; - - /** - * Get sector name - */ - getName(): string; - - /** - * Update sector name. - * @param value - New sector name - */ - setName(value: string): void; - - /** - * Check if the sector is open - */ - isOpen(): boolean; - - /** - * Update Sector open state - */ - setOpen(value: boolean): void; - - /** - * Check if the sector is visible - */ - isVisible(): boolean; - - /** - * Get sector properties. - * @param [opts = {}] - Options - * @param [opts.withValue = false] - Get only properties with value - * @param [opts.withParentValue = false] - Get only properties with parent value - */ - getProperties(opts?: { - withValue?: boolean; - withParentValue?: boolean; - }): AnyProperty[]; - } - - interface PropertyOptions { - - /** - * Property id, eg. `my-property-id`. - */ - id: string; - /** - * Related CSS property name, eg. `text-align`. - */ - property: string; - /** - * Defaul value of the property. - */ - default: string; - /** - * Label to use in UI, eg. `Text Align`. - */ - label: string; - /** - * Change callback. - \n - ```js - onChange: ({ property, from, to }) => { - console.log(`Changed property`, property.getName(), { from, to }); - } - ``` - */ - onChange?: (...params: any[]) => any; - } - - interface Property extends Backbone.Model { - /** - * Get property id - */ - getId(): string; - - /** - * Get the property type. - * The type of the property is defined on property creation and based on its value the proper Property class is assigned. - * The default type is `base`. - */ - getType(): string; + /** + * The Component object represents a single node of our template structure, so when you update its properties the changes are + * immediately reflected on the canvas and in the code to export (indeed, when you ask to export the code we just go through all + * the tree of nodes). + * An example on how to update properties: + * ```js + * component.set({ + * tagName: 'span', + * attributes: { ... }, + * removable: false, + * }); + * component.get('tagName'); + * // -> 'span' + * ``` + * + * [Component]: component.html + */ + interface Component extends Backbone.Model { + view?: ComponentView; - /** - * Get name (the CSS property name). - */ - getName(): string; + /** + * Hook method, called once the model is created + */ + init(): void; - /** - * Get property label. - * @param {Object} [opts={}] Options - * @param {Boolean} [opts.locale=true] Use the locale string from i18n module - */ - getLabel(opts?: {locale?: boolean}): string; - - /** - * Get property value. - * @param [opts = {}] - Options - * @param [opts.noDefault = false] - Avoid returning the default value - */ - getValue(opts?: { - noDefault?: boolean; - }): string; - - /** - * Check if the property has value. - * @param [opts = {}] - Options - * @param [opts.noParent = false] - Ignore the value if it comes from the parent target. - */ - hasValue(opts?: { - noParent?: boolean; - }): boolean; - - /** - * Indicates if the current value is coming from a parent target (eg. another CSSRule). - */ - hasValueParent(): boolean; - - /** - * Get the CSS style object of the property. - * @param {Object} [opts={}] Options - * @param {Boolean} [opts.camelCase] Return property name in camelCase. - * @example - * // In case the property is `color` with a value of `red`. - * console.log(property.getStyle()); - * // { color: 'red' }; - */ - getStyle(opts?: {camelCase?: boolean}): any; - - /** - * Get the default value. - */ - getDefaultValue(): string; - - /** - * Update the value. - * The change is also propagated to the selected targets (eg. CSS rule). - * @param value - New value - * @param [opts = {}] - Options - * @param [opts.partial = false] - If `true` the update on targets won't be considered complete (not stored in UndoManager) - * @param [opts.noTarget = false] - If `true` the change won't be propagated to selected targets. - */ - upValue(value: string, opts?: { - partial?: boolean; - noTarget?: boolean; - }): void; - - /** - * Check if the sector is visible - */ - isVisible(): boolean; - - /** - * Clear the value. - * The change is also propagated to the selected targets (eg. the css property is cleared). - * @param [opts = {}] - Options - * @param [opts.noTarget = false] - If `true` the change won't be propagated to selected targets. - */ - clear(opts?: { - noTarget?: boolean; - }): void; - - /** - * Indicates if the current value comes directly from the selected target and so can be cleared. - */ - canClear(): boolean; - - /** - * If the current property is a sub-property, this will return the parent Property. - */ - getParent(): any; - - /** - * Indicates if the property is full-width in UI. - */ - isFull(): boolean; - } - - interface PropertyNumberOptions extends PropertyOptions { - /** - * Array of units, eg. `['px', '%']` - */ - units: String[]; - /** - * Minimum value. - */ - min: number; - /** - * Maximum value. - */ - max: number; - /** - * Step value. - */ - step: number; - } - - interface PropertyNumber extends Property { - /** - * Get property units. - */ - getUnits(): String[]; - - /** - * Get property unit value. - */ - getUnit(): string; - - /** - * Get min value. - */ - getMin(): number; - - /** - * Get max value. - */ - getMax(): number; - - /** - * Get step value. - */ - getStep(): number; - - /** - * Update property unit value. - * The change is also propagated to the selected targets. - * @param unit - New unit value - * @param [opts = {}] - Options - * @param [opts.noTarget = false] - If `true` the change won't be propagated to selected targets. - */ - upUnit(unit: string, opts?: { - noTarget?: boolean; - }): string; - } - - interface SelectOption { - id?: string - value?: string - label? : string - name?: string - } - - interface PropertySelectOptions extends PropertyOptions { - /** - * Array of option definitions. - \n - ```js - options: [ - { id: '100', label: 'Set 100' }, - { id: '200', label: 'Set 200' }, - ] - ``` - */ - options: SelectOption[]; - } - - interface PropertySelect extends Property { - /** - * Get available options. - * @returns Array of options - */ - getOptions(): SelectOption[]; - - /** - * Get current selected option or by id. - * @param [id] - Option id. - */ - getOption(id?: string): any | null; - - /** - * Update options. - * @param value - New array of options, eg. `[{ id: 'val-1', label: 'Value 1' }]` - */ - setOptions(value: SelectOption[]): void; - - /** - * Add new option. - * @param value - Option object, eg. `{ id: 'val-1', label: 'Value 1' }` - */ - addOption(value: SelectOption): void; - - /** - * Get the option id from the option object. - * @param option - Option object - * @returns Option id - */ - getOptionId(option: SelectOption): string; - - /** - * Get option label. - * @param id - Option id or the option object - * @param [opts = {}] - Options - * @param [opts.locale = true] - Use the locale string from i18n module - * @returns Option label - */ - getOptionLabel(id: string | any, opts?: { - locale?: boolean; - }): string; - } + /** + * Hook method, called when the model has been updated (eg. updated some model's property) + * @param property - Property name, if triggered after some property update + * @param value - Property value, if triggered after some property update + * @param previous - Property previous value, if triggered after some property update + */ + updated(property: string, value: any, previous: any): void; - interface PropertyCompositeOptions extends PropertyOptions { + /** + * Hook method, called once the model has been removed + */ + removed(): void; - /** - * Array of sub properties, eg. `[{ type: 'number', property: 'margin-top' }, ...]` - */ - properties: AnyProperty[]; - /** - * Indicate if the final CSS property is splitted (detached: `margin-top: X; margin-right: Y; ...`) or combined (not detached: `margin: X Y ...;`) - */ - detached?: boolean; - /** - * Value used to split property values, default `" "`. - * @defaultValue ' ' - */ - separator?: string | RegExp; - /** - * Value used to join property values, default `" "`. - * @defaultValue ' ' - */ - join?: string; - /** - * Custom logic for getting property values from the target style object. - \n - ```js - fromStyle: (style) => { - const margins = parseMarginShorthand(style.margin); - return { - 'margin-top': margins.top, - // ... - }; - } - ``` - */ - fromStyle?: (style : Record) => Record; - /** - * Custom logic for creating the CSS style object to apply on selected targets. - \n - ```js - toStyle: (values) => { - const top = values['margin-top'] || 0; - const right = values['margin-right'] || 0; - // ... - return { - margin: `${top} ${right} ...`, - }; - } - ``` - */ - toStyle?: (values : Record) => Record; - } - interface PropertyComposite extends Property { - /** - * Get properties. - */ - getProperties(): AnyProperty[]; + /** + * Check component's type + * @example + * component.is('image') + * // -> false + * @param type - Component type + */ + is(type: string): boolean; - /** - * Get property by id. - * @param id - Property id. - */ - getProperty(id: string): any; + /** + * Return all the propeties + */ + props(): ComponentProperties; - /** - * Get property at index. - */ - getPropertyAt(index: number): any; + /** + * Get the index of the component in the parent collection. + */ + index(): number; - /** - * Check if the property is detached. - */ - isDetached(): boolean; - - /** - * Get current values of properties. - * @example - * // In case the property is `margin` with sub properties like `margin-top`, `margin-right`, etc. - * console.log(property.getValues()); - * // { 'margin-top': '10px', 'margin-right': '20px', ... }; - * @param [opts = {}] - Options - * @param [opts.byName = false] - Use property names as a key instead of the id. - */ - getValues(opts?: { - byName?: boolean; - }): any; + /** + * Change the drag mode of the component. + * To get more about this feature read: https://github.com/artf/grapesjs/issues/1936 + * @param value - Drag mode, options: 'absolute' | 'translate' + */ + setDragMode(value: string): this; - /** - * Get property separator. - */ - getSeparator(): RegExp; + /** + * Find inner components by query string. + * **ATTENTION**: this method works only with already rendered component + * @example + * component.find('div > .class'); + * // -> [Component, Component, ...] + * @param query - Query string + * @returns Array of components + */ + find(query: string): Component[]; - /** - * Get the join value. - */ - getJoin(): string; - } + /** + * Find all inner components by component type. + * The advantage of this method over `find` is that you can use it + * also before rendering the component + * @example + * const allImages = component.findType('image'); + * console.log(allImages[0]) // prints the first found component + * @param type - Component type + */ + findType(type: string): Component[]; - type AnyProperty = Property | PropertyNumber | PropertySelect | PropertyComposite | PropertyStack; + /** + * Find the closest parent component by query string. + * **ATTENTION**: this method works only with already rendered component + * @example + * component.closest('div.some-class'); + * // -> Component + * @param query - Query string + */ + closest(query: string): Component; - interface Layer extends Backbone.Model<{}> { - /** - * Get layer id. - */ - getId() : string + /** + * Find the closest parent component by its type. + * The advantage of this method over `closest` is that you can use it + * also before rendering the component + * @example + * const Section = component.closestType('section'); + * console.log(Section); + * @param type - Component type + * @returns Found component, otherwise `undefined` + */ + closestType(type: string): Component; - /** - * Get layer index. - */ - getIndex() : number + /** + * The method returns a Boolean value indicating whether the passed + * component is a descendant of a given component + * @param component - Component to check + */ + contains(component: Component): boolean; - /** - * Get layer values. - * @param {Object} [opts={}] Options - * @param {Boolean} [opts.camelCase] Return property names in camelCase. - */ - getValues(opts?: {camelCase? : boolean}) : any + /** + * Replace a component with another one + * @example + * component.replaceWith('
Some new content
'); + * // -> Component + * @param el - Component or HTML string + * @returns New added component/s + */ + replaceWith(el: string | Component): Component | Component[]; - /** - * Get layer label. - */ - getLabel() : string + /** + * Update attributes of the component + * @example + * component.setAttributes({ id: 'test', 'data-key': 'value' }); + * @param attrs - Key value attributes + * @param options - Options for the model update + */ + setAttributes(attrs: any, options: any): this; - /** - * Check if the layer is selected. - */ - isSelected() : boolean + /** + * Add attributes to the component + * @example + * component.addAttributes({ 'data-key': 'value' }); + * @param attrs - Key value attributes + * @param options - Options for the model update + */ + addAttributes(attrs: any, options: any): this; - /** - * Select the layer. - */ - select() : any + /** + * Remove attributes from the component + * @example + * component.removeAttributes('some-attr'); + * component.removeAttributes(['some-attr1', 'some-attr2']); + * @param attrs - Array of attributes to remove + * @param options - Options for the model update + */ + removeAttributes(attrs: string | String[], options: any): this; - /** - * Remove the layer. - */ - remove() : any + /** + * Get the style of the component + */ + getStyle(): any; - /** - * Move layer to a new index. - * @param index New index - */ - move(index : number) : any + /** + * Set the style on the component + * @example + * component.setStyle({ color: 'red' }); + * @param prop - Key value style object + */ + setStyle(prop: any): any; - /** - * Get style object for the preview. - * @param [opts={}] Options. Same of `PropertyStack.getStyleFromLayer` - * @returns Style object - */ - getStylePreview(opts: object) : any + /** + * Return all component's attributes + */ + getAttributes(): Record; - /** - * Check if the property has the preview enabled for this layer. - */ - hasPreview() : boolean - } + /** + * Add classes + * @example + * model.addClass('class1'); + * model.addClass('class1 class2'); + * model.addClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + * @param classes - Array or string of classes + * @returns Array of added selectors + */ + addClass(classes: String[] | string): any[]; - interface PropertyStackOptions extends PropertyCompositeOptions { - /** - * Indicate if the layer should display a preview. - */ - preview?: boolean; - /** - * The separator used to split layer values. - * @defaultValue ', ' - */ - layerSeparator?: string | RegExp; - /** - * Value used to join layer values. - * @defaultValue ', ' - */ - layerJoin?: string; - /** - * Custom logic for creating layer labels. - \n - ```js - layerLabel: (layer) => { - const values = layer.getValues(); - return `A: ${values['prop-a']} B: ${values['prop-b']}`; - } - ``` - */ - layerLabel?: (...params: any[]) => any; - } + /** + * Set classes (resets current collection) + * @example + * model.setClass('class1'); + * model.setClass('class1 class2'); + * model.setClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + * @param classes - Array or string of classes + * @returns Array of added selectors + */ + setClass(classes: String[] | string): any[]; - interface PropertyStack extends PropertyComposite { - /** - * Get all available layers. - */ - getLayers(): Layer[]; - - /** - * Get layer by index. - * @example - * // Get the first layer - * const layerFirst = property.getLayer(0); - * // Get the last layer - * const layers = this.getLayers(); - * const layerLast = property.getLayer(layers.length - 1); - * @param [index = 0] - Layer index position. - */ - getLayer(index?: number): Layer | null; - - /** - * Get selected layer. - */ - getSelectedLayer(): Layer | null; - - /** - * Select layer. - * Without a selected layer any update made on inner properties has no effect. - * @example - * const layer = property.getLayer(0); - * property.selectLayer(layer); - * @param layer Layer to select - */ - selectLayer(layer: Layer): void; + /** + * Remove classes + * @example + * model.removeClass('class1'); + * model.removeClass('class1 class2'); + * model.removeClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + * @param classes - Array or string of classes + * @returns Array of removed selectors + */ + removeClass(classes: String[] | string): any[]; - /** - * Select layer by index. - * @example - * property.selectLayerAt(1); - * @param index - Index of the layer to select. - */ - selectLayerAt(index: number): void; - - /** - * Move layer by index. - * @example - * const layer = property.getLayer(1); - * property.moveLayer(layer, 0); - * @param index - New layer index. - */ - moveLayer(layer: Layer, index: number): void; - - /** - * Add new layer to the stack. - * @example - * // Add new layer at the beginning of the stack with custom values - * property.addLayer({ 'sub-prop1': 'value1', 'sub-prop2': 'value2' }, { at: 0 }); - * @param [props = {}] - Custom property values to use in a new layer. - * @param [opts = {}] - Options - * @param [opts.at] - Position index (by default the layer will be appended at the end). - */ - addLayer(props?: any, opts?: { - at?: number; - }): Layer; + /** + * Returns component's classes as an array of strings + */ + getClasses(): any[]; - /** - * Remove layer. - * @example - * const layer = property.getLayer(0); - * property.removeLayer(layer); - */ - removeLayer(layer: Layer): Layer; + /** + * Add new component children + * @example + * someComponent.get('components').length // -> 0 + * const videoComponent = someComponent.append('
')[0]; + * // This will add 2 components (`video` and `div`) to your `someComponent` + * someComponent.get('components').length // -> 2 + * // You can pass components directly + * otherComponent.append(otherComponent2); + * otherComponent.append([otherComponent3, otherComponent4]); + * // append at specific index (eg. at the beginning) + * someComponent.append(otherComponent, { at: 0 }); + * @param components - Component to add + * @param [opts = {}] - Options for the append action + * @returns Array of appended components + */ + append(components: Component | string, opts?: any): any[]; - /** - * Remove layer by index. - * @example - * property.removeLayerAt(0); - * @param index - Index of the layer to remove - */ - removeLayerAt(index: number): Layer | null; + /** + * Set new collection if `components` are provided, otherwise the + * current collection is returned + * @example + * // Set new collection + * component.components('
'); + * // Get current collection + * const collection = component.components(); + * console.log(collection.length); + * // -> 2 + * @param [components] - Component Definitions or HTML string + * @param [opts = {}] - Options, same as in `Component.append()` + */ + components( + components?: Component | string, + opts?: any + ): Backbone.Collection; - /** - * Get the layer label. The label can be customized with the `layerLabel` property. - * @example - * const layer = this.getLayer(1); - * const label = this.getLayerLabel(layer); - */ - getLayerLabel(layer: Layer): string; - - /** - * Get style object from the layer. - * @param [opts = {}] - Options - * @param [opts.camelCase] - Return property names in camelCase. - * @param [opts.number] - Limit the result of the number types, eg. `number: { min: -3, max: 3 }` - * @returns Style object - */ - getStyleFromLayer(layer: Layer, opts?: { - camelCase?: boolean; - number?: any; - }): any; + /** + * If exists, returns the child component at specific index. + * @example + * // Return first child + * component.getChildAt(0); + * // Return second child + * component.getChildAt(1); + * @param index - Index of the component to return + */ + getChildAt(index: number): any; - /** - * Get preview style object from the layer. - * If the property has `preview: false` the returned object will be empty. - * @param [opts = {}] - Options. Same of `getStyleFromLayer` - * @returns Style object - */ - getStylePreview(layer: Layer, opts?: any): any; - - /** - * Get layer separator. - */ - getLayerSeparator(): RegExp; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/storage_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * storageManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('storage:start', () => { ... }); - * - * // Use the API - * const storageManager = editor.StorageManager; - * storageManager.add(...); - * ``` - * - * ## Available Events - * * `storage:start` - Before the storage request is started - * * `storage:start:store` - Before the store request. The object to store is passed as an argumnet (which you can edit) - * * `storage:start:load` - Before the load request. Items to load are passed as an argumnet (which you can edit) - * * `storage:load` - Triggered when something was loaded from the storage, loaded object passed as an argumnet - * * `storage:store` - Triggered when something is stored to the storage, stored object passed as an argumnet - * * `storage:end` - After the storage request is ended - * * `storage:end:store` - After the store request - * * `storage:end:load` - After the load request - * * `storage:error` - On any error on storage request, passes the error as an argument - * * `storage:error:store` - Error on store request, passes the error as an argument - * * `storage:error:load` - Error on load request, passes the error as an argument - * - * ## Methods - * * [getConfig](#getconfig) - * * [isAutosave](#isautosave) - * * [setAutosave](#setautosave) - * * [getStepsBeforeSave](#getstepsbeforesave) - * * [setStepsBeforeSave](#setstepsbeforesave) - * * [setStepsBeforeSave](#setstepsbeforesave) - * * [getStorages](#getstorages) - * * [getCurrent](#getcurrent) - * * [getCurrentStorage](#getcurrentstorage) - * * [setCurrent](#setcurrent) - * * [add](#add) - * * [get](#get) - * * [store](#store) - * * [load](#load) - */ - interface StorageManager { - /** - * Get configuration object - */ - getConfig(): StorageManagerConfig; - /** - * Checks if autosave is enabled - */ - isAutosave(): boolean; - /** - * Set autosave value - */ - setAutosave(v: boolean): this; - /** - * Returns number of steps required before trigger autosave - */ - getStepsBeforeSave(): number; - /** - * Set steps required before trigger autosave - */ - setStepsBeforeSave(v: number): this; - /** - * Add new storage - * @example - * storageManager.add('local2', { - * async load(storageOptions) { - * // ... - * }, - * async store(data, storageOptions) { - * // ... - * }, - * }); - * @param id - Storage ID - * @param storage - Storage wrapper - * @param storage.load - Load method - * @param storage.store - Store method - */ - add(id: string, storage: IStorage): this; - /** - * Returns storage by id - * @param id - Storage ID - */ - get(id: string): IStorage | null; - /** - * Returns all storages - */ - getStorages(): Record; - /** - * Returns current storage type - */ - getCurrent(): string; - /** - * Set current storage type - * @param id - Storage ID - */ - setCurrent(id: string): this; - /** - * Store data in the current storage. - * @param data Project data. - * @param options Storage options. - * @returns Stored data. - * @example - * const data = editor.getProjectData(); - * await storageManager.store(data); - */ - store(data: ProjectData, options: StorageOptions): Promise; - /** - * Load resource from the current storage by keys - * @param options Storage options. - * @returns Loaded data. - * @example - * const data = await storageManager.load(); - * editor.loadProjectData(data); - * */ - load(options: StorageOptions): Promise; - /** - * Get current storage - */ - getCurrentStorage(): IStorage; - } - - interface ProjectData { - - } - - interface StorageOptions { - - } - - interface IStorage { - load: (options: StorageOptions) => Promise; - store: (data: ProjectData, options: StorageOptions) => Promise; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/device_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * deviceManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const deviceManager = editor.Devices; - * ``` - * ## Available Events - * * `device:add` - Added new device. The [Device] is passed as an argument to the callback - * * `device:remove` - Device removed. The [Device] is passed as an argument to the callback - * * `device:select` - New device selected. The newly selected [Device] and the previous one, are passed as arguments to the callback - * * `device:update` - Device updated. The updated [Device] and the object containing changes are passed as arguments to the callback - * * `device` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback - * - * ## Methods - * * [add](#add) - * * [get](#get) - * * [getDevices](#getdevices) - * * [remove](#remove) - * * [select](#select) - * * [getSelected](#getselected) - * - * [Device]: device.html - */ - interface Devices { - /** - * Add new device - * @example - * const device1 = deviceManager.add({ - * // Without an explicit ID, the `name` will be taken. In case of missing `name`, a random ID will be created. - * id: 'tablet', - * name: 'Tablet', - * width: '900px', // This width will be applied on the canvas frame and for the CSS media - * }); - * const device2 = deviceManager.add({ - * id: 'tablet2', - * name: 'Tablet 2', - * width: '800px', // This width will be applied on the canvas frame - * widthMedia: '810px', // This width that will be used for the CSS media - * height: '600px', // Height will be applied on the canvas frame - * }); - * @param props - Device properties - */ - add(props: any): any; - /** - * Return device by ID - * @example - * const device = deviceManager.get('Tablet'); - * console.log(JSON.stringify(device)); - * // {name: 'Tablet', width: '900px'} - * @param id - ID of the device - */ - get(id: string): any; - /** - * Remove device - * @example - * const removed = deviceManager.remove('device-id'); - * // or by passing the Device - * const device = deviceManager.get('device-id'); - * deviceManager.remove(device); - */ - remove(): any; - /** - * Return all devices - * @example - * const devices = deviceManager.getDevices(); - * console.log(JSON.stringify(devices)); - * // [{name: 'Desktop', width: ''}, ...] - */ - getDevices(): any; - /** - * Change the selected device. This will update the frame in the canvas - * @example - * deviceManager.select('some-id'); - * // or by passing the page - * const device = deviceManager.get('some-id'); - * deviceManager.select(device); - */ - select(): void; - /** - * Get the selected device - * @example - * const selected = deviceManager.getSelected(); - */ - getSelected(): any; - } + /** + * If exists, returns the last child component. + * @example + * const lastChild = component.getLastChild(); + */ + getLastChild(): any; - interface DeviceOptions { - /** - * Device type, eg. `Mobile` - * @defaultValue '' - */ - name?: string; - /** - * Width to set for the editor iframe, eg. '900px' - */ - width?: string; - /** - * Height to set for the editor iframe, eg. '600px' - * @defaultValue '' - */ - height?: string; - /** - * The width which will be used in media queries, If empty the width will be used - * @defaultValue '' - */ - widthMedia?: string; - /** - * Setup the order of media queries - */ - priority?: number; - } - - interface Device extends Backbone.Model { - getName() : string - getWidthMedia() : string - } - - /** - * Selectors in GrapesJS are used in CSS Composer inside Rules and in Components as classes. To illustrate this concept let's take - * a look at this code: - * - * ```css - * span > #send-btn.btn{ - * ... - * } - * ``` - * ```html - * - * - * - * ``` - * - * In this scenario we get: - * * span -> selector of type `tag` - * * send-btn -> selector of type `id` - * * btn -> selector of type `class` - * - * So, for example, being `btn` the same class entity it'll be easier to refactor and track things. - * - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/selector_manager/config/config.js) - * ```js - * const editor = grapesjs.init({ - * selectorManager: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('selector:add', (selector) => { ... }); - * - * // Use the API - * const sm = editor.Selectors; - * sm.add(...); - * ``` - * - * ## Available Events - * * `selector:add` - Selector added. The [Selector] is passed as an argument to the callback. - * * `selector:remove` - Selector removed. The [Selector] is passed as an argument to the callback. - * * `selector:update` - Selector updated. The [Selector] and the object containing changes are passed as arguments to the callback. - * * `selector:state` - States changed. An object containing all the available data about the triggered event is passed as an argument to the callback. - * * `selector` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback. - * - * ## Methods - * * [getConfig](#getconfig) - * * [add](#add) - * * [get](#get) - * * [remove](#remove) - * * [getAll](#getall) - * * [setState](#setstate) - * * [getState](#getstate) - * * [getStates](#getstates) - * * [setStates](#setstates) - * * [getSelected](#getselected) - * * [addSelected](#addselected) - * * [removeSelected](#removeselected) - * * [getSelectedTargets](#getselectedtargets) - * * [setComponentFirst](#setcomponentfirst) - * * [getComponentFirst](#getcomponentfirst) - * - * [Selector]: selector.html - * [State]: state.html - * [Component]: component.html - * [CssRule]: css_rule.html - */ - interface SelectorManager { - /** - * Get configuration object - */ - getConfig(): SelectorManagerConfig; - /** - * Add a new selector to the collection if it does not already exist. - * You can pass selectors properties or string identifiers. - * @example - * const selector = selectorManager.add({ name: 'my-class', label: 'My class' }); - * console.log(selector.toString()) // `.my-class` - * // Same as - * const selector = selectorManager.add('.my-class'); - * console.log(selector.toString()) // `.my-class` - * @param props - Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` - * @param [opts] - Selector options - */ - add(props: any | string, opts?: SelectorOptions): any; - /** - * Get the selector by its name/type - * @example - * const selector = selectorManager.get('.my-class'); - * // Get Id - * const selectorId = selectorManager.get('#my-id'); - * @param name - Selector name or string identifier - */ - get(name: string): any; - /** - * Remove Selector. - * @example - * const removed = selectorManager.remove('.myclass'); - * // or by passing the Selector - * selectorManager.remove(selectorManager.get('.myclass')); - */ - remove(): any; - /** - * Change the selector state - * @example - * selectorManager.setState('hover'); - * @param value - State value - */ - setState(value: string): this; - /** - * Get the current selector state value - */ - getState(): string; - /** - * Get states - */ - getStates(): any; - /** - * Set a new collection of states - * @example - * const states = selectorManager.setStates([ - * { name: 'hover', label: 'Hover' }, - * { name: 'nth-of-type(2n)', label: 'Even/Odd' } - * ]); - * @param states - Array of new states - */ - setStates(states: object[]): any; - /** - * Get commonly selected selectors, based on all selected components. - * @example - * const selected = selectorManager.getSelected(); - * console.log(selected.map(s => s.toString())) - */ - getSelected(): any; - /** - * Add new selector to all selected components. - * @example - * selectorManager.addSelected('.new-class'); - * @param props - Selector properties or string identifiers, eg. `{ name: 'my-class', label: 'My class' }`, `.my-cls` - */ - addSelected(props: any | string): void; - /** - * Remove a common selector from all selected components. - * @example - * selectorManager.removeSelected('.myclass'); - */ - removeSelected(): void; - /** - * Get the array of currently selected targets. - * @example - * const targetsToStyle = selectorManager.getSelectedTargets(); - * console.log(targetsToStyle.map(target => target.getSelectorsString())) - */ - getSelectedTargets(): any; - /** - * Update component-first option. - * If the component-first is enabled, all the style changes will be applied on selected components (ID rules) instead - * of selectors (which would change styles on all components with those classes). - */ - setComponentFirst(value: boolean): void; - /** - * Get the value of component-first option. - */ - getComponentFirst(): boolean; - /** - * Get all selectors - */ - getAll(): any; - } + /** + * Remove all inner components + * * @return {this} + */ + empty(): void; - interface SelectorOptions { - /** - * Selector name, eg. `my-class` - */ - name: string; - /** - * Selector label, eg. `My Class` - */ - label: string; - /** - * Type of the selector. 1 (class) | 2 (id) - * @defaultValue 1 - */ - type?: number; - /** - * If not active, it's not selectable by the Style Manager. - * @defaultValue true - */ - active?: boolean; - /** - * If true, it can't be seen by the Style Manager, but it will be rendered in the canvas and in export code. - */ - private?: boolean; - /** - * If true, it can't be removed from the attacched component. - */ - protected?: boolean; - } - - interface Selector extends Backbone.Model { - /** - * Get selector label. - * @example - * // Given such selector: { name: 'my-selector', label: 'My selector' } - * console.log(selector.getLabel()); - * // -> `My selector` - */ - getLabel(): string; - - /** - * Update selector label. - * @param {String} label New label - * @example - * // Given such selector: { name: 'my-selector', label: 'My selector' } - * selector.setLabel('New Label') - * console.log(selector.getLabel()); - * // -> `New Label` - */ - setLabel(label: string): void; + /** + * Get the parent component, if exists + * @example + * component.parent(); + * // -> Component + */ + parent(): Component | null; - /** - * Get selector active state. - */ - getActive(): boolean; + /** + * Get traits. + * @example + * const traits = component.getTraits(); + * console.log(traits); + * // [Trait, Trait, Trait, ...] + */ + getTraits(): Trait[]; - /** - * Update selector active state. - * @param value - New active state - */ - setActive(value: boolean): void; - } + /** + * Replace current collection of traits with a new one. + * @example + * const traits = component.setTraits([{ type: 'checkbox', name: 'disabled'}, ...]); + * console.log(traits); + * // [Trait, ...] + * @param traits - Array of trait definitions + */ + setTraits(traits: object[]): Trait[]; - interface StateOptions { - /** - * State name, eg. `hover`, `nth-of-type(2n)` - */ - name: string; - /** - * State label, eg. `Hover`, `Even/Odd` - */ - label: string; - } + /** + * Get the trait by id/name. + * @example + * const traitTitle = component.getTrait('title'); + * traitTitle && traitTitle.set('label', 'New label'); + * @param id - The `id` or `name` of the trait + * @returns Trait getModelToStyle + */ + getTrait(id: string): Trait | null; - interface State extends Backbone.Model { + /** + * Update a trait. + * @example + * component.updateTrait('title', { + * type: 'select', + * options: [ 'Option 1', 'Option 2' ], + * }); + * @param id - The `id` or `name` of the trait + * @param props - Object with the props to update + */ + updateTrait(id: string, props: any): this; - /** - * Get state name - */ - getName(): string; + /** + * Get the trait position index by id/name. Useful in case you want to + * replace some trait, at runtime, with something else. + * @example + * const traitTitle = component.getTraitIndex('title'); + * console.log(traitTitle); // 1 + * @param id - The `id` or `name` of the trait + * @returns Index position of the current trait + */ + getTraitIndex(id: string): number; - /** - * Get state label. If label was not provided, the name will be returned. - */ - getLabel(): string; - } - - /** - * This module manages CSS rules in the canvas. - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/css_composer/config/config.js) - * ```js - * const editor = grapesjs.init({ - * cssComposer: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const css = editor.Css; - * ``` - * - * * [addRules](#addrules) - * * [setRule](#setrule) - * * [getRule](#getrule) - * * [getRules](#getrules) - * * [remove](#remove) - * * [clear](#clear) - * - * [CssRule]: css_rule.html - */ - interface CssComposer { - /** - * Add CssRules via CSS string. - * @example - * const addedRules = css.addRules('.my-cls{ color: red } @media (max-width: 992px) { .my-cls{ color: darkred } }'); - * // Check rules - * console.log(addedRules.map(rule => rule.toCSS())); - * @param css - CSS string of rules to add. - */ - addRules(css: string): any; - /** - * Add/update the CssRule. - * @example - * // Simple class-based rule - * const rule = css.setRule('.class1.class2', { color: 'red' }); - * console.log(rule.toCSS()) // output: .class1.class2 { color: red } - * // With state and other mixed selector - * const rule = css.setRule('.class1.class2:hover, div#myid', { color: 'red' }); - * // output: .class1.class2:hover, div#myid { color: red } - * // With media - * const rule = css.setRule('.class1:hover', { color: 'red' }, { - * atRuleType: 'media', - * atRuleParams: '(min-width: 500px)', - * }); - * // output: @media (min-width: 500px) { .class1:hover { color: red } } - * @param selectors - Selector string, eg. `.myclass` - * @param style - Style properties and values - * @param [opts = {}] - Additional properties - * @param [opts.atRuleType = ''] - At-rule type, eg. `media` - * @param [opts.atRuleParams = ''] - At-rule parameters, eg. `(min-width: 500px)` - */ - setRule(selectors: string, style: any, opts?: { - atRuleType?: string; - atRuleParams?: string; - }): any; - /** - * Get the CssRule. - * @example - * const rule = css.getRule('.myclass1:hover'); - * const rule2 = css.getRule('.myclass1:hover, div#myid'); - * const rule3 = css.getRule('.myclass1', { - * atRuleType: 'media', - * atRuleParams: '(min-width: 500px)', - * }); - * @param selectors - Selector string, eg. `.myclass:hover` - * @param [opts = {}] - Additional properties - * @param [opts.atRuleType = ''] - At-rule type, eg. `media` - * @param [opts.atRuleParams = ''] - At-rule parameters, eg. '(min-width: 500px)' - */ - getRule(selectors: string, opts?: { - atRuleType?: string; - atRuleParams?: string; - }): any; - /** - * Get all rules or filtered by a matching selector. - * @example - * // Take all the component specific rules - * const id = someComponent.getId(); - * const rules = css.getRules(`#${id}`); - * console.log(rules.map(rule => rule.toCSS())) - * // All rules in the project - * console.log(css.getRules()) - * @param [selector = ''] - Selector, eg. `.myclass` - */ - getRules(selector?: string): any; - /** - * Remove rule, by CssRule or matching selector (eg. the selector will match also at-rules like `@media`) - * @example - * // Remove by CssRule - * const toRemove = css.getRules('.my-cls'); - * css.remove(toRemove); - * // Remove by selector - * css.remove('.my-cls-2'); - */ - remove(): any; - /** - * Remove all rules - */ - clear(): this; - } - - interface Styleable { - /** - * To trigger the style change event on models I have to - * pass a new object instance - * @param prop - */ - extendStyle(prop : object) : object + /** + * Remove trait/s by id/s. + * @example + * component.removeTrait('title'); + * component.removeTrait(['title', 'id']); + * @param id - The `id`/`name` of the trait (or an array) + * @returns Array of removed traits + */ + removeTrait(id: string | String[]): Trait[]; - /** - * Get style object - */ - getStyle(prop? : string) : object + /** + * Add new trait/s. + * @example + * component.addTrait('title', { at: 1 }); // Add title trait (`at` option is the position index) + * component.addTrait({ + * type: 'checkbox', + * name: 'disabled', + * }); + * component.addTrait(['title', {...}, ...]); + * @param trait - Trait to add (or an array of traits) + * @param opts - Options for the add + * @returns Array of added traits + */ + addTrait( + trait: string | any | (String | object)[], + opts: Record + ): Trait[]; - /** - * Set new style object - * @return {Object} Applied properties - */ - setStyle(prop : object | string, opts?: object) : object + /** + * Get the name of the component + */ + getName(): string; - /** - * Add style property - * @example - * this.addStyle({color: 'red'}); - * this.addStyle('color', 'blue'); - */ - addStyle(prop : object | string, value?: string, opts?: object) : void + /** + * Get the icon string + */ + getIcon(): string; - /** - * Remove style property - */ - removeStyle(prop : string) : void + /** + * Return HTML string of the component + * @example + * // Simple HTML return + * component.set({ tagName: 'span' }); + * component.setAttributes({ title: 'Hello' }); + * component.toHTML(); + * // -> + * + * // Custom attributes + * component.toHTML({ attributes: { 'data-test': 'Hello' } }); + * // -> + * + * // Custom dynamic attributes + * component.toHTML({ + * attributes(component, attributes) { + * if (component.get('tagName') == 'span') { + * attributes.title = 'Custom attribute'; + * } + * return attributes; + * }, + * }); + * // -> + * @param [opts = {}] - Options + * @param [opts.tag] - Custom tagName + * @param [opts.attributes = null] - You can pass an object of custom attributes to replace with the current ones or you can even pass a function to generate attributes dynamically. + * @param [opts.withProps] - Include component properties as `data-gjs-*` attributes. This allows you to have re-importable HTML. + * @param [opts.altQuoteAttr] - In case the attribute value contains a `"` char, instead of escaping it (`attr="value ""`), the attribute will be quoted using single quotes (`attr='value "'`). + * @returns HTML string + */ + toHTML(opts?: { + tag?: string; + attributes?: any | ((...params: any[]) => any); + withProps?: boolean; + altQuoteAttr?: boolean; + }): string; - /** - * Returns string of style properties - */ - styleToString(opts?: object) : string - } + /** + * Get inner HTML of the component + * @param [opts = {}] - Same options of `toHTML` + * @returns HTML string + */ + getInnerHTML(opts?: any): string; - interface CssRuleOptions { - /** - * Array of selectors - */ - selectors: Selector[]; - /** - * Object containing style definitions - */ - style: any; - /** - * Additional string css selectors - * @defaultValue '' - */ - selectorsAdd?: string; - /** - * Type of at-rule, eg. `media`, 'font-face' - * @defaultValue '' - */ - atRuleType?: string; - /** - * At-rule value, eg. `(max-width: 1000px)` - * @defaultValue '' - */ - mediaText?: string; - /** - * This property is used only on at-rules, like 'page' or 'font-face', where the block containes only style declarations - */ - singleAtRule?: boolean; - /** - * State of the rule, eg: `hover`, `focused` - * @defaultValue '' - */ - state?: string; - /** - * If true, sets `!important` on all properties. You can also pass an array to specify properties on which use important - */ - important?: boolean | String[]; - /** - * Indicates if the rule is stylable from the editor + /** + * Return an object containing only changed props + */ + getChangedProps(): void; - [Device]: device.html - [State]: state.html - [Component]: component.html - * @defaultValue true - */ - stylable?: boolean; - } - interface CssRule extends Backbone.Model, Styleable { - /** - * Returns the at-rule statement when exists, eg. `@media (...)`, `@keyframes` - * @example - * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { - * atRuleType: 'media', - * atRuleParams: '(min-width: 500px)' - * }); - * cssRule.getAtRule(); // "@media (min-width: 500px)" - */ - getAtRule(): string; - - /** - * Return selectors of the rule as a string - * @example - * const cssRule = editor.Css.setRule('.class1:hover', { color: 'red' }); - * cssRule.selectorsToString(); // ".class1:hover" - * cssRule.selectorsToString({ skipState: true }); // ".class1" - * @param [opts] - Options - * @param [opts.skipState] - Skip state from the result - */ - selectorsToString(opts?: { - skipState?: boolean; - }): string; - - /** - * Get declaration block (without the at-rule statement) - * @example - * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { - * atRuleType: 'media', - * atRuleParams: '(min-width: 500px)' - * }); - * cssRule.getDeclaration() // ".class1{color:red;}" - * @param [opts = {}] - Options (same as in `selectorsToString`) - */ - getDeclaration(opts?: any): string; + /** + * Get block id + */ + getId(): string; - /** - * Get the Device the rule is related to. - * @example - * const device = rule.getDevice(); - * console.log(device?.getName()); - */ - getDevice(): Device | null; + /** + * Set new id on the component + */ + setId(id: string): this; - /** - * Get the State the rule is related to. - * @example - * const state = rule.getState(); - * console.log(state?.getLabel()); - */ - getState(): State | null; + /** + * Get the DOM element of the component. + * This works only if the component is already rendered + * @param frame - Specific frame from which taking the element + */ + getEl(frame?: Frame): HTMLElement; - /** - * Returns the related Component (valid only for component-specific rules). - * @example - * const cmp = rule.getComponent(); - * console.log(cmp?.toHTML()); - */ - getComponent(): Component | null; - - /** - * Return the CSS string of the rule - * @example - * const cssRule = editor.Css.setRule('.class1', { color: 'red' }, { - * atRuleType: 'media', - * atRuleParams: '(min-width: 500px)' - * }); - * cssRule.toCSS() // "@media (min-width: 500px){.class1{color:red;}}" - * @param [opts = {}] - Options (same as in `getDeclaration`) - * @returns CSS string - */ - toCSS(opts?: any): string; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/modal_dialog/config/config.js) - * ```js - * const editor = grapesjs.init({ - * modal: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const modal = editor.Modal; - * ``` - * - * ## Available Events - * * `modal:open` - Modal is opened - * * `modal:close` - Modal is closed - * * `modal` - Event triggered on any change related to the modal. An object containing all the available data about the triggered event is passed as an argument to the callback. - * - * ## Methods - * * [open](#open) - * * [close](#close) - * * [isOpen](#isopen) - * * [setTitle](#settitle) - * * [getTitle](#gettitle) - * * [setContent](#setcontent) - * * [getContent](#getcontent) - * * [onceClose](#onceclose) - * * [onceOpen](#onceopen) - */ - interface Modal { - /** - * Open the modal window - * @example - * modal.open({ - * title: 'My title', - * content: 'My content', - * attributes: { class: 'my-class' }, - * }); - * @param [opts = {}] - Options - * @param [opts.title] - Title to set for the modal - * @param [opts.content] - Content to set for the modal - * @param [opts.attributes] - Updates the modal wrapper with custom attributes - */ - open(opts?: { - title?: string | HTMLElement; - content?: string | HTMLElement; - attributes?: any; - }): this; - /** - * Close the modal window - * @example - * modal.close(); - */ - close(): this; - /** - * Execute callback when the modal will be closed. - * The callback will be called one only time - * @example - * modal.onceClose(() => { - * console.log('The modal is closed'); - * }); - * @param clb - Callback to call - */ - onceClose(clb: (...params: any[]) => any): this; - /** - * Execute callback when the modal will be opened. - * The callback will be called one only time - * @example - * modal.onceOpen(() => { - * console.log('The modal is opened'); - * }); - * @param clb - Callback to call - */ - onceOpen(clb: (...params: any[]) => any): this; - /** - * Checks if the modal window is open - * @example - * modal.isOpen(); // true | false - */ - isOpen(): boolean; - /** - * Set the title to the modal window - * @example - * // pass a string - * modal.setTitle('Some title'); - * // or an HTMLElement - * const el = document.createElement('div'); - * el.innerText = 'New title'; - * modal.setTitle(el); - * @param title - Title - */ - setTitle(title: string | HTMLElement): this; - /** - * Returns the title of the modal window - * @example - * modal.getTitle(); - */ - getTitle(): string | HTMLElement; - /** - * Set the content of the modal window - * @example - * // pass a string - * modal.setContent('Some content'); - * // or an HTMLElement - * const el = document.createElement('div'); - * el.innerText = 'New content'; - * modal.setContent(el); - * @param content - Content - */ - setContent(content: string | HTMLElement): this; - /** - * Get the content of the modal window - * @example - * modal.getContent(); - */ - getContent(): string | HTMLElement; - } - - /** - * This module allows to customize the built-in toolbar of the Rich Text Editor and use commands from the [HTML Editing APIs](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand). - * It's highly recommended to keep this toolbar as small as possible, especially from styling commands (eg. 'fontSize') and leave this task to the Style Manager - * - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/rich_text_editor/config/config.js) - * ```js - * const editor = grapesjs.init({ - * richTextEditor: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('rte:enable', () => { ... }); - * - * // Use the API - * const rte = editor.RichTextEditor; - * rte.add(...); - * ``` - * - * ## Available Events - * * `rte:enable` - RTE enabled. The view, on which RTE is enabled, is passed as an argument - * * `rte:disable` - RTE disabled. The view, on which RTE is disabled, is passed as an argument - * - * ## Methods - * * [add](#add) - * * [get](#get) - * * [getAll](#getall) - * * [remove](#remove) - * * [getToolbarEl](#gettoolbarel) - */ - interface RichTextEditor { - /** - * Add a new action to the built-in RTE toolbar - * @example - * rte.add('bold', { - * icon: 'B', - * attributes: {title: 'Bold'}, - * result: rte => rte.exec('bold') - * }); - * rte.add('link', { - * icon: document.getElementById('t'), - * attributes: {title: 'Link',} - * // Example on it's easy to wrap a selected content - * result: rte => rte.insertHTML(`${rte.selection()}`) - * }); - * // An example with fontSize - * rte.add('fontSize', { - * icon: ``, - * // Bind the 'result' on 'change' listener - * event: 'change', - * result: (rte, action) => rte.exec('fontSize', action.btn.firstChild.value), - * // Callback on any input change (mousedown, keydown, etc..) - * update: (rte, action) => { - * const value = rte.doc.queryCommandValue(action.name); - * if (value != 'false') { // value is a string - * action.btn.firstChild.value = value; - * } - * } - * }) - * // An example with state - * const isValidAnchor = (rte) => { - * // a utility function to help determine if the selected is a valid anchor node - * const anchor = rte.selection().anchorNode; - * const parentNode = anchor && anchor.parentNode; - * const nextSibling = anchor && anchor.nextSibling; - * return (parentNode && parentNode.nodeName == 'A') || (nextSibling && nextSibling.nodeName == 'A') - * } - * rte.add('toggleAnchor', { - * icon: ``, - * state: (rte, doc) => { - * if (rte && rte.selection()) { - * // `btnState` is a integer, -1 for disabled, 0 for inactive, 1 for active - * return isValidAnchor(rte) ? btnState.ACTIVE : btnState.INACTIVE; - * } else { - * return btnState.INACTIVE; - * } - * }, - * result: (rte, action) => { - * if (isValidAnchor(rte)) { - * rte.exec('unlink'); - * } else { - * rte.insertHTML(`${rte.selection()}`); - * } - * } - * }) - * @param name - Action name - * @param action - Action options - */ - add(name: string, action: any): void; - /** - * Get the action by its name - * @example - * const action = rte.get('bold'); - * // {name: 'bold', ...} - * @param name - Action name - */ - get(name: string): any; - /** - * Get all actions - */ - getAll(): any[]; - /** - * Remove the action from the toolbar - * @example - * const action = rte.remove('bold'); - * // {name: 'bold', ...} - * @returns Removed action - */ - remove(name: string): any; - /** - * Get the toolbar element - */ - getToolbarEl(): HTMLElement; - } - - /** - * You can customize the initial state of the module from the editor initialization - * ```js - * const editor = grapesjs.init({ - * keymaps: { - * // Object of keymaps - * defaults: { - * 'your-namespace:keymap-name' { - * keys: '⌘+z, ctrl+z', - * handler: 'some-command-id' - * }, - * ... - * } - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('keymap:add', () => { ... }); - * - * // Use the API - * const keymaps = editor.Keymaps; - * keymaps.add(...); - * ``` - * - * ## Available Events - * * `keymap:add` - New keymap added. The new keyamp object is passed as an argument - * * `keymap:remove` - Keymap removed. The removed keyamp object is passed as an argument - * * `keymap:emit` - Some keymap emitted, in arguments you get keymapId, shortcutUsed, Event - * * `keymap:emit:{keymapId}` - `keymapId` emitted, in arguments you get keymapId, shortcutUsed, Event - * - * ## Methods - * * [getConfig](#getconfig) - * * [add](#add) - * * [get](#get) - * * [getAll](#getAll) - * * [remove](#remove) - * * [removeAll](#removeall) - */ - interface Keymaps { - /** - * Get module configurations - * @returns Configuration object - */ - getConfig(): any; - /** - * Add new keymap - * @example - * // 'ns' is just a custom namespace - * keymaps.add('ns:my-keymap', '⌘+j, ⌘+u, ctrl+j, alt+u', editor => { - * console.log('do stuff'); - * }); - * // or - * keymaps.add('ns:my-keymap', '⌘+s, ctrl+s', 'some-gjs-command'); - * - * // listen to events - * editor.on('keymap:emit', (id, shortcut, e) => { - * // ... - * }) - * @param id - Keymap id - * @param keys - Keymap keys, eg. `ctrl+a`, `⌘+z, ctrl+z` - * @param handler - Keymap handler, might be a function - * @param [opts = {}] - Options - * @returns Added keymap - * or just a command id as a string - */ - add(id: string, keys: string, handler: ((...params: any[]) => any) | string, opts?: any): any; - /** - * Get the keymap by id - * @example - * keymaps.get('ns:my-keymap'); - * // -> {keys, handler}; - * @param id - Keymap id - * @returns Keymap object - */ - get(id: string): any; - /** - * Get all keymaps - * @example - * keymaps.getAll(); - * // -> {id1: {}, id2: {}}; - */ - getAll(): any; - /** - * Remove the keymap by id - * @example - * keymaps.remove('ns:my-keymap'); - * // -> {keys, handler}; - * @param id - Keymap id - * @returns Removed keymap - */ - remove(id: string): any; - /** - * Remove all binded keymaps - */ - removeAll(): Keymaps; - } - - /** - * This module allows to manage the stack of changes applied in canvas. - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const um = editor.UndoManager; - * ``` - * - * * [getConfig](#getconfig) - * * [add](#add) - * * [remove](#remove) - * * [removeAll](#removeall) - * * [start](#start) - * * [stop](#stop) - * * [undo](#undo) - * * [undoAll](#undoall) - * * [redo](#redo) - * * [redoAll](#redoall) - * * [hasUndo](#hasundo) - * * [hasRedo](#hasredo) - * * [getStack](#getstack) - * * [clear](#clear) - */ - interface UndoManager { - /** - * Get module configurations - * @example - * const config = um.getConfig(); - * // { ... } - * @returns Configuration object - */ - getConfig(): any; - /** - * Add an entity (Model/Collection) to track - * Note: New Components and CSSRules will be added automatically - * @example - * um.add(someModelOrCollection); - * @param entity - Entity to track - */ - add(entity: Backbone.GenericModel | Backbone.Collection): UndoManager; - /** - * Remove and stop tracking the entity (Model/Collection) - * @example - * um.remove(someModelOrCollection); - * @param entity - Entity to remove - */ - remove(entity: Backbone.GenericModel | Backbone.Collection): UndoManager; - /** - * Remove all entities - * @example - * um.removeAll(); - */ - removeAll(): UndoManager; - /** - * Start/resume tracking changes - * @example - * um.start(); - */ - start(): UndoManager; - /** - * Stop tracking changes - * @example - * um.stop(); - */ - stop(): UndoManager; - /** - * Undo last change - * @example - * um.undo(); - */ - undo(): UndoManager; - /** - * Undo all changes - * @example - * um.undoAll(); - */ - undoAll(): UndoManager; - /** - * Redo last change - * @example - * um.redo(); - */ - redo(): UndoManager; - /** - * Redo all changes - * @example - * um.redoAll(); - */ - redoAll(): UndoManager; - /** - * Checks if exists an available undo - * @example - * um.hasUndo(); - */ - hasUndo(): boolean; - /** - * Checks if exists an available redo - * @example - * um.hasRedo(); - */ - hasRedo(): boolean; - /** - * Check if the entity (Model/Collection) to tracked - * Note: New Components and CSSRules will be added automatically - * @param entity - Entity to track - */ - isRegistered(entity: Backbone.GenericModel | Backbone.Collection): boolean; - /** - * Get stack of changes - * @example - * const stack = um.getStack(); - * stack.each(item => ...); - */ - getStack(): Backbone.Collection; - /** - * Get grouped undo manager stack. - * The difference between `getStack` is when you do multiple operations at a time, - * like appending multiple components: - * `editor.getWrapper().append(`
C1
C2
`);` - * `getStack` will return a collection length of 2. - * `getStackGroup` instead will group them as a single operation (the first - * inserted component will be returned in the list) by returning an array length of 1. - */ - getStackGroup(): any[]; - /** - * Clear the stack - * @example - * um.clear(); - */ - clear(): UndoManager; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/canvas/config/config.js) - * ```js - * const editor = grapesjs.init({ - * canvas: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API and listen to its events. Before using these methods, you should get the module from the instance. - * - * ```js - * // Listen to events - * editor.on('canvas:drop', () => { ... }); - * - * // Use the API - * const canvas = editor.Canvas; - * canvas.setCoords(...); - * ``` - * ## Available Events - * * `canvas:dragenter` - When something is dragged inside the canvas, `DataTransfer` instance passed as an argument - * * `canvas:dragover` - When something is dragging on canvas, `DataTransfer` instance passed as an argument - * * `canvas:drop` - Something is dropped in canvas, `DataTransfer` instance and the dropped model are passed as arguments - * * `canvas:dragend` - When a drag operation is ended, `DataTransfer` instance passed as an argument - * * `canvas:dragdata` - On any dataTransfer parse, `DataTransfer` instance and the `result` are passed as arguments. - * By changing `result.content` you're able to customize what is dropped - * - * ## Methods - * * [getConfig](#getconfig) - * * [getElement](#getelement) - * * [getFrameEl](#getframeel) - * * [getWindow](#getwindow) - * * [getDocument](#getdocument) - * * [getBody](#getbody) - * * [setCustomBadgeLabel](#setcustombadgelabel) - * * [hasFocus](#hasfocus) - * * [scrollTo](#scrollto) - * * [setZoom](#setzoom) - * * [getZoom](#getzoom) - * * [getCoords](#getcoords) - * * [setCoords](#setcoords) - * - * [Component]: component.html - * [Frame]: frame.html - */ - interface Canvas { - /** - * Get the configuration object - * @example - * console.log(canvas.getConfig()) - * @returns Configuration object - */ - getConfig(): CanvasConfig; - /** - * Get the canvas element - */ - getElement(): HTMLElement; - /** - * Get the main frame element of the canvas - */ - getFrameEl(): HTMLIFrameElement; - /** - * Get the main frame window instance - */ - getWindow(): Window; - /** - * Get the main frame document element - */ - getDocument(): HTMLDocument; - /** - * Get the main frame body element - */ - getBody(): HTMLBodyElement; - /** - * Set custom badge naming strategy - * @example - * canvas.setCustomBadgeLabel(function(component){ - * return component.getName(); - * }); - */ - setCustomBadgeLabel(f: (...params: any[]) => any): void; - /** - * Get canvas rectangular data - */ - getRect(): any; - /** - * Check if the canvas is focused - */ - hasFocus(): boolean; - /** - * Scroll canvas to the element if it's not visible. The scrolling is - * executed via `scrollIntoView` API and options of this method are - * passed to it. For instance, you can scroll smoothly by using - * `{ behavior: 'smooth' }`. - * @example - * const selected = editor.getSelected(); - * // Scroll smoothly (this behavior can be polyfilled) - * canvas.scrollTo(selected, { behavior: 'smooth' }); - * // Force the scroll, even if the element is alredy visible - * canvas.scrollTo(selected, { force: true }); - * @param [opts = {}] - Options, same as options for `scrollIntoView` - * @param [opts.force = false] - Force the scroll, even if the element is already visible - */ - scrollTo(el: HTMLElement | Component, opts?: { - force?: boolean; - }): void; - /** - * Set canvas zoom value - * @example - * canvas.setZoom(50); // set zoom to 50% - * @param value - The zoom value, from 0 to 100 - */ - setZoom(value: number): this; - /** - * Get canvas zoom value - * @example - * canvas.setZoom(50); // set zoom to 50% - * const zoom = canvas.getZoom(); // 50 - */ - getZoom(): number; - /** - * Set canvas position coordinates - * @example - * canvas.setCoords(100, 100); - * @param x - Horizontal position - * @param y - Vertical position - */ - setCoords(x: number, y: number): this; - /** - * Get canvas position coordinates - * @example - * canvas.setCoords(100, 100); - * const coords = canvas.getCoords(); - * // { x: 100, y: 100 } - * @returns Object containing coordinates - */ - getCoords(): any; - /** - * Add new frame to the canvas - * @example - * canvas.addFrame({ - * name: 'Mobile home page', - * x: 100, // Position in canvas - * y: 100, - * width: 500, // Frame dimensions - * height: 600, - * // device: 'DEVICE-ID', - * components: [ - * '

Title frame

', - * '

Paragraph frame

', - * ], - * styles: ` - * .testh { color: red; } - * .testp { color: blue; } - * `, - * }); - * @param props - Frame properties - */ - addFrame(props: any): any; - } + /** + * Get the View of the component. + * This works only if the component is already rendered + * @param frame - Get View of a specific frame + */ + getView(frame?: Frame): ComponentView; - interface FrameOptions { - /** - * Wrapper component definition. You can also pass an HTML string as components of the default wrapper component. - */ - component: any | string; - /** - * Width of the frame. By default, the canvas width will be taken. - * @defaultValue '' - */ - width?: string; - /** - * Height of the frame. By default, the canvas height will be taken. - * @defaultValue '' - */ - height?: string; - /** - * Horizontal position of the frame in the canvas. - */ - x?: number; - /** - * Vertical position of the frame in the canvas. - */ - y?: number; - } - - interface Frame extends Backbone.Model { - - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/i18n/config.js) - * ```js - * const editor = grapesjs.init({ - * i18n: { - * locale: 'en', - * localeFallback: 'en', - * messages: { - * it: { hello: 'Ciao', ... }, - * ... - * } - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const i18n = editor.I18n; - * ``` - * - * ### Events - * * `i18n:add` - New set of messages is added - * * `i18n:update` - The set of messages is updated - * * `i18n:locale` - Locale changed - */ - interface I18n { - /** - * Get module configurations - * @returns Configuration object - */ - getConfig(): any; - /** - * Update current locale - * @example - * i18n.setLocale('it'); - * @param locale - Locale value - */ - setLocale(locale: string): this; - /** - * Get current locale - * @returns Current locale value - */ - getLocale(): string; - /** - * Get all messages - * @example - * i18n.getMessages(); - * // -> { en: { hello: '...' }, ... } - * i18n.getMessages('en'); - * // -> { hello: '...' } - * @param [lang] - Specify the language of messages to return - * @param [opts] - Options - * @param [opts.debug] - Show warnings in case of missing language - */ - getMessages(lang?: string, opts?: { - debug?: boolean; - }): any; - /** - * Set new set of messages - * @example - * i18n.getMessages(); - * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } } - * i18n.setMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } }); - * // Set replaced - * i18n.getMessages(); - * // -> { en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } } - * @param msg - Set of messages - */ - setMessages(msg: any): this; - /** - * Update messages - * @example - * i18n.getMessages(); - * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2', } } - * i18n.addMessages({ en: { msg2: 'Msg 2 up', msg3: 'Msg 3', } }); - * // Set updated - * i18n.getMessages(); - * // -> { en: { msg1: 'Msg 1', msg2: 'Msg 2 up', msg3: 'Msg 3', } } - * @param msg - Set of messages to add - */ - addMessages(msg: any): this; - /** - * Translate the locale message - * @example - * obj.setMessages({ - * en: { msg: 'Msg', msg2: 'Msg {test}'}, - * it: { msg2: 'Msg {test} it'}, - * }); - * obj.t('msg'); - * // -> outputs `Msg` - * obj.t('msg2', { params: { test: 'hello' } }); // use params - * // -> outputs `Msg hello` - * obj.t('msg2', { l: 'it', params: { test: 'hello' } }); // custom local - * // -> outputs `Msg hello it` - * @param key - Label to translate - * @param [opts] - Options for the translation - * @param [opts.params] - Params for the translation - * @param [opts.debug] - Show warnings in case of missing resources - */ - t(key: string, opts?: { - params?: any; - debug?: boolean; - }): string; - } - - /** - * You can customize the initial state of the module from the editor initialization - * ```js - * const editor = grapesjs.init({ - * .... - * pageManager: { - * pages: [ - * { - * id: 'page-id', - * styles: `.my-class { color: red }`, // or a JSON of styles - * component: '
My element
', // or a JSON of components - * } - * ] - * }, - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const pageManager = editor.Pages; - * ``` - * - * ## Available Events - * * `page:add` - Added new page. The page is passed as an argument to the callback - * * `page:remove` - Page removed. The page is passed as an argument to the callback - * * `page:select` - New page selected. The newly selected page and the previous one, are passed as arguments to the callback - * * `page:update` - Page updated. The updated page and the object containing changes are passed as arguments to the callback - * * `page` - Catch-all event for all the events mentioned above. An object containing all the available data about the triggered event is passed as an argument to the callback - * - * ## Methods - * * [add](#add) - * * [get](#get) - * * [getAll](#getall) - * * [getAllWrappers](#getallwrappers) - * * [getMain](#getmain) - * * [remove](#remove) - * * [select](#select) - * * [getSelected](#getselected) - * - * [Page]: page.html - * [Component]: component.html - */ - interface Pages { - /** - * Add new page - * @example - * const newPage = pageManager.add({ - * id: 'new-page-id', // without an explicit ID, a random one will be created - * styles: `.my-class { color: red }`, // or a JSON of styles - * component: '
My element
', // or a JSON of components - * }); - * @param props - Page properties - * @param [opts] - Options - */ - add(props: any, opts?: any): any; - /** - * Remove page - * @example - * const removedPage = pageManager.remove('page-id'); - * // or by passing the page - * const somePage = pageManager.get('page-id'); - * pageManager.remove(somePage); - */ - remove(): any; - /** - * Get page by id - * @example - * const somePage = pageManager.get('page-id'); - * @param id - Page id - */ - get(id: string): any; - /** - * Get main page (the first one available) - * @example - * const mainPage = pageManager.getMain(); - */ - getMain(): any; - /** - * Get all pages - * @example - * const arrayOfPages = pageManager.getAll(); - */ - getAll(): any; - /** - * Get wrapper components (aka body) from all pages and frames. - * @example - * const wrappers = pageManager.getAllWrappers(); - * // Get all `image` components from the project - * const allImages = wrappers.map(wrp => wrp.findType('image')).flat(); - */ - getAllWrappers(): any; - /** - * Change the selected page. This will switch the page rendered in canvas - * @example - * pageManager.select('page-id'); - * // or by passing the page - * const somePage = pageManager.get('page-id'); - * pageManager.select(somePage); - */ - select(): this; - /** - * Get the selected page - * @example - * const selectedPage = pageManager.getSelected(); - */ - getSelected(): any; - } - - interface PageOptions { - frames : Frame[] - } - - interface Page extends Backbone.Model { - /** - * Get page id - */ - getId(): string; - - /** - * Get page name - */ - getName(): string; - - /** - * Update page name - * @param value - New page name - */ - setName(value: string): void; - - /** - * Get all frames - * @example - * const arrayOfFrames = page.getAllFrames(); - */ - getAllFrames(): Frame[]; - - /** - * Get the first frame of the page (identified always as the main one) - * @example - * const mainFrame = page.getMainFrame(); - */ - getMainFrame(): Frame; - - /** - * Get the root component (usually is the `wrapper` component) from the main frame - * @example - * const rootComponent = page.getMainComponent(); - * console.log(rootComponent.toHTML()); - */ - getMainComponent(): Component; - } - - /** - * You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](https://github.com/artf/grapesjs/blob/master/src/parser/config/config.js) - * ```js - * const editor = grapesjs.init({ - * parser: { - * // options - * } - * }) - * ``` - * - * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance - * - * ```js - * const { Parser } = editor; - * ``` - * ## Available Events - * * `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument - * * `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument - * - * ## Methods - * * [getConfig](#getconfig) - * * [parseHtml](#parsehtml) - * * [parseCss](#parsecss) - */ - interface Parser { - /** - * Get the configuration object - * @example - * console.log(Parser.getConfig()) - * @returns Configuration object - */ - getConfig(): any; - /** - * Parse HTML string and return the object containing the Component Definition - * @example - * const resHtml = Parser.parseHtml(`
Hi
`, { - * htmlType: 'text/html', // default - * }); - * // By using the `text/html`, this will fix automatically all the HTML syntax issues - * // Indeed the final representation, in this case, will be `
Hi
` - * const resXml = Parser.parseHtml(`
Hi
`, { - * htmlType: 'application/xml', - * }); - * // This will preserve the original format as, from the XML point of view, is a valid format - * @param input - HTML string to parse - * @param [options] - Options - * @param [options.htmlType] - [HTML mime type](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02) to parse - * @param [options.allowScripts = false] - Allow `