Subversion Repositories oidplus

Rev

Rev 637 | Rev 759 | Go to most recent revision | View as "text/javascript" | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /**
  2.  * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3.  * Licensed under the LGPL or a commercial license.
  4.  * For LGPL see License.txt in the project root for license information.
  5.  * For commercial licenses see https://www.tiny.cloud/
  6.  *
  7.  * Version: 5.10.2 (2021-11-17)
  8.  */
  9. (function () {
  10.     'use strict';
  11.  
  12.     var typeOf$1 = function (x) {
  13.       if (x === null) {
  14.         return 'null';
  15.       }
  16.       if (x === undefined) {
  17.         return 'undefined';
  18.       }
  19.       var t = typeof x;
  20.       if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  21.         return 'array';
  22.       }
  23.       if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  24.         return 'string';
  25.       }
  26.       return t;
  27.     };
  28.     var isEquatableType = function (x) {
  29.       return [
  30.         'undefined',
  31.         'boolean',
  32.         'number',
  33.         'string',
  34.         'function',
  35.         'xml',
  36.         'null'
  37.       ].indexOf(x) !== -1;
  38.     };
  39.  
  40.     var sort$1 = function (xs, compareFn) {
  41.       var clone = Array.prototype.slice.call(xs);
  42.       return clone.sort(compareFn);
  43.     };
  44.  
  45.     var contramap = function (eqa, f) {
  46.       return eq$2(function (x, y) {
  47.         return eqa.eq(f(x), f(y));
  48.       });
  49.     };
  50.     var eq$2 = function (f) {
  51.       return { eq: f };
  52.     };
  53.     var tripleEq = eq$2(function (x, y) {
  54.       return x === y;
  55.     });
  56.     var eqString = tripleEq;
  57.     var eqArray = function (eqa) {
  58.       return eq$2(function (x, y) {
  59.         if (x.length !== y.length) {
  60.           return false;
  61.         }
  62.         var len = x.length;
  63.         for (var i = 0; i < len; i++) {
  64.           if (!eqa.eq(x[i], y[i])) {
  65.             return false;
  66.           }
  67.         }
  68.         return true;
  69.       });
  70.     };
  71.     var eqSortedArray = function (eqa, compareFn) {
  72.       return contramap(eqArray(eqa), function (xs) {
  73.         return sort$1(xs, compareFn);
  74.       });
  75.     };
  76.     var eqRecord = function (eqa) {
  77.       return eq$2(function (x, y) {
  78.         var kx = Object.keys(x);
  79.         var ky = Object.keys(y);
  80.         if (!eqSortedArray(eqString).eq(kx, ky)) {
  81.           return false;
  82.         }
  83.         var len = kx.length;
  84.         for (var i = 0; i < len; i++) {
  85.           var q = kx[i];
  86.           if (!eqa.eq(x[q], y[q])) {
  87.             return false;
  88.           }
  89.         }
  90.         return true;
  91.       });
  92.     };
  93.     var eqAny = eq$2(function (x, y) {
  94.       if (x === y) {
  95.         return true;
  96.       }
  97.       var tx = typeOf$1(x);
  98.       var ty = typeOf$1(y);
  99.       if (tx !== ty) {
  100.         return false;
  101.       }
  102.       if (isEquatableType(tx)) {
  103.         return x === y;
  104.       } else if (tx === 'array') {
  105.         return eqArray(eqAny).eq(x, y);
  106.       } else if (tx === 'object') {
  107.         return eqRecord(eqAny).eq(x, y);
  108.       }
  109.       return false;
  110.     });
  111.  
  112.     var typeOf = function (x) {
  113.       var t = typeof x;
  114.       if (x === null) {
  115.         return 'null';
  116.       } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  117.         return 'array';
  118.       } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  119.         return 'string';
  120.       } else {
  121.         return t;
  122.       }
  123.     };
  124.     var isType$1 = function (type) {
  125.       return function (value) {
  126.         return typeOf(value) === type;
  127.       };
  128.     };
  129.     var isSimpleType = function (type) {
  130.       return function (value) {
  131.         return typeof value === type;
  132.       };
  133.     };
  134.     var eq$1 = function (t) {
  135.       return function (a) {
  136.         return t === a;
  137.       };
  138.     };
  139.     var isString$1 = isType$1('string');
  140.     var isObject = isType$1('object');
  141.     var isArray$1 = isType$1('array');
  142.     var isNull = eq$1(null);
  143.     var isBoolean = isSimpleType('boolean');
  144.     var isUndefined = eq$1(undefined);
  145.     var isNullable = function (a) {
  146.       return a === null || a === undefined;
  147.     };
  148.     var isNonNullable = function (a) {
  149.       return !isNullable(a);
  150.     };
  151.     var isFunction = isSimpleType('function');
  152.     var isNumber = isSimpleType('number');
  153.  
  154.     var noop = function () {
  155.     };
  156.     var compose = function (fa, fb) {
  157.       return function () {
  158.         var args = [];
  159.         for (var _i = 0; _i < arguments.length; _i++) {
  160.           args[_i] = arguments[_i];
  161.         }
  162.         return fa(fb.apply(null, args));
  163.       };
  164.     };
  165.     var compose1 = function (fbc, fab) {
  166.       return function (a) {
  167.         return fbc(fab(a));
  168.       };
  169.     };
  170.     var constant = function (value) {
  171.       return function () {
  172.         return value;
  173.       };
  174.     };
  175.     var identity = function (x) {
  176.       return x;
  177.     };
  178.     var tripleEquals = function (a, b) {
  179.       return a === b;
  180.     };
  181.     function curry(fn) {
  182.       var initialArgs = [];
  183.       for (var _i = 1; _i < arguments.length; _i++) {
  184.         initialArgs[_i - 1] = arguments[_i];
  185.       }
  186.       return function () {
  187.         var restArgs = [];
  188.         for (var _i = 0; _i < arguments.length; _i++) {
  189.           restArgs[_i] = arguments[_i];
  190.         }
  191.         var all = initialArgs.concat(restArgs);
  192.         return fn.apply(null, all);
  193.       };
  194.     }
  195.     var not = function (f) {
  196.       return function (t) {
  197.         return !f(t);
  198.       };
  199.     };
  200.     var die = function (msg) {
  201.       return function () {
  202.         throw new Error(msg);
  203.       };
  204.     };
  205.     var apply = function (f) {
  206.       return f();
  207.     };
  208.     var call = function (f) {
  209.       f();
  210.     };
  211.     var never = constant(false);
  212.     var always = constant(true);
  213.  
  214.     var none = function () {
  215.       return NONE;
  216.     };
  217.     var NONE = function () {
  218.       var call = function (thunk) {
  219.         return thunk();
  220.       };
  221.       var id = identity;
  222.       var me = {
  223.         fold: function (n, _s) {
  224.           return n();
  225.         },
  226.         isSome: never,
  227.         isNone: always,
  228.         getOr: id,
  229.         getOrThunk: call,
  230.         getOrDie: function (msg) {
  231.           throw new Error(msg || 'error: getOrDie called on none.');
  232.         },
  233.         getOrNull: constant(null),
  234.         getOrUndefined: constant(undefined),
  235.         or: id,
  236.         orThunk: call,
  237.         map: none,
  238.         each: noop,
  239.         bind: none,
  240.         exists: never,
  241.         forall: always,
  242.         filter: function () {
  243.           return none();
  244.         },
  245.         toArray: function () {
  246.           return [];
  247.         },
  248.         toString: constant('none()')
  249.       };
  250.       return me;
  251.     }();
  252.     var some = function (a) {
  253.       var constant_a = constant(a);
  254.       var self = function () {
  255.         return me;
  256.       };
  257.       var bind = function (f) {
  258.         return f(a);
  259.       };
  260.       var me = {
  261.         fold: function (n, s) {
  262.           return s(a);
  263.         },
  264.         isSome: always,
  265.         isNone: never,
  266.         getOr: constant_a,
  267.         getOrThunk: constant_a,
  268.         getOrDie: constant_a,
  269.         getOrNull: constant_a,
  270.         getOrUndefined: constant_a,
  271.         or: self,
  272.         orThunk: self,
  273.         map: function (f) {
  274.           return some(f(a));
  275.         },
  276.         each: function (f) {
  277.           f(a);
  278.         },
  279.         bind: bind,
  280.         exists: bind,
  281.         forall: bind,
  282.         filter: function (f) {
  283.           return f(a) ? me : NONE;
  284.         },
  285.         toArray: function () {
  286.           return [a];
  287.         },
  288.         toString: function () {
  289.           return 'some(' + a + ')';
  290.         }
  291.       };
  292.       return me;
  293.     };
  294.     var from$1 = function (value) {
  295.       return value === null || value === undefined ? NONE : some(value);
  296.     };
  297.     var Optional = {
  298.       some: some,
  299.       none: none,
  300.       from: from$1
  301.     };
  302.  
  303.     var nativeSlice = Array.prototype.slice;
  304.     var nativeIndexOf = Array.prototype.indexOf;
  305.     var nativePush = Array.prototype.push;
  306.     var rawIndexOf = function (ts, t) {
  307.       return nativeIndexOf.call(ts, t);
  308.     };
  309.     var indexOf$2 = function (xs, x) {
  310.       var r = rawIndexOf(xs, x);
  311.       return r === -1 ? Optional.none() : Optional.some(r);
  312.     };
  313.     var contains$3 = function (xs, x) {
  314.       return rawIndexOf(xs, x) > -1;
  315.     };
  316.     var exists = function (xs, pred) {
  317.       for (var i = 0, len = xs.length; i < len; i++) {
  318.         var x = xs[i];
  319.         if (pred(x, i)) {
  320.           return true;
  321.         }
  322.       }
  323.       return false;
  324.     };
  325.     var map$3 = function (xs, f) {
  326.       var len = xs.length;
  327.       var r = new Array(len);
  328.       for (var i = 0; i < len; i++) {
  329.         var x = xs[i];
  330.         r[i] = f(x, i);
  331.       }
  332.       return r;
  333.     };
  334.     var each$k = function (xs, f) {
  335.       for (var i = 0, len = xs.length; i < len; i++) {
  336.         var x = xs[i];
  337.         f(x, i);
  338.       }
  339.     };
  340.     var eachr = function (xs, f) {
  341.       for (var i = xs.length - 1; i >= 0; i--) {
  342.         var x = xs[i];
  343.         f(x, i);
  344.       }
  345.     };
  346.     var partition = function (xs, pred) {
  347.       var pass = [];
  348.       var fail = [];
  349.       for (var i = 0, len = xs.length; i < len; i++) {
  350.         var x = xs[i];
  351.         var arr = pred(x, i) ? pass : fail;
  352.         arr.push(x);
  353.       }
  354.       return {
  355.         pass: pass,
  356.         fail: fail
  357.       };
  358.     };
  359.     var filter$4 = function (xs, pred) {
  360.       var r = [];
  361.       for (var i = 0, len = xs.length; i < len; i++) {
  362.         var x = xs[i];
  363.         if (pred(x, i)) {
  364.           r.push(x);
  365.         }
  366.       }
  367.       return r;
  368.     };
  369.     var foldr = function (xs, f, acc) {
  370.       eachr(xs, function (x, i) {
  371.         acc = f(acc, x, i);
  372.       });
  373.       return acc;
  374.     };
  375.     var foldl = function (xs, f, acc) {
  376.       each$k(xs, function (x, i) {
  377.         acc = f(acc, x, i);
  378.       });
  379.       return acc;
  380.     };
  381.     var findUntil$1 = function (xs, pred, until) {
  382.       for (var i = 0, len = xs.length; i < len; i++) {
  383.         var x = xs[i];
  384.         if (pred(x, i)) {
  385.           return Optional.some(x);
  386.         } else if (until(x, i)) {
  387.           break;
  388.         }
  389.       }
  390.       return Optional.none();
  391.     };
  392.     var find$3 = function (xs, pred) {
  393.       return findUntil$1(xs, pred, never);
  394.     };
  395.     var findIndex$2 = function (xs, pred) {
  396.       for (var i = 0, len = xs.length; i < len; i++) {
  397.         var x = xs[i];
  398.         if (pred(x, i)) {
  399.           return Optional.some(i);
  400.         }
  401.       }
  402.       return Optional.none();
  403.     };
  404.     var flatten = function (xs) {
  405.       var r = [];
  406.       for (var i = 0, len = xs.length; i < len; ++i) {
  407.         if (!isArray$1(xs[i])) {
  408.           throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  409.         }
  410.         nativePush.apply(r, xs[i]);
  411.       }
  412.       return r;
  413.     };
  414.     var bind = function (xs, f) {
  415.       return flatten(map$3(xs, f));
  416.     };
  417.     var forall = function (xs, pred) {
  418.       for (var i = 0, len = xs.length; i < len; ++i) {
  419.         var x = xs[i];
  420.         if (pred(x, i) !== true) {
  421.           return false;
  422.         }
  423.       }
  424.       return true;
  425.     };
  426.     var reverse = function (xs) {
  427.       var r = nativeSlice.call(xs, 0);
  428.       r.reverse();
  429.       return r;
  430.     };
  431.     var difference = function (a1, a2) {
  432.       return filter$4(a1, function (x) {
  433.         return !contains$3(a2, x);
  434.       });
  435.     };
  436.     var mapToObject = function (xs, f) {
  437.       var r = {};
  438.       for (var i = 0, len = xs.length; i < len; i++) {
  439.         var x = xs[i];
  440.         r[String(x)] = f(x, i);
  441.       }
  442.       return r;
  443.     };
  444.     var sort = function (xs, comparator) {
  445.       var copy = nativeSlice.call(xs, 0);
  446.       copy.sort(comparator);
  447.       return copy;
  448.     };
  449.     var get$a = function (xs, i) {
  450.       return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  451.     };
  452.     var head = function (xs) {
  453.       return get$a(xs, 0);
  454.     };
  455.     var last$2 = function (xs) {
  456.       return get$a(xs, xs.length - 1);
  457.     };
  458.     var from = isFunction(Array.from) ? Array.from : function (x) {
  459.       return nativeSlice.call(x);
  460.     };
  461.     var findMap = function (arr, f) {
  462.       for (var i = 0; i < arr.length; i++) {
  463.         var r = f(arr[i], i);
  464.         if (r.isSome()) {
  465.           return r;
  466.         }
  467.       }
  468.       return Optional.none();
  469.     };
  470.  
  471.     var keys = Object.keys;
  472.     var hasOwnProperty$1 = Object.hasOwnProperty;
  473.     var each$j = function (obj, f) {
  474.       var props = keys(obj);
  475.       for (var k = 0, len = props.length; k < len; k++) {
  476.         var i = props[k];
  477.         var x = obj[i];
  478.         f(x, i);
  479.       }
  480.     };
  481.     var map$2 = function (obj, f) {
  482.       return tupleMap(obj, function (x, i) {
  483.         return {
  484.           k: i,
  485.           v: f(x, i)
  486.         };
  487.       });
  488.     };
  489.     var tupleMap = function (obj, f) {
  490.       var r = {};
  491.       each$j(obj, function (x, i) {
  492.         var tuple = f(x, i);
  493.         r[tuple.k] = tuple.v;
  494.       });
  495.       return r;
  496.     };
  497.     var objAcc = function (r) {
  498.       return function (x, i) {
  499.         r[i] = x;
  500.       };
  501.     };
  502.     var internalFilter = function (obj, pred, onTrue, onFalse) {
  503.       var r = {};
  504.       each$j(obj, function (x, i) {
  505.         (pred(x, i) ? onTrue : onFalse)(x, i);
  506.       });
  507.       return r;
  508.     };
  509.     var bifilter = function (obj, pred) {
  510.       var t = {};
  511.       var f = {};
  512.       internalFilter(obj, pred, objAcc(t), objAcc(f));
  513.       return {
  514.         t: t,
  515.         f: f
  516.       };
  517.     };
  518.     var filter$3 = function (obj, pred) {
  519.       var t = {};
  520.       internalFilter(obj, pred, objAcc(t), noop);
  521.       return t;
  522.     };
  523.     var mapToArray = function (obj, f) {
  524.       var r = [];
  525.       each$j(obj, function (value, name) {
  526.         r.push(f(value, name));
  527.       });
  528.       return r;
  529.     };
  530.     var values = function (obj) {
  531.       return mapToArray(obj, identity);
  532.     };
  533.     var get$9 = function (obj, key) {
  534.       return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  535.     };
  536.     var has$2 = function (obj, key) {
  537.       return hasOwnProperty$1.call(obj, key);
  538.     };
  539.     var hasNonNullableKey = function (obj, key) {
  540.       return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  541.     };
  542.     var equal$1 = function (a1, a2, eq) {
  543.       if (eq === void 0) {
  544.         eq = eqAny;
  545.       }
  546.       return eqRecord(eq).eq(a1, a2);
  547.     };
  548.  
  549.     var isArray = Array.isArray;
  550.     var toArray$1 = function (obj) {
  551.       if (!isArray(obj)) {
  552.         var array = [];
  553.         for (var i = 0, l = obj.length; i < l; i++) {
  554.           array[i] = obj[i];
  555.         }
  556.         return array;
  557.       } else {
  558.         return obj;
  559.       }
  560.     };
  561.     var each$i = function (o, cb, s) {
  562.       var n, l;
  563.       if (!o) {
  564.         return false;
  565.       }
  566.       s = s || o;
  567.       if (o.length !== undefined) {
  568.         for (n = 0, l = o.length; n < l; n++) {
  569.           if (cb.call(s, o[n], n, o) === false) {
  570.             return false;
  571.           }
  572.         }
  573.       } else {
  574.         for (n in o) {
  575.           if (has$2(o, n)) {
  576.             if (cb.call(s, o[n], n, o) === false) {
  577.               return false;
  578.             }
  579.           }
  580.         }
  581.       }
  582.       return true;
  583.     };
  584.     var map$1 = function (array, callback) {
  585.       var out = [];
  586.       each$i(array, function (item, index) {
  587.         out.push(callback(item, index, array));
  588.       });
  589.       return out;
  590.     };
  591.     var filter$2 = function (a, f) {
  592.       var o = [];
  593.       each$i(a, function (v, index) {
  594.         if (!f || f(v, index, a)) {
  595.           o.push(v);
  596.         }
  597.       });
  598.       return o;
  599.     };
  600.     var indexOf$1 = function (a, v) {
  601.       if (a) {
  602.         for (var i = 0, l = a.length; i < l; i++) {
  603.           if (a[i] === v) {
  604.             return i;
  605.           }
  606.         }
  607.       }
  608.       return -1;
  609.     };
  610.     var reduce = function (collection, iteratee, accumulator, thisArg) {
  611.       var acc = isUndefined(accumulator) ? collection[0] : accumulator;
  612.       for (var i = 0; i < collection.length; i++) {
  613.         acc = iteratee.call(thisArg, acc, collection[i], i);
  614.       }
  615.       return acc;
  616.     };
  617.     var findIndex$1 = function (array, predicate, thisArg) {
  618.       var i, l;
  619.       for (i = 0, l = array.length; i < l; i++) {
  620.         if (predicate.call(thisArg, array[i], i, array)) {
  621.           return i;
  622.         }
  623.       }
  624.       return -1;
  625.     };
  626.     var last$1 = function (collection) {
  627.       return collection[collection.length - 1];
  628.     };
  629.  
  630.     var __assign = function () {
  631.       __assign = Object.assign || function __assign(t) {
  632.         for (var s, i = 1, n = arguments.length; i < n; i++) {
  633.           s = arguments[i];
  634.           for (var p in s)
  635.             if (Object.prototype.hasOwnProperty.call(s, p))
  636.               t[p] = s[p];
  637.         }
  638.         return t;
  639.       };
  640.       return __assign.apply(this, arguments);
  641.     };
  642.     function __rest(s, e) {
  643.       var t = {};
  644.       for (var p in s)
  645.         if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  646.           t[p] = s[p];
  647.       if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  648.         for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  649.           if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  650.             t[p[i]] = s[p[i]];
  651.         }
  652.       return t;
  653.     }
  654.     function __spreadArray(to, from, pack) {
  655.       if (pack || arguments.length === 2)
  656.         for (var i = 0, l = from.length, ar; i < l; i++) {
  657.           if (ar || !(i in from)) {
  658.             if (!ar)
  659.               ar = Array.prototype.slice.call(from, 0, i);
  660.             ar[i] = from[i];
  661.           }
  662.         }
  663.       return to.concat(ar || Array.prototype.slice.call(from));
  664.     }
  665.  
  666.     var cached = function (f) {
  667.       var called = false;
  668.       var r;
  669.       return function () {
  670.         var args = [];
  671.         for (var _i = 0; _i < arguments.length; _i++) {
  672.           args[_i] = arguments[_i];
  673.         }
  674.         if (!called) {
  675.           called = true;
  676.           r = f.apply(null, args);
  677.         }
  678.         return r;
  679.       };
  680.     };
  681.  
  682.     var DeviceType = function (os, browser, userAgent, mediaMatch) {
  683.       var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  684.       var isiPhone = os.isiOS() && !isiPad;
  685.       var isMobile = os.isiOS() || os.isAndroid();
  686.       var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  687.       var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  688.       var isPhone = isiPhone || isMobile && !isTablet;
  689.       var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  690.       var isDesktop = !isPhone && !isTablet && !iOSwebview;
  691.       return {
  692.         isiPad: constant(isiPad),
  693.         isiPhone: constant(isiPhone),
  694.         isTablet: constant(isTablet),
  695.         isPhone: constant(isPhone),
  696.         isTouch: constant(isTouch),
  697.         isAndroid: os.isAndroid,
  698.         isiOS: os.isiOS,
  699.         isWebView: constant(iOSwebview),
  700.         isDesktop: constant(isDesktop)
  701.       };
  702.     };
  703.  
  704.     var firstMatch = function (regexes, s) {
  705.       for (var i = 0; i < regexes.length; i++) {
  706.         var x = regexes[i];
  707.         if (x.test(s)) {
  708.           return x;
  709.         }
  710.       }
  711.       return undefined;
  712.     };
  713.     var find$2 = function (regexes, agent) {
  714.       var r = firstMatch(regexes, agent);
  715.       if (!r) {
  716.         return {
  717.           major: 0,
  718.           minor: 0
  719.         };
  720.       }
  721.       var group = function (i) {
  722.         return Number(agent.replace(r, '$' + i));
  723.       };
  724.       return nu$4(group(1), group(2));
  725.     };
  726.     var detect$3 = function (versionRegexes, agent) {
  727.       var cleanedAgent = String(agent).toLowerCase();
  728.       if (versionRegexes.length === 0) {
  729.         return unknown$2();
  730.       }
  731.       return find$2(versionRegexes, cleanedAgent);
  732.     };
  733.     var unknown$2 = function () {
  734.       return nu$4(0, 0);
  735.     };
  736.     var nu$4 = function (major, minor) {
  737.       return {
  738.         major: major,
  739.         minor: minor
  740.       };
  741.     };
  742.     var Version = {
  743.       nu: nu$4,
  744.       detect: detect$3,
  745.       unknown: unknown$2
  746.     };
  747.  
  748.     var detectBrowser$1 = function (browsers, userAgentData) {
  749.       return findMap(userAgentData.brands, function (uaBrand) {
  750.         var lcBrand = uaBrand.brand.toLowerCase();
  751.         return find$3(browsers, function (browser) {
  752.           var _a;
  753.           return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  754.         }).map(function (info) {
  755.           return {
  756.             current: info.name,
  757.             version: Version.nu(parseInt(uaBrand.version, 10), 0)
  758.           };
  759.         });
  760.       });
  761.     };
  762.  
  763.     var detect$2 = function (candidates, userAgent) {
  764.       var agent = String(userAgent).toLowerCase();
  765.       return find$3(candidates, function (candidate) {
  766.         return candidate.search(agent);
  767.       });
  768.     };
  769.     var detectBrowser = function (browsers, userAgent) {
  770.       return detect$2(browsers, userAgent).map(function (browser) {
  771.         var version = Version.detect(browser.versionRegexes, userAgent);
  772.         return {
  773.           current: browser.name,
  774.           version: version
  775.         };
  776.       });
  777.     };
  778.     var detectOs = function (oses, userAgent) {
  779.       return detect$2(oses, userAgent).map(function (os) {
  780.         var version = Version.detect(os.versionRegexes, userAgent);
  781.         return {
  782.           current: os.name,
  783.           version: version
  784.         };
  785.       });
  786.     };
  787.  
  788.     var removeFromStart = function (str, numChars) {
  789.       return str.substring(numChars);
  790.     };
  791.  
  792.     var checkRange = function (str, substr, start) {
  793.       return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  794.     };
  795.     var removeLeading = function (str, prefix) {
  796.       return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  797.     };
  798.     var contains$2 = function (str, substr) {
  799.       return str.indexOf(substr) !== -1;
  800.     };
  801.     var startsWith = function (str, prefix) {
  802.       return checkRange(str, prefix, 0);
  803.     };
  804.     var blank = function (r) {
  805.       return function (s) {
  806.         return s.replace(r, '');
  807.       };
  808.     };
  809.     var trim$4 = blank(/^\s+|\s+$/g);
  810.     var lTrim = blank(/^\s+/g);
  811.     var rTrim = blank(/\s+$/g);
  812.     var isNotEmpty = function (s) {
  813.       return s.length > 0;
  814.     };
  815.     var isEmpty$3 = function (s) {
  816.       return !isNotEmpty(s);
  817.     };
  818.  
  819.     var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  820.     var checkContains = function (target) {
  821.       return function (uastring) {
  822.         return contains$2(uastring, target);
  823.       };
  824.     };
  825.     var browsers = [
  826.       {
  827.         name: 'Edge',
  828.         versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  829.         search: function (uastring) {
  830.           return contains$2(uastring, 'edge/') && contains$2(uastring, 'chrome') && contains$2(uastring, 'safari') && contains$2(uastring, 'applewebkit');
  831.         }
  832.       },
  833.       {
  834.         name: 'Chrome',
  835.         brand: 'Chromium',
  836.         versionRegexes: [
  837.           /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  838.           normalVersionRegex
  839.         ],
  840.         search: function (uastring) {
  841.           return contains$2(uastring, 'chrome') && !contains$2(uastring, 'chromeframe');
  842.         }
  843.       },
  844.       {
  845.         name: 'IE',
  846.         versionRegexes: [
  847.           /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  848.           /.*?rv:([0-9]+)\.([0-9]+).*/
  849.         ],
  850.         search: function (uastring) {
  851.           return contains$2(uastring, 'msie') || contains$2(uastring, 'trident');
  852.         }
  853.       },
  854.       {
  855.         name: 'Opera',
  856.         versionRegexes: [
  857.           normalVersionRegex,
  858.           /.*?opera\/([0-9]+)\.([0-9]+).*/
  859.         ],
  860.         search: checkContains('opera')
  861.       },
  862.       {
  863.         name: 'Firefox',
  864.         versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  865.         search: checkContains('firefox')
  866.       },
  867.       {
  868.         name: 'Safari',
  869.         versionRegexes: [
  870.           normalVersionRegex,
  871.           /.*?cpu os ([0-9]+)_([0-9]+).*/
  872.         ],
  873.         search: function (uastring) {
  874.           return (contains$2(uastring, 'safari') || contains$2(uastring, 'mobile/')) && contains$2(uastring, 'applewebkit');
  875.         }
  876.       }
  877.     ];
  878.     var oses = [
  879.       {
  880.         name: 'Windows',
  881.         search: checkContains('win'),
  882.         versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  883.       },
  884.       {
  885.         name: 'iOS',
  886.         search: function (uastring) {
  887.           return contains$2(uastring, 'iphone') || contains$2(uastring, 'ipad');
  888.         },
  889.         versionRegexes: [
  890.           /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  891.           /.*cpu os ([0-9]+)_([0-9]+).*/,
  892.           /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  893.         ]
  894.       },
  895.       {
  896.         name: 'Android',
  897.         search: checkContains('android'),
  898.         versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  899.       },
  900.       {
  901.         name: 'OSX',
  902.         search: checkContains('mac os x'),
  903.         versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  904.       },
  905.       {
  906.         name: 'Linux',
  907.         search: checkContains('linux'),
  908.         versionRegexes: []
  909.       },
  910.       {
  911.         name: 'Solaris',
  912.         search: checkContains('sunos'),
  913.         versionRegexes: []
  914.       },
  915.       {
  916.         name: 'FreeBSD',
  917.         search: checkContains('freebsd'),
  918.         versionRegexes: []
  919.       },
  920.       {
  921.         name: 'ChromeOS',
  922.         search: checkContains('cros'),
  923.         versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  924.       }
  925.     ];
  926.     var PlatformInfo = {
  927.       browsers: constant(browsers),
  928.       oses: constant(oses)
  929.     };
  930.  
  931.     var edge = 'Edge';
  932.     var chrome = 'Chrome';
  933.     var ie$1 = 'IE';
  934.     var opera = 'Opera';
  935.     var firefox = 'Firefox';
  936.     var safari = 'Safari';
  937.     var unknown$1 = function () {
  938.       return nu$3({
  939.         current: undefined,
  940.         version: Version.unknown()
  941.       });
  942.     };
  943.     var nu$3 = function (info) {
  944.       var current = info.current;
  945.       var version = info.version;
  946.       var isBrowser = function (name) {
  947.         return function () {
  948.           return current === name;
  949.         };
  950.       };
  951.       return {
  952.         current: current,
  953.         version: version,
  954.         isEdge: isBrowser(edge),
  955.         isChrome: isBrowser(chrome),
  956.         isIE: isBrowser(ie$1),
  957.         isOpera: isBrowser(opera),
  958.         isFirefox: isBrowser(firefox),
  959.         isSafari: isBrowser(safari)
  960.       };
  961.     };
  962.     var Browser = {
  963.       unknown: unknown$1,
  964.       nu: nu$3,
  965.       edge: constant(edge),
  966.       chrome: constant(chrome),
  967.       ie: constant(ie$1),
  968.       opera: constant(opera),
  969.       firefox: constant(firefox),
  970.       safari: constant(safari)
  971.     };
  972.  
  973.     var windows = 'Windows';
  974.     var ios = 'iOS';
  975.     var android = 'Android';
  976.     var linux = 'Linux';
  977.     var osx = 'OSX';
  978.     var solaris = 'Solaris';
  979.     var freebsd = 'FreeBSD';
  980.     var chromeos = 'ChromeOS';
  981.     var unknown = function () {
  982.       return nu$2({
  983.         current: undefined,
  984.         version: Version.unknown()
  985.       });
  986.     };
  987.     var nu$2 = function (info) {
  988.       var current = info.current;
  989.       var version = info.version;
  990.       var isOS = function (name) {
  991.         return function () {
  992.           return current === name;
  993.         };
  994.       };
  995.       return {
  996.         current: current,
  997.         version: version,
  998.         isWindows: isOS(windows),
  999.         isiOS: isOS(ios),
  1000.         isAndroid: isOS(android),
  1001.         isOSX: isOS(osx),
  1002.         isLinux: isOS(linux),
  1003.         isSolaris: isOS(solaris),
  1004.         isFreeBSD: isOS(freebsd),
  1005.         isChromeOS: isOS(chromeos)
  1006.       };
  1007.     };
  1008.     var OperatingSystem = {
  1009.       unknown: unknown,
  1010.       nu: nu$2,
  1011.       windows: constant(windows),
  1012.       ios: constant(ios),
  1013.       android: constant(android),
  1014.       linux: constant(linux),
  1015.       osx: constant(osx),
  1016.       solaris: constant(solaris),
  1017.       freebsd: constant(freebsd),
  1018.       chromeos: constant(chromeos)
  1019.     };
  1020.  
  1021.     var detect$1 = function (userAgent, userAgentDataOpt, mediaMatch) {
  1022.       var browsers = PlatformInfo.browsers();
  1023.       var oses = PlatformInfo.oses();
  1024.       var browser = userAgentDataOpt.bind(function (userAgentData) {
  1025.         return detectBrowser$1(browsers, userAgentData);
  1026.       }).orThunk(function () {
  1027.         return detectBrowser(browsers, userAgent);
  1028.       }).fold(Browser.unknown, Browser.nu);
  1029.       var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1030.       var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1031.       return {
  1032.         browser: browser,
  1033.         os: os,
  1034.         deviceType: deviceType
  1035.       };
  1036.     };
  1037.     var PlatformDetection = { detect: detect$1 };
  1038.  
  1039.     var mediaMatch = function (query) {
  1040.       return window.matchMedia(query).matches;
  1041.     };
  1042.     var platform$2 = cached(function () {
  1043.       return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  1044.     });
  1045.     var detect = function () {
  1046.       return platform$2();
  1047.     };
  1048.  
  1049.     var userAgent = navigator.userAgent;
  1050.     var platform$1 = detect();
  1051.     var browser$4 = platform$1.browser;
  1052.     var os = platform$1.os;
  1053.     var deviceType = platform$1.deviceType;
  1054.     var webkit = /WebKit/.test(userAgent) && !browser$4.isEdge();
  1055.     var fileApi = 'FormData' in window && 'FileReader' in window && 'URL' in window && !!URL.createObjectURL;
  1056.     var windowsPhone = userAgent.indexOf('Windows Phone') !== -1;
  1057.     var Env = {
  1058.       opera: browser$4.isOpera(),
  1059.       webkit: webkit,
  1060.       ie: browser$4.isIE() || browser$4.isEdge() ? browser$4.version.major : false,
  1061.       gecko: browser$4.isFirefox(),
  1062.       mac: os.isOSX() || os.isiOS(),
  1063.       iOS: deviceType.isiPad() || deviceType.isiPhone(),
  1064.       android: os.isAndroid(),
  1065.       contentEditable: true,
  1066.       transparentSrc: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
  1067.       caretAfter: true,
  1068.       range: window.getSelection && 'Range' in window,
  1069.       documentMode: browser$4.isIE() ? document.documentMode || 7 : 10,
  1070.       fileApi: fileApi,
  1071.       ceFalse: true,
  1072.       cacheSuffix: null,
  1073.       container: null,
  1074.       experimentalShadowDom: false,
  1075.       canHaveCSP: !browser$4.isIE(),
  1076.       desktop: deviceType.isDesktop(),
  1077.       windowsPhone: windowsPhone,
  1078.       browser: {
  1079.         current: browser$4.current,
  1080.         version: browser$4.version,
  1081.         isChrome: browser$4.isChrome,
  1082.         isEdge: browser$4.isEdge,
  1083.         isFirefox: browser$4.isFirefox,
  1084.         isIE: browser$4.isIE,
  1085.         isOpera: browser$4.isOpera,
  1086.         isSafari: browser$4.isSafari
  1087.       },
  1088.       os: {
  1089.         current: os.current,
  1090.         version: os.version,
  1091.         isAndroid: os.isAndroid,
  1092.         isChromeOS: os.isChromeOS,
  1093.         isFreeBSD: os.isFreeBSD,
  1094.         isiOS: os.isiOS,
  1095.         isLinux: os.isLinux,
  1096.         isOSX: os.isOSX,
  1097.         isSolaris: os.isSolaris,
  1098.         isWindows: os.isWindows
  1099.       },
  1100.       deviceType: {
  1101.         isDesktop: deviceType.isDesktop,
  1102.         isiPad: deviceType.isiPad,
  1103.         isiPhone: deviceType.isiPhone,
  1104.         isPhone: deviceType.isPhone,
  1105.         isTablet: deviceType.isTablet,
  1106.         isTouch: deviceType.isTouch,
  1107.         isWebView: deviceType.isWebView
  1108.       }
  1109.     };
  1110.  
  1111.     var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
  1112.     var trim$3 = function (str) {
  1113.       return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp$2, '');
  1114.     };
  1115.     var is$3 = function (obj, type) {
  1116.       if (!type) {
  1117.         return obj !== undefined;
  1118.       }
  1119.       if (type === 'array' && isArray(obj)) {
  1120.         return true;
  1121.       }
  1122.       return typeof obj === type;
  1123.     };
  1124.     var makeMap$4 = function (items, delim, map) {
  1125.       var i;
  1126.       items = items || [];
  1127.       delim = delim || ',';
  1128.       if (typeof items === 'string') {
  1129.         items = items.split(delim);
  1130.       }
  1131.       map = map || {};
  1132.       i = items.length;
  1133.       while (i--) {
  1134.         map[items[i]] = {};
  1135.       }
  1136.       return map;
  1137.     };
  1138.     var hasOwnProperty = has$2;
  1139.     var create$9 = function (s, p, root) {
  1140.       var self = this;
  1141.       var sp, scn, c, de = 0;
  1142.       s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1143.       var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
  1144.       var ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1145.       if (ns[cn]) {
  1146.         return;
  1147.       }
  1148.       if (s[2] === 'static') {
  1149.         ns[cn] = p;
  1150.         if (this.onCreate) {
  1151.           this.onCreate(s[2], s[3], ns[cn]);
  1152.         }
  1153.         return;
  1154.       }
  1155.       if (!p[cn]) {
  1156.         p[cn] = function () {
  1157.         };
  1158.         de = 1;
  1159.       }
  1160.       ns[cn] = p[cn];
  1161.       self.extend(ns[cn].prototype, p);
  1162.       if (s[5]) {
  1163.         sp = self.resolve(s[5]).prototype;
  1164.         scn = s[5].match(/\.(\w+)$/i)[1];
  1165.         c = ns[cn];
  1166.         if (de) {
  1167.           ns[cn] = function () {
  1168.             return sp[scn].apply(this, arguments);
  1169.           };
  1170.         } else {
  1171.           ns[cn] = function () {
  1172.             this.parent = sp[scn];
  1173.             return c.apply(this, arguments);
  1174.           };
  1175.         }
  1176.         ns[cn].prototype[cn] = ns[cn];
  1177.         self.each(sp, function (f, n) {
  1178.           ns[cn].prototype[n] = sp[n];
  1179.         });
  1180.         self.each(p, function (f, n) {
  1181.           if (sp[n]) {
  1182.             ns[cn].prototype[n] = function () {
  1183.               this.parent = sp[n];
  1184.               return f.apply(this, arguments);
  1185.             };
  1186.           } else {
  1187.             if (n !== cn) {
  1188.               ns[cn].prototype[n] = f;
  1189.             }
  1190.           }
  1191.         });
  1192.       }
  1193.       self.each(p.static, function (f, n) {
  1194.         ns[cn][n] = f;
  1195.       });
  1196.     };
  1197.     var extend$6 = function (obj) {
  1198.       var exts = [];
  1199.       for (var _i = 1; _i < arguments.length; _i++) {
  1200.         exts[_i - 1] = arguments[_i];
  1201.       }
  1202.       for (var i = 0; i < exts.length; i++) {
  1203.         var ext = exts[i];
  1204.         for (var name_1 in ext) {
  1205.           if (has$2(ext, name_1)) {
  1206.             var value = ext[name_1];
  1207.             if (value !== undefined) {
  1208.               obj[name_1] = value;
  1209.             }
  1210.           }
  1211.         }
  1212.       }
  1213.       return obj;
  1214.     };
  1215.     var walk$3 = function (o, f, n, s) {
  1216.       s = s || this;
  1217.       if (o) {
  1218.         if (n) {
  1219.           o = o[n];
  1220.         }
  1221.         each$i(o, function (o, i) {
  1222.           if (f.call(s, o, i, n) === false) {
  1223.             return false;
  1224.           }
  1225.           walk$3(o, f, n, s);
  1226.         });
  1227.       }
  1228.     };
  1229.     var createNS = function (n, o) {
  1230.       var i, v;
  1231.       o = o || window;
  1232.       n = n.split('.');
  1233.       for (i = 0; i < n.length; i++) {
  1234.         v = n[i];
  1235.         if (!o[v]) {
  1236.           o[v] = {};
  1237.         }
  1238.         o = o[v];
  1239.       }
  1240.       return o;
  1241.     };
  1242.     var resolve$3 = function (n, o) {
  1243.       var i, l;
  1244.       o = o || window;
  1245.       n = n.split('.');
  1246.       for (i = 0, l = n.length; i < l; i++) {
  1247.         o = o[n[i]];
  1248.         if (!o) {
  1249.           break;
  1250.         }
  1251.       }
  1252.       return o;
  1253.     };
  1254.     var explode$4 = function (s, d) {
  1255.       if (!s || is$3(s, 'array')) {
  1256.         return s;
  1257.       }
  1258.       return map$1(s.split(d || ','), trim$3);
  1259.     };
  1260.     var _addCacheSuffix = function (url) {
  1261.       var cacheSuffix = Env.cacheSuffix;
  1262.       if (cacheSuffix) {
  1263.         url += (url.indexOf('?') === -1 ? '?' : '&') + cacheSuffix;
  1264.       }
  1265.       return url;
  1266.     };
  1267.     var Tools = {
  1268.       trim: trim$3,
  1269.       isArray: isArray,
  1270.       is: is$3,
  1271.       toArray: toArray$1,
  1272.       makeMap: makeMap$4,
  1273.       each: each$i,
  1274.       map: map$1,
  1275.       grep: filter$2,
  1276.       inArray: indexOf$1,
  1277.       hasOwn: hasOwnProperty,
  1278.       extend: extend$6,
  1279.       create: create$9,
  1280.       walk: walk$3,
  1281.       createNS: createNS,
  1282.       resolve: resolve$3,
  1283.       explode: explode$4,
  1284.       _addCacheSuffix: _addCacheSuffix
  1285.     };
  1286.  
  1287.     var fromHtml$1 = function (html, scope) {
  1288.       var doc = scope || document;
  1289.       var div = doc.createElement('div');
  1290.       div.innerHTML = html;
  1291.       if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1292.         console.error('HTML does not have a single root node', html);
  1293.         throw new Error('HTML must have a single root node');
  1294.       }
  1295.       return fromDom$2(div.childNodes[0]);
  1296.     };
  1297.     var fromTag = function (tag, scope) {
  1298.       var doc = scope || document;
  1299.       var node = doc.createElement(tag);
  1300.       return fromDom$2(node);
  1301.     };
  1302.     var fromText = function (text, scope) {
  1303.       var doc = scope || document;
  1304.       var node = doc.createTextNode(text);
  1305.       return fromDom$2(node);
  1306.     };
  1307.     var fromDom$2 = function (node) {
  1308.       if (node === null || node === undefined) {
  1309.         throw new Error('Node cannot be null or undefined');
  1310.       }
  1311.       return { dom: node };
  1312.     };
  1313.     var fromPoint$1 = function (docElm, x, y) {
  1314.       return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
  1315.     };
  1316.     var SugarElement = {
  1317.       fromHtml: fromHtml$1,
  1318.       fromTag: fromTag,
  1319.       fromText: fromText,
  1320.       fromDom: fromDom$2,
  1321.       fromPoint: fromPoint$1
  1322.     };
  1323.  
  1324.     var toArray = function (target, f) {
  1325.       var r = [];
  1326.       var recurse = function (e) {
  1327.         r.push(e);
  1328.         return f(e);
  1329.       };
  1330.       var cur = f(target);
  1331.       do {
  1332.         cur = cur.bind(recurse);
  1333.       } while (cur.isSome());
  1334.       return r;
  1335.     };
  1336.  
  1337.     var compareDocumentPosition = function (a, b, match) {
  1338.       return (a.compareDocumentPosition(b) & match) !== 0;
  1339.     };
  1340.     var documentPositionContainedBy = function (a, b) {
  1341.       return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1342.     };
  1343.  
  1344.     var COMMENT = 8;
  1345.     var DOCUMENT = 9;
  1346.     var DOCUMENT_FRAGMENT = 11;
  1347.     var ELEMENT = 1;
  1348.     var TEXT = 3;
  1349.  
  1350.     var is$2 = function (element, selector) {
  1351.       var dom = element.dom;
  1352.       if (dom.nodeType !== ELEMENT) {
  1353.         return false;
  1354.       } else {
  1355.         var elem = dom;
  1356.         if (elem.matches !== undefined) {
  1357.           return elem.matches(selector);
  1358.         } else if (elem.msMatchesSelector !== undefined) {
  1359.           return elem.msMatchesSelector(selector);
  1360.         } else if (elem.webkitMatchesSelector !== undefined) {
  1361.           return elem.webkitMatchesSelector(selector);
  1362.         } else if (elem.mozMatchesSelector !== undefined) {
  1363.           return elem.mozMatchesSelector(selector);
  1364.         } else {
  1365.           throw new Error('Browser lacks native selectors');
  1366.         }
  1367.       }
  1368.     };
  1369.     var bypassSelector = function (dom) {
  1370.       return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1371.     };
  1372.     var all = function (selector, scope) {
  1373.       var base = scope === undefined ? document : scope.dom;
  1374.       return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
  1375.     };
  1376.     var one = function (selector, scope) {
  1377.       var base = scope === undefined ? document : scope.dom;
  1378.       return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1379.     };
  1380.  
  1381.     var eq = function (e1, e2) {
  1382.       return e1.dom === e2.dom;
  1383.     };
  1384.     var regularContains = function (e1, e2) {
  1385.       var d1 = e1.dom;
  1386.       var d2 = e2.dom;
  1387.       return d1 === d2 ? false : d1.contains(d2);
  1388.     };
  1389.     var ieContains = function (e1, e2) {
  1390.       return documentPositionContainedBy(e1.dom, e2.dom);
  1391.     };
  1392.     var contains$1 = function (e1, e2) {
  1393.       return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1394.     };
  1395.  
  1396.     typeof window !== 'undefined' ? window : Function('return this;')();
  1397.  
  1398.     var name = function (element) {
  1399.       var r = element.dom.nodeName;
  1400.       return r.toLowerCase();
  1401.     };
  1402.     var type = function (element) {
  1403.       return element.dom.nodeType;
  1404.     };
  1405.     var isType = function (t) {
  1406.       return function (element) {
  1407.         return type(element) === t;
  1408.       };
  1409.     };
  1410.     var isComment$1 = function (element) {
  1411.       return type(element) === COMMENT || name(element) === '#comment';
  1412.     };
  1413.     var isElement$6 = isType(ELEMENT);
  1414.     var isText$8 = isType(TEXT);
  1415.     var isDocument$2 = isType(DOCUMENT);
  1416.     var isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
  1417.     var isTag = function (tag) {
  1418.       return function (e) {
  1419.         return isElement$6(e) && name(e) === tag;
  1420.       };
  1421.     };
  1422.  
  1423.     var owner$1 = function (element) {
  1424.       return SugarElement.fromDom(element.dom.ownerDocument);
  1425.     };
  1426.     var documentOrOwner = function (dos) {
  1427.       return isDocument$2(dos) ? dos : owner$1(dos);
  1428.     };
  1429.     var documentElement = function (element) {
  1430.       return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1431.     };
  1432.     var defaultView = function (element) {
  1433.       return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1434.     };
  1435.     var parent = function (element) {
  1436.       return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1437.     };
  1438.     var parents$1 = function (element, isRoot) {
  1439.       var stop = isFunction(isRoot) ? isRoot : never;
  1440.       var dom = element.dom;
  1441.       var ret = [];
  1442.       while (dom.parentNode !== null && dom.parentNode !== undefined) {
  1443.         var rawParent = dom.parentNode;
  1444.         var p = SugarElement.fromDom(rawParent);
  1445.         ret.push(p);
  1446.         if (stop(p) === true) {
  1447.           break;
  1448.         } else {
  1449.           dom = rawParent;
  1450.         }
  1451.       }
  1452.       return ret;
  1453.     };
  1454.     var siblings = function (element) {
  1455.       var filterSelf = function (elements) {
  1456.         return filter$4(elements, function (x) {
  1457.           return !eq(element, x);
  1458.         });
  1459.       };
  1460.       return parent(element).map(children).map(filterSelf).getOr([]);
  1461.     };
  1462.     var prevSibling = function (element) {
  1463.       return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
  1464.     };
  1465.     var nextSibling = function (element) {
  1466.       return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1467.     };
  1468.     var prevSiblings = function (element) {
  1469.       return reverse(toArray(element, prevSibling));
  1470.     };
  1471.     var nextSiblings = function (element) {
  1472.       return toArray(element, nextSibling);
  1473.     };
  1474.     var children = function (element) {
  1475.       return map$3(element.dom.childNodes, SugarElement.fromDom);
  1476.     };
  1477.     var child$1 = function (element, index) {
  1478.       var cs = element.dom.childNodes;
  1479.       return Optional.from(cs[index]).map(SugarElement.fromDom);
  1480.     };
  1481.     var firstChild = function (element) {
  1482.       return child$1(element, 0);
  1483.     };
  1484.     var lastChild = function (element) {
  1485.       return child$1(element, element.dom.childNodes.length - 1);
  1486.     };
  1487.     var childNodesCount = function (element) {
  1488.       return element.dom.childNodes.length;
  1489.     };
  1490.  
  1491.     var getHead = function (doc) {
  1492.       var b = doc.dom.head;
  1493.       if (b === null || b === undefined) {
  1494.         throw new Error('Head is not available yet');
  1495.       }
  1496.       return SugarElement.fromDom(b);
  1497.     };
  1498.  
  1499.     var isShadowRoot = function (dos) {
  1500.       return isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
  1501.     };
  1502.     var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1503.     var isSupported$1 = constant(supported);
  1504.     var getRootNode = supported ? function (e) {
  1505.       return SugarElement.fromDom(e.dom.getRootNode());
  1506.     } : documentOrOwner;
  1507.     var getStyleContainer = function (dos) {
  1508.       return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
  1509.     };
  1510.     var getShadowRoot = function (e) {
  1511.       var r = getRootNode(e);
  1512.       return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1513.     };
  1514.     var getShadowHost = function (e) {
  1515.       return SugarElement.fromDom(e.dom.host);
  1516.     };
  1517.     var getOriginalEventTarget = function (event) {
  1518.       if (isSupported$1() && isNonNullable(event.target)) {
  1519.         var el = SugarElement.fromDom(event.target);
  1520.         if (isElement$6(el) && isOpenShadowHost(el)) {
  1521.           if (event.composed && event.composedPath) {
  1522.             var composedPath = event.composedPath();
  1523.             if (composedPath) {
  1524.               return head(composedPath);
  1525.             }
  1526.           }
  1527.         }
  1528.       }
  1529.       return Optional.from(event.target);
  1530.     };
  1531.     var isOpenShadowHost = function (element) {
  1532.       return isNonNullable(element.dom.shadowRoot);
  1533.     };
  1534.  
  1535.     var before$4 = function (marker, element) {
  1536.       var parent$1 = parent(marker);
  1537.       parent$1.each(function (v) {
  1538.         v.dom.insertBefore(element.dom, marker.dom);
  1539.       });
  1540.     };
  1541.     var after$3 = function (marker, element) {
  1542.       var sibling = nextSibling(marker);
  1543.       sibling.fold(function () {
  1544.         var parent$1 = parent(marker);
  1545.         parent$1.each(function (v) {
  1546.           append$1(v, element);
  1547.         });
  1548.       }, function (v) {
  1549.         before$4(v, element);
  1550.       });
  1551.     };
  1552.     var prepend = function (parent, element) {
  1553.       var firstChild$1 = firstChild(parent);
  1554.       firstChild$1.fold(function () {
  1555.         append$1(parent, element);
  1556.       }, function (v) {
  1557.         parent.dom.insertBefore(element.dom, v.dom);
  1558.       });
  1559.     };
  1560.     var append$1 = function (parent, element) {
  1561.       parent.dom.appendChild(element.dom);
  1562.     };
  1563.     var wrap$3 = function (element, wrapper) {
  1564.       before$4(element, wrapper);
  1565.       append$1(wrapper, element);
  1566.     };
  1567.  
  1568.     var before$3 = function (marker, elements) {
  1569.       each$k(elements, function (x) {
  1570.         before$4(marker, x);
  1571.       });
  1572.     };
  1573.     var append = function (parent, elements) {
  1574.       each$k(elements, function (x) {
  1575.         append$1(parent, x);
  1576.       });
  1577.     };
  1578.  
  1579.     var empty = function (element) {
  1580.       element.dom.textContent = '';
  1581.       each$k(children(element), function (rogue) {
  1582.         remove$7(rogue);
  1583.       });
  1584.     };
  1585.     var remove$7 = function (element) {
  1586.       var dom = element.dom;
  1587.       if (dom.parentNode !== null) {
  1588.         dom.parentNode.removeChild(dom);
  1589.       }
  1590.     };
  1591.     var unwrap = function (wrapper) {
  1592.       var children$1 = children(wrapper);
  1593.       if (children$1.length > 0) {
  1594.         before$3(wrapper, children$1);
  1595.       }
  1596.       remove$7(wrapper);
  1597.     };
  1598.  
  1599.     var inBody = function (element) {
  1600.       var dom = isText$8(element) ? element.dom.parentNode : element.dom;
  1601.       if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1602.         return false;
  1603.       }
  1604.       var doc = dom.ownerDocument;
  1605.       return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1606.         return doc.body.contains(dom);
  1607.       }, compose1(inBody, getShadowHost));
  1608.     };
  1609.  
  1610.     var r = function (left, top) {
  1611.       var translate = function (x, y) {
  1612.         return r(left + x, top + y);
  1613.       };
  1614.       return {
  1615.         left: left,
  1616.         top: top,
  1617.         translate: translate
  1618.       };
  1619.     };
  1620.     var SugarPosition = r;
  1621.  
  1622.     var boxPosition = function (dom) {
  1623.       var box = dom.getBoundingClientRect();
  1624.       return SugarPosition(box.left, box.top);
  1625.     };
  1626.     var firstDefinedOrZero = function (a, b) {
  1627.       if (a !== undefined) {
  1628.         return a;
  1629.       } else {
  1630.         return b !== undefined ? b : 0;
  1631.       }
  1632.     };
  1633.     var absolute = function (element) {
  1634.       var doc = element.dom.ownerDocument;
  1635.       var body = doc.body;
  1636.       var win = doc.defaultView;
  1637.       var html = doc.documentElement;
  1638.       if (body === element.dom) {
  1639.         return SugarPosition(body.offsetLeft, body.offsetTop);
  1640.       }
  1641.       var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1642.       var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1643.       var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1644.       var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1645.       return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1646.     };
  1647.     var viewport = function (element) {
  1648.       var dom = element.dom;
  1649.       var doc = dom.ownerDocument;
  1650.       var body = doc.body;
  1651.       if (body === dom) {
  1652.         return SugarPosition(body.offsetLeft, body.offsetTop);
  1653.       }
  1654.       if (!inBody(element)) {
  1655.         return SugarPosition(0, 0);
  1656.       }
  1657.       return boxPosition(dom);
  1658.     };
  1659.  
  1660.     var get$8 = function (_DOC) {
  1661.       var doc = _DOC !== undefined ? _DOC.dom : document;
  1662.       var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1663.       var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1664.       return SugarPosition(x, y);
  1665.     };
  1666.     var to = function (x, y, _DOC) {
  1667.       var doc = _DOC !== undefined ? _DOC.dom : document;
  1668.       var win = doc.defaultView;
  1669.       if (win) {
  1670.         win.scrollTo(x, y);
  1671.       }
  1672.     };
  1673.     var intoView = function (element, alignToTop) {
  1674.       var isSafari = detect().browser.isSafari();
  1675.       if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
  1676.         element.dom.scrollIntoViewIfNeeded(false);
  1677.       } else {
  1678.         element.dom.scrollIntoView(alignToTop);
  1679.       }
  1680.     };
  1681.  
  1682.     var get$7 = function (_win) {
  1683.       var win = _win === undefined ? window : _win;
  1684.       if (detect().browser.isFirefox()) {
  1685.         return Optional.none();
  1686.       } else {
  1687.         return Optional.from(win['visualViewport']);
  1688.       }
  1689.     };
  1690.     var bounds = function (x, y, width, height) {
  1691.       return {
  1692.         x: x,
  1693.         y: y,
  1694.         width: width,
  1695.         height: height,
  1696.         right: x + width,
  1697.         bottom: y + height
  1698.       };
  1699.     };
  1700.     var getBounds = function (_win) {
  1701.       var win = _win === undefined ? window : _win;
  1702.       var doc = win.document;
  1703.       var scroll = get$8(SugarElement.fromDom(doc));
  1704.       return get$7(win).fold(function () {
  1705.         var html = win.document.documentElement;
  1706.         var width = html.clientWidth;
  1707.         var height = html.clientHeight;
  1708.         return bounds(scroll.left, scroll.top, width, height);
  1709.       }, function (visualViewport) {
  1710.         return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1711.       });
  1712.     };
  1713.  
  1714.     var isNodeType = function (type) {
  1715.       return function (node) {
  1716.         return !!node && node.nodeType === type;
  1717.       };
  1718.     };
  1719.     var isRestrictedNode = function (node) {
  1720.       return !!node && !Object.getPrototypeOf(node);
  1721.     };
  1722.     var isElement$5 = isNodeType(1);
  1723.     var matchNodeNames = function (names) {
  1724.       var lowercasedNames = names.map(function (s) {
  1725.         return s.toLowerCase();
  1726.       });
  1727.       return function (node) {
  1728.         if (node && node.nodeName) {
  1729.           var nodeName = node.nodeName.toLowerCase();
  1730.           return contains$3(lowercasedNames, nodeName);
  1731.         }
  1732.         return false;
  1733.       };
  1734.     };
  1735.     var matchStyleValues = function (name, values) {
  1736.       var items = values.toLowerCase().split(' ');
  1737.       return function (node) {
  1738.         if (isElement$5(node)) {
  1739.           for (var i = 0; i < items.length; i++) {
  1740.             var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
  1741.             var cssValue = computed ? computed.getPropertyValue(name) : null;
  1742.             if (cssValue === items[i]) {
  1743.               return true;
  1744.             }
  1745.           }
  1746.         }
  1747.         return false;
  1748.       };
  1749.     };
  1750.     var hasAttribute = function (attrName) {
  1751.       return function (node) {
  1752.         return isElement$5(node) && node.hasAttribute(attrName);
  1753.       };
  1754.     };
  1755.     var hasAttributeValue = function (attrName, attrValue) {
  1756.       return function (node) {
  1757.         return isElement$5(node) && node.getAttribute(attrName) === attrValue;
  1758.       };
  1759.     };
  1760.     var isBogus$2 = function (node) {
  1761.       return isElement$5(node) && node.hasAttribute('data-mce-bogus');
  1762.     };
  1763.     var isBogusAll$1 = function (node) {
  1764.       return isElement$5(node) && node.getAttribute('data-mce-bogus') === 'all';
  1765.     };
  1766.     var isTable$3 = function (node) {
  1767.       return isElement$5(node) && node.tagName === 'TABLE';
  1768.     };
  1769.     var hasContentEditableState = function (value) {
  1770.       return function (node) {
  1771.         if (isElement$5(node)) {
  1772.           if (node.contentEditable === value) {
  1773.             return true;
  1774.           }
  1775.           if (node.getAttribute('data-mce-contenteditable') === value) {
  1776.             return true;
  1777.           }
  1778.         }
  1779.         return false;
  1780.       };
  1781.     };
  1782.     var isTextareaOrInput = matchNodeNames([
  1783.       'textarea',
  1784.       'input'
  1785.     ]);
  1786.     var isText$7 = isNodeType(3);
  1787.     var isComment = isNodeType(8);
  1788.     var isDocument$1 = isNodeType(9);
  1789.     var isDocumentFragment = isNodeType(11);
  1790.     var isBr$5 = matchNodeNames(['br']);
  1791.     var isImg = matchNodeNames(['img']);
  1792.     var isContentEditableTrue$4 = hasContentEditableState('true');
  1793.     var isContentEditableFalse$b = hasContentEditableState('false');
  1794.     var isTableCell$5 = matchNodeNames([
  1795.       'td',
  1796.       'th'
  1797.     ]);
  1798.     var isMedia$2 = matchNodeNames([
  1799.       'video',
  1800.       'audio',
  1801.       'object',
  1802.       'embed'
  1803.     ]);
  1804.  
  1805.     var is$1 = function (lhs, rhs, comparator) {
  1806.       if (comparator === void 0) {
  1807.         comparator = tripleEquals;
  1808.       }
  1809.       return lhs.exists(function (left) {
  1810.         return comparator(left, rhs);
  1811.       });
  1812.     };
  1813.     var cat = function (arr) {
  1814.       var r = [];
  1815.       var push = function (x) {
  1816.         r.push(x);
  1817.       };
  1818.       for (var i = 0; i < arr.length; i++) {
  1819.         arr[i].each(push);
  1820.       }
  1821.       return r;
  1822.     };
  1823.     var lift2 = function (oa, ob, f) {
  1824.       return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  1825.     };
  1826.     var lift3 = function (oa, ob, oc, f) {
  1827.       return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  1828.     };
  1829.     var someIf = function (b, a) {
  1830.       return b ? Optional.some(a) : Optional.none();
  1831.     };
  1832.  
  1833.     var isSupported = function (dom) {
  1834.       return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  1835.     };
  1836.  
  1837.     var rawSet = function (dom, key, value) {
  1838.       if (isString$1(value) || isBoolean(value) || isNumber(value)) {
  1839.         dom.setAttribute(key, value + '');
  1840.       } else {
  1841.         console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1842.         throw new Error('Attribute value was not simple');
  1843.       }
  1844.     };
  1845.     var set$1 = function (element, key, value) {
  1846.       rawSet(element.dom, key, value);
  1847.     };
  1848.     var setAll$1 = function (element, attrs) {
  1849.       var dom = element.dom;
  1850.       each$j(attrs, function (v, k) {
  1851.         rawSet(dom, k, v);
  1852.       });
  1853.     };
  1854.     var get$6 = function (element, key) {
  1855.       var v = element.dom.getAttribute(key);
  1856.       return v === null ? undefined : v;
  1857.     };
  1858.     var getOpt = function (element, key) {
  1859.       return Optional.from(get$6(element, key));
  1860.     };
  1861.     var has$1 = function (element, key) {
  1862.       var dom = element.dom;
  1863.       return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1864.     };
  1865.     var remove$6 = function (element, key) {
  1866.       element.dom.removeAttribute(key);
  1867.     };
  1868.     var clone$3 = function (element) {
  1869.       return foldl(element.dom.attributes, function (acc, attr) {
  1870.         acc[attr.name] = attr.value;
  1871.         return acc;
  1872.       }, {});
  1873.     };
  1874.  
  1875.     var internalSet = function (dom, property, value) {
  1876.       if (!isString$1(value)) {
  1877.         console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1878.         throw new Error('CSS value must be a string: ' + value);
  1879.       }
  1880.       if (isSupported(dom)) {
  1881.         dom.style.setProperty(property, value);
  1882.       }
  1883.     };
  1884.     var setAll = function (element, css) {
  1885.       var dom = element.dom;
  1886.       each$j(css, function (v, k) {
  1887.         internalSet(dom, k, v);
  1888.       });
  1889.     };
  1890.     var get$5 = function (element, property) {
  1891.       var dom = element.dom;
  1892.       var styles = window.getComputedStyle(dom);
  1893.       var r = styles.getPropertyValue(property);
  1894.       return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1895.     };
  1896.     var getUnsafeProperty = function (dom, property) {
  1897.       return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  1898.     };
  1899.     var getRaw = function (element, property) {
  1900.       var dom = element.dom;
  1901.       var raw = getUnsafeProperty(dom, property);
  1902.       return Optional.from(raw).filter(function (r) {
  1903.         return r.length > 0;
  1904.       });
  1905.     };
  1906.     var getAllRaw = function (element) {
  1907.       var css = {};
  1908.       var dom = element.dom;
  1909.       if (isSupported(dom)) {
  1910.         for (var i = 0; i < dom.style.length; i++) {
  1911.           var ruleName = dom.style.item(i);
  1912.           css[ruleName] = dom.style[ruleName];
  1913.         }
  1914.       }
  1915.       return css;
  1916.     };
  1917.     var reflow = function (e) {
  1918.       return e.dom.offsetWidth;
  1919.     };
  1920.  
  1921.     var browser$3 = detect().browser;
  1922.     var firstElement = function (nodes) {
  1923.       return find$3(nodes, isElement$6);
  1924.     };
  1925.     var getTableCaptionDeltaY = function (elm) {
  1926.       if (browser$3.isFirefox() && name(elm) === 'table') {
  1927.         return firstElement(children(elm)).filter(function (elm) {
  1928.           return name(elm) === 'caption';
  1929.         }).bind(function (caption) {
  1930.           return firstElement(nextSiblings(caption)).map(function (body) {
  1931.             var bodyTop = body.dom.offsetTop;
  1932.             var captionTop = caption.dom.offsetTop;
  1933.             var captionHeight = caption.dom.offsetHeight;
  1934.             return bodyTop <= captionTop ? -captionHeight : 0;
  1935.           });
  1936.         }).getOr(0);
  1937.       } else {
  1938.         return 0;
  1939.       }
  1940.     };
  1941.     var hasChild = function (elm, child) {
  1942.       return elm.children && contains$3(elm.children, child);
  1943.     };
  1944.     var getPos = function (body, elm, rootElm) {
  1945.       var x = 0, y = 0;
  1946.       var doc = body.ownerDocument;
  1947.       rootElm = rootElm ? rootElm : body;
  1948.       if (elm) {
  1949.         if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), 'position') === 'static') {
  1950.           var pos = elm.getBoundingClientRect();
  1951.           x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - doc.documentElement.clientLeft;
  1952.           y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - doc.documentElement.clientTop;
  1953.           return {
  1954.             x: x,
  1955.             y: y
  1956.           };
  1957.         }
  1958.         var offsetParent = elm;
  1959.         while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1960.           var castOffsetParent = offsetParent;
  1961.           x += castOffsetParent.offsetLeft || 0;
  1962.           y += castOffsetParent.offsetTop || 0;
  1963.           offsetParent = castOffsetParent.offsetParent;
  1964.         }
  1965.         offsetParent = elm.parentNode;
  1966.         while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
  1967.           x -= offsetParent.scrollLeft || 0;
  1968.           y -= offsetParent.scrollTop || 0;
  1969.           offsetParent = offsetParent.parentNode;
  1970.         }
  1971.         y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
  1972.       }
  1973.       return {
  1974.         x: x,
  1975.         y: y
  1976.       };
  1977.     };
  1978.  
  1979.     var exports$1 = {}, module$1 = { exports: exports$1 };
  1980.     (function (define, exports, module, require) {
  1981.       (function (global, factory) {
  1982.         typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  1983.       }(this, function () {
  1984.         var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1985.         var promise = { exports: {} };
  1986.         (function (module) {
  1987.           (function (root) {
  1988.             var setTimeoutFunc = setTimeout;
  1989.             function noop() {
  1990.             }
  1991.             function bind(fn, thisArg) {
  1992.               return function () {
  1993.                 fn.apply(thisArg, arguments);
  1994.               };
  1995.             }
  1996.             function Promise(fn) {
  1997.               if (typeof this !== 'object')
  1998.                 throw new TypeError('Promises must be constructed via new');
  1999.               if (typeof fn !== 'function')
  2000.                 throw new TypeError('not a function');
  2001.               this._state = 0;
  2002.               this._handled = false;
  2003.               this._value = undefined;
  2004.               this._deferreds = [];
  2005.               doResolve(fn, this);
  2006.             }
  2007.             function handle(self, deferred) {
  2008.               while (self._state === 3) {
  2009.                 self = self._value;
  2010.               }
  2011.               if (self._state === 0) {
  2012.                 self._deferreds.push(deferred);
  2013.                 return;
  2014.               }
  2015.               self._handled = true;
  2016.               Promise._immediateFn(function () {
  2017.                 var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  2018.                 if (cb === null) {
  2019.                   (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  2020.                   return;
  2021.                 }
  2022.                 var ret;
  2023.                 try {
  2024.                   ret = cb(self._value);
  2025.                 } catch (e) {
  2026.                   reject(deferred.promise, e);
  2027.                   return;
  2028.                 }
  2029.                 resolve(deferred.promise, ret);
  2030.               });
  2031.             }
  2032.             function resolve(self, newValue) {
  2033.               try {
  2034.                 if (newValue === self)
  2035.                   throw new TypeError('A promise cannot be resolved with itself.');
  2036.                 if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  2037.                   var then = newValue.then;
  2038.                   if (newValue instanceof Promise) {
  2039.                     self._state = 3;
  2040.                     self._value = newValue;
  2041.                     finale(self);
  2042.                     return;
  2043.                   } else if (typeof then === 'function') {
  2044.                     doResolve(bind(then, newValue), self);
  2045.                     return;
  2046.                   }
  2047.                 }
  2048.                 self._state = 1;
  2049.                 self._value = newValue;
  2050.                 finale(self);
  2051.               } catch (e) {
  2052.                 reject(self, e);
  2053.               }
  2054.             }
  2055.             function reject(self, newValue) {
  2056.               self._state = 2;
  2057.               self._value = newValue;
  2058.               finale(self);
  2059.             }
  2060.             function finale(self) {
  2061.               if (self._state === 2 && self._deferreds.length === 0) {
  2062.                 Promise._immediateFn(function () {
  2063.                   if (!self._handled) {
  2064.                     Promise._unhandledRejectionFn(self._value);
  2065.                   }
  2066.                 });
  2067.               }
  2068.               for (var i = 0, len = self._deferreds.length; i < len; i++) {
  2069.                 handle(self, self._deferreds[i]);
  2070.               }
  2071.               self._deferreds = null;
  2072.             }
  2073.             function Handler(onFulfilled, onRejected, promise) {
  2074.               this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  2075.               this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  2076.               this.promise = promise;
  2077.             }
  2078.             function doResolve(fn, self) {
  2079.               var done = false;
  2080.               try {
  2081.                 fn(function (value) {
  2082.                   if (done)
  2083.                     return;
  2084.                   done = true;
  2085.                   resolve(self, value);
  2086.                 }, function (reason) {
  2087.                   if (done)
  2088.                     return;
  2089.                   done = true;
  2090.                   reject(self, reason);
  2091.                 });
  2092.               } catch (ex) {
  2093.                 if (done)
  2094.                   return;
  2095.                 done = true;
  2096.                 reject(self, ex);
  2097.               }
  2098.             }
  2099.             Promise.prototype['catch'] = function (onRejected) {
  2100.               return this.then(null, onRejected);
  2101.             };
  2102.             Promise.prototype.then = function (onFulfilled, onRejected) {
  2103.               var prom = new this.constructor(noop);
  2104.               handle(this, new Handler(onFulfilled, onRejected, prom));
  2105.               return prom;
  2106.             };
  2107.             Promise.all = function (arr) {
  2108.               var args = Array.prototype.slice.call(arr);
  2109.               return new Promise(function (resolve, reject) {
  2110.                 if (args.length === 0)
  2111.                   return resolve([]);
  2112.                 var remaining = args.length;
  2113.                 function res(i, val) {
  2114.                   try {
  2115.                     if (val && (typeof val === 'object' || typeof val === 'function')) {
  2116.                       var then = val.then;
  2117.                       if (typeof then === 'function') {
  2118.                         then.call(val, function (val) {
  2119.                           res(i, val);
  2120.                         }, reject);
  2121.                         return;
  2122.                       }
  2123.                     }
  2124.                     args[i] = val;
  2125.                     if (--remaining === 0) {
  2126.                       resolve(args);
  2127.                     }
  2128.                   } catch (ex) {
  2129.                     reject(ex);
  2130.                   }
  2131.                 }
  2132.                 for (var i = 0; i < args.length; i++) {
  2133.                   res(i, args[i]);
  2134.                 }
  2135.               });
  2136.             };
  2137.             Promise.resolve = function (value) {
  2138.               if (value && typeof value === 'object' && value.constructor === Promise) {
  2139.                 return value;
  2140.               }
  2141.               return new Promise(function (resolve) {
  2142.                 resolve(value);
  2143.               });
  2144.             };
  2145.             Promise.reject = function (value) {
  2146.               return new Promise(function (resolve, reject) {
  2147.                 reject(value);
  2148.               });
  2149.             };
  2150.             Promise.race = function (values) {
  2151.               return new Promise(function (resolve, reject) {
  2152.                 for (var i = 0, len = values.length; i < len; i++) {
  2153.                   values[i].then(resolve, reject);
  2154.                 }
  2155.               });
  2156.             };
  2157.             Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  2158.               setImmediate(fn);
  2159.             } : function (fn) {
  2160.               setTimeoutFunc(fn, 0);
  2161.             };
  2162.             Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  2163.               if (typeof console !== 'undefined' && console) {
  2164.                 console.warn('Possible Unhandled Promise Rejection:', err);
  2165.               }
  2166.             };
  2167.             Promise._setImmediateFn = function _setImmediateFn(fn) {
  2168.               Promise._immediateFn = fn;
  2169.             };
  2170.             Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  2171.               Promise._unhandledRejectionFn = fn;
  2172.             };
  2173.             if (module.exports) {
  2174.               module.exports = Promise;
  2175.             } else if (!root.Promise) {
  2176.               root.Promise = Promise;
  2177.             }
  2178.           }(commonjsGlobal));
  2179.         }(promise));
  2180.         var promisePolyfill = promise.exports;
  2181.         var Global = function () {
  2182.           if (typeof window !== 'undefined') {
  2183.             return window;
  2184.           } else {
  2185.             return Function('return this;')();
  2186.           }
  2187.         }();
  2188.         var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  2189.         return promisePolyfill_1;
  2190.       }));
  2191.     }(undefined, exports$1, module$1));
  2192.     var Promise$1 = module$1.exports.boltExport;
  2193.  
  2194.     var nu$1 = function (baseFn) {
  2195.       var data = Optional.none();
  2196.       var callbacks = [];
  2197.       var map = function (f) {
  2198.         return nu$1(function (nCallback) {
  2199.           get(function (data) {
  2200.             nCallback(f(data));
  2201.           });
  2202.         });
  2203.       };
  2204.       var get = function (nCallback) {
  2205.         if (isReady()) {
  2206.           call(nCallback);
  2207.         } else {
  2208.           callbacks.push(nCallback);
  2209.         }
  2210.       };
  2211.       var set = function (x) {
  2212.         if (!isReady()) {
  2213.           data = Optional.some(x);
  2214.           run(callbacks);
  2215.           callbacks = [];
  2216.         }
  2217.       };
  2218.       var isReady = function () {
  2219.         return data.isSome();
  2220.       };
  2221.       var run = function (cbs) {
  2222.         each$k(cbs, call);
  2223.       };
  2224.       var call = function (cb) {
  2225.         data.each(function (x) {
  2226.           setTimeout(function () {
  2227.             cb(x);
  2228.           }, 0);
  2229.         });
  2230.       };
  2231.       baseFn(set);
  2232.       return {
  2233.         get: get,
  2234.         map: map,
  2235.         isReady: isReady
  2236.       };
  2237.     };
  2238.     var pure$1 = function (a) {
  2239.       return nu$1(function (callback) {
  2240.         callback(a);
  2241.       });
  2242.     };
  2243.     var LazyValue = {
  2244.       nu: nu$1,
  2245.       pure: pure$1
  2246.     };
  2247.  
  2248.     var errorReporter = function (err) {
  2249.       setTimeout(function () {
  2250.         throw err;
  2251.       }, 0);
  2252.     };
  2253.     var make = function (run) {
  2254.       var get = function (callback) {
  2255.         run().then(callback, errorReporter);
  2256.       };
  2257.       var map = function (fab) {
  2258.         return make(function () {
  2259.           return run().then(fab);
  2260.         });
  2261.       };
  2262.       var bind = function (aFutureB) {
  2263.         return make(function () {
  2264.           return run().then(function (v) {
  2265.             return aFutureB(v).toPromise();
  2266.           });
  2267.         });
  2268.       };
  2269.       var anonBind = function (futureB) {
  2270.         return make(function () {
  2271.           return run().then(function () {
  2272.             return futureB.toPromise();
  2273.           });
  2274.         });
  2275.       };
  2276.       var toLazy = function () {
  2277.         return LazyValue.nu(get);
  2278.       };
  2279.       var toCached = function () {
  2280.         var cache = null;
  2281.         return make(function () {
  2282.           if (cache === null) {
  2283.             cache = run();
  2284.           }
  2285.           return cache;
  2286.         });
  2287.       };
  2288.       var toPromise = run;
  2289.       return {
  2290.         map: map,
  2291.         bind: bind,
  2292.         anonBind: anonBind,
  2293.         toLazy: toLazy,
  2294.         toCached: toCached,
  2295.         toPromise: toPromise,
  2296.         get: get
  2297.       };
  2298.     };
  2299.     var nu = function (baseFn) {
  2300.       return make(function () {
  2301.         return new Promise$1(baseFn);
  2302.       });
  2303.     };
  2304.     var pure = function (a) {
  2305.       return make(function () {
  2306.         return Promise$1.resolve(a);
  2307.       });
  2308.     };
  2309.     var Future = {
  2310.       nu: nu,
  2311.       pure: pure
  2312.     };
  2313.  
  2314.     var par$1 = function (asyncValues, nu) {
  2315.       return nu(function (callback) {
  2316.         var r = [];
  2317.         var count = 0;
  2318.         var cb = function (i) {
  2319.           return function (value) {
  2320.             r[i] = value;
  2321.             count++;
  2322.             if (count >= asyncValues.length) {
  2323.               callback(r);
  2324.             }
  2325.           };
  2326.         };
  2327.         if (asyncValues.length === 0) {
  2328.           callback([]);
  2329.         } else {
  2330.           each$k(asyncValues, function (asyncValue, i) {
  2331.             asyncValue.get(cb(i));
  2332.           });
  2333.         }
  2334.       });
  2335.     };
  2336.  
  2337.     var par = function (futures) {
  2338.       return par$1(futures, Future.nu);
  2339.     };
  2340.  
  2341.     var value$1 = function (o) {
  2342.       var or = function (_opt) {
  2343.         return value$1(o);
  2344.       };
  2345.       var orThunk = function (_f) {
  2346.         return value$1(o);
  2347.       };
  2348.       var map = function (f) {
  2349.         return value$1(f(o));
  2350.       };
  2351.       var mapError = function (_f) {
  2352.         return value$1(o);
  2353.       };
  2354.       var each = function (f) {
  2355.         f(o);
  2356.       };
  2357.       var bind = function (f) {
  2358.         return f(o);
  2359.       };
  2360.       var fold = function (_, onValue) {
  2361.         return onValue(o);
  2362.       };
  2363.       var exists = function (f) {
  2364.         return f(o);
  2365.       };
  2366.       var forall = function (f) {
  2367.         return f(o);
  2368.       };
  2369.       var toOptional = function () {
  2370.         return Optional.some(o);
  2371.       };
  2372.       return {
  2373.         isValue: always,
  2374.         isError: never,
  2375.         getOr: constant(o),
  2376.         getOrThunk: constant(o),
  2377.         getOrDie: constant(o),
  2378.         or: or,
  2379.         orThunk: orThunk,
  2380.         fold: fold,
  2381.         map: map,
  2382.         mapError: mapError,
  2383.         each: each,
  2384.         bind: bind,
  2385.         exists: exists,
  2386.         forall: forall,
  2387.         toOptional: toOptional
  2388.       };
  2389.     };
  2390.     var error = function (message) {
  2391.       var getOrThunk = function (f) {
  2392.         return f();
  2393.       };
  2394.       var getOrDie = function () {
  2395.         return die(String(message))();
  2396.       };
  2397.       var or = identity;
  2398.       var orThunk = function (f) {
  2399.         return f();
  2400.       };
  2401.       var map = function (_f) {
  2402.         return error(message);
  2403.       };
  2404.       var mapError = function (f) {
  2405.         return error(f(message));
  2406.       };
  2407.       var bind = function (_f) {
  2408.         return error(message);
  2409.       };
  2410.       var fold = function (onError, _) {
  2411.         return onError(message);
  2412.       };
  2413.       return {
  2414.         isValue: never,
  2415.         isError: always,
  2416.         getOr: identity,
  2417.         getOrThunk: getOrThunk,
  2418.         getOrDie: getOrDie,
  2419.         or: or,
  2420.         orThunk: orThunk,
  2421.         fold: fold,
  2422.         map: map,
  2423.         mapError: mapError,
  2424.         each: noop,
  2425.         bind: bind,
  2426.         exists: never,
  2427.         forall: always,
  2428.         toOptional: Optional.none
  2429.       };
  2430.     };
  2431.     var fromOption = function (opt, err) {
  2432.       return opt.fold(function () {
  2433.         return error(err);
  2434.       }, value$1);
  2435.     };
  2436.     var Result = {
  2437.       value: value$1,
  2438.       error: error,
  2439.       fromOption: fromOption
  2440.     };
  2441.  
  2442.     var generate$1 = function (cases) {
  2443.       if (!isArray$1(cases)) {
  2444.         throw new Error('cases must be an array');
  2445.       }
  2446.       if (cases.length === 0) {
  2447.         throw new Error('there must be at least one case');
  2448.       }
  2449.       var constructors = [];
  2450.       var adt = {};
  2451.       each$k(cases, function (acase, count) {
  2452.         var keys$1 = keys(acase);
  2453.         if (keys$1.length !== 1) {
  2454.           throw new Error('one and only one name per case');
  2455.         }
  2456.         var key = keys$1[0];
  2457.         var value = acase[key];
  2458.         if (adt[key] !== undefined) {
  2459.           throw new Error('duplicate key detected:' + key);
  2460.         } else if (key === 'cata') {
  2461.           throw new Error('cannot have a case named cata (sorry)');
  2462.         } else if (!isArray$1(value)) {
  2463.           throw new Error('case arguments must be an array');
  2464.         }
  2465.         constructors.push(key);
  2466.         adt[key] = function () {
  2467.           var args = [];
  2468.           for (var _i = 0; _i < arguments.length; _i++) {
  2469.             args[_i] = arguments[_i];
  2470.           }
  2471.           var argLength = args.length;
  2472.           if (argLength !== value.length) {
  2473.             throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2474.           }
  2475.           var match = function (branches) {
  2476.             var branchKeys = keys(branches);
  2477.             if (constructors.length !== branchKeys.length) {
  2478.               throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2479.             }
  2480.             var allReqd = forall(constructors, function (reqKey) {
  2481.               return contains$3(branchKeys, reqKey);
  2482.             });
  2483.             if (!allReqd) {
  2484.               throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2485.             }
  2486.             return branches[key].apply(null, args);
  2487.           };
  2488.           return {
  2489.             fold: function () {
  2490.               var foldArgs = [];
  2491.               for (var _i = 0; _i < arguments.length; _i++) {
  2492.                 foldArgs[_i] = arguments[_i];
  2493.               }
  2494.               if (foldArgs.length !== cases.length) {
  2495.                 throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2496.               }
  2497.               var target = foldArgs[count];
  2498.               return target.apply(null, args);
  2499.             },
  2500.             match: match,
  2501.             log: function (label) {
  2502.               console.log(label, {
  2503.                 constructors: constructors,
  2504.                 constructor: key,
  2505.                 params: args
  2506.               });
  2507.             }
  2508.           };
  2509.         };
  2510.       });
  2511.       return adt;
  2512.     };
  2513.     var Adt = { generate: generate$1 };
  2514.  
  2515.     Adt.generate([
  2516.       {
  2517.         bothErrors: [
  2518.           'error1',
  2519.           'error2'
  2520.         ]
  2521.       },
  2522.       {
  2523.         firstError: [
  2524.           'error1',
  2525.           'value2'
  2526.         ]
  2527.       },
  2528.       {
  2529.         secondError: [
  2530.           'value1',
  2531.           'error2'
  2532.         ]
  2533.       },
  2534.       {
  2535.         bothValues: [
  2536.           'value1',
  2537.           'value2'
  2538.         ]
  2539.       }
  2540.     ]);
  2541.     var unite = function (result) {
  2542.       return result.fold(identity, identity);
  2543.     };
  2544.  
  2545.     function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  2546.       if (is(scope, a)) {
  2547.         return Optional.some(scope);
  2548.       } else if (isFunction(isRoot) && isRoot(scope)) {
  2549.         return Optional.none();
  2550.       } else {
  2551.         return ancestor(scope, a, isRoot);
  2552.       }
  2553.     }
  2554.  
  2555.     var ancestor$3 = function (scope, predicate, isRoot) {
  2556.       var element = scope.dom;
  2557.       var stop = isFunction(isRoot) ? isRoot : never;
  2558.       while (element.parentNode) {
  2559.         element = element.parentNode;
  2560.         var el = SugarElement.fromDom(element);
  2561.         if (predicate(el)) {
  2562.           return Optional.some(el);
  2563.         } else if (stop(el)) {
  2564.           break;
  2565.         }
  2566.       }
  2567.       return Optional.none();
  2568.     };
  2569.     var closest$3 = function (scope, predicate, isRoot) {
  2570.       var is = function (s, test) {
  2571.         return test(s);
  2572.       };
  2573.       return ClosestOrAncestor(is, ancestor$3, scope, predicate, isRoot);
  2574.     };
  2575.     var sibling$2 = function (scope, predicate) {
  2576.       var element = scope.dom;
  2577.       if (!element.parentNode) {
  2578.         return Optional.none();
  2579.       }
  2580.       return child(SugarElement.fromDom(element.parentNode), function (x) {
  2581.         return !eq(scope, x) && predicate(x);
  2582.       });
  2583.     };
  2584.     var child = function (scope, predicate) {
  2585.       var pred = function (node) {
  2586.         return predicate(SugarElement.fromDom(node));
  2587.       };
  2588.       var result = find$3(scope.dom.childNodes, pred);
  2589.       return result.map(SugarElement.fromDom);
  2590.     };
  2591.  
  2592.     var ancestor$2 = function (scope, selector, isRoot) {
  2593.       return ancestor$3(scope, function (e) {
  2594.         return is$2(e, selector);
  2595.       }, isRoot);
  2596.     };
  2597.     var descendant = function (scope, selector) {
  2598.       return one(selector, scope);
  2599.     };
  2600.     var closest$2 = function (scope, selector, isRoot) {
  2601.       var is = function (element, selector) {
  2602.         return is$2(element, selector);
  2603.       };
  2604.       return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
  2605.     };
  2606.  
  2607.     var promiseObj = window.Promise ? window.Promise : Promise$1;
  2608.  
  2609.     var requestAnimationFramePromise;
  2610.     var requestAnimationFrame = function (callback, element) {
  2611.       var requestAnimationFrameFunc = window.requestAnimationFrame;
  2612.       var vendors = [
  2613.         'ms',
  2614.         'moz',
  2615.         'webkit'
  2616.       ];
  2617.       var featurefill = function (cb) {
  2618.         window.setTimeout(cb, 0);
  2619.       };
  2620.       for (var i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
  2621.         requestAnimationFrameFunc = window[vendors[i] + 'RequestAnimationFrame'];
  2622.       }
  2623.       if (!requestAnimationFrameFunc) {
  2624.         requestAnimationFrameFunc = featurefill;
  2625.       }
  2626.       requestAnimationFrameFunc(callback, element);
  2627.     };
  2628.     var wrappedSetTimeout = function (callback, time) {
  2629.       if (typeof time !== 'number') {
  2630.         time = 0;
  2631.       }
  2632.       return setTimeout(callback, time);
  2633.     };
  2634.     var wrappedSetInterval = function (callback, time) {
  2635.       if (typeof time !== 'number') {
  2636.         time = 1;
  2637.       }
  2638.       return setInterval(callback, time);
  2639.     };
  2640.     var wrappedClearTimeout = function (id) {
  2641.       return clearTimeout(id);
  2642.     };
  2643.     var wrappedClearInterval = function (id) {
  2644.       return clearInterval(id);
  2645.     };
  2646.     var debounce = function (callback, time) {
  2647.       var timer;
  2648.       var func = function () {
  2649.         var args = [];
  2650.         for (var _i = 0; _i < arguments.length; _i++) {
  2651.           args[_i] = arguments[_i];
  2652.         }
  2653.         clearTimeout(timer);
  2654.         timer = wrappedSetTimeout(function () {
  2655.           callback.apply(this, args);
  2656.         }, time);
  2657.       };
  2658.       func.stop = function () {
  2659.         clearTimeout(timer);
  2660.       };
  2661.       return func;
  2662.     };
  2663.     var Delay = {
  2664.       requestAnimationFrame: function (callback, element) {
  2665.         if (requestAnimationFramePromise) {
  2666.           requestAnimationFramePromise.then(callback);
  2667.           return;
  2668.         }
  2669.         requestAnimationFramePromise = new promiseObj(function (resolve) {
  2670.           if (!element) {
  2671.             element = document.body;
  2672.           }
  2673.           requestAnimationFrame(resolve, element);
  2674.         }).then(callback);
  2675.       },
  2676.       setTimeout: wrappedSetTimeout,
  2677.       setInterval: wrappedSetInterval,
  2678.       setEditorTimeout: function (editor, callback, time) {
  2679.         return wrappedSetTimeout(function () {
  2680.           if (!editor.removed) {
  2681.             callback();
  2682.           }
  2683.         }, time);
  2684.       },
  2685.       setEditorInterval: function (editor, callback, time) {
  2686.         var timer = wrappedSetInterval(function () {
  2687.           if (!editor.removed) {
  2688.             callback();
  2689.           } else {
  2690.             clearInterval(timer);
  2691.           }
  2692.         }, time);
  2693.         return timer;
  2694.       },
  2695.       debounce: debounce,
  2696.       throttle: debounce,
  2697.       clearInterval: wrappedClearInterval,
  2698.       clearTimeout: wrappedClearTimeout
  2699.     };
  2700.  
  2701.     var StyleSheetLoader = function (documentOrShadowRoot, settings) {
  2702.       if (settings === void 0) {
  2703.         settings = {};
  2704.       }
  2705.       var idCount = 0;
  2706.       var loadedStates = {};
  2707.       var edos = SugarElement.fromDom(documentOrShadowRoot);
  2708.       var doc = documentOrOwner(edos);
  2709.       var maxLoadTime = settings.maxLoadTime || 5000;
  2710.       var _setReferrerPolicy = function (referrerPolicy) {
  2711.         settings.referrerPolicy = referrerPolicy;
  2712.       };
  2713.       var addStyle = function (element) {
  2714.         append$1(getStyleContainer(edos), element);
  2715.       };
  2716.       var removeStyle = function (id) {
  2717.         var styleContainer = getStyleContainer(edos);
  2718.         descendant(styleContainer, '#' + id).each(remove$7);
  2719.       };
  2720.       var getOrCreateState = function (url) {
  2721.         return get$9(loadedStates, url).getOrThunk(function () {
  2722.           return {
  2723.             id: 'mce-u' + idCount++,
  2724.             passed: [],
  2725.             failed: [],
  2726.             count: 0
  2727.           };
  2728.         });
  2729.       };
  2730.       var load = function (url, success, failure) {
  2731.         var link;
  2732.         var urlWithSuffix = Tools._addCacheSuffix(url);
  2733.         var state = getOrCreateState(urlWithSuffix);
  2734.         loadedStates[urlWithSuffix] = state;
  2735.         state.count++;
  2736.         var resolve = function (callbacks, status) {
  2737.           var i = callbacks.length;
  2738.           while (i--) {
  2739.             callbacks[i]();
  2740.           }
  2741.           state.status = status;
  2742.           state.passed = [];
  2743.           state.failed = [];
  2744.           if (link) {
  2745.             link.onload = null;
  2746.             link.onerror = null;
  2747.             link = null;
  2748.           }
  2749.         };
  2750.         var passed = function () {
  2751.           return resolve(state.passed, 2);
  2752.         };
  2753.         var failed = function () {
  2754.           return resolve(state.failed, 3);
  2755.         };
  2756.         var wait = function (testCallback, waitCallback) {
  2757.           if (!testCallback()) {
  2758.             if (Date.now() - startTime < maxLoadTime) {
  2759.               Delay.setTimeout(waitCallback);
  2760.             } else {
  2761.               failed();
  2762.             }
  2763.           }
  2764.         };
  2765.         var waitForWebKitLinkLoaded = function () {
  2766.           wait(function () {
  2767.             var styleSheets = documentOrShadowRoot.styleSheets;
  2768.             var i = styleSheets.length;
  2769.             while (i--) {
  2770.               var styleSheet = styleSheets[i];
  2771.               var owner = styleSheet.ownerNode;
  2772.               if (owner && owner.id === link.id) {
  2773.                 passed();
  2774.                 return true;
  2775.               }
  2776.             }
  2777.             return false;
  2778.           }, waitForWebKitLinkLoaded);
  2779.         };
  2780.         if (success) {
  2781.           state.passed.push(success);
  2782.         }
  2783.         if (failure) {
  2784.           state.failed.push(failure);
  2785.         }
  2786.         if (state.status === 1) {
  2787.           return;
  2788.         }
  2789.         if (state.status === 2) {
  2790.           passed();
  2791.           return;
  2792.         }
  2793.         if (state.status === 3) {
  2794.           failed();
  2795.           return;
  2796.         }
  2797.         state.status = 1;
  2798.         var linkElem = SugarElement.fromTag('link', doc.dom);
  2799.         setAll$1(linkElem, {
  2800.           rel: 'stylesheet',
  2801.           type: 'text/css',
  2802.           id: state.id
  2803.         });
  2804.         var startTime = Date.now();
  2805.         if (settings.contentCssCors) {
  2806.           set$1(linkElem, 'crossOrigin', 'anonymous');
  2807.         }
  2808.         if (settings.referrerPolicy) {
  2809.           set$1(linkElem, 'referrerpolicy', settings.referrerPolicy);
  2810.         }
  2811.         link = linkElem.dom;
  2812.         link.onload = waitForWebKitLinkLoaded;
  2813.         link.onerror = failed;
  2814.         addStyle(linkElem);
  2815.         set$1(linkElem, 'href', urlWithSuffix);
  2816.       };
  2817.       var loadF = function (url) {
  2818.         return Future.nu(function (resolve) {
  2819.           load(url, compose(resolve, constant(Result.value(url))), compose(resolve, constant(Result.error(url))));
  2820.         });
  2821.       };
  2822.       var loadAll = function (urls, success, failure) {
  2823.         par(map$3(urls, loadF)).get(function (result) {
  2824.           var parts = partition(result, function (r) {
  2825.             return r.isValue();
  2826.           });
  2827.           if (parts.fail.length > 0) {
  2828.             failure(parts.fail.map(unite));
  2829.           } else {
  2830.             success(parts.pass.map(unite));
  2831.           }
  2832.         });
  2833.       };
  2834.       var unload = function (url) {
  2835.         var urlWithSuffix = Tools._addCacheSuffix(url);
  2836.         get$9(loadedStates, urlWithSuffix).each(function (state) {
  2837.           var count = --state.count;
  2838.           if (count === 0) {
  2839.             delete loadedStates[urlWithSuffix];
  2840.             removeStyle(state.id);
  2841.           }
  2842.         });
  2843.       };
  2844.       var unloadAll = function (urls) {
  2845.         each$k(urls, function (url) {
  2846.           unload(url);
  2847.         });
  2848.       };
  2849.       return {
  2850.         load: load,
  2851.         loadAll: loadAll,
  2852.         unload: unload,
  2853.         unloadAll: unloadAll,
  2854.         _setReferrerPolicy: _setReferrerPolicy
  2855.       };
  2856.     };
  2857.  
  2858.     var create$8 = function () {
  2859.       var map = new WeakMap();
  2860.       var forElement = function (referenceElement, settings) {
  2861.         var root = getRootNode(referenceElement);
  2862.         var rootDom = root.dom;
  2863.         return Optional.from(map.get(rootDom)).getOrThunk(function () {
  2864.           var sl = StyleSheetLoader(rootDom, settings);
  2865.           map.set(rootDom, sl);
  2866.           return sl;
  2867.         });
  2868.       };
  2869.       return { forElement: forElement };
  2870.     };
  2871.     var instance = create$8();
  2872.  
  2873.     var DomTreeWalker = function () {
  2874.       function DomTreeWalker(startNode, rootNode) {
  2875.         this.node = startNode;
  2876.         this.rootNode = rootNode;
  2877.         this.current = this.current.bind(this);
  2878.         this.next = this.next.bind(this);
  2879.         this.prev = this.prev.bind(this);
  2880.         this.prev2 = this.prev2.bind(this);
  2881.       }
  2882.       DomTreeWalker.prototype.current = function () {
  2883.         return this.node;
  2884.       };
  2885.       DomTreeWalker.prototype.next = function (shallow) {
  2886.         this.node = this.findSibling(this.node, 'firstChild', 'nextSibling', shallow);
  2887.         return this.node;
  2888.       };
  2889.       DomTreeWalker.prototype.prev = function (shallow) {
  2890.         this.node = this.findSibling(this.node, 'lastChild', 'previousSibling', shallow);
  2891.         return this.node;
  2892.       };
  2893.       DomTreeWalker.prototype.prev2 = function (shallow) {
  2894.         this.node = this.findPreviousNode(this.node, 'lastChild', 'previousSibling', shallow);
  2895.         return this.node;
  2896.       };
  2897.       DomTreeWalker.prototype.findSibling = function (node, startName, siblingName, shallow) {
  2898.         var sibling, parent;
  2899.         if (node) {
  2900.           if (!shallow && node[startName]) {
  2901.             return node[startName];
  2902.           }
  2903.           if (node !== this.rootNode) {
  2904.             sibling = node[siblingName];
  2905.             if (sibling) {
  2906.               return sibling;
  2907.             }
  2908.             for (parent = node.parentNode; parent && parent !== this.rootNode; parent = parent.parentNode) {
  2909.               sibling = parent[siblingName];
  2910.               if (sibling) {
  2911.                 return sibling;
  2912.               }
  2913.             }
  2914.           }
  2915.         }
  2916.       };
  2917.       DomTreeWalker.prototype.findPreviousNode = function (node, startName, siblingName, shallow) {
  2918.         var sibling, parent, child;
  2919.         if (node) {
  2920.           sibling = node[siblingName];
  2921.           if (this.rootNode && sibling === this.rootNode) {
  2922.             return;
  2923.           }
  2924.           if (sibling) {
  2925.             if (!shallow) {
  2926.               for (child = sibling[startName]; child; child = child[startName]) {
  2927.                 if (!child[startName]) {
  2928.                   return child;
  2929.                 }
  2930.               }
  2931.             }
  2932.             return sibling;
  2933.           }
  2934.           parent = node.parentNode;
  2935.           if (parent && parent !== this.rootNode) {
  2936.             return parent;
  2937.           }
  2938.         }
  2939.       };
  2940.       return DomTreeWalker;
  2941.     }();
  2942.  
  2943.     var blocks = [
  2944.       'article',
  2945.       'aside',
  2946.       'details',
  2947.       'div',
  2948.       'dt',
  2949.       'figcaption',
  2950.       'footer',
  2951.       'form',
  2952.       'fieldset',
  2953.       'header',
  2954.       'hgroup',
  2955.       'html',
  2956.       'main',
  2957.       'nav',
  2958.       'section',
  2959.       'summary',
  2960.       'body',
  2961.       'p',
  2962.       'dl',
  2963.       'multicol',
  2964.       'dd',
  2965.       'figure',
  2966.       'address',
  2967.       'center',
  2968.       'blockquote',
  2969.       'h1',
  2970.       'h2',
  2971.       'h3',
  2972.       'h4',
  2973.       'h5',
  2974.       'h6',
  2975.       'listing',
  2976.       'xmp',
  2977.       'pre',
  2978.       'plaintext',
  2979.       'menu',
  2980.       'dir',
  2981.       'ul',
  2982.       'ol',
  2983.       'li',
  2984.       'hr',
  2985.       'table',
  2986.       'tbody',
  2987.       'thead',
  2988.       'tfoot',
  2989.       'th',
  2990.       'tr',
  2991.       'td',
  2992.       'caption'
  2993.     ];
  2994.     var tableCells = [
  2995.       'td',
  2996.       'th'
  2997.     ];
  2998.     var tableSections = [
  2999.       'thead',
  3000.       'tbody',
  3001.       'tfoot'
  3002.     ];
  3003.     var textBlocks = [
  3004.       'h1',
  3005.       'h2',
  3006.       'h3',
  3007.       'h4',
  3008.       'h5',
  3009.       'h6',
  3010.       'p',
  3011.       'div',
  3012.       'address',
  3013.       'pre',
  3014.       'form',
  3015.       'blockquote',
  3016.       'center',
  3017.       'dir',
  3018.       'fieldset',
  3019.       'header',
  3020.       'footer',
  3021.       'article',
  3022.       'section',
  3023.       'hgroup',
  3024.       'aside',
  3025.       'nav',
  3026.       'figure'
  3027.     ];
  3028.     var headings = [
  3029.       'h1',
  3030.       'h2',
  3031.       'h3',
  3032.       'h4',
  3033.       'h5',
  3034.       'h6'
  3035.     ];
  3036.     var listItems$1 = [
  3037.       'li',
  3038.       'dd',
  3039.       'dt'
  3040.     ];
  3041.     var lists = [
  3042.       'ul',
  3043.       'ol',
  3044.       'dl'
  3045.     ];
  3046.     var wsElements = [
  3047.       'pre',
  3048.       'script',
  3049.       'textarea',
  3050.       'style'
  3051.     ];
  3052.     var lazyLookup = function (items) {
  3053.       var lookup;
  3054.       return function (node) {
  3055.         lookup = lookup ? lookup : mapToObject(items, always);
  3056.         return has$2(lookup, name(node));
  3057.       };
  3058.     };
  3059.     var isHeading = lazyLookup(headings);
  3060.     var isBlock$2 = lazyLookup(blocks);
  3061.     var isTable$2 = function (node) {
  3062.       return name(node) === 'table';
  3063.     };
  3064.     var isInline$1 = function (node) {
  3065.       return isElement$6(node) && !isBlock$2(node);
  3066.     };
  3067.     var isBr$4 = function (node) {
  3068.       return isElement$6(node) && name(node) === 'br';
  3069.     };
  3070.     var isTextBlock$2 = lazyLookup(textBlocks);
  3071.     var isList = lazyLookup(lists);
  3072.     var isListItem = lazyLookup(listItems$1);
  3073.     var isTableSection = lazyLookup(tableSections);
  3074.     var isTableCell$4 = lazyLookup(tableCells);
  3075.     var isWsPreserveElement = lazyLookup(wsElements);
  3076.  
  3077.     var ancestor$1 = function (scope, selector, isRoot) {
  3078.       return ancestor$2(scope, selector, isRoot).isSome();
  3079.     };
  3080.  
  3081.     var zeroWidth = '\uFEFF';
  3082.     var nbsp = '\xA0';
  3083.     var isZwsp$1 = function (char) {
  3084.       return char === zeroWidth;
  3085.     };
  3086.     var removeZwsp = function (s) {
  3087.       return s.replace(/\uFEFF/g, '');
  3088.     };
  3089.  
  3090.     var ZWSP$1 = zeroWidth;
  3091.     var isZwsp = isZwsp$1;
  3092.     var trim$2 = removeZwsp;
  3093.  
  3094.     var isElement$4 = isElement$5;
  3095.     var isText$6 = isText$7;
  3096.     var isCaretContainerBlock$1 = function (node) {
  3097.       if (isText$6(node)) {
  3098.         node = node.parentNode;
  3099.       }
  3100.       return isElement$4(node) && node.hasAttribute('data-mce-caret');
  3101.     };
  3102.     var isCaretContainerInline = function (node) {
  3103.       return isText$6(node) && isZwsp(node.data);
  3104.     };
  3105.     var isCaretContainer$2 = function (node) {
  3106.       return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
  3107.     };
  3108.     var hasContent = function (node) {
  3109.       return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
  3110.     };
  3111.     var insertInline$1 = function (node, before) {
  3112.       var doc = node.ownerDocument;
  3113.       var textNode = doc.createTextNode(ZWSP$1);
  3114.       var parentNode = node.parentNode;
  3115.       if (!before) {
  3116.         var sibling = node.nextSibling;
  3117.         if (isText$6(sibling)) {
  3118.           if (isCaretContainer$2(sibling)) {
  3119.             return sibling;
  3120.           }
  3121.           if (startsWithCaretContainer$1(sibling)) {
  3122.             sibling.splitText(1);
  3123.             return sibling;
  3124.           }
  3125.         }
  3126.         if (node.nextSibling) {
  3127.           parentNode.insertBefore(textNode, node.nextSibling);
  3128.         } else {
  3129.           parentNode.appendChild(textNode);
  3130.         }
  3131.       } else {
  3132.         var sibling = node.previousSibling;
  3133.         if (isText$6(sibling)) {
  3134.           if (isCaretContainer$2(sibling)) {
  3135.             return sibling;
  3136.           }
  3137.           if (endsWithCaretContainer$1(sibling)) {
  3138.             return sibling.splitText(sibling.data.length - 1);
  3139.           }
  3140.         }
  3141.         parentNode.insertBefore(textNode, node);
  3142.       }
  3143.       return textNode;
  3144.     };
  3145.     var isBeforeInline = function (pos) {
  3146.       var container = pos.container();
  3147.       if (!isText$7(container)) {
  3148.         return false;
  3149.       }
  3150.       return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
  3151.     };
  3152.     var isAfterInline = function (pos) {
  3153.       var container = pos.container();
  3154.       if (!isText$7(container)) {
  3155.         return false;
  3156.       }
  3157.       return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
  3158.     };
  3159.     var createBogusBr = function () {
  3160.       var br = document.createElement('br');
  3161.       br.setAttribute('data-mce-bogus', '1');
  3162.       return br;
  3163.     };
  3164.     var insertBlock$1 = function (blockName, node, before) {
  3165.       var doc = node.ownerDocument;
  3166.       var blockNode = doc.createElement(blockName);
  3167.       blockNode.setAttribute('data-mce-caret', before ? 'before' : 'after');
  3168.       blockNode.setAttribute('data-mce-bogus', 'all');
  3169.       blockNode.appendChild(createBogusBr());
  3170.       var parentNode = node.parentNode;
  3171.       if (!before) {
  3172.         if (node.nextSibling) {
  3173.           parentNode.insertBefore(blockNode, node.nextSibling);
  3174.         } else {
  3175.           parentNode.appendChild(blockNode);
  3176.         }
  3177.       } else {
  3178.         parentNode.insertBefore(blockNode, node);
  3179.       }
  3180.       return blockNode;
  3181.     };
  3182.     var startsWithCaretContainer$1 = function (node) {
  3183.       return isText$6(node) && node.data[0] === ZWSP$1;
  3184.     };
  3185.     var endsWithCaretContainer$1 = function (node) {
  3186.       return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
  3187.     };
  3188.     var trimBogusBr = function (elm) {
  3189.       var brs = elm.getElementsByTagName('br');
  3190.       var lastBr = brs[brs.length - 1];
  3191.       if (isBogus$2(lastBr)) {
  3192.         lastBr.parentNode.removeChild(lastBr);
  3193.       }
  3194.     };
  3195.     var showCaretContainerBlock = function (caretContainer) {
  3196.       if (caretContainer && caretContainer.hasAttribute('data-mce-caret')) {
  3197.         trimBogusBr(caretContainer);
  3198.         caretContainer.removeAttribute('data-mce-caret');
  3199.         caretContainer.removeAttribute('data-mce-bogus');
  3200.         caretContainer.removeAttribute('style');
  3201.         caretContainer.removeAttribute('_moz_abspos');
  3202.         return caretContainer;
  3203.       }
  3204.       return null;
  3205.     };
  3206.     var isRangeInCaretContainerBlock = function (range) {
  3207.       return isCaretContainerBlock$1(range.startContainer);
  3208.     };
  3209.  
  3210.     var isContentEditableTrue$3 = isContentEditableTrue$4;
  3211.     var isContentEditableFalse$a = isContentEditableFalse$b;
  3212.     var isBr$3 = isBr$5;
  3213.     var isText$5 = isText$7;
  3214.     var isInvalidTextElement = matchNodeNames([
  3215.       'script',
  3216.       'style',
  3217.       'textarea'
  3218.     ]);
  3219.     var isAtomicInline = matchNodeNames([
  3220.       'img',
  3221.       'input',
  3222.       'textarea',
  3223.       'hr',
  3224.       'iframe',
  3225.       'video',
  3226.       'audio',
  3227.       'object',
  3228.       'embed'
  3229.     ]);
  3230.     var isTable$1 = matchNodeNames(['table']);
  3231.     var isCaretContainer$1 = isCaretContainer$2;
  3232.     var isCaretCandidate$3 = function (node) {
  3233.       if (isCaretContainer$1(node)) {
  3234.         return false;
  3235.       }
  3236.       if (isText$5(node)) {
  3237.         return !isInvalidTextElement(node.parentNode);
  3238.       }
  3239.       return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
  3240.     };
  3241.     var isUnselectable = function (node) {
  3242.       return isElement$5(node) && node.getAttribute('unselectable') === 'true';
  3243.     };
  3244.     var isNonUiContentEditableFalse = function (node) {
  3245.       return isUnselectable(node) === false && isContentEditableFalse$a(node);
  3246.     };
  3247.     var isInEditable = function (node, root) {
  3248.       for (node = node.parentNode; node && node !== root; node = node.parentNode) {
  3249.         if (isNonUiContentEditableFalse(node)) {
  3250.           return false;
  3251.         }
  3252.         if (isContentEditableTrue$3(node)) {
  3253.           return true;
  3254.         }
  3255.       }
  3256.       return true;
  3257.     };
  3258.     var isAtomicContentEditableFalse = function (node) {
  3259.       if (!isNonUiContentEditableFalse(node)) {
  3260.         return false;
  3261.       }
  3262.       return foldl(from(node.getElementsByTagName('*')), function (result, elm) {
  3263.         return result || isContentEditableTrue$3(elm);
  3264.       }, false) !== true;
  3265.     };
  3266.     var isAtomic$1 = function (node) {
  3267.       return isAtomicInline(node) || isAtomicContentEditableFalse(node);
  3268.     };
  3269.     var isEditableCaretCandidate$1 = function (node, root) {
  3270.       return isCaretCandidate$3(node) && isInEditable(node, root);
  3271.     };
  3272.  
  3273.     var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
  3274.     var isWhitespaceText = function (text) {
  3275.       return whiteSpaceRegExp$1.test(text);
  3276.     };
  3277.  
  3278.     var hasWhitespacePreserveParent = function (node, rootNode) {
  3279.       var rootElement = SugarElement.fromDom(rootNode);
  3280.       var startNode = SugarElement.fromDom(node);
  3281.       return ancestor$1(startNode, 'pre,code', curry(eq, rootElement));
  3282.     };
  3283.     var isWhitespace = function (node, rootNode) {
  3284.       return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
  3285.     };
  3286.     var isNamedAnchor = function (node) {
  3287.       return isElement$5(node) && node.nodeName === 'A' && !node.hasAttribute('href') && (node.hasAttribute('name') || node.hasAttribute('id'));
  3288.     };
  3289.     var isContent$1 = function (node, rootNode) {
  3290.       return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
  3291.     };
  3292.     var isBookmark = hasAttribute('data-mce-bookmark');
  3293.     var isBogus$1 = hasAttribute('data-mce-bogus');
  3294.     var isBogusAll = hasAttributeValue('data-mce-bogus', 'all');
  3295.     var isEmptyNode = function (targetNode, skipBogus) {
  3296.       var brCount = 0;
  3297.       if (isContent$1(targetNode, targetNode)) {
  3298.         return false;
  3299.       } else {
  3300.         var node = targetNode.firstChild;
  3301.         if (!node) {
  3302.           return true;
  3303.         }
  3304.         var walker = new DomTreeWalker(node, targetNode);
  3305.         do {
  3306.           if (skipBogus) {
  3307.             if (isBogusAll(node)) {
  3308.               node = walker.next(true);
  3309.               continue;
  3310.             }
  3311.             if (isBogus$1(node)) {
  3312.               node = walker.next();
  3313.               continue;
  3314.             }
  3315.           }
  3316.           if (isBr$5(node)) {
  3317.             brCount++;
  3318.             node = walker.next();
  3319.             continue;
  3320.           }
  3321.           if (isContent$1(node, targetNode)) {
  3322.             return false;
  3323.           }
  3324.           node = walker.next();
  3325.         } while (node);
  3326.         return brCount <= 1;
  3327.       }
  3328.     };
  3329.     var isEmpty$2 = function (elm, skipBogus) {
  3330.       if (skipBogus === void 0) {
  3331.         skipBogus = true;
  3332.       }
  3333.       return isEmptyNode(elm.dom, skipBogus);
  3334.     };
  3335.  
  3336.     var isSpan = function (node) {
  3337.       return node.nodeName.toLowerCase() === 'span';
  3338.     };
  3339.     var isInlineContent = function (node, root) {
  3340.       return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
  3341.     };
  3342.     var surroundedByInlineContent = function (node, root) {
  3343.       var prev = new DomTreeWalker(node, root).prev(false);
  3344.       var next = new DomTreeWalker(node, root).next(false);
  3345.       var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
  3346.       var nextIsInline = isUndefined(next) || isInlineContent(next, root);
  3347.       return prevIsInline && nextIsInline;
  3348.     };
  3349.     var isBookmarkNode$2 = function (node) {
  3350.       return isSpan(node) && node.getAttribute('data-mce-type') === 'bookmark';
  3351.     };
  3352.     var isKeepTextNode = function (node, root) {
  3353.       return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
  3354.     };
  3355.     var isKeepElement = function (node) {
  3356.       return isElement$5(node) ? node.childNodes.length > 0 : false;
  3357.     };
  3358.     var isDocument = function (node) {
  3359.       return isDocumentFragment(node) || isDocument$1(node);
  3360.     };
  3361.     var trimNode = function (dom, node, root) {
  3362.       var rootNode = root || node;
  3363.       if (isElement$5(node) && isBookmarkNode$2(node)) {
  3364.         return node;
  3365.       }
  3366.       var children = node.childNodes;
  3367.       for (var i = children.length - 1; i >= 0; i--) {
  3368.         trimNode(dom, children[i], rootNode);
  3369.       }
  3370.       if (isElement$5(node)) {
  3371.         var currentChildren = node.childNodes;
  3372.         if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
  3373.           node.parentNode.insertBefore(currentChildren[0], node);
  3374.         }
  3375.       }
  3376.       if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
  3377.         dom.remove(node);
  3378.       }
  3379.       return node;
  3380.     };
  3381.  
  3382.     var makeMap$3 = Tools.makeMap;
  3383.     var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3384.     var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  3385.     var rawCharsRegExp = /[<>&\"\']/g;
  3386.     var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
  3387.     var asciiMap = {
  3388.       128: '\u20AC',
  3389.       130: '\u201A',
  3390.       131: '\u0192',
  3391.       132: '\u201E',
  3392.       133: '\u2026',
  3393.       134: '\u2020',
  3394.       135: '\u2021',
  3395.       136: '\u02c6',
  3396.       137: '\u2030',
  3397.       138: '\u0160',
  3398.       139: '\u2039',
  3399.       140: '\u0152',
  3400.       142: '\u017d',
  3401.       145: '\u2018',
  3402.       146: '\u2019',
  3403.       147: '\u201C',
  3404.       148: '\u201D',
  3405.       149: '\u2022',
  3406.       150: '\u2013',
  3407.       151: '\u2014',
  3408.       152: '\u02DC',
  3409.       153: '\u2122',
  3410.       154: '\u0161',
  3411.       155: '\u203A',
  3412.       156: '\u0153',
  3413.       158: '\u017e',
  3414.       159: '\u0178'
  3415.     };
  3416.     var baseEntities = {
  3417.       '"': '&quot;',
  3418.       '\'': '&#39;',
  3419.       '<': '&lt;',
  3420.       '>': '&gt;',
  3421.       '&': '&amp;',
  3422.       '`': '&#96;'
  3423.     };
  3424.     var reverseEntities = {
  3425.       '&lt;': '<',
  3426.       '&gt;': '>',
  3427.       '&amp;': '&',
  3428.       '&quot;': '"',
  3429.       '&apos;': '\''
  3430.     };
  3431.     var nativeDecode = function (text) {
  3432.       var elm = SugarElement.fromTag('div').dom;
  3433.       elm.innerHTML = text;
  3434.       return elm.textContent || elm.innerText || text;
  3435.     };
  3436.     var buildEntitiesLookup = function (items, radix) {
  3437.       var i, chr, entity;
  3438.       var lookup = {};
  3439.       if (items) {
  3440.         items = items.split(',');
  3441.         radix = radix || 10;
  3442.         for (i = 0; i < items.length; i += 2) {
  3443.           chr = String.fromCharCode(parseInt(items[i], radix));
  3444.           if (!baseEntities[chr]) {
  3445.             entity = '&' + items[i + 1] + ';';
  3446.             lookup[chr] = entity;
  3447.             lookup[entity] = chr;
  3448.           }
  3449.         }
  3450.         return lookup;
  3451.       }
  3452.     };
  3453.     var namedEntities = buildEntitiesLookup('50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
  3454.     var encodeRaw = function (text, attr) {
  3455.       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3456.         return baseEntities[chr] || chr;
  3457.       });
  3458.     };
  3459.     var encodeAllRaw = function (text) {
  3460.       return ('' + text).replace(rawCharsRegExp, function (chr) {
  3461.         return baseEntities[chr] || chr;
  3462.       });
  3463.     };
  3464.     var encodeNumeric = function (text, attr) {
  3465.       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3466.         if (chr.length > 1) {
  3467.           return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3468.         }
  3469.         return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  3470.       });
  3471.     };
  3472.     var encodeNamed = function (text, attr, entities) {
  3473.       entities = entities || namedEntities;
  3474.       return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3475.         return baseEntities[chr] || entities[chr] || chr;
  3476.       });
  3477.     };
  3478.     var getEncodeFunc = function (name, entities) {
  3479.       var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
  3480.       var encodeNamedAndNumeric = function (text, attr) {
  3481.         return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) {
  3482.           if (baseEntities[chr] !== undefined) {
  3483.             return baseEntities[chr];
  3484.           }
  3485.           if (entitiesMap[chr] !== undefined) {
  3486.             return entitiesMap[chr];
  3487.           }
  3488.           if (chr.length > 1) {
  3489.             return '&#' + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ';';
  3490.           }
  3491.           return '&#' + chr.charCodeAt(0) + ';';
  3492.         });
  3493.       };
  3494.       var encodeCustomNamed = function (text, attr) {
  3495.         return encodeNamed(text, attr, entitiesMap);
  3496.       };
  3497.       var nameMap = makeMap$3(name.replace(/\+/g, ','));
  3498.       if (nameMap.named && nameMap.numeric) {
  3499.         return encodeNamedAndNumeric;
  3500.       }
  3501.       if (nameMap.named) {
  3502.         if (entities) {
  3503.           return encodeCustomNamed;
  3504.         }
  3505.         return encodeNamed;
  3506.       }
  3507.       if (nameMap.numeric) {
  3508.         return encodeNumeric;
  3509.       }
  3510.       return encodeRaw;
  3511.     };
  3512.     var decode = function (text) {
  3513.       return text.replace(entityRegExp, function (all, numeric) {
  3514.         if (numeric) {
  3515.           if (numeric.charAt(0).toLowerCase() === 'x') {
  3516.             numeric = parseInt(numeric.substr(1), 16);
  3517.           } else {
  3518.             numeric = parseInt(numeric, 10);
  3519.           }
  3520.           if (numeric > 65535) {
  3521.             numeric -= 65536;
  3522.             return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
  3523.           }
  3524.           return asciiMap[numeric] || String.fromCharCode(numeric);
  3525.         }
  3526.         return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  3527.       });
  3528.     };
  3529.     var Entities = {
  3530.       encodeRaw: encodeRaw,
  3531.       encodeAllRaw: encodeAllRaw,
  3532.       encodeNumeric: encodeNumeric,
  3533.       encodeNamed: encodeNamed,
  3534.       getEncodeFunc: getEncodeFunc,
  3535.       decode: decode
  3536.     };
  3537.  
  3538.     var mapCache = {}, dummyObj = {};
  3539.     var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
  3540.     var split$1 = function (items, delim) {
  3541.       items = Tools.trim(items);
  3542.       return items ? items.split(delim || ' ') : [];
  3543.     };
  3544.     var compileSchema = function (type) {
  3545.       var schema = {};
  3546.       var globalAttributes, blockContent;
  3547.       var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3548.       var add = function (name, attributes, children) {
  3549.         var ni, attributesOrder, element;
  3550.         var arrayToMap = function (array, obj) {
  3551.           var map = {};
  3552.           var i, l;
  3553.           for (i = 0, l = array.length; i < l; i++) {
  3554.             map[array[i]] = obj || {};
  3555.           }
  3556.           return map;
  3557.         };
  3558.         children = children || [];
  3559.         attributes = attributes || '';
  3560.         if (typeof children === 'string') {
  3561.           children = split$1(children);
  3562.         }
  3563.         var names = split$1(name);
  3564.         ni = names.length;
  3565.         while (ni--) {
  3566.           attributesOrder = split$1([
  3567.             globalAttributes,
  3568.             attributes
  3569.           ].join(' '));
  3570.           element = {
  3571.             attributes: arrayToMap(attributesOrder),
  3572.             attributesOrder: attributesOrder,
  3573.             children: arrayToMap(children, dummyObj)
  3574.           };
  3575.           schema[names[ni]] = element;
  3576.         }
  3577.       };
  3578.       var addAttrs = function (name, attributes) {
  3579.         var ni, schemaItem, i, l;
  3580.         var names = split$1(name);
  3581.         ni = names.length;
  3582.         var attrs = split$1(attributes);
  3583.         while (ni--) {
  3584.           schemaItem = schema[names[ni]];
  3585.           for (i = 0, l = attrs.length; i < l; i++) {
  3586.             schemaItem.attributes[attrs[i]] = {};
  3587.             schemaItem.attributesOrder.push(attrs[i]);
  3588.           }
  3589.         }
  3590.       };
  3591.       if (mapCache[type]) {
  3592.         return mapCache[type];
  3593.       }
  3594.       globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3595.       blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3596.       phrasingContent = 'a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd ' + 'label map noscript object q s samp script select small span strong sub sup ' + 'textarea u var #text #comment';
  3597.       if (type !== 'html4') {
  3598.         globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3599.         blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3600.         phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3601.       }
  3602.       if (type !== 'html5-strict') {
  3603.         globalAttributes += ' xml:lang';
  3604.         html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3605.         phrasingContent = [
  3606.           phrasingContent,
  3607.           html4PhrasingContent
  3608.         ].join(' ');
  3609.         each$h(split$1(html4PhrasingContent), function (name) {
  3610.           add(name, '', phrasingContent);
  3611.         });
  3612.         html4BlockContent = 'center dir isindex noframes';
  3613.         blockContent = [
  3614.           blockContent,
  3615.           html4BlockContent
  3616.         ].join(' ');
  3617.         flowContent = [
  3618.           blockContent,
  3619.           phrasingContent
  3620.         ].join(' ');
  3621.         each$h(split$1(html4BlockContent), function (name) {
  3622.           add(name, '', flowContent);
  3623.         });
  3624.       }
  3625.       flowContent = flowContent || [
  3626.         blockContent,
  3627.         phrasingContent
  3628.       ].join(' ');
  3629.       add('html', 'manifest', 'head body');
  3630.       add('head', '', 'base command link meta noscript script style title');
  3631.       add('title hr noscript br');
  3632.       add('base', 'href target');
  3633.       add('link', 'href rel media hreflang type sizes hreflang');
  3634.       add('meta', 'name http-equiv content charset');
  3635.       add('style', 'media type scoped');
  3636.       add('script', 'src async defer type charset');
  3637.       add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3638.       add('address dt dd div caption', '', flowContent);
  3639.       add('h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent);
  3640.       add('blockquote', 'cite', flowContent);
  3641.       add('ol', 'reversed start type', 'li');
  3642.       add('ul', '', 'li');
  3643.       add('li', 'value', flowContent);
  3644.       add('dl', '', 'dt dd');
  3645.       add('a', 'href target rel media hreflang type', phrasingContent);
  3646.       add('q', 'cite', phrasingContent);
  3647.       add('ins del', 'cite datetime', flowContent);
  3648.       add('img', 'src sizes srcset alt usemap ismap width height');
  3649.       add('iframe', 'src name width height', flowContent);
  3650.       add('embed', 'src type width height');
  3651.       add('object', 'data type typemustmatch name usemap form width height', [
  3652.         flowContent,
  3653.         'param'
  3654.       ].join(' '));
  3655.       add('param', 'name value');
  3656.       add('map', 'name', [
  3657.         flowContent,
  3658.         'area'
  3659.       ].join(' '));
  3660.       add('area', 'alt coords shape href target rel media hreflang type');
  3661.       add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3662.       add('colgroup', 'span', 'col');
  3663.       add('col', 'span');
  3664.       add('tbody thead tfoot', '', 'tr');
  3665.       add('tr', '', 'td th');
  3666.       add('td', 'colspan rowspan headers', flowContent);
  3667.       add('th', 'colspan rowspan headers scope abbr', flowContent);
  3668.       add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3669.       add('fieldset', 'disabled form name', [
  3670.         flowContent,
  3671.         'legend'
  3672.       ].join(' '));
  3673.       add('label', 'form for', phrasingContent);
  3674.       add('input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' + 'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width');
  3675.       add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3676.       add('select', 'disabled form multiple name required size', 'option optgroup');
  3677.       add('optgroup', 'disabled label', 'option');
  3678.       add('option', 'disabled label selected value');
  3679.       add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3680.       add('menu', 'type label', [
  3681.         flowContent,
  3682.         'li'
  3683.       ].join(' '));
  3684.       add('noscript', '', flowContent);
  3685.       if (type !== 'html4') {
  3686.         add('wbr');
  3687.         add('ruby', '', [
  3688.           phrasingContent,
  3689.           'rt rp'
  3690.         ].join(' '));
  3691.         add('figcaption', '', flowContent);
  3692.         add('mark rt rp summary bdi', '', phrasingContent);
  3693.         add('canvas', 'width height', flowContent);
  3694.         add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3695.           flowContent,
  3696.           'track source'
  3697.         ].join(' '));
  3698.         add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3699.           flowContent,
  3700.           'track source'
  3701.         ].join(' '));
  3702.         add('picture', '', 'img source');
  3703.         add('source', 'src srcset type media sizes');
  3704.         add('track', 'kind src srclang label default');
  3705.         add('datalist', '', [
  3706.           phrasingContent,
  3707.           'option'
  3708.         ].join(' '));
  3709.         add('article section nav aside main header footer', '', flowContent);
  3710.         add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3711.         add('figure', '', [
  3712.           flowContent,
  3713.           'figcaption'
  3714.         ].join(' '));
  3715.         add('time', 'datetime', phrasingContent);
  3716.         add('dialog', 'open', flowContent);
  3717.         add('command', 'type label icon disabled checked radiogroup command');
  3718.         add('output', 'for form name', phrasingContent);
  3719.         add('progress', 'value max', phrasingContent);
  3720.         add('meter', 'value min max low high optimum', phrasingContent);
  3721.         add('details', 'open', [
  3722.           flowContent,
  3723.           'summary'
  3724.         ].join(' '));
  3725.         add('keygen', 'autofocus challenge disabled form keytype name');
  3726.       }
  3727.       if (type !== 'html5-strict') {
  3728.         addAttrs('script', 'language xml:space');
  3729.         addAttrs('style', 'xml:space');
  3730.         addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  3731.         addAttrs('embed', 'align name hspace vspace');
  3732.         addAttrs('param', 'valuetype type');
  3733.         addAttrs('a', 'charset name rev shape coords');
  3734.         addAttrs('br', 'clear');
  3735.         addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  3736.         addAttrs('img', 'name longdesc align border hspace vspace');
  3737.         addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  3738.         addAttrs('font basefont', 'size color face');
  3739.         addAttrs('input', 'usemap align');
  3740.         addAttrs('select');
  3741.         addAttrs('textarea');
  3742.         addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  3743.         addAttrs('ul', 'type compact');
  3744.         addAttrs('li', 'type');
  3745.         addAttrs('ol dl menu dir', 'compact');
  3746.         addAttrs('pre', 'width xml:space');
  3747.         addAttrs('hr', 'align noshade size width');
  3748.         addAttrs('isindex', 'prompt');
  3749.         addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3750.         addAttrs('col', 'width align char charoff valign');
  3751.         addAttrs('colgroup', 'width align char charoff valign');
  3752.         addAttrs('thead', 'align char charoff valign');
  3753.         addAttrs('tr', 'align char charoff valign bgcolor');
  3754.         addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3755.         addAttrs('form', 'accept');
  3756.         addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3757.         addAttrs('tfoot', 'align char charoff valign');
  3758.         addAttrs('tbody', 'align char charoff valign');
  3759.         addAttrs('area', 'nohref');
  3760.         addAttrs('body', 'background bgcolor text link vlink alink');
  3761.       }
  3762.       if (type !== 'html4') {
  3763.         addAttrs('input button select textarea', 'autofocus');
  3764.         addAttrs('input textarea', 'placeholder');
  3765.         addAttrs('a', 'download');
  3766.         addAttrs('link script img', 'crossorigin');
  3767.         addAttrs('img', 'loading');
  3768.         addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  3769.       }
  3770.       each$h(split$1('a form meter progress dfn'), function (name) {
  3771.         if (schema[name]) {
  3772.           delete schema[name].children[name];
  3773.         }
  3774.       });
  3775.       delete schema.caption.children.table;
  3776.       delete schema.script;
  3777.       mapCache[type] = schema;
  3778.       return schema;
  3779.     };
  3780.     var compileElementMap = function (value, mode) {
  3781.       var styles;
  3782.       if (value) {
  3783.         styles = {};
  3784.         if (typeof value === 'string') {
  3785.           value = { '*': value };
  3786.         }
  3787.         each$h(value, function (value, key) {
  3788.           styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  3789.         });
  3790.       }
  3791.       return styles;
  3792.     };
  3793.     var Schema = function (settings) {
  3794.       var elements = {};
  3795.       var children = {};
  3796.       var patternElements = [];
  3797.       var customElementsMap = {}, specialElements = {};
  3798.       var createLookupTable = function (option, defaultValue, extendWith) {
  3799.         var value = settings[option];
  3800.         if (!value) {
  3801.           value = mapCache[option];
  3802.           if (!value) {
  3803.             value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  3804.             value = extend$5(value, extendWith);
  3805.             mapCache[option] = value;
  3806.           }
  3807.         } else {
  3808.           value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3809.         }
  3810.         return value;
  3811.       };
  3812.       settings = settings || {};
  3813.       var schemaItems = compileSchema(settings.schema);
  3814.       if (settings.verify_html === false) {
  3815.         settings.valid_elements = '*[*]';
  3816.       }
  3817.       var validStyles = compileElementMap(settings.valid_styles);
  3818.       var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3819.       var validClasses = compileElementMap(settings.valid_classes, 'map');
  3820.       var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3821.       var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3822.       var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3823.       var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  3824.       var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3825.       var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  3826.       var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  3827.       var textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside main nav figure');
  3828.       var blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' + 'datalist select optgroup figcaption details summary', textBlockElementsMap);
  3829.       var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font strike u var cite ' + 'dfn code mark q sup sub samp');
  3830.       each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  3831.         specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3832.       });
  3833.       var patternToRegExp = function (str) {
  3834.         return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3835.       };
  3836.       var addValidElements = function (validElements) {
  3837.         var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  3838.         var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  3839.         if (validElements) {
  3840.           var validElementsArr = split$1(validElements, ',');
  3841.           if (elements['@']) {
  3842.             globalAttributes = elements['@'].attributes;
  3843.             globalAttributesOrder = elements['@'].attributesOrder;
  3844.           }
  3845.           for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3846.             matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3847.             if (matches) {
  3848.               prefix = matches[1];
  3849.               elementName = matches[2];
  3850.               outputName = matches[3];
  3851.               attrData = matches[5];
  3852.               attributes = {};
  3853.               attributesOrder = [];
  3854.               element = {
  3855.                 attributes: attributes,
  3856.                 attributesOrder: attributesOrder
  3857.               };
  3858.               if (prefix === '#') {
  3859.                 element.paddEmpty = true;
  3860.               }
  3861.               if (prefix === '-') {
  3862.                 element.removeEmpty = true;
  3863.               }
  3864.               if (matches[4] === '!') {
  3865.                 element.removeEmptyAttrs = true;
  3866.               }
  3867.               if (globalAttributes) {
  3868.                 each$j(globalAttributes, function (value, key) {
  3869.                   attributes[key] = value;
  3870.                 });
  3871.                 attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  3872.               }
  3873.               if (attrData) {
  3874.                 attrData = split$1(attrData, '|');
  3875.                 for (ai = 0, al = attrData.length; ai < al; ai++) {
  3876.                   matches = attrRuleRegExp.exec(attrData[ai]);
  3877.                   if (matches) {
  3878.                     attr = {};
  3879.                     attrType = matches[1];
  3880.                     attrName = matches[2].replace(/[\\:]:/g, ':');
  3881.                     prefix = matches[3];
  3882.                     value = matches[4];
  3883.                     if (attrType === '!') {
  3884.                       element.attributesRequired = element.attributesRequired || [];
  3885.                       element.attributesRequired.push(attrName);
  3886.                       attr.required = true;
  3887.                     }
  3888.                     if (attrType === '-') {
  3889.                       delete attributes[attrName];
  3890.                       attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  3891.                       continue;
  3892.                     }
  3893.                     if (prefix) {
  3894.                       if (prefix === '=') {
  3895.                         element.attributesDefault = element.attributesDefault || [];
  3896.                         element.attributesDefault.push({
  3897.                           name: attrName,
  3898.                           value: value
  3899.                         });
  3900.                         attr.defaultValue = value;
  3901.                       }
  3902.                       if (prefix === ':') {
  3903.                         element.attributesForced = element.attributesForced || [];
  3904.                         element.attributesForced.push({
  3905.                           name: attrName,
  3906.                           value: value
  3907.                         });
  3908.                         attr.forcedValue = value;
  3909.                       }
  3910.                       if (prefix === '<') {
  3911.                         attr.validValues = makeMap$2(value, '?');
  3912.                       }
  3913.                     }
  3914.                     if (hasPatternsRegExp.test(attrName)) {
  3915.                       element.attributePatterns = element.attributePatterns || [];
  3916.                       attr.pattern = patternToRegExp(attrName);
  3917.                       element.attributePatterns.push(attr);
  3918.                     } else {
  3919.                       if (!attributes[attrName]) {
  3920.                         attributesOrder.push(attrName);
  3921.                       }
  3922.                       attributes[attrName] = attr;
  3923.                     }
  3924.                   }
  3925.                 }
  3926.               }
  3927.               if (!globalAttributes && elementName === '@') {
  3928.                 globalAttributes = attributes;
  3929.                 globalAttributesOrder = attributesOrder;
  3930.               }
  3931.               if (outputName) {
  3932.                 element.outputName = elementName;
  3933.                 elements[outputName] = element;
  3934.               }
  3935.               if (hasPatternsRegExp.test(elementName)) {
  3936.                 element.pattern = patternToRegExp(elementName);
  3937.                 patternElements.push(element);
  3938.               } else {
  3939.                 elements[elementName] = element;
  3940.               }
  3941.             }
  3942.           }
  3943.         }
  3944.       };
  3945.       var setValidElements = function (validElements) {
  3946.         elements = {};
  3947.         patternElements = [];
  3948.         addValidElements(validElements);
  3949.         each$h(schemaItems, function (element, name) {
  3950.           children[name] = element.children;
  3951.         });
  3952.       };
  3953.       var addCustomElements = function (customElements) {
  3954.         var customElementRegExp = /^(~)?(.+)$/;
  3955.         if (customElements) {
  3956.           mapCache.text_block_elements = mapCache.block_elements = null;
  3957.           each$h(split$1(customElements, ','), function (rule) {
  3958.             var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3959.             children[name] = children[cloneName];
  3960.             customElementsMap[name] = cloneName;
  3961.             if (!inline) {
  3962.               blockElementsMap[name.toUpperCase()] = {};
  3963.               blockElementsMap[name] = {};
  3964.             }
  3965.             if (!elements[name]) {
  3966.               var customRule = elements[cloneName];
  3967.               customRule = extend$5({}, customRule);
  3968.               delete customRule.removeEmptyAttrs;
  3969.               delete customRule.removeEmpty;
  3970.               elements[name] = customRule;
  3971.             }
  3972.             each$h(children, function (element, elmName) {
  3973.               if (element[cloneName]) {
  3974.                 children[elmName] = element = extend$5({}, children[elmName]);
  3975.                 element[name] = element[cloneName];
  3976.               }
  3977.             });
  3978.           });
  3979.         }
  3980.       };
  3981.       var addValidChildren = function (validChildren) {
  3982.         var childRuleRegExp = /^([+\-]?)([A-Za-z0-9_\-.\u00b7\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u037d\u037f-\u1fff\u200c-\u200d\u203f-\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]+)\[([^\]]+)]$/;
  3983.         mapCache[settings.schema] = null;
  3984.         if (validChildren) {
  3985.           each$h(split$1(validChildren, ','), function (rule) {
  3986.             var matches = childRuleRegExp.exec(rule);
  3987.             var parent, prefix;
  3988.             if (matches) {
  3989.               prefix = matches[1];
  3990.               if (prefix) {
  3991.                 parent = children[matches[2]];
  3992.               } else {
  3993.                 parent = children[matches[2]] = { '#comment': {} };
  3994.               }
  3995.               parent = children[matches[2]];
  3996.               each$h(split$1(matches[3], '|'), function (child) {
  3997.                 if (prefix === '-') {
  3998.                   delete parent[child];
  3999.                 } else {
  4000.                   parent[child] = {};
  4001.                 }
  4002.               });
  4003.             }
  4004.           });
  4005.         }
  4006.       };
  4007.       var getElementRule = function (name) {
  4008.         var element = elements[name], i;
  4009.         if (element) {
  4010.           return element;
  4011.         }
  4012.         i = patternElements.length;
  4013.         while (i--) {
  4014.           element = patternElements[i];
  4015.           if (element.pattern.test(name)) {
  4016.             return element;
  4017.           }
  4018.         }
  4019.       };
  4020.       if (!settings.valid_elements) {
  4021.         each$h(schemaItems, function (element, name) {
  4022.           elements[name] = {
  4023.             attributes: element.attributes,
  4024.             attributesOrder: element.attributesOrder
  4025.           };
  4026.           children[name] = element.children;
  4027.         });
  4028.         if (settings.schema !== 'html5') {
  4029.           each$h(split$1('strong/b em/i'), function (item) {
  4030.             var items = split$1(item, '/');
  4031.             elements[items[1]].outputName = items[0];
  4032.           });
  4033.         }
  4034.         each$h(split$1('ol ul sub sup blockquote span font a table tbody strong em b i'), function (name) {
  4035.           if (elements[name]) {
  4036.             elements[name].removeEmpty = true;
  4037.           }
  4038.         });
  4039.         each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  4040.           elements[name].paddEmpty = true;
  4041.         });
  4042.         each$h(split$1('span'), function (name) {
  4043.           elements[name].removeEmptyAttrs = true;
  4044.         });
  4045.       } else {
  4046.         setValidElements(settings.valid_elements);
  4047.       }
  4048.       addCustomElements(settings.custom_elements);
  4049.       addValidChildren(settings.valid_children);
  4050.       addValidElements(settings.extended_valid_elements);
  4051.       addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  4052.       each$h({
  4053.         dd: 'dl',
  4054.         dt: 'dl',
  4055.         li: 'ul ol',
  4056.         td: 'tr',
  4057.         th: 'tr',
  4058.         tr: 'tbody thead tfoot',
  4059.         tbody: 'table',
  4060.         thead: 'table',
  4061.         tfoot: 'table',
  4062.         legend: 'fieldset',
  4063.         area: 'map',
  4064.         param: 'video audio object'
  4065.       }, function (parents, item) {
  4066.         if (elements[item]) {
  4067.           elements[item].parentsRequired = split$1(parents);
  4068.         }
  4069.       });
  4070.       if (settings.invalid_elements) {
  4071.         each$h(explode$3(settings.invalid_elements), function (item) {
  4072.           if (elements[item]) {
  4073.             delete elements[item];
  4074.           }
  4075.         });
  4076.       }
  4077.       if (!getElementRule('span')) {
  4078.         addValidElements('span[!data-mce-type|*]');
  4079.       }
  4080.       var getValidStyles = constant(validStyles);
  4081.       var getInvalidStyles = constant(invalidStyles);
  4082.       var getValidClasses = constant(validClasses);
  4083.       var getBoolAttrs = constant(boolAttrMap);
  4084.       var getBlockElements = constant(blockElementsMap);
  4085.       var getTextBlockElements = constant(textBlockElementsMap);
  4086.       var getTextInlineElements = constant(textInlineElementsMap);
  4087.       var getShortEndedElements = constant(shortEndedElementsMap);
  4088.       var getSelfClosingElements = constant(selfClosingElementsMap);
  4089.       var getNonEmptyElements = constant(nonEmptyElementsMap);
  4090.       var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4091.       var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4092.       var getSpecialElements = constant(specialElements);
  4093.       var isValidChild = function (name, child) {
  4094.         var parent = children[name.toLowerCase()];
  4095.         return !!(parent && parent[child.toLowerCase()]);
  4096.       };
  4097.       var isValid = function (name, attr) {
  4098.         var attrPatterns, i;
  4099.         var rule = getElementRule(name);
  4100.         if (rule) {
  4101.           if (attr) {
  4102.             if (rule.attributes[attr]) {
  4103.               return true;
  4104.             }
  4105.             attrPatterns = rule.attributePatterns;
  4106.             if (attrPatterns) {
  4107.               i = attrPatterns.length;
  4108.               while (i--) {
  4109.                 if (attrPatterns[i].pattern.test(name)) {
  4110.                   return true;
  4111.                 }
  4112.               }
  4113.             }
  4114.           } else {
  4115.             return true;
  4116.           }
  4117.         }
  4118.         return false;
  4119.       };
  4120.       var getCustomElements = constant(customElementsMap);
  4121.       return {
  4122.         children: children,
  4123.         elements: elements,
  4124.         getValidStyles: getValidStyles,
  4125.         getValidClasses: getValidClasses,
  4126.         getBlockElements: getBlockElements,
  4127.         getInvalidStyles: getInvalidStyles,
  4128.         getShortEndedElements: getShortEndedElements,
  4129.         getTextBlockElements: getTextBlockElements,
  4130.         getTextInlineElements: getTextInlineElements,
  4131.         getBoolAttrs: getBoolAttrs,
  4132.         getElementRule: getElementRule,
  4133.         getSelfClosingElements: getSelfClosingElements,
  4134.         getNonEmptyElements: getNonEmptyElements,
  4135.         getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4136.         getWhiteSpaceElements: getWhiteSpaceElements,
  4137.         getSpecialElements: getSpecialElements,
  4138.         isValidChild: isValidChild,
  4139.         isValid: isValid,
  4140.         getCustomElements: getCustomElements,
  4141.         addValidElements: addValidElements,
  4142.         setValidElements: setValidElements,
  4143.         addCustomElements: addCustomElements,
  4144.         addValidChildren: addValidChildren
  4145.       };
  4146.     };
  4147.  
  4148.     var toHex = function (match, r, g, b) {
  4149.       var hex = function (val) {
  4150.         val = parseInt(val, 10).toString(16);
  4151.         return val.length > 1 ? val : '0' + val;
  4152.       };
  4153.       return '#' + hex(r) + hex(g) + hex(b);
  4154.     };
  4155.     var Styles = function (settings, schema) {
  4156.       var _this = this;
  4157.       var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4158.       var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4159.       var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4160.       var trimRightRegExp = /\s+$/;
  4161.       var i;
  4162.       var encodingLookup = {};
  4163.       var validStyles;
  4164.       var invalidStyles;
  4165.       var invisibleChar = zeroWidth;
  4166.       settings = settings || {};
  4167.       if (schema) {
  4168.         validStyles = schema.getValidStyles();
  4169.         invalidStyles = schema.getInvalidStyles();
  4170.       }
  4171.       var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4172.       for (i = 0; i < encodingItems.length; i++) {
  4173.         encodingLookup[encodingItems[i]] = invisibleChar + i;
  4174.         encodingLookup[invisibleChar + i] = encodingItems[i];
  4175.       }
  4176.       return {
  4177.         toHex: function (color) {
  4178.           return color.replace(rgbRegExp, toHex);
  4179.         },
  4180.         parse: function (css) {
  4181.           var styles = {};
  4182.           var matches, name, value, isEncoded;
  4183.           var urlConverter = settings.url_converter;
  4184.           var urlConverterScope = settings.url_converter_scope || _this;
  4185.           var compress = function (prefix, suffix, noJoin) {
  4186.             var top = styles[prefix + '-top' + suffix];
  4187.             if (!top) {
  4188.               return;
  4189.             }
  4190.             var right = styles[prefix + '-right' + suffix];
  4191.             if (!right) {
  4192.               return;
  4193.             }
  4194.             var bottom = styles[prefix + '-bottom' + suffix];
  4195.             if (!bottom) {
  4196.               return;
  4197.             }
  4198.             var left = styles[prefix + '-left' + suffix];
  4199.             if (!left) {
  4200.               return;
  4201.             }
  4202.             var box = [
  4203.               top,
  4204.               right,
  4205.               bottom,
  4206.               left
  4207.             ];
  4208.             i = box.length - 1;
  4209.             while (i--) {
  4210.               if (box[i] !== box[i + 1]) {
  4211.                 break;
  4212.               }
  4213.             }
  4214.             if (i > -1 && noJoin) {
  4215.               return;
  4216.             }
  4217.             styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4218.             delete styles[prefix + '-top' + suffix];
  4219.             delete styles[prefix + '-right' + suffix];
  4220.             delete styles[prefix + '-bottom' + suffix];
  4221.             delete styles[prefix + '-left' + suffix];
  4222.           };
  4223.           var canCompress = function (key) {
  4224.             var value = styles[key], i;
  4225.             if (!value) {
  4226.               return;
  4227.             }
  4228.             value = value.split(' ');
  4229.             i = value.length;
  4230.             while (i--) {
  4231.               if (value[i] !== value[0]) {
  4232.                 return false;
  4233.               }
  4234.             }
  4235.             styles[key] = value[0];
  4236.             return true;
  4237.           };
  4238.           var compress2 = function (target, a, b, c) {
  4239.             if (!canCompress(a)) {
  4240.               return;
  4241.             }
  4242.             if (!canCompress(b)) {
  4243.               return;
  4244.             }
  4245.             if (!canCompress(c)) {
  4246.               return;
  4247.             }
  4248.             styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4249.             delete styles[a];
  4250.             delete styles[b];
  4251.             delete styles[c];
  4252.           };
  4253.           var encode = function (str) {
  4254.             isEncoded = true;
  4255.             return encodingLookup[str];
  4256.           };
  4257.           var decode = function (str, keepSlashes) {
  4258.             if (isEncoded) {
  4259.               str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4260.                 return encodingLookup[str];
  4261.               });
  4262.             }
  4263.             if (!keepSlashes) {
  4264.               str = str.replace(/\\([\'\";:])/g, '$1');
  4265.             }
  4266.             return str;
  4267.           };
  4268.           var decodeSingleHexSequence = function (escSeq) {
  4269.             return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4270.           };
  4271.           var decodeHexSequences = function (value) {
  4272.             return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4273.           };
  4274.           var processUrl = function (match, url, url2, url3, str, str2) {
  4275.             str = str || str2;
  4276.             if (str) {
  4277.               str = decode(str);
  4278.               return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4279.             }
  4280.             url = decode(url || url2 || url3);
  4281.             if (!settings.allow_script_urls) {
  4282.               var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4283.               if (/(java|vb)script:/i.test(scriptUrl)) {
  4284.                 return '';
  4285.               }
  4286.               if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4287.                 return '';
  4288.               }
  4289.             }
  4290.             if (urlConverter) {
  4291.               url = urlConverter.call(urlConverterScope, url, 'style');
  4292.             }
  4293.             return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4294.           };
  4295.           if (css) {
  4296.             css = css.replace(/[\u0000-\u001F]/g, '');
  4297.             css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4298.               return str.replace(/[;:]/g, encode);
  4299.             });
  4300.             while (matches = styleRegExp.exec(css)) {
  4301.               styleRegExp.lastIndex = matches.index + matches[0].length;
  4302.               name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4303.               value = matches[2].replace(trimRightRegExp, '');
  4304.               if (name && value) {
  4305.                 name = decodeHexSequences(name);
  4306.                 value = decodeHexSequences(value);
  4307.                 if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4308.                   continue;
  4309.                 }
  4310.                 if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4311.                   continue;
  4312.                 }
  4313.                 if (name === 'font-weight' && value === '700') {
  4314.                   value = 'bold';
  4315.                 } else if (name === 'color' || name === 'background-color') {
  4316.                   value = value.toLowerCase();
  4317.                 }
  4318.                 value = value.replace(rgbRegExp, toHex);
  4319.                 value = value.replace(urlOrStrRegExp, processUrl);
  4320.                 styles[name] = isEncoded ? decode(value, true) : value;
  4321.               }
  4322.             }
  4323.             compress('border', '', true);
  4324.             compress('border', '-width');
  4325.             compress('border', '-color');
  4326.             compress('border', '-style');
  4327.             compress('padding', '');
  4328.             compress('margin', '');
  4329.             compress2('border', 'border-width', 'border-style', 'border-color');
  4330.             if (styles.border === 'medium none') {
  4331.               delete styles.border;
  4332.             }
  4333.             if (styles['border-image'] === 'none') {
  4334.               delete styles['border-image'];
  4335.             }
  4336.           }
  4337.           return styles;
  4338.         },
  4339.         serialize: function (styles, elementName) {
  4340.           var css = '';
  4341.           var serializeStyles = function (name) {
  4342.             var value;
  4343.             var styleList = validStyles[name];
  4344.             if (styleList) {
  4345.               for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4346.                 name = styleList[i_1];
  4347.                 value = styles[name];
  4348.                 if (value) {
  4349.                   css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4350.                 }
  4351.               }
  4352.             }
  4353.           };
  4354.           var isValid = function (name, elementName) {
  4355.             var styleMap = invalidStyles['*'];
  4356.             if (styleMap && styleMap[name]) {
  4357.               return false;
  4358.             }
  4359.             styleMap = invalidStyles[elementName];
  4360.             return !(styleMap && styleMap[name]);
  4361.           };
  4362.           if (elementName && validStyles) {
  4363.             serializeStyles('*');
  4364.             serializeStyles(elementName);
  4365.           } else {
  4366.             each$j(styles, function (value, name) {
  4367.               if (value && (!invalidStyles || isValid(name, elementName))) {
  4368.                 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4369.               }
  4370.             });
  4371.           }
  4372.           return css;
  4373.         }
  4374.       };
  4375.     };
  4376.  
  4377.     var deprecated = {
  4378.       keyLocation: true,
  4379.       layerX: true,
  4380.       layerY: true,
  4381.       returnValue: true,
  4382.       webkitMovementX: true,
  4383.       webkitMovementY: true,
  4384.       keyIdentifier: true,
  4385.       mozPressure: true
  4386.     };
  4387.     var isNativeEvent = function (event) {
  4388.       return event instanceof Event || isFunction(event.initEvent);
  4389.     };
  4390.     var hasIsDefaultPrevented = function (event) {
  4391.       return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4392.     };
  4393.     var needsNormalizing = function (event) {
  4394.       return isNullable(event.preventDefault) || isNativeEvent(event);
  4395.     };
  4396.     var clone$2 = function (originalEvent, data) {
  4397.       var event = data !== null && data !== void 0 ? data : {};
  4398.       for (var name_1 in originalEvent) {
  4399.         if (!has$2(deprecated, name_1)) {
  4400.           event[name_1] = originalEvent[name_1];
  4401.         }
  4402.       }
  4403.       if (isNonNullable(event.composedPath)) {
  4404.         event.composedPath = function () {
  4405.           return originalEvent.composedPath();
  4406.         };
  4407.       }
  4408.       return event;
  4409.     };
  4410.     var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4411.       var _a;
  4412.       var event = clone$2(originalEvent, data);
  4413.       event.type = type;
  4414.       if (isNullable(event.target)) {
  4415.         event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4416.       }
  4417.       if (needsNormalizing(originalEvent)) {
  4418.         event.preventDefault = function () {
  4419.           event.defaultPrevented = true;
  4420.           event.isDefaultPrevented = always;
  4421.           if (isFunction(originalEvent.preventDefault)) {
  4422.             originalEvent.preventDefault();
  4423.           } else if (isNativeEvent(originalEvent)) {
  4424.             originalEvent.returnValue = false;
  4425.           }
  4426.         };
  4427.         event.stopPropagation = function () {
  4428.           event.cancelBubble = true;
  4429.           event.isPropagationStopped = always;
  4430.           if (isFunction(originalEvent.stopPropagation)) {
  4431.             originalEvent.stopPropagation();
  4432.           } else if (isNativeEvent(originalEvent)) {
  4433.             originalEvent.cancelBubble = true;
  4434.           }
  4435.         };
  4436.         event.stopImmediatePropagation = function () {
  4437.           event.isImmediatePropagationStopped = always;
  4438.           event.stopPropagation();
  4439.         };
  4440.         if (!hasIsDefaultPrevented(event)) {
  4441.           event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4442.           event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4443.           event.isImmediatePropagationStopped = never;
  4444.         }
  4445.       }
  4446.       return event;
  4447.     };
  4448.  
  4449.     var eventExpandoPrefix = 'mce-data-';
  4450.     var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4451.     var addEvent = function (target, name, callback, capture) {
  4452.       if (target.addEventListener) {
  4453.         target.addEventListener(name, callback, capture || false);
  4454.       } else if (target.attachEvent) {
  4455.         target.attachEvent('on' + name, callback);
  4456.       }
  4457.     };
  4458.     var removeEvent = function (target, name, callback, capture) {
  4459.       if (target.removeEventListener) {
  4460.         target.removeEventListener(name, callback, capture || false);
  4461.       } else if (target.detachEvent) {
  4462.         target.detachEvent('on' + name, callback);
  4463.       }
  4464.     };
  4465.     var isMouseEvent = function (event) {
  4466.       return isNonNullable(event) && mouseEventRe.test(event.type);
  4467.     };
  4468.     var fix = function (originalEvent, data) {
  4469.       var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4470.       if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4471.         var eventDoc = event.target.ownerDocument || document;
  4472.         var doc = eventDoc.documentElement;
  4473.         var body = eventDoc.body;
  4474.         var mouseEvent = event;
  4475.         mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4476.         mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4477.       }
  4478.       if (isUndefined(event.metaKey)) {
  4479.         event.metaKey = false;
  4480.       }
  4481.       return event;
  4482.     };
  4483.     var bindOnReady = function (win, callback, eventUtils) {
  4484.       var doc = win.document, event = { type: 'ready' };
  4485.       if (eventUtils.domLoaded) {
  4486.         callback(event);
  4487.         return;
  4488.       }
  4489.       var isDocReady = function () {
  4490.         return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4491.       };
  4492.       var readyHandler = function () {
  4493.         removeEvent(win, 'DOMContentLoaded', readyHandler);
  4494.         removeEvent(win, 'load', readyHandler);
  4495.         if (!eventUtils.domLoaded) {
  4496.           eventUtils.domLoaded = true;
  4497.           callback(event);
  4498.         }
  4499.         win = null;
  4500.       };
  4501.       if (isDocReady()) {
  4502.         readyHandler();
  4503.       } else {
  4504.         addEvent(win, 'DOMContentLoaded', readyHandler);
  4505.       }
  4506.       if (!eventUtils.domLoaded) {
  4507.         addEvent(win, 'load', readyHandler);
  4508.       }
  4509.     };
  4510.     var EventUtils = function () {
  4511.       function EventUtils() {
  4512.         this.domLoaded = false;
  4513.         this.events = {};
  4514.         this.count = 1;
  4515.         this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4516.         this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4517.         this.hasFocusIn = 'onfocusin' in document.documentElement;
  4518.         this.count = 1;
  4519.       }
  4520.       EventUtils.prototype.bind = function (target, names, callback, scope) {
  4521.         var self = this;
  4522.         var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4523.         var win = window;
  4524.         var defaultNativeHandler = function (evt) {
  4525.           self.executeHandlers(fix(evt || win.event), id);
  4526.         };
  4527.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4528.           return;
  4529.         }
  4530.         if (!target[self.expando]) {
  4531.           id = self.count++;
  4532.           target[self.expando] = id;
  4533.           self.events[id] = {};
  4534.         } else {
  4535.           id = target[self.expando];
  4536.         }
  4537.         scope = scope || target;
  4538.         var namesList = names.split(' ');
  4539.         i = namesList.length;
  4540.         while (i--) {
  4541.           name = namesList[i];
  4542.           nativeHandler = defaultNativeHandler;
  4543.           fakeName = capture = false;
  4544.           if (name === 'DOMContentLoaded') {
  4545.             name = 'ready';
  4546.           }
  4547.           if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4548.             callback.call(scope, fix({ type: name }));
  4549.             continue;
  4550.           }
  4551.           if (!self.hasMouseEnterLeave) {
  4552.             fakeName = self.mouseEnterLeave[name];
  4553.             if (fakeName) {
  4554.               nativeHandler = function (evt) {
  4555.                 var current = evt.currentTarget;
  4556.                 var related = evt.relatedTarget;
  4557.                 if (related && current.contains) {
  4558.                   related = current.contains(related);
  4559.                 } else {
  4560.                   while (related && related !== current) {
  4561.                     related = related.parentNode;
  4562.                   }
  4563.                 }
  4564.                 if (!related) {
  4565.                   evt = fix(evt || win.event);
  4566.                   evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4567.                   evt.target = current;
  4568.                   self.executeHandlers(evt, id);
  4569.                 }
  4570.               };
  4571.             }
  4572.           }
  4573.           if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4574.             capture = true;
  4575.             fakeName = name === 'focusin' ? 'focus' : 'blur';
  4576.             nativeHandler = function (evt) {
  4577.               evt = fix(evt || win.event);
  4578.               evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4579.               self.executeHandlers(evt, id);
  4580.             };
  4581.           }
  4582.           callbackList = self.events[id][name];
  4583.           if (!callbackList) {
  4584.             self.events[id][name] = callbackList = [{
  4585.                 func: callback,
  4586.                 scope: scope
  4587.               }];
  4588.             callbackList.fakeName = fakeName;
  4589.             callbackList.capture = capture;
  4590.             callbackList.nativeHandler = nativeHandler;
  4591.             if (name === 'ready') {
  4592.               bindOnReady(target, nativeHandler, self);
  4593.             } else {
  4594.               addEvent(target, fakeName || name, nativeHandler, capture);
  4595.             }
  4596.           } else {
  4597.             if (name === 'ready' && self.domLoaded) {
  4598.               callback(fix({ type: name }));
  4599.             } else {
  4600.               callbackList.push({
  4601.                 func: callback,
  4602.                 scope: scope
  4603.               });
  4604.             }
  4605.           }
  4606.         }
  4607.         target = callbackList = null;
  4608.         return callback;
  4609.       };
  4610.       EventUtils.prototype.unbind = function (target, names, callback) {
  4611.         var callbackList, i, ci, name, eventMap;
  4612.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4613.           return this;
  4614.         }
  4615.         var id = target[this.expando];
  4616.         if (id) {
  4617.           eventMap = this.events[id];
  4618.           if (names) {
  4619.             var namesList = names.split(' ');
  4620.             i = namesList.length;
  4621.             while (i--) {
  4622.               name = namesList[i];
  4623.               callbackList = eventMap[name];
  4624.               if (callbackList) {
  4625.                 if (callback) {
  4626.                   ci = callbackList.length;
  4627.                   while (ci--) {
  4628.                     if (callbackList[ci].func === callback) {
  4629.                       var nativeHandler = callbackList.nativeHandler;
  4630.                       var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4631.                       callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4632.                       callbackList.nativeHandler = nativeHandler;
  4633.                       callbackList.fakeName = fakeName;
  4634.                       callbackList.capture = capture;
  4635.                       eventMap[name] = callbackList;
  4636.                     }
  4637.                   }
  4638.                 }
  4639.                 if (!callback || callbackList.length === 0) {
  4640.                   delete eventMap[name];
  4641.                   removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4642.                 }
  4643.               }
  4644.             }
  4645.           } else {
  4646.             each$j(eventMap, function (callbackList, name) {
  4647.               removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4648.             });
  4649.             eventMap = {};
  4650.           }
  4651.           for (name in eventMap) {
  4652.             if (has$2(eventMap, name)) {
  4653.               return this;
  4654.             }
  4655.           }
  4656.           delete this.events[id];
  4657.           try {
  4658.             delete target[this.expando];
  4659.           } catch (ex) {
  4660.             target[this.expando] = null;
  4661.           }
  4662.         }
  4663.         return this;
  4664.       };
  4665.       EventUtils.prototype.fire = function (target, name, args) {
  4666.         var id;
  4667.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4668.           return this;
  4669.         }
  4670.         var event = fix({
  4671.           type: name,
  4672.           target: target
  4673.         }, args);
  4674.         do {
  4675.           id = target[this.expando];
  4676.           if (id) {
  4677.             this.executeHandlers(event, id);
  4678.           }
  4679.           target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4680.         } while (target && !event.isPropagationStopped());
  4681.         return this;
  4682.       };
  4683.       EventUtils.prototype.clean = function (target) {
  4684.         var i, children;
  4685.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4686.           return this;
  4687.         }
  4688.         if (target[this.expando]) {
  4689.           this.unbind(target);
  4690.         }
  4691.         if (!target.getElementsByTagName) {
  4692.           target = target.document;
  4693.         }
  4694.         if (target && target.getElementsByTagName) {
  4695.           this.unbind(target);
  4696.           children = target.getElementsByTagName('*');
  4697.           i = children.length;
  4698.           while (i--) {
  4699.             target = children[i];
  4700.             if (target[this.expando]) {
  4701.               this.unbind(target);
  4702.             }
  4703.           }
  4704.         }
  4705.         return this;
  4706.       };
  4707.       EventUtils.prototype.destroy = function () {
  4708.         this.events = {};
  4709.       };
  4710.       EventUtils.prototype.cancel = function (e) {
  4711.         if (e) {
  4712.           e.preventDefault();
  4713.           e.stopImmediatePropagation();
  4714.         }
  4715.         return false;
  4716.       };
  4717.       EventUtils.prototype.executeHandlers = function (evt, id) {
  4718.         var container = this.events[id];
  4719.         var callbackList = container && container[evt.type];
  4720.         if (callbackList) {
  4721.           for (var i = 0, l = callbackList.length; i < l; i++) {
  4722.             var callback = callbackList[i];
  4723.             if (callback && callback.func.call(callback.scope, evt) === false) {
  4724.               evt.preventDefault();
  4725.             }
  4726.             if (evt.isImmediatePropagationStopped()) {
  4727.               return;
  4728.             }
  4729.           }
  4730.         }
  4731.       };
  4732.       EventUtils.Event = new EventUtils();
  4733.       return EventUtils;
  4734.     }();
  4735.  
  4736.     var support, Expr, getText, isXML, tokenize, compile, select$1, outermostContext, sortInput, hasDuplicate, setDocument, document$1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, expando = 'sizzle' + -new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function (a, b) {
  4737.         if (a === b) {
  4738.           hasDuplicate = true;
  4739.         }
  4740.         return 0;
  4741.       }, strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push$1 = arr.push, slice$1 = arr.slice, indexOf = arr.indexOf || function (elem) {
  4742.         var i = 0, len = this.length;
  4743.         for (; i < len; i++) {
  4744.           if (this[i] === elem) {
  4745.             return i;
  4746.           }
  4747.         }
  4748.         return -1;
  4749.       }, booleans = 'checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped', whitespace = '[\\x20\\t\\r\\n\\f]', identifier = '(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+', attributes = '\\[' + whitespace + '*(' + identifier + ')(?:' + whitespace + '*([*^$|!~]?=)' + whitespace + '*(?:\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)"|(' + identifier + '))|)' + whitespace + '*\\]', pseudos = ':(' + identifier + ')(?:\\((' + '(\'((?:\\\\.|[^\\\\\'])*)\'|"((?:\\\\.|[^\\\\"])*)")|' + '((?:\\\\.|[^\\\\()[\\]]|' + attributes + ')*)|' + '.*' + ')\\)|)', rtrim = new RegExp('^' + whitespace + '+|((?:^|[^\\\\])(?:\\\\.)*)' + whitespace + '+$', 'g'), rcomma = new RegExp('^' + whitespace + '*,' + whitespace + '*'), rcombinators = new RegExp('^' + whitespace + '*([>+~]|' + whitespace + ')' + whitespace + '*'), rattributeQuotes = new RegExp('=' + whitespace + '*([^\\]\'"]*?)' + whitespace + '*\\]', 'g'), rpseudo = new RegExp(pseudos), ridentifier = new RegExp('^' + identifier + '$'), matchExpr = {
  4750.         ID: new RegExp('^#(' + identifier + ')'),
  4751.         CLASS: new RegExp('^\\.(' + identifier + ')'),
  4752.         TAG: new RegExp('^(' + identifier + '|[*])'),
  4753.         ATTR: new RegExp('^' + attributes),
  4754.         PSEUDO: new RegExp('^' + pseudos),
  4755.         CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  4756.         bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  4757.         needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  4758.       }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr$1 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, runescape = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig'), funescape = function (_, escaped, escapedWhitespace) {
  4759.         var high = '0x' + escaped - 65536;
  4760.         return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  4761.       };
  4762.     try {
  4763.       push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  4764.       arr[preferredDoc.childNodes.length].nodeType;
  4765.     } catch (e) {
  4766.       push$1 = {
  4767.         apply: arr.length ? function (target, els) {
  4768.           push_native.apply(target, slice$1.call(els));
  4769.         } : function (target, els) {
  4770.           var j = target.length, i = 0;
  4771.           while (target[j++] = els[i++]) {
  4772.           }
  4773.           target.length = j - 1;
  4774.         }
  4775.       };
  4776.     }
  4777.     var Sizzle = function (selector, context, results, seed) {
  4778.       var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  4779.       if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  4780.         setDocument(context);
  4781.       }
  4782.       context = context || document$1;
  4783.       results = results || [];
  4784.       if (!selector || typeof selector !== 'string') {
  4785.         return results;
  4786.       }
  4787.       if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  4788.         return [];
  4789.       }
  4790.       if (documentIsHTML && !seed) {
  4791.         if (match = rquickExpr$1.exec(selector)) {
  4792.           if (m = match[1]) {
  4793.             if (nodeType === 9) {
  4794.               elem = context.getElementById(m);
  4795.               if (elem && elem.parentNode) {
  4796.                 if (elem.id === m) {
  4797.                   results.push(elem);
  4798.                   return results;
  4799.                 }
  4800.               } else {
  4801.                 return results;
  4802.               }
  4803.             } else {
  4804.               if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  4805.                 results.push(elem);
  4806.                 return results;
  4807.               }
  4808.             }
  4809.           } else if (match[2]) {
  4810.             push$1.apply(results, context.getElementsByTagName(selector));
  4811.             return results;
  4812.           } else if ((m = match[3]) && support.getElementsByClassName) {
  4813.             push$1.apply(results, context.getElementsByClassName(m));
  4814.             return results;
  4815.           }
  4816.         }
  4817.         if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  4818.           nid = old = expando;
  4819.           newContext = context;
  4820.           newSelector = nodeType === 9 && selector;
  4821.           if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  4822.             groups = tokenize(selector);
  4823.             if (old = context.getAttribute('id')) {
  4824.               nid = old.replace(rescape, '\\$&');
  4825.             } else {
  4826.               context.setAttribute('id', nid);
  4827.             }
  4828.             nid = '[id=\'' + nid + '\'] ';
  4829.             i = groups.length;
  4830.             while (i--) {
  4831.               groups[i] = nid + toSelector(groups[i]);
  4832.             }
  4833.             newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  4834.             newSelector = groups.join(',');
  4835.           }
  4836.           if (newSelector) {
  4837.             try {
  4838.               push$1.apply(results, newContext.querySelectorAll(newSelector));
  4839.               return results;
  4840.             } catch (qsaError) {
  4841.             } finally {
  4842.               if (!old) {
  4843.                 context.removeAttribute('id');
  4844.               }
  4845.             }
  4846.           }
  4847.         }
  4848.       }
  4849.       return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  4850.     };
  4851.     function createCache() {
  4852.       var keys = [];
  4853.       function cache(key, value) {
  4854.         if (keys.push(key + ' ') > Expr.cacheLength) {
  4855.           delete cache[keys.shift()];
  4856.         }
  4857.         return cache[key + ' '] = value;
  4858.       }
  4859.       return cache;
  4860.     }
  4861.     function markFunction(fn) {
  4862.       fn[expando] = true;
  4863.       return fn;
  4864.     }
  4865.     function siblingCheck(a, b) {
  4866.       var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  4867.       if (diff) {
  4868.         return diff;
  4869.       }
  4870.       if (cur) {
  4871.         while (cur = cur.nextSibling) {
  4872.           if (cur === b) {
  4873.             return -1;
  4874.           }
  4875.         }
  4876.       }
  4877.       return a ? 1 : -1;
  4878.     }
  4879.     function createInputPseudo(type) {
  4880.       return function (elem) {
  4881.         var name = elem.nodeName.toLowerCase();
  4882.         return name === 'input' && elem.type === type;
  4883.       };
  4884.     }
  4885.     function createButtonPseudo(type) {
  4886.       return function (elem) {
  4887.         var name = elem.nodeName.toLowerCase();
  4888.         return (name === 'input' || name === 'button') && elem.type === type;
  4889.       };
  4890.     }
  4891.     function createPositionalPseudo(fn) {
  4892.       return markFunction(function (argument) {
  4893.         argument = +argument;
  4894.         return markFunction(function (seed, matches) {
  4895.           var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  4896.           while (i--) {
  4897.             if (seed[j = matchIndexes[i]]) {
  4898.               seed[j] = !(matches[j] = seed[j]);
  4899.             }
  4900.           }
  4901.         });
  4902.       });
  4903.     }
  4904.     function testContext(context) {
  4905.       return context && typeof context.getElementsByTagName !== strundefined && context;
  4906.     }
  4907.     support = Sizzle.support = {};
  4908.     isXML = Sizzle.isXML = function (elem) {
  4909.       var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  4910.       return documentElement ? documentElement.nodeName !== 'HTML' : false;
  4911.     };
  4912.     setDocument = Sizzle.setDocument = function (node) {
  4913.       var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  4914.       function getTop(win) {
  4915.         try {
  4916.           return win.top;
  4917.         } catch (ex) {
  4918.         }
  4919.         return null;
  4920.       }
  4921.       if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  4922.         return document$1;
  4923.       }
  4924.       document$1 = doc;
  4925.       docElem = doc.documentElement;
  4926.       documentIsHTML = !isXML(doc);
  4927.       if (parent && parent !== getTop(parent)) {
  4928.         if (parent.addEventListener) {
  4929.           parent.addEventListener('unload', function () {
  4930.             setDocument();
  4931.           }, false);
  4932.         } else if (parent.attachEvent) {
  4933.           parent.attachEvent('onunload', function () {
  4934.             setDocument();
  4935.           });
  4936.         }
  4937.       }
  4938.       support.attributes = true;
  4939.       support.getElementsByTagName = true;
  4940.       support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  4941.       support.getById = true;
  4942.       Expr.find.ID = function (id, context) {
  4943.         if (typeof context.getElementById !== strundefined && documentIsHTML) {
  4944.           var m = context.getElementById(id);
  4945.           return m && m.parentNode ? [m] : [];
  4946.         }
  4947.       };
  4948.       Expr.filter.ID = function (id) {
  4949.         var attrId = id.replace(runescape, funescape);
  4950.         return function (elem) {
  4951.           return elem.getAttribute('id') === attrId;
  4952.         };
  4953.       };
  4954.       Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  4955.         if (typeof context.getElementsByTagName !== strundefined) {
  4956.           return context.getElementsByTagName(tag);
  4957.         }
  4958.       } : function (tag, context) {
  4959.         var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  4960.         if (tag === '*') {
  4961.           while (elem = results[i++]) {
  4962.             if (elem.nodeType === 1) {
  4963.               tmp.push(elem);
  4964.             }
  4965.           }
  4966.           return tmp;
  4967.         }
  4968.         return results;
  4969.       };
  4970.       Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  4971.         if (documentIsHTML) {
  4972.           return context.getElementsByClassName(className);
  4973.         }
  4974.       };
  4975.       rbuggyMatches = [];
  4976.       rbuggyQSA = [];
  4977.       support.disconnectedMatch = true;
  4978.       rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  4979.       rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  4980.       hasCompare = rnative.test(docElem.compareDocumentPosition);
  4981.       contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  4982.         var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  4983.         return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  4984.       } : function (a, b) {
  4985.         if (b) {
  4986.           while (b = b.parentNode) {
  4987.             if (b === a) {
  4988.               return true;
  4989.             }
  4990.           }
  4991.         }
  4992.         return false;
  4993.       };
  4994.       sortOrder = hasCompare ? function (a, b) {
  4995.         if (a === b) {
  4996.           hasDuplicate = true;
  4997.           return 0;
  4998.         }
  4999.         var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  5000.         if (compare) {
  5001.           return compare;
  5002.         }
  5003.         compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  5004.         if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  5005.           if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  5006.             return -1;
  5007.           }
  5008.           if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  5009.             return 1;
  5010.           }
  5011.           return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5012.         }
  5013.         return compare & 4 ? -1 : 1;
  5014.       } : function (a, b) {
  5015.         if (a === b) {
  5016.           hasDuplicate = true;
  5017.           return 0;
  5018.         }
  5019.         var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  5020.         if (!aup || !bup) {
  5021.           return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5022.         } else if (aup === bup) {
  5023.           return siblingCheck(a, b);
  5024.         }
  5025.         cur = a;
  5026.         while (cur = cur.parentNode) {
  5027.           ap.unshift(cur);
  5028.         }
  5029.         cur = b;
  5030.         while (cur = cur.parentNode) {
  5031.           bp.unshift(cur);
  5032.         }
  5033.         while (ap[i] === bp[i]) {
  5034.           i++;
  5035.         }
  5036.         return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  5037.       };
  5038.       return doc;
  5039.     };
  5040.     Sizzle.matches = function (expr, elements) {
  5041.       return Sizzle(expr, null, null, elements);
  5042.     };
  5043.     Sizzle.matchesSelector = function (elem, expr) {
  5044.       if ((elem.ownerDocument || elem) !== document$1) {
  5045.         setDocument(elem);
  5046.       }
  5047.       expr = expr.replace(rattributeQuotes, '=\'$1\']');
  5048.       if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  5049.         try {
  5050.           var ret = matches.call(elem, expr);
  5051.           if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  5052.             return ret;
  5053.           }
  5054.         } catch (e) {
  5055.         }
  5056.       }
  5057.       return Sizzle(expr, document$1, null, [elem]).length > 0;
  5058.     };
  5059.     Sizzle.contains = function (context, elem) {
  5060.       if ((context.ownerDocument || context) !== document$1) {
  5061.         setDocument(context);
  5062.       }
  5063.       return contains(context, elem);
  5064.     };
  5065.     Sizzle.attr = function (elem, name) {
  5066.       if ((elem.ownerDocument || elem) !== document$1) {
  5067.         setDocument(elem);
  5068.       }
  5069.       var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5070.       return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5071.     };
  5072.     Sizzle.error = function (msg) {
  5073.       throw new Error('Syntax error, unrecognized expression: ' + msg);
  5074.     };
  5075.     Sizzle.uniqueSort = function (results) {
  5076.       var elem, duplicates = [], j = 0, i = 0;
  5077.       hasDuplicate = !support.detectDuplicates;
  5078.       sortInput = !support.sortStable && results.slice(0);
  5079.       results.sort(sortOrder);
  5080.       if (hasDuplicate) {
  5081.         while (elem = results[i++]) {
  5082.           if (elem === results[i]) {
  5083.             j = duplicates.push(i);
  5084.           }
  5085.         }
  5086.         while (j--) {
  5087.           results.splice(duplicates[j], 1);
  5088.         }
  5089.       }
  5090.       sortInput = null;
  5091.       return results;
  5092.     };
  5093.     getText = Sizzle.getText = function (elem) {
  5094.       var node, ret = '', i = 0, nodeType = elem.nodeType;
  5095.       if (!nodeType) {
  5096.         while (node = elem[i++]) {
  5097.           ret += getText(node);
  5098.         }
  5099.       } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5100.         if (typeof elem.textContent === 'string') {
  5101.           return elem.textContent;
  5102.         } else {
  5103.           for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5104.             ret += getText(elem);
  5105.           }
  5106.         }
  5107.       } else if (nodeType === 3 || nodeType === 4) {
  5108.         return elem.nodeValue;
  5109.       }
  5110.       return ret;
  5111.     };
  5112.     Expr = Sizzle.selectors = {
  5113.       cacheLength: 50,
  5114.       createPseudo: markFunction,
  5115.       match: matchExpr,
  5116.       attrHandle: {},
  5117.       find: {},
  5118.       relative: {
  5119.         '>': {
  5120.           dir: 'parentNode',
  5121.           first: true
  5122.         },
  5123.         ' ': { dir: 'parentNode' },
  5124.         '+': {
  5125.           dir: 'previousSibling',
  5126.           first: true
  5127.         },
  5128.         '~': { dir: 'previousSibling' }
  5129.       },
  5130.       preFilter: {
  5131.         ATTR: function (match) {
  5132.           match[1] = match[1].replace(runescape, funescape);
  5133.           match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5134.           if (match[2] === '~=') {
  5135.             match[3] = ' ' + match[3] + ' ';
  5136.           }
  5137.           return match.slice(0, 4);
  5138.         },
  5139.         CHILD: function (match) {
  5140.           match[1] = match[1].toLowerCase();
  5141.           if (match[1].slice(0, 3) === 'nth') {
  5142.             if (!match[3]) {
  5143.               Sizzle.error(match[0]);
  5144.             }
  5145.             match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5146.             match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5147.           } else if (match[3]) {
  5148.             Sizzle.error(match[0]);
  5149.           }
  5150.           return match;
  5151.         },
  5152.         PSEUDO: function (match) {
  5153.           var excess, unquoted = !match[6] && match[2];
  5154.           if (matchExpr.CHILD.test(match[0])) {
  5155.             return null;
  5156.           }
  5157.           if (match[3]) {
  5158.             match[2] = match[4] || match[5] || '';
  5159.           } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5160.             match[0] = match[0].slice(0, excess);
  5161.             match[2] = unquoted.slice(0, excess);
  5162.           }
  5163.           return match.slice(0, 3);
  5164.         }
  5165.       },
  5166.       filter: {
  5167.         TAG: function (nodeNameSelector) {
  5168.           var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5169.           return nodeNameSelector === '*' ? function () {
  5170.             return true;
  5171.           } : function (elem) {
  5172.             return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5173.           };
  5174.         },
  5175.         CLASS: function (className) {
  5176.           var pattern = classCache[className + ' '];
  5177.           return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5178.             return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5179.           });
  5180.         },
  5181.         ATTR: function (name, operator, check) {
  5182.           return function (elem) {
  5183.             var result = Sizzle.attr(elem, name);
  5184.             if (result == null) {
  5185.               return operator === '!=';
  5186.             }
  5187.             if (!operator) {
  5188.               return true;
  5189.             }
  5190.             result += '';
  5191.             return operator === '=' ? result === check : operator === '!=' ? result !== check : operator === '^=' ? check && result.indexOf(check) === 0 : operator === '*=' ? check && result.indexOf(check) > -1 : operator === '$=' ? check && result.slice(-check.length) === check : operator === '~=' ? (' ' + result + ' ').indexOf(check) > -1 : operator === '|=' ? result === check || result.slice(0, check.length + 1) === check + '-' : false;
  5192.           };
  5193.         },
  5194.         CHILD: function (type, what, argument, first, last) {
  5195.           var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5196.           return first === 1 && last === 0 ? function (elem) {
  5197.             return !!elem.parentNode;
  5198.           } : function (elem, context, xml) {
  5199.             var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5200.             if (parent) {
  5201.               if (simple) {
  5202.                 while (dir) {
  5203.                   node = elem;
  5204.                   while (node = node[dir]) {
  5205.                     if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5206.                       return false;
  5207.                     }
  5208.                   }
  5209.                   start = dir = type === 'only' && !start && 'nextSibling';
  5210.                 }
  5211.                 return true;
  5212.               }
  5213.               start = [forward ? parent.firstChild : parent.lastChild];
  5214.               if (forward && useCache) {
  5215.                 outerCache = parent[expando] || (parent[expando] = {});
  5216.                 cache = outerCache[type] || [];
  5217.                 nodeIndex = cache[0] === dirruns && cache[1];
  5218.                 diff = cache[0] === dirruns && cache[2];
  5219.                 node = nodeIndex && parent.childNodes[nodeIndex];
  5220.                 while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5221.                   if (node.nodeType === 1 && ++diff && node === elem) {
  5222.                     outerCache[type] = [
  5223.                       dirruns,
  5224.                       nodeIndex,
  5225.                       diff
  5226.                     ];
  5227.                     break;
  5228.                   }
  5229.                 }
  5230.               } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5231.                 diff = cache[1];
  5232.               } else {
  5233.                 while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5234.                   if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5235.                     if (useCache) {
  5236.                       (node[expando] || (node[expando] = {}))[type] = [
  5237.                         dirruns,
  5238.                         diff
  5239.                       ];
  5240.                     }
  5241.                     if (node === elem) {
  5242.                       break;
  5243.                     }
  5244.                   }
  5245.                 }
  5246.               }
  5247.               diff -= last;
  5248.               return diff === first || diff % first === 0 && diff / first >= 0;
  5249.             }
  5250.           };
  5251.         },
  5252.         PSEUDO: function (pseudo, argument) {
  5253.           var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5254.           if (fn[expando]) {
  5255.             return fn(argument);
  5256.           }
  5257.           if (fn.length > 1) {
  5258.             args = [
  5259.               pseudo,
  5260.               pseudo,
  5261.               '',
  5262.               argument
  5263.             ];
  5264.             return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5265.               var idx, matched = fn(seed, argument), i = matched.length;
  5266.               while (i--) {
  5267.                 idx = indexOf.call(seed, matched[i]);
  5268.                 seed[idx] = !(matches[idx] = matched[i]);
  5269.               }
  5270.             }) : function (elem) {
  5271.               return fn(elem, 0, args);
  5272.             };
  5273.           }
  5274.           return fn;
  5275.         }
  5276.       },
  5277.       pseudos: {
  5278.         not: markFunction(function (selector) {
  5279.           var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5280.           return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5281.             var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5282.             while (i--) {
  5283.               if (elem = unmatched[i]) {
  5284.                 seed[i] = !(matches[i] = elem);
  5285.               }
  5286.             }
  5287.           }) : function (elem, context, xml) {
  5288.             input[0] = elem;
  5289.             matcher(input, null, xml, results);
  5290.             input[0] = null;
  5291.             return !results.pop();
  5292.           };
  5293.         }),
  5294.         has: markFunction(function (selector) {
  5295.           return function (elem) {
  5296.             return Sizzle(selector, elem).length > 0;
  5297.           };
  5298.         }),
  5299.         contains: markFunction(function (text) {
  5300.           text = text.replace(runescape, funescape);
  5301.           return function (elem) {
  5302.             return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5303.           };
  5304.         }),
  5305.         lang: markFunction(function (lang) {
  5306.           if (!ridentifier.test(lang || '')) {
  5307.             Sizzle.error('unsupported lang: ' + lang);
  5308.           }
  5309.           lang = lang.replace(runescape, funescape).toLowerCase();
  5310.           return function (elem) {
  5311.             var elemLang;
  5312.             do {
  5313.               if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5314.                 elemLang = elemLang.toLowerCase();
  5315.                 return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5316.               }
  5317.             } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5318.             return false;
  5319.           };
  5320.         }),
  5321.         target: function (elem) {
  5322.           var hash = window.location && window.location.hash;
  5323.           return hash && hash.slice(1) === elem.id;
  5324.         },
  5325.         root: function (elem) {
  5326.           return elem === docElem;
  5327.         },
  5328.         focus: function (elem) {
  5329.           return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5330.         },
  5331.         enabled: function (elem) {
  5332.           return elem.disabled === false;
  5333.         },
  5334.         disabled: function (elem) {
  5335.           return elem.disabled === true;
  5336.         },
  5337.         checked: function (elem) {
  5338.           var nodeName = elem.nodeName.toLowerCase();
  5339.           return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5340.         },
  5341.         selected: function (elem) {
  5342.           if (elem.parentNode) {
  5343.             elem.parentNode.selectedIndex;
  5344.           }
  5345.           return elem.selected === true;
  5346.         },
  5347.         empty: function (elem) {
  5348.           for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5349.             if (elem.nodeType < 6) {
  5350.               return false;
  5351.             }
  5352.           }
  5353.           return true;
  5354.         },
  5355.         parent: function (elem) {
  5356.           return !Expr.pseudos.empty(elem);
  5357.         },
  5358.         header: function (elem) {
  5359.           return rheader.test(elem.nodeName);
  5360.         },
  5361.         input: function (elem) {
  5362.           return rinputs.test(elem.nodeName);
  5363.         },
  5364.         button: function (elem) {
  5365.           var name = elem.nodeName.toLowerCase();
  5366.           return name === 'input' && elem.type === 'button' || name === 'button';
  5367.         },
  5368.         text: function (elem) {
  5369.           var attr;
  5370.           return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5371.         },
  5372.         first: createPositionalPseudo(function () {
  5373.           return [0];
  5374.         }),
  5375.         last: createPositionalPseudo(function (matchIndexes, length) {
  5376.           return [length - 1];
  5377.         }),
  5378.         eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5379.           return [argument < 0 ? argument + length : argument];
  5380.         }),
  5381.         even: createPositionalPseudo(function (matchIndexes, length) {
  5382.           var i = 0;
  5383.           for (; i < length; i += 2) {
  5384.             matchIndexes.push(i);
  5385.           }
  5386.           return matchIndexes;
  5387.         }),
  5388.         odd: createPositionalPseudo(function (matchIndexes, length) {
  5389.           var i = 1;
  5390.           for (; i < length; i += 2) {
  5391.             matchIndexes.push(i);
  5392.           }
  5393.           return matchIndexes;
  5394.         }),
  5395.         lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5396.           var i = argument < 0 ? argument + length : argument;
  5397.           for (; --i >= 0;) {
  5398.             matchIndexes.push(i);
  5399.           }
  5400.           return matchIndexes;
  5401.         }),
  5402.         gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5403.           var i = argument < 0 ? argument + length : argument;
  5404.           for (; ++i < length;) {
  5405.             matchIndexes.push(i);
  5406.           }
  5407.           return matchIndexes;
  5408.         })
  5409.       }
  5410.     };
  5411.     Expr.pseudos.nth = Expr.pseudos.eq;
  5412.     each$k([
  5413.       'radio',
  5414.       'checkbox',
  5415.       'file',
  5416.       'password',
  5417.       'image'
  5418.     ], function (i) {
  5419.       Expr.pseudos[i] = createInputPseudo(i);
  5420.     });
  5421.     each$k([
  5422.       'submit',
  5423.       'reset'
  5424.     ], function (i) {
  5425.       Expr.pseudos[i] = createButtonPseudo(i);
  5426.     });
  5427.     function setFilters() {
  5428.     }
  5429.     setFilters.prototype = Expr.filters = Expr.pseudos;
  5430.     Expr.setFilters = new setFilters();
  5431.     tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5432.       var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5433.       if (cached) {
  5434.         return parseOnly ? 0 : cached.slice(0);
  5435.       }
  5436.       soFar = selector;
  5437.       groups = [];
  5438.       preFilters = Expr.preFilter;
  5439.       while (soFar) {
  5440.         if (!matched || (match = rcomma.exec(soFar))) {
  5441.           if (match) {
  5442.             soFar = soFar.slice(match[0].length) || soFar;
  5443.           }
  5444.           groups.push(tokens = []);
  5445.         }
  5446.         matched = false;
  5447.         if (match = rcombinators.exec(soFar)) {
  5448.           matched = match.shift();
  5449.           tokens.push({
  5450.             value: matched,
  5451.             type: match[0].replace(rtrim, ' ')
  5452.           });
  5453.           soFar = soFar.slice(matched.length);
  5454.         }
  5455.         for (type in Expr.filter) {
  5456.           if (!Expr.filter.hasOwnProperty(type)) {
  5457.             continue;
  5458.           }
  5459.           if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5460.             matched = match.shift();
  5461.             tokens.push({
  5462.               value: matched,
  5463.               type: type,
  5464.               matches: match
  5465.             });
  5466.             soFar = soFar.slice(matched.length);
  5467.           }
  5468.         }
  5469.         if (!matched) {
  5470.           break;
  5471.         }
  5472.       }
  5473.       return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5474.     };
  5475.     function toSelector(tokens) {
  5476.       var i = 0, len = tokens.length, selector = '';
  5477.       for (; i < len; i++) {
  5478.         selector += tokens[i].value;
  5479.       }
  5480.       return selector;
  5481.     }
  5482.     function addCombinator(matcher, combinator, base) {
  5483.       var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5484.       return combinator.first ? function (elem, context, xml) {
  5485.         while (elem = elem[dir]) {
  5486.           if (elem.nodeType === 1 || checkNonElements) {
  5487.             return matcher(elem, context, xml);
  5488.           }
  5489.         }
  5490.       } : function (elem, context, xml) {
  5491.         var oldCache, outerCache, newCache = [
  5492.             dirruns,
  5493.             doneName
  5494.           ];
  5495.         if (xml) {
  5496.           while (elem = elem[dir]) {
  5497.             if (elem.nodeType === 1 || checkNonElements) {
  5498.               if (matcher(elem, context, xml)) {
  5499.                 return true;
  5500.               }
  5501.             }
  5502.           }
  5503.         } else {
  5504.           while (elem = elem[dir]) {
  5505.             if (elem.nodeType === 1 || checkNonElements) {
  5506.               outerCache = elem[expando] || (elem[expando] = {});
  5507.               if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5508.                 return newCache[2] = oldCache[2];
  5509.               } else {
  5510.                 outerCache[dir] = newCache;
  5511.                 if (newCache[2] = matcher(elem, context, xml)) {
  5512.                   return true;
  5513.                 }
  5514.               }
  5515.             }
  5516.           }
  5517.         }
  5518.       };
  5519.     }
  5520.     function elementMatcher(matchers) {
  5521.       return matchers.length > 1 ? function (elem, context, xml) {
  5522.         var i = matchers.length;
  5523.         while (i--) {
  5524.           if (!matchers[i](elem, context, xml)) {
  5525.             return false;
  5526.           }
  5527.         }
  5528.         return true;
  5529.       } : matchers[0];
  5530.     }
  5531.     function multipleContexts(selector, contexts, results) {
  5532.       var i = 0, len = contexts.length;
  5533.       for (; i < len; i++) {
  5534.         Sizzle(selector, contexts[i], results);
  5535.       }
  5536.       return results;
  5537.     }
  5538.     function condense(unmatched, map, filter, context, xml) {
  5539.       var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5540.       for (; i < len; i++) {
  5541.         if (elem = unmatched[i]) {
  5542.           if (!filter || filter(elem, context, xml)) {
  5543.             newUnmatched.push(elem);
  5544.             if (mapped) {
  5545.               map.push(i);
  5546.             }
  5547.           }
  5548.         }
  5549.       }
  5550.       return newUnmatched;
  5551.     }
  5552.     function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5553.       if (postFilter && !postFilter[expando]) {
  5554.         postFilter = setMatcher(postFilter);
  5555.       }
  5556.       if (postFinder && !postFinder[expando]) {
  5557.         postFinder = setMatcher(postFinder, postSelector);
  5558.       }
  5559.       return markFunction(function (seed, results, context, xml) {
  5560.         var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || '*', context.nodeType ? [context] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
  5561.         if (matcher) {
  5562.           matcher(matcherIn, matcherOut, context, xml);
  5563.         }
  5564.         if (postFilter) {
  5565.           temp = condense(matcherOut, postMap);
  5566.           postFilter(temp, [], context, xml);
  5567.           i = temp.length;
  5568.           while (i--) {
  5569.             if (elem = temp[i]) {
  5570.               matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5571.             }
  5572.           }
  5573.         }
  5574.         if (seed) {
  5575.           if (postFinder || preFilter) {
  5576.             if (postFinder) {
  5577.               temp = [];
  5578.               i = matcherOut.length;
  5579.               while (i--) {
  5580.                 if (elem = matcherOut[i]) {
  5581.                   temp.push(matcherIn[i] = elem);
  5582.                 }
  5583.               }
  5584.               postFinder(null, matcherOut = [], temp, xml);
  5585.             }
  5586.             i = matcherOut.length;
  5587.             while (i--) {
  5588.               if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5589.                 seed[temp] = !(results[temp] = elem);
  5590.               }
  5591.             }
  5592.           }
  5593.         } else {
  5594.           matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5595.           if (postFinder) {
  5596.             postFinder(null, results, matcherOut, xml);
  5597.           } else {
  5598.             push$1.apply(results, matcherOut);
  5599.           }
  5600.         }
  5601.       });
  5602.     }
  5603.     function matcherFromTokens(tokens) {
  5604.       var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[' '], i = leadingRelative ? 1 : 0, matchContext = addCombinator(function (elem) {
  5605.           return elem === checkContext;
  5606.         }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5607.           return indexOf.call(checkContext, elem) > -1;
  5608.         }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5609.             var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5610.             checkContext = null;
  5611.             return ret;
  5612.           }];
  5613.       for (; i < len; i++) {
  5614.         if (matcher = Expr.relative[tokens[i].type]) {
  5615.           matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5616.         } else {
  5617.           matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5618.           if (matcher[expando]) {
  5619.             j = ++i;
  5620.             for (; j < len; j++) {
  5621.               if (Expr.relative[tokens[j].type]) {
  5622.                 break;
  5623.               }
  5624.             }
  5625.             return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && toSelector(tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === ' ' ? '*' : '' })).replace(rtrim, '$1'), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
  5626.           }
  5627.           matchers.push(matcher);
  5628.         }
  5629.       }
  5630.       return elementMatcher(matchers);
  5631.     }
  5632.     function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5633.       var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5634.           var elem, j, matcher, matchedCount = 0, i = '0', unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find.TAG('*', outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
  5635.           if (outermost) {
  5636.             outermostContext = context !== document$1 && context;
  5637.           }
  5638.           for (; i !== len && (elem = elems[i]) != null; i++) {
  5639.             if (byElement && elem) {
  5640.               j = 0;
  5641.               while (matcher = elementMatchers[j++]) {
  5642.                 if (matcher(elem, context, xml)) {
  5643.                   results.push(elem);
  5644.                   break;
  5645.                 }
  5646.               }
  5647.               if (outermost) {
  5648.                 dirruns = dirrunsUnique;
  5649.               }
  5650.             }
  5651.             if (bySet) {
  5652.               if (elem = !matcher && elem) {
  5653.                 matchedCount--;
  5654.               }
  5655.               if (seed) {
  5656.                 unmatched.push(elem);
  5657.               }
  5658.             }
  5659.           }
  5660.           matchedCount += i;
  5661.           if (bySet && i !== matchedCount) {
  5662.             j = 0;
  5663.             while (matcher = setMatchers[j++]) {
  5664.               matcher(unmatched, setMatched, context, xml);
  5665.             }
  5666.             if (seed) {
  5667.               if (matchedCount > 0) {
  5668.                 while (i--) {
  5669.                   if (!(unmatched[i] || setMatched[i])) {
  5670.                     setMatched[i] = pop.call(results);
  5671.                   }
  5672.                 }
  5673.               }
  5674.               setMatched = condense(setMatched);
  5675.             }
  5676.             push$1.apply(results, setMatched);
  5677.             if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5678.               Sizzle.uniqueSort(results);
  5679.             }
  5680.           }
  5681.           if (outermost) {
  5682.             dirruns = dirrunsUnique;
  5683.             outermostContext = contextBackup;
  5684.           }
  5685.           return unmatched;
  5686.         };
  5687.       return bySet ? markFunction(superMatcher) : superMatcher;
  5688.     }
  5689.     compile = Sizzle.compile = function (selector, match) {
  5690.       var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5691.       if (!cached) {
  5692.         if (!match) {
  5693.           match = tokenize(selector);
  5694.         }
  5695.         i = match.length;
  5696.         while (i--) {
  5697.           cached = matcherFromTokens(match[i]);
  5698.           if (cached[expando]) {
  5699.             setMatchers.push(cached);
  5700.           } else {
  5701.             elementMatchers.push(cached);
  5702.           }
  5703.         }
  5704.         cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5705.         cached.selector = selector;
  5706.       }
  5707.       return cached;
  5708.     };
  5709.     select$1 = Sizzle.select = function (selector, context, results, seed) {
  5710.       var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  5711.       results = results || [];
  5712.       if (match.length === 1) {
  5713.         tokens = match[0] = match[0].slice(0);
  5714.         if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  5715.           context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  5716.           if (!context) {
  5717.             return results;
  5718.           } else if (compiled) {
  5719.             context = context.parentNode;
  5720.           }
  5721.           selector = selector.slice(tokens.shift().value.length);
  5722.         }
  5723.         i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  5724.         while (i--) {
  5725.           token = tokens[i];
  5726.           if (Expr.relative[type = token.type]) {
  5727.             break;
  5728.           }
  5729.           if (find = Expr.find[type]) {
  5730.             if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  5731.               tokens.splice(i, 1);
  5732.               selector = seed.length && toSelector(tokens);
  5733.               if (!selector) {
  5734.                 push$1.apply(results, seed);
  5735.                 return results;
  5736.               }
  5737.               break;
  5738.             }
  5739.           }
  5740.         }
  5741.       }
  5742.       (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  5743.       return results;
  5744.     };
  5745.     support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  5746.     support.detectDuplicates = !!hasDuplicate;
  5747.     setDocument();
  5748.     support.sortDetached = true;
  5749.  
  5750.     var doc = document;
  5751.     var push = Array.prototype.push;
  5752.     var slice = Array.prototype.slice;
  5753.     var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  5754.     var Event$1 = EventUtils.Event;
  5755.     var skipUniques = Tools.makeMap('children,contents,next,prev');
  5756.     var isDefined = function (obj) {
  5757.       return typeof obj !== 'undefined';
  5758.     };
  5759.     var isString = function (obj) {
  5760.       return typeof obj === 'string';
  5761.     };
  5762.     var isWindow = function (obj) {
  5763.       return obj && obj === obj.window;
  5764.     };
  5765.     var createFragment$1 = function (html, fragDoc) {
  5766.       fragDoc = fragDoc || doc;
  5767.       var container = fragDoc.createElement('div');
  5768.       var frag = fragDoc.createDocumentFragment();
  5769.       container.innerHTML = html;
  5770.       var node;
  5771.       while (node = container.firstChild) {
  5772.         frag.appendChild(node);
  5773.       }
  5774.       return frag;
  5775.     };
  5776.     var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  5777.       var i;
  5778.       if (isString(sourceItem)) {
  5779.         sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  5780.       } else if (sourceItem.length && !sourceItem.nodeType) {
  5781.         sourceItem = DomQuery.makeArray(sourceItem);
  5782.         if (reverse) {
  5783.           for (i = sourceItem.length - 1; i >= 0; i--) {
  5784.             domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5785.           }
  5786.         } else {
  5787.           for (i = 0; i < sourceItem.length; i++) {
  5788.             domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5789.           }
  5790.         }
  5791.         return targetNodes;
  5792.       }
  5793.       if (sourceItem.nodeType) {
  5794.         i = targetNodes.length;
  5795.         while (i--) {
  5796.           callback.call(targetNodes[i], sourceItem);
  5797.         }
  5798.       }
  5799.       return targetNodes;
  5800.     };
  5801.     var hasClass = function (node, className) {
  5802.       return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  5803.     };
  5804.     var wrap$2 = function (elements, wrapper, all) {
  5805.       var lastParent, newWrapper;
  5806.       wrapper = DomQuery(wrapper)[0];
  5807.       elements.each(function () {
  5808.         var self = this;
  5809.         if (!all || lastParent !== self.parentNode) {
  5810.           lastParent = self.parentNode;
  5811.           newWrapper = wrapper.cloneNode(false);
  5812.           self.parentNode.insertBefore(newWrapper, self);
  5813.           newWrapper.appendChild(self);
  5814.         } else {
  5815.           newWrapper.appendChild(self);
  5816.         }
  5817.       });
  5818.       return elements;
  5819.     };
  5820.     var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  5821.     var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  5822.     var propFix = {
  5823.       for: 'htmlFor',
  5824.       class: 'className',
  5825.       readonly: 'readOnly'
  5826.     };
  5827.     var cssFix = { float: 'cssFloat' };
  5828.     var attrHooks = {}, cssHooks = {};
  5829.     var DomQueryConstructor = function (selector, context) {
  5830.       return new DomQuery.fn.init(selector, context);
  5831.     };
  5832.     var inArray$1 = function (item, array) {
  5833.       var i;
  5834.       if (array.indexOf) {
  5835.         return array.indexOf(item);
  5836.       }
  5837.       i = array.length;
  5838.       while (i--) {
  5839.         if (array[i] === item) {
  5840.           return i;
  5841.         }
  5842.       }
  5843.       return -1;
  5844.     };
  5845.     var whiteSpaceRegExp = /^\s*|\s*$/g;
  5846.     var trim$1 = function (str) {
  5847.       return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  5848.     };
  5849.     var each$g = function (obj, callback) {
  5850.       var length, key, i, value;
  5851.       if (obj) {
  5852.         length = obj.length;
  5853.         if (length === undefined) {
  5854.           for (key in obj) {
  5855.             if (obj.hasOwnProperty(key)) {
  5856.               value = obj[key];
  5857.               if (callback.call(value, key, value) === false) {
  5858.                 break;
  5859.               }
  5860.             }
  5861.           }
  5862.         } else {
  5863.           for (i = 0; i < length; i++) {
  5864.             value = obj[i];
  5865.             if (callback.call(value, i, value) === false) {
  5866.               break;
  5867.             }
  5868.           }
  5869.         }
  5870.       }
  5871.       return obj;
  5872.     };
  5873.     var grep$2 = function (array, callback) {
  5874.       var out = [];
  5875.       each$g(array, function (i, item) {
  5876.         if (callback(item, i)) {
  5877.           out.push(item);
  5878.         }
  5879.       });
  5880.       return out;
  5881.     };
  5882.     var getElementDocument = function (element) {
  5883.       if (!element) {
  5884.         return doc;
  5885.       }
  5886.       if (element.nodeType === 9) {
  5887.         return element;
  5888.       }
  5889.       return element.ownerDocument;
  5890.     };
  5891.     DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  5892.       constructor: DomQueryConstructor,
  5893.       selector: '',
  5894.       context: null,
  5895.       length: 0,
  5896.       init: function (selector, context) {
  5897.         var self = this;
  5898.         var match, node;
  5899.         if (!selector) {
  5900.           return self;
  5901.         }
  5902.         if (selector.nodeType) {
  5903.           self.context = self[0] = selector;
  5904.           self.length = 1;
  5905.           return self;
  5906.         }
  5907.         if (context && context.nodeType) {
  5908.           self.context = context;
  5909.         } else {
  5910.           if (context) {
  5911.             return DomQuery(selector).attr(context);
  5912.           }
  5913.           self.context = context = document;
  5914.         }
  5915.         if (isString(selector)) {
  5916.           self.selector = selector;
  5917.           if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  5918.             match = [
  5919.               null,
  5920.               selector,
  5921.               null
  5922.             ];
  5923.           } else {
  5924.             match = rquickExpr.exec(selector);
  5925.           }
  5926.           if (match) {
  5927.             if (match[1]) {
  5928.               node = createFragment$1(selector, getElementDocument(context)).firstChild;
  5929.               while (node) {
  5930.                 push.call(self, node);
  5931.                 node = node.nextSibling;
  5932.               }
  5933.             } else {
  5934.               node = getElementDocument(context).getElementById(match[2]);
  5935.               if (!node) {
  5936.                 return self;
  5937.               }
  5938.               if (node.id !== match[2]) {
  5939.                 return self.find(selector);
  5940.               }
  5941.               self.length = 1;
  5942.               self[0] = node;
  5943.             }
  5944.           } else {
  5945.             return DomQuery(context).find(selector);
  5946.           }
  5947.         } else {
  5948.           this.add(selector, false);
  5949.         }
  5950.         return self;
  5951.       },
  5952.       toArray: function () {
  5953.         return Tools.toArray(this);
  5954.       },
  5955.       add: function (items, sort) {
  5956.         var self = this;
  5957.         var nodes, i;
  5958.         if (isString(items)) {
  5959.           return self.add(DomQuery(items));
  5960.         }
  5961.         if (sort !== false) {
  5962.           nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  5963.           self.length = nodes.length;
  5964.           for (i = 0; i < nodes.length; i++) {
  5965.             self[i] = nodes[i];
  5966.           }
  5967.         } else {
  5968.           push.apply(self, DomQuery.makeArray(items));
  5969.         }
  5970.         return self;
  5971.       },
  5972.       attr: function (name, value) {
  5973.         var self = this;
  5974.         var hook;
  5975.         if (typeof name === 'object') {
  5976.           each$g(name, function (name, value) {
  5977.             self.attr(name, value);
  5978.           });
  5979.         } else if (isDefined(value)) {
  5980.           this.each(function () {
  5981.             var hook;
  5982.             if (this.nodeType === 1) {
  5983.               hook = attrHooks[name];
  5984.               if (hook && hook.set) {
  5985.                 hook.set(this, value);
  5986.                 return;
  5987.               }
  5988.               if (value === null) {
  5989.                 this.removeAttribute(name, 2);
  5990.               } else {
  5991.                 this.setAttribute(name, value, 2);
  5992.               }
  5993.             }
  5994.           });
  5995.         } else {
  5996.           if (self[0] && self[0].nodeType === 1) {
  5997.             hook = attrHooks[name];
  5998.             if (hook && hook.get) {
  5999.               return hook.get(self[0], name);
  6000.             }
  6001.             if (booleanMap[name]) {
  6002.               return self.prop(name) ? name : undefined;
  6003.             }
  6004.             value = self[0].getAttribute(name, 2);
  6005.             if (value === null) {
  6006.               value = undefined;
  6007.             }
  6008.           }
  6009.           return value;
  6010.         }
  6011.         return self;
  6012.       },
  6013.       removeAttr: function (name) {
  6014.         return this.attr(name, null);
  6015.       },
  6016.       prop: function (name, value) {
  6017.         var self = this;
  6018.         name = propFix[name] || name;
  6019.         if (typeof name === 'object') {
  6020.           each$g(name, function (name, value) {
  6021.             self.prop(name, value);
  6022.           });
  6023.         } else if (isDefined(value)) {
  6024.           this.each(function () {
  6025.             if (this.nodeType === 1) {
  6026.               this[name] = value;
  6027.             }
  6028.           });
  6029.         } else {
  6030.           if (self[0] && self[0].nodeType && name in self[0]) {
  6031.             return self[0][name];
  6032.           }
  6033.           return value;
  6034.         }
  6035.         return self;
  6036.       },
  6037.       css: function (name, value) {
  6038.         var self = this;
  6039.         var elm, hook;
  6040.         var camel = function (name) {
  6041.           return name.replace(/-(\D)/g, function (a, b) {
  6042.             return b.toUpperCase();
  6043.           });
  6044.         };
  6045.         var dashed = function (name) {
  6046.           return name.replace(/[A-Z]/g, function (a) {
  6047.             return '-' + a;
  6048.           });
  6049.         };
  6050.         if (typeof name === 'object') {
  6051.           each$g(name, function (name, value) {
  6052.             self.css(name, value);
  6053.           });
  6054.         } else {
  6055.           if (isDefined(value)) {
  6056.             name = camel(name);
  6057.             if (typeof value === 'number' && !numericCssMap[name]) {
  6058.               value = value.toString() + 'px';
  6059.             }
  6060.             self.each(function () {
  6061.               var style = this.style;
  6062.               hook = cssHooks[name];
  6063.               if (hook && hook.set) {
  6064.                 hook.set(this, value);
  6065.                 return;
  6066.               }
  6067.               try {
  6068.                 this.style[cssFix[name] || name] = value;
  6069.               } catch (ex) {
  6070.               }
  6071.               if (value === null || value === '') {
  6072.                 if (style.removeProperty) {
  6073.                   style.removeProperty(dashed(name));
  6074.                 } else {
  6075.                   style.removeAttribute(name);
  6076.                 }
  6077.               }
  6078.             });
  6079.           } else {
  6080.             elm = self[0];
  6081.             hook = cssHooks[name];
  6082.             if (hook && hook.get) {
  6083.               return hook.get(elm);
  6084.             }
  6085.             if (elm.ownerDocument.defaultView) {
  6086.               try {
  6087.                 return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6088.               } catch (ex) {
  6089.                 return undefined;
  6090.               }
  6091.             } else if (elm.currentStyle) {
  6092.               return elm.currentStyle[camel(name)];
  6093.             } else {
  6094.               return '';
  6095.             }
  6096.           }
  6097.         }
  6098.         return self;
  6099.       },
  6100.       remove: function () {
  6101.         var self = this;
  6102.         var node, i = this.length;
  6103.         while (i--) {
  6104.           node = self[i];
  6105.           Event$1.clean(node);
  6106.           if (node.parentNode) {
  6107.             node.parentNode.removeChild(node);
  6108.           }
  6109.         }
  6110.         return this;
  6111.       },
  6112.       empty: function () {
  6113.         var self = this;
  6114.         var node, i = this.length;
  6115.         while (i--) {
  6116.           node = self[i];
  6117.           while (node.firstChild) {
  6118.             node.removeChild(node.firstChild);
  6119.           }
  6120.         }
  6121.         return this;
  6122.       },
  6123.       html: function (value) {
  6124.         var self = this;
  6125.         var i;
  6126.         if (isDefined(value)) {
  6127.           i = self.length;
  6128.           try {
  6129.             while (i--) {
  6130.               self[i].innerHTML = value;
  6131.             }
  6132.           } catch (ex) {
  6133.             DomQuery(self[i]).empty().append(value);
  6134.           }
  6135.           return self;
  6136.         }
  6137.         return self[0] ? self[0].innerHTML : '';
  6138.       },
  6139.       text: function (value) {
  6140.         var self = this;
  6141.         var i;
  6142.         if (isDefined(value)) {
  6143.           i = self.length;
  6144.           while (i--) {
  6145.             if ('innerText' in self[i]) {
  6146.               self[i].innerText = value;
  6147.             } else {
  6148.               self[0].textContent = value;
  6149.             }
  6150.           }
  6151.           return self;
  6152.         }
  6153.         return self[0] ? self[0].innerText || self[0].textContent : '';
  6154.       },
  6155.       append: function () {
  6156.         return domManipulate(this, arguments, function (node) {
  6157.           if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6158.             this.appendChild(node);
  6159.           }
  6160.         });
  6161.       },
  6162.       prepend: function () {
  6163.         return domManipulate(this, arguments, function (node) {
  6164.           if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6165.             this.insertBefore(node, this.firstChild);
  6166.           }
  6167.         }, true);
  6168.       },
  6169.       before: function () {
  6170.         var self = this;
  6171.         if (self[0] && self[0].parentNode) {
  6172.           return domManipulate(self, arguments, function (node) {
  6173.             this.parentNode.insertBefore(node, this);
  6174.           });
  6175.         }
  6176.         return self;
  6177.       },
  6178.       after: function () {
  6179.         var self = this;
  6180.         if (self[0] && self[0].parentNode) {
  6181.           return domManipulate(self, arguments, function (node) {
  6182.             this.parentNode.insertBefore(node, this.nextSibling);
  6183.           }, true);
  6184.         }
  6185.         return self;
  6186.       },
  6187.       appendTo: function (val) {
  6188.         DomQuery(val).append(this);
  6189.         return this;
  6190.       },
  6191.       prependTo: function (val) {
  6192.         DomQuery(val).prepend(this);
  6193.         return this;
  6194.       },
  6195.       replaceWith: function (content) {
  6196.         return this.before(content).remove();
  6197.       },
  6198.       wrap: function (content) {
  6199.         return wrap$2(this, content);
  6200.       },
  6201.       wrapAll: function (content) {
  6202.         return wrap$2(this, content, true);
  6203.       },
  6204.       wrapInner: function (content) {
  6205.         this.each(function () {
  6206.           DomQuery(this).contents().wrapAll(content);
  6207.         });
  6208.         return this;
  6209.       },
  6210.       unwrap: function () {
  6211.         return this.parent().each(function () {
  6212.           DomQuery(this).replaceWith(this.childNodes);
  6213.         });
  6214.       },
  6215.       clone: function () {
  6216.         var result = [];
  6217.         this.each(function () {
  6218.           result.push(this.cloneNode(true));
  6219.         });
  6220.         return DomQuery(result);
  6221.       },
  6222.       addClass: function (className) {
  6223.         return this.toggleClass(className, true);
  6224.       },
  6225.       removeClass: function (className) {
  6226.         return this.toggleClass(className, false);
  6227.       },
  6228.       toggleClass: function (className, state) {
  6229.         var self = this;
  6230.         if (typeof className !== 'string') {
  6231.           return self;
  6232.         }
  6233.         if (className.indexOf(' ') !== -1) {
  6234.           each$g(className.split(' '), function () {
  6235.             self.toggleClass(this, state);
  6236.           });
  6237.         } else {
  6238.           self.each(function (index, node) {
  6239.             var classState = hasClass(node, className);
  6240.             if (classState !== state) {
  6241.               var existingClassName = node.className;
  6242.               if (classState) {
  6243.                 node.className = trim$1((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6244.               } else {
  6245.                 node.className += existingClassName ? ' ' + className : className;
  6246.               }
  6247.             }
  6248.           });
  6249.         }
  6250.         return self;
  6251.       },
  6252.       hasClass: function (className) {
  6253.         return hasClass(this[0], className);
  6254.       },
  6255.       each: function (callback) {
  6256.         return each$g(this, callback);
  6257.       },
  6258.       on: function (name, callback) {
  6259.         return this.each(function () {
  6260.           Event$1.bind(this, name, callback);
  6261.         });
  6262.       },
  6263.       off: function (name, callback) {
  6264.         return this.each(function () {
  6265.           Event$1.unbind(this, name, callback);
  6266.         });
  6267.       },
  6268.       trigger: function (name) {
  6269.         return this.each(function () {
  6270.           if (typeof name === 'object') {
  6271.             Event$1.fire(this, name.type, name);
  6272.           } else {
  6273.             Event$1.fire(this, name);
  6274.           }
  6275.         });
  6276.       },
  6277.       show: function () {
  6278.         return this.css('display', '');
  6279.       },
  6280.       hide: function () {
  6281.         return this.css('display', 'none');
  6282.       },
  6283.       slice: function () {
  6284.         return DomQuery(slice.apply(this, arguments));
  6285.       },
  6286.       eq: function (index) {
  6287.         return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6288.       },
  6289.       first: function () {
  6290.         return this.eq(0);
  6291.       },
  6292.       last: function () {
  6293.         return this.eq(-1);
  6294.       },
  6295.       find: function (selector) {
  6296.         var i, l;
  6297.         var ret = [];
  6298.         for (i = 0, l = this.length; i < l; i++) {
  6299.           DomQuery.find(selector, this[i], ret);
  6300.         }
  6301.         return DomQuery(ret);
  6302.       },
  6303.       filter: function (selector) {
  6304.         if (typeof selector === 'function') {
  6305.           return DomQuery(grep$2(this.toArray(), function (item, i) {
  6306.             return selector(i, item);
  6307.           }));
  6308.         }
  6309.         return DomQuery(DomQuery.filter(selector, this.toArray()));
  6310.       },
  6311.       closest: function (selector) {
  6312.         var result = [];
  6313.         if (selector instanceof DomQuery) {
  6314.           selector = selector[0];
  6315.         }
  6316.         this.each(function (i, node) {
  6317.           while (node) {
  6318.             if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6319.               result.push(node);
  6320.               break;
  6321.             } else if (node === selector) {
  6322.               result.push(node);
  6323.               break;
  6324.             }
  6325.             node = node.parentNode;
  6326.           }
  6327.         });
  6328.         return DomQuery(result);
  6329.       },
  6330.       offset: function (offset) {
  6331.         var elm, doc, docElm;
  6332.         var x = 0, y = 0, pos;
  6333.         if (!offset) {
  6334.           elm = this[0];
  6335.           if (elm) {
  6336.             doc = elm.ownerDocument;
  6337.             docElm = doc.documentElement;
  6338.             if (elm.getBoundingClientRect) {
  6339.               pos = elm.getBoundingClientRect();
  6340.               x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6341.               y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6342.             }
  6343.           }
  6344.           return {
  6345.             left: x,
  6346.             top: y
  6347.           };
  6348.         }
  6349.         return this.css(offset);
  6350.       },
  6351.       push: push,
  6352.       sort: Array.prototype.sort,
  6353.       splice: Array.prototype.splice
  6354.     };
  6355.     Tools.extend(DomQueryConstructor, {
  6356.       extend: Tools.extend,
  6357.       makeArray: function (object) {
  6358.         if (isWindow(object) || object.nodeType) {
  6359.           return [object];
  6360.         }
  6361.         return Tools.toArray(object);
  6362.       },
  6363.       inArray: inArray$1,
  6364.       isArray: Tools.isArray,
  6365.       each: each$g,
  6366.       trim: trim$1,
  6367.       grep: grep$2,
  6368.       find: Sizzle,
  6369.       expr: Sizzle.selectors,
  6370.       unique: Sizzle.uniqueSort,
  6371.       text: Sizzle.getText,
  6372.       contains: Sizzle.contains,
  6373.       filter: function (expr, elems, not) {
  6374.         var i = elems.length;
  6375.         if (not) {
  6376.           expr = ':not(' + expr + ')';
  6377.         }
  6378.         while (i--) {
  6379.           if (elems[i].nodeType !== 1) {
  6380.             elems.splice(i, 1);
  6381.           }
  6382.         }
  6383.         if (elems.length === 1) {
  6384.           elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6385.         } else {
  6386.           elems = DomQuery.find.matches(expr, elems);
  6387.         }
  6388.         return elems;
  6389.       }
  6390.     });
  6391.     var dir = function (el, prop, until) {
  6392.       var matched = [];
  6393.       var cur = el[prop];
  6394.       if (typeof until !== 'string' && until instanceof DomQuery) {
  6395.         until = until[0];
  6396.       }
  6397.       while (cur && cur.nodeType !== 9) {
  6398.         if (until !== undefined) {
  6399.           if (cur === until) {
  6400.             break;
  6401.           }
  6402.           if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6403.             break;
  6404.           }
  6405.         }
  6406.         if (cur.nodeType === 1) {
  6407.           matched.push(cur);
  6408.         }
  6409.         cur = cur[prop];
  6410.       }
  6411.       return matched;
  6412.     };
  6413.     var sibling$1 = function (node, siblingName, nodeType, until) {
  6414.       var result = [];
  6415.       if (until instanceof DomQuery) {
  6416.         until = until[0];
  6417.       }
  6418.       for (; node; node = node[siblingName]) {
  6419.         if (nodeType && node.nodeType !== nodeType) {
  6420.           continue;
  6421.         }
  6422.         if (until !== undefined) {
  6423.           if (node === until) {
  6424.             break;
  6425.           }
  6426.           if (typeof until === 'string' && DomQuery(node).is(until)) {
  6427.             break;
  6428.           }
  6429.         }
  6430.         result.push(node);
  6431.       }
  6432.       return result;
  6433.     };
  6434.     var firstSibling = function (node, siblingName, nodeType) {
  6435.       for (node = node[siblingName]; node; node = node[siblingName]) {
  6436.         if (node.nodeType === nodeType) {
  6437.           return node;
  6438.         }
  6439.       }
  6440.       return null;
  6441.     };
  6442.     each$g({
  6443.       parent: function (node) {
  6444.         var parent = node.parentNode;
  6445.         return parent && parent.nodeType !== 11 ? parent : null;
  6446.       },
  6447.       parents: function (node) {
  6448.         return dir(node, 'parentNode');
  6449.       },
  6450.       next: function (node) {
  6451.         return firstSibling(node, 'nextSibling', 1);
  6452.       },
  6453.       prev: function (node) {
  6454.         return firstSibling(node, 'previousSibling', 1);
  6455.       },
  6456.       children: function (node) {
  6457.         return sibling$1(node.firstChild, 'nextSibling', 1);
  6458.       },
  6459.       contents: function (node) {
  6460.         return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6461.       }
  6462.     }, function (name, fn) {
  6463.       DomQueryConstructor.fn[name] = function (selector) {
  6464.         var self = this;
  6465.         var result = [];
  6466.         self.each(function () {
  6467.           var nodes = fn.call(result, this, selector, result);
  6468.           if (nodes) {
  6469.             if (DomQuery.isArray(nodes)) {
  6470.               result.push.apply(result, nodes);
  6471.             } else {
  6472.               result.push(nodes);
  6473.             }
  6474.           }
  6475.         });
  6476.         if (this.length > 1) {
  6477.           if (!skipUniques[name]) {
  6478.             result = DomQuery.unique(result);
  6479.           }
  6480.           if (name.indexOf('parents') === 0) {
  6481.             result = result.reverse();
  6482.           }
  6483.         }
  6484.         var wrappedResult = DomQuery(result);
  6485.         if (selector) {
  6486.           return wrappedResult.filter(selector);
  6487.         }
  6488.         return wrappedResult;
  6489.       };
  6490.     });
  6491.     each$g({
  6492.       parentsUntil: function (node, until) {
  6493.         return dir(node, 'parentNode', until);
  6494.       },
  6495.       nextUntil: function (node, until) {
  6496.         return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6497.       },
  6498.       prevUntil: function (node, until) {
  6499.         return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6500.       }
  6501.     }, function (name, fn) {
  6502.       DomQueryConstructor.fn[name] = function (selector, filter) {
  6503.         var self = this;
  6504.         var result = [];
  6505.         self.each(function () {
  6506.           var nodes = fn.call(result, this, selector, result);
  6507.           if (nodes) {
  6508.             if (DomQuery.isArray(nodes)) {
  6509.               result.push.apply(result, nodes);
  6510.             } else {
  6511.               result.push(nodes);
  6512.             }
  6513.           }
  6514.         });
  6515.         if (this.length > 1) {
  6516.           result = DomQuery.unique(result);
  6517.           if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6518.             result = result.reverse();
  6519.           }
  6520.         }
  6521.         var wrappedResult = DomQuery(result);
  6522.         if (filter) {
  6523.           return wrappedResult.filter(filter);
  6524.         }
  6525.         return wrappedResult;
  6526.       };
  6527.     });
  6528.     DomQueryConstructor.fn.is = function (selector) {
  6529.       return !!selector && this.filter(selector).length > 0;
  6530.     };
  6531.     DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6532.     DomQueryConstructor.overrideDefaults = function (callback) {
  6533.       var defaults;
  6534.       var sub = function (selector, context) {
  6535.         defaults = defaults || callback();
  6536.         if (arguments.length === 0) {
  6537.           selector = defaults.element;
  6538.         }
  6539.         if (!context) {
  6540.           context = defaults.context;
  6541.         }
  6542.         return new sub.fn.init(selector, context);
  6543.       };
  6544.       DomQuery.extend(sub, this);
  6545.       return sub;
  6546.     };
  6547.     DomQueryConstructor.attrHooks = attrHooks;
  6548.     DomQueryConstructor.cssHooks = cssHooks;
  6549.     var DomQuery = DomQueryConstructor;
  6550.  
  6551.     var each$f = Tools.each;
  6552.     var grep$1 = Tools.grep;
  6553.     var isIE = Env.ie;
  6554.     var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6555.     var setupAttrHooks = function (styles, settings, getContext) {
  6556.       var keepValues = settings.keep_values;
  6557.       var keepUrlHook = {
  6558.         set: function ($elm, value, name) {
  6559.           if (settings.url_converter && value !== null) {
  6560.             value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6561.           }
  6562.           $elm.attr('data-mce-' + name, value).attr(name, value);
  6563.         },
  6564.         get: function ($elm, name) {
  6565.           return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6566.         }
  6567.       };
  6568.       var attrHooks = {
  6569.         style: {
  6570.           set: function ($elm, value) {
  6571.             if (value !== null && typeof value === 'object') {
  6572.               $elm.css(value);
  6573.               return;
  6574.             }
  6575.             if (keepValues) {
  6576.               $elm.attr('data-mce-style', value);
  6577.             }
  6578.             if (value !== null && typeof value === 'string') {
  6579.               $elm.removeAttr('style');
  6580.               $elm.css(styles.parse(value));
  6581.             } else {
  6582.               $elm.attr('style', value);
  6583.             }
  6584.           },
  6585.           get: function ($elm) {
  6586.             var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6587.             value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6588.             return value;
  6589.           }
  6590.         }
  6591.       };
  6592.       if (keepValues) {
  6593.         attrHooks.href = attrHooks.src = keepUrlHook;
  6594.       }
  6595.       return attrHooks;
  6596.     };
  6597.     var updateInternalStyleAttr = function (styles, $elm) {
  6598.       var rawValue = $elm.attr('style');
  6599.       var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6600.       if (!value) {
  6601.         value = null;
  6602.       }
  6603.       $elm.attr('data-mce-style', value);
  6604.     };
  6605.     var findNodeIndex = function (node, normalized) {
  6606.       var idx = 0, lastNodeType, nodeType;
  6607.       if (node) {
  6608.         for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6609.           nodeType = node.nodeType;
  6610.           if (normalized && nodeType === 3) {
  6611.             if (nodeType === lastNodeType || !node.nodeValue.length) {
  6612.               continue;
  6613.             }
  6614.           }
  6615.           idx++;
  6616.           lastNodeType = nodeType;
  6617.         }
  6618.       }
  6619.       return idx;
  6620.     };
  6621.     var DOMUtils = function (doc, settings) {
  6622.       if (settings === void 0) {
  6623.         settings = {};
  6624.       }
  6625.       var addedStyles = {};
  6626.       var win = window;
  6627.       var files = {};
  6628.       var counter = 0;
  6629.       var stdMode = true;
  6630.       var boxModel = true;
  6631.       var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6632.         contentCssCors: settings.contentCssCors,
  6633.         referrerPolicy: settings.referrerPolicy
  6634.       });
  6635.       var boundEvents = [];
  6636.       var schema = settings.schema ? settings.schema : Schema({});
  6637.       var styles = Styles({
  6638.         url_converter: settings.url_converter,
  6639.         url_converter_scope: settings.url_converter_scope
  6640.       }, settings.schema);
  6641.       var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6642.       var blockElementsMap = schema.getBlockElements();
  6643.       var $ = DomQuery.overrideDefaults(function () {
  6644.         return {
  6645.           context: doc,
  6646.           element: self.getRoot()
  6647.         };
  6648.       });
  6649.       var isBlock = function (node) {
  6650.         if (typeof node === 'string') {
  6651.           return !!blockElementsMap[node];
  6652.         } else if (node) {
  6653.           var type = node.nodeType;
  6654.           if (type) {
  6655.             return !!(type === 1 && blockElementsMap[node.nodeName]);
  6656.           }
  6657.         }
  6658.         return false;
  6659.       };
  6660.       var get = function (elm) {
  6661.         return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  6662.       };
  6663.       var $$ = function (elm) {
  6664.         return $(typeof elm === 'string' ? get(elm) : elm);
  6665.       };
  6666.       var getAttrib = function (elm, name, defaultVal) {
  6667.         var hook, value;
  6668.         var $elm = $$(elm);
  6669.         if ($elm.length) {
  6670.           hook = attrHooks[name];
  6671.           if (hook && hook.get) {
  6672.             value = hook.get($elm, name);
  6673.           } else {
  6674.             value = $elm.attr(name);
  6675.           }
  6676.         }
  6677.         if (typeof value === 'undefined') {
  6678.           value = defaultVal || '';
  6679.         }
  6680.         return value;
  6681.       };
  6682.       var getAttribs = function (elm) {
  6683.         var node = get(elm);
  6684.         if (!node) {
  6685.           return [];
  6686.         }
  6687.         return node.attributes;
  6688.       };
  6689.       var setAttrib = function (elm, name, value) {
  6690.         if (value === '') {
  6691.           value = null;
  6692.         }
  6693.         var $elm = $$(elm);
  6694.         var originalValue = $elm.attr(name);
  6695.         if (!$elm.length) {
  6696.           return;
  6697.         }
  6698.         var hook = attrHooks[name];
  6699.         if (hook && hook.set) {
  6700.           hook.set($elm, value, name);
  6701.         } else {
  6702.           $elm.attr(name, value);
  6703.         }
  6704.         if (originalValue !== value && settings.onSetAttrib) {
  6705.           settings.onSetAttrib({
  6706.             attrElm: $elm,
  6707.             attrName: name,
  6708.             attrValue: value
  6709.           });
  6710.         }
  6711.       };
  6712.       var clone = function (node, deep) {
  6713.         if (!isIE || node.nodeType !== 1 || deep) {
  6714.           return node.cloneNode(deep);
  6715.         } else {
  6716.           var clone_1 = doc.createElement(node.nodeName);
  6717.           each$f(getAttribs(node), function (attr) {
  6718.             setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  6719.           });
  6720.           return clone_1;
  6721.         }
  6722.       };
  6723.       var getRoot = function () {
  6724.         return settings.root_element || doc.body;
  6725.       };
  6726.       var getViewPort = function (argWin) {
  6727.         var vp = getBounds(argWin);
  6728.         return {
  6729.           x: vp.x,
  6730.           y: vp.y,
  6731.           w: vp.width,
  6732.           h: vp.height
  6733.         };
  6734.       };
  6735.       var getPos$1 = function (elm, rootElm) {
  6736.         return getPos(doc.body, get(elm), rootElm);
  6737.       };
  6738.       var setStyle = function (elm, name, value) {
  6739.         var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  6740.         if (settings.update_styles) {
  6741.           updateInternalStyleAttr(styles, $elm);
  6742.         }
  6743.       };
  6744.       var setStyles = function (elm, stylesArg) {
  6745.         var $elm = $$(elm).css(stylesArg);
  6746.         if (settings.update_styles) {
  6747.           updateInternalStyleAttr(styles, $elm);
  6748.         }
  6749.       };
  6750.       var getStyle = function (elm, name, computed) {
  6751.         var $elm = $$(elm);
  6752.         if (computed) {
  6753.           return $elm.css(name);
  6754.         }
  6755.         name = name.replace(/-(\D)/g, function (a, b) {
  6756.           return b.toUpperCase();
  6757.         });
  6758.         if (name === 'float') {
  6759.           name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  6760.         }
  6761.         return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  6762.       };
  6763.       var getSize = function (elm) {
  6764.         var w, h;
  6765.         elm = get(elm);
  6766.         w = getStyle(elm, 'width');
  6767.         h = getStyle(elm, 'height');
  6768.         if (w.indexOf('px') === -1) {
  6769.           w = 0;
  6770.         }
  6771.         if (h.indexOf('px') === -1) {
  6772.           h = 0;
  6773.         }
  6774.         return {
  6775.           w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  6776.           h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  6777.         };
  6778.       };
  6779.       var getRect = function (elm) {
  6780.         elm = get(elm);
  6781.         var pos = getPos$1(elm);
  6782.         var size = getSize(elm);
  6783.         return {
  6784.           x: pos.x,
  6785.           y: pos.y,
  6786.           w: size.w,
  6787.           h: size.h
  6788.         };
  6789.       };
  6790.       var is = function (elm, selector) {
  6791.         var i;
  6792.         if (!elm) {
  6793.           return false;
  6794.         }
  6795.         if (!Array.isArray(elm)) {
  6796.           if (selector === '*') {
  6797.             return elm.nodeType === 1;
  6798.           }
  6799.           if (simpleSelectorRe.test(selector)) {
  6800.             var selectors = selector.toLowerCase().split(/,/);
  6801.             var elmName = elm.nodeName.toLowerCase();
  6802.             for (i = selectors.length - 1; i >= 0; i--) {
  6803.               if (selectors[i] === elmName) {
  6804.                 return true;
  6805.               }
  6806.             }
  6807.             return false;
  6808.           }
  6809.           if (elm.nodeType && elm.nodeType !== 1) {
  6810.             return false;
  6811.           }
  6812.         }
  6813.         var elms = !Array.isArray(elm) ? [elm] : elm;
  6814.         return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  6815.       };
  6816.       var getParents = function (elm, selector, root, collect) {
  6817.         var result = [];
  6818.         var selectorVal;
  6819.         var node = get(elm);
  6820.         collect = collect === undefined;
  6821.         root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  6822.         if (Tools.is(selector, 'string')) {
  6823.           selectorVal = selector;
  6824.           if (selector === '*') {
  6825.             selector = function (node) {
  6826.               return node.nodeType === 1;
  6827.             };
  6828.           } else {
  6829.             selector = function (node) {
  6830.               return is(node, selectorVal);
  6831.             };
  6832.           }
  6833.         }
  6834.         while (node) {
  6835.           if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  6836.             break;
  6837.           }
  6838.           if (!selector || typeof selector === 'function' && selector(node)) {
  6839.             if (collect) {
  6840.               result.push(node);
  6841.             } else {
  6842.               return [node];
  6843.             }
  6844.           }
  6845.           node = node.parentNode;
  6846.         }
  6847.         return collect ? result : null;
  6848.       };
  6849.       var getParent = function (node, selector, root) {
  6850.         var parents = getParents(node, selector, root, false);
  6851.         return parents && parents.length > 0 ? parents[0] : null;
  6852.       };
  6853.       var _findSib = function (node, selector, name) {
  6854.         var func = selector;
  6855.         if (node) {
  6856.           if (typeof selector === 'string') {
  6857.             func = function (node) {
  6858.               return is(node, selector);
  6859.             };
  6860.           }
  6861.           for (node = node[name]; node; node = node[name]) {
  6862.             if (typeof func === 'function' && func(node)) {
  6863.               return node;
  6864.             }
  6865.           }
  6866.         }
  6867.         return null;
  6868.       };
  6869.       var getNext = function (node, selector) {
  6870.         return _findSib(node, selector, 'nextSibling');
  6871.       };
  6872.       var getPrev = function (node, selector) {
  6873.         return _findSib(node, selector, 'previousSibling');
  6874.       };
  6875.       var select = function (selector, scope) {
  6876.         return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  6877.       };
  6878.       var run = function (elm, func, scope) {
  6879.         var result;
  6880.         var node = typeof elm === 'string' ? get(elm) : elm;
  6881.         if (!node) {
  6882.           return false;
  6883.         }
  6884.         if (Tools.isArray(node) && (node.length || node.length === 0)) {
  6885.           result = [];
  6886.           each$f(node, function (elm, i) {
  6887.             if (elm) {
  6888.               result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  6889.             }
  6890.           });
  6891.           return result;
  6892.         }
  6893.         var context = scope ? scope : this;
  6894.         return func.call(context, node);
  6895.       };
  6896.       var setAttribs = function (elm, attrs) {
  6897.         $$(elm).each(function (i, node) {
  6898.           each$f(attrs, function (value, name) {
  6899.             setAttrib(node, name, value);
  6900.           });
  6901.         });
  6902.       };
  6903.       var setHTML = function (elm, html) {
  6904.         var $elm = $$(elm);
  6905.         if (isIE) {
  6906.           $elm.each(function (i, target) {
  6907.             if (target.canHaveHTML === false) {
  6908.               return;
  6909.             }
  6910.             while (target.firstChild) {
  6911.               target.removeChild(target.firstChild);
  6912.             }
  6913.             try {
  6914.               target.innerHTML = '<br>' + html;
  6915.               target.removeChild(target.firstChild);
  6916.             } catch (ex) {
  6917.               DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  6918.             }
  6919.             return html;
  6920.           });
  6921.         } else {
  6922.           $elm.html(html);
  6923.         }
  6924.       };
  6925.       var add = function (parentElm, name, attrs, html, create) {
  6926.         return run(parentElm, function (parentElm) {
  6927.           var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  6928.           setAttribs(newElm, attrs);
  6929.           if (html) {
  6930.             if (typeof html !== 'string' && html.nodeType) {
  6931.               newElm.appendChild(html);
  6932.             } else if (typeof html === 'string') {
  6933.               setHTML(newElm, html);
  6934.             }
  6935.           }
  6936.           return !create ? parentElm.appendChild(newElm) : newElm;
  6937.         });
  6938.       };
  6939.       var create = function (name, attrs, html) {
  6940.         return add(doc.createElement(name), name, attrs, html, true);
  6941.       };
  6942.       var decode = Entities.decode;
  6943.       var encode = Entities.encodeAllRaw;
  6944.       var createHTML = function (name, attrs, html) {
  6945.         var outHtml = '', key;
  6946.         outHtml += '<' + name;
  6947.         for (key in attrs) {
  6948.           if (hasNonNullableKey(attrs, key)) {
  6949.             outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  6950.           }
  6951.         }
  6952.         if (typeof html !== 'undefined') {
  6953.           return outHtml + '>' + html + '</' + name + '>';
  6954.         }
  6955.         return outHtml + ' />';
  6956.       };
  6957.       var createFragment = function (html) {
  6958.         var node;
  6959.         var container = doc.createElement('div');
  6960.         var frag = doc.createDocumentFragment();
  6961.         frag.appendChild(container);
  6962.         if (html) {
  6963.           container.innerHTML = html;
  6964.         }
  6965.         while (node = container.firstChild) {
  6966.           frag.appendChild(node);
  6967.         }
  6968.         frag.removeChild(container);
  6969.         return frag;
  6970.       };
  6971.       var remove = function (node, keepChildren) {
  6972.         var $node = $$(node);
  6973.         if (keepChildren) {
  6974.           $node.each(function () {
  6975.             var child;
  6976.             while (child = this.firstChild) {
  6977.               if (child.nodeType === 3 && child.data.length === 0) {
  6978.                 this.removeChild(child);
  6979.               } else {
  6980.                 this.parentNode.insertBefore(child, this);
  6981.               }
  6982.             }
  6983.           }).remove();
  6984.         } else {
  6985.           $node.remove();
  6986.         }
  6987.         return $node.length > 1 ? $node.toArray() : $node[0];
  6988.       };
  6989.       var removeAllAttribs = function (e) {
  6990.         return run(e, function (e) {
  6991.           var i;
  6992.           var attrs = e.attributes;
  6993.           for (i = attrs.length - 1; i >= 0; i--) {
  6994.             e.removeAttributeNode(attrs.item(i));
  6995.           }
  6996.         });
  6997.       };
  6998.       var parseStyle = function (cssText) {
  6999.         return styles.parse(cssText);
  7000.       };
  7001.       var serializeStyle = function (stylesArg, name) {
  7002.         return styles.serialize(stylesArg, name);
  7003.       };
  7004.       var addStyle = function (cssText) {
  7005.         var head, styleElm;
  7006.         if (self !== DOMUtils.DOM && doc === document) {
  7007.           if (addedStyles[cssText]) {
  7008.             return;
  7009.           }
  7010.           addedStyles[cssText] = true;
  7011.         }
  7012.         styleElm = doc.getElementById('mceDefaultStyles');
  7013.         if (!styleElm) {
  7014.           styleElm = doc.createElement('style');
  7015.           styleElm.id = 'mceDefaultStyles';
  7016.           styleElm.type = 'text/css';
  7017.           head = doc.getElementsByTagName('head')[0];
  7018.           if (head.firstChild) {
  7019.             head.insertBefore(styleElm, head.firstChild);
  7020.           } else {
  7021.             head.appendChild(styleElm);
  7022.           }
  7023.         }
  7024.         if (styleElm.styleSheet) {
  7025.           styleElm.styleSheet.cssText += cssText;
  7026.         } else {
  7027.           styleElm.appendChild(doc.createTextNode(cssText));
  7028.         }
  7029.       };
  7030.       var loadCSS = function (urls) {
  7031.         if (!urls) {
  7032.           urls = '';
  7033.         }
  7034.         each$k(urls.split(','), function (url) {
  7035.           files[url] = true;
  7036.           styleSheetLoader.load(url, noop);
  7037.         });
  7038.       };
  7039.       var toggleClass = function (elm, cls, state) {
  7040.         $$(elm).toggleClass(cls, state).each(function () {
  7041.           if (this.className === '') {
  7042.             DomQuery(this).attr('class', null);
  7043.           }
  7044.         });
  7045.       };
  7046.       var addClass = function (elm, cls) {
  7047.         $$(elm).addClass(cls);
  7048.       };
  7049.       var removeClass = function (elm, cls) {
  7050.         toggleClass(elm, cls, false);
  7051.       };
  7052.       var hasClass = function (elm, cls) {
  7053.         return $$(elm).hasClass(cls);
  7054.       };
  7055.       var show = function (elm) {
  7056.         $$(elm).show();
  7057.       };
  7058.       var hide = function (elm) {
  7059.         $$(elm).hide();
  7060.       };
  7061.       var isHidden = function (elm) {
  7062.         return $$(elm).css('display') === 'none';
  7063.       };
  7064.       var uniqueId = function (prefix) {
  7065.         return (!prefix ? 'mce_' : prefix) + counter++;
  7066.       };
  7067.       var getOuterHTML = function (elm) {
  7068.         var node = typeof elm === 'string' ? get(elm) : elm;
  7069.         return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7070.       };
  7071.       var setOuterHTML = function (elm, html) {
  7072.         $$(elm).each(function () {
  7073.           try {
  7074.             if ('outerHTML' in this) {
  7075.               this.outerHTML = html;
  7076.               return;
  7077.             }
  7078.           } catch (ex) {
  7079.           }
  7080.           remove(DomQuery(this).html(html), true);
  7081.         });
  7082.       };
  7083.       var insertAfter = function (node, reference) {
  7084.         var referenceNode = get(reference);
  7085.         return run(node, function (node) {
  7086.           var parent = referenceNode.parentNode;
  7087.           var nextSibling = referenceNode.nextSibling;
  7088.           if (nextSibling) {
  7089.             parent.insertBefore(node, nextSibling);
  7090.           } else {
  7091.             parent.appendChild(node);
  7092.           }
  7093.           return node;
  7094.         });
  7095.       };
  7096.       var replace = function (newElm, oldElm, keepChildren) {
  7097.         return run(oldElm, function (oldElm) {
  7098.           if (Tools.is(oldElm, 'array')) {
  7099.             newElm = newElm.cloneNode(true);
  7100.           }
  7101.           if (keepChildren) {
  7102.             each$f(grep$1(oldElm.childNodes), function (node) {
  7103.               newElm.appendChild(node);
  7104.             });
  7105.           }
  7106.           return oldElm.parentNode.replaceChild(newElm, oldElm);
  7107.         });
  7108.       };
  7109.       var rename = function (elm, name) {
  7110.         var newElm;
  7111.         if (elm.nodeName !== name.toUpperCase()) {
  7112.           newElm = create(name);
  7113.           each$f(getAttribs(elm), function (attrNode) {
  7114.             setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7115.           });
  7116.           replace(newElm, elm, true);
  7117.         }
  7118.         return newElm || elm;
  7119.       };
  7120.       var findCommonAncestor = function (a, b) {
  7121.         var ps = a, pe;
  7122.         while (ps) {
  7123.           pe = b;
  7124.           while (pe && ps !== pe) {
  7125.             pe = pe.parentNode;
  7126.           }
  7127.           if (ps === pe) {
  7128.             break;
  7129.           }
  7130.           ps = ps.parentNode;
  7131.         }
  7132.         if (!ps && a.ownerDocument) {
  7133.           return a.ownerDocument.documentElement;
  7134.         }
  7135.         return ps;
  7136.       };
  7137.       var toHex = function (rgbVal) {
  7138.         return styles.toHex(Tools.trim(rgbVal));
  7139.       };
  7140.       var isNonEmptyElement = function (node) {
  7141.         if (isElement$5(node)) {
  7142.           var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7143.           if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7144.             return true;
  7145.           }
  7146.         }
  7147.         return false;
  7148.       };
  7149.       var isEmpty = function (node, elements) {
  7150.         var type, name, brCount = 0;
  7151.         if (isNonEmptyElement(node)) {
  7152.           return false;
  7153.         }
  7154.         node = node.firstChild;
  7155.         if (node) {
  7156.           var walker = new DomTreeWalker(node, node.parentNode);
  7157.           var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7158.           elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7159.           do {
  7160.             type = node.nodeType;
  7161.             if (isElement$5(node)) {
  7162.               var bogusVal = node.getAttribute('data-mce-bogus');
  7163.               if (bogusVal) {
  7164.                 node = walker.next(bogusVal === 'all');
  7165.                 continue;
  7166.               }
  7167.               name = node.nodeName.toLowerCase();
  7168.               if (elements && elements[name]) {
  7169.                 if (name === 'br') {
  7170.                   brCount++;
  7171.                   node = walker.next();
  7172.                   continue;
  7173.                 }
  7174.                 return false;
  7175.               }
  7176.               if (isNonEmptyElement(node)) {
  7177.                 return false;
  7178.               }
  7179.             }
  7180.             if (type === 8) {
  7181.               return false;
  7182.             }
  7183.             if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7184.               return false;
  7185.             }
  7186.             if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7187.               return false;
  7188.             }
  7189.             node = walker.next();
  7190.           } while (node);
  7191.         }
  7192.         return brCount <= 1;
  7193.       };
  7194.       var createRng = function () {
  7195.         return doc.createRange();
  7196.       };
  7197.       var split = function (parentElm, splitElm, replacementElm) {
  7198.         var range = createRng();
  7199.         var beforeFragment;
  7200.         var afterFragment;
  7201.         var parentNode;
  7202.         if (parentElm && splitElm) {
  7203.           range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7204.           range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7205.           beforeFragment = range.extractContents();
  7206.           range = createRng();
  7207.           range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7208.           range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7209.           afterFragment = range.extractContents();
  7210.           parentNode = parentElm.parentNode;
  7211.           parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7212.           if (replacementElm) {
  7213.             parentNode.insertBefore(replacementElm, parentElm);
  7214.           } else {
  7215.             parentNode.insertBefore(splitElm, parentElm);
  7216.           }
  7217.           parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7218.           remove(parentElm);
  7219.           return replacementElm || splitElm;
  7220.         }
  7221.       };
  7222.       var bind = function (target, name, func, scope) {
  7223.         if (Tools.isArray(target)) {
  7224.           var i = target.length;
  7225.           var rv = [];
  7226.           while (i--) {
  7227.             rv[i] = bind(target[i], name, func, scope);
  7228.           }
  7229.           return rv;
  7230.         }
  7231.         if (settings.collect && (target === doc || target === win)) {
  7232.           boundEvents.push([
  7233.             target,
  7234.             name,
  7235.             func,
  7236.             scope
  7237.           ]);
  7238.         }
  7239.         var output = events.bind(target, name, func, scope || self);
  7240.         return output;
  7241.       };
  7242.       var unbind = function (target, name, func) {
  7243.         if (Tools.isArray(target)) {
  7244.           var i = target.length;
  7245.           var rv = [];
  7246.           while (i--) {
  7247.             rv[i] = unbind(target[i], name, func);
  7248.           }
  7249.           return rv;
  7250.         } else {
  7251.           if (boundEvents.length > 0 && (target === doc || target === win)) {
  7252.             var i = boundEvents.length;
  7253.             while (i--) {
  7254.               var item = boundEvents[i];
  7255.               if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7256.                 events.unbind(item[0], item[1], item[2]);
  7257.               }
  7258.             }
  7259.           }
  7260.           return events.unbind(target, name, func);
  7261.         }
  7262.       };
  7263.       var fire = function (target, name, evt) {
  7264.         return events.fire(target, name, evt);
  7265.       };
  7266.       var getContentEditable = function (node) {
  7267.         if (node && isElement$5(node)) {
  7268.           var contentEditable = node.getAttribute('data-mce-contenteditable');
  7269.           if (contentEditable && contentEditable !== 'inherit') {
  7270.             return contentEditable;
  7271.           }
  7272.           return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7273.         } else {
  7274.           return null;
  7275.         }
  7276.       };
  7277.       var getContentEditableParent = function (node) {
  7278.         var root = getRoot();
  7279.         var state = null;
  7280.         for (; node && node !== root; node = node.parentNode) {
  7281.           state = getContentEditable(node);
  7282.           if (state !== null) {
  7283.             break;
  7284.           }
  7285.         }
  7286.         return state;
  7287.       };
  7288.       var destroy = function () {
  7289.         if (boundEvents.length > 0) {
  7290.           var i = boundEvents.length;
  7291.           while (i--) {
  7292.             var item = boundEvents[i];
  7293.             events.unbind(item[0], item[1], item[2]);
  7294.           }
  7295.         }
  7296.         each$j(files, function (_, url) {
  7297.           styleSheetLoader.unload(url);
  7298.           delete files[url];
  7299.         });
  7300.         if (Sizzle.setDocument) {
  7301.           Sizzle.setDocument();
  7302.         }
  7303.       };
  7304.       var isChildOf = function (node, parent) {
  7305.         if (!isIE) {
  7306.           return node === parent || parent.contains(node);
  7307.         } else {
  7308.           while (node) {
  7309.             if (parent === node) {
  7310.               return true;
  7311.             }
  7312.             node = node.parentNode;
  7313.           }
  7314.           return false;
  7315.         }
  7316.       };
  7317.       var dumpRng = function (r) {
  7318.         return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7319.       };
  7320.       var self = {
  7321.         doc: doc,
  7322.         settings: settings,
  7323.         win: win,
  7324.         files: files,
  7325.         stdMode: stdMode,
  7326.         boxModel: boxModel,
  7327.         styleSheetLoader: styleSheetLoader,
  7328.         boundEvents: boundEvents,
  7329.         styles: styles,
  7330.         schema: schema,
  7331.         events: events,
  7332.         isBlock: isBlock,
  7333.         $: $,
  7334.         $$: $$,
  7335.         root: null,
  7336.         clone: clone,
  7337.         getRoot: getRoot,
  7338.         getViewPort: getViewPort,
  7339.         getRect: getRect,
  7340.         getSize: getSize,
  7341.         getParent: getParent,
  7342.         getParents: getParents,
  7343.         get: get,
  7344.         getNext: getNext,
  7345.         getPrev: getPrev,
  7346.         select: select,
  7347.         is: is,
  7348.         add: add,
  7349.         create: create,
  7350.         createHTML: createHTML,
  7351.         createFragment: createFragment,
  7352.         remove: remove,
  7353.         setStyle: setStyle,
  7354.         getStyle: getStyle,
  7355.         setStyles: setStyles,
  7356.         removeAllAttribs: removeAllAttribs,
  7357.         setAttrib: setAttrib,
  7358.         setAttribs: setAttribs,
  7359.         getAttrib: getAttrib,
  7360.         getPos: getPos$1,
  7361.         parseStyle: parseStyle,
  7362.         serializeStyle: serializeStyle,
  7363.         addStyle: addStyle,
  7364.         loadCSS: loadCSS,
  7365.         addClass: addClass,
  7366.         removeClass: removeClass,
  7367.         hasClass: hasClass,
  7368.         toggleClass: toggleClass,
  7369.         show: show,
  7370.         hide: hide,
  7371.         isHidden: isHidden,
  7372.         uniqueId: uniqueId,
  7373.         setHTML: setHTML,
  7374.         getOuterHTML: getOuterHTML,
  7375.         setOuterHTML: setOuterHTML,
  7376.         decode: decode,
  7377.         encode: encode,
  7378.         insertAfter: insertAfter,
  7379.         replace: replace,
  7380.         rename: rename,
  7381.         findCommonAncestor: findCommonAncestor,
  7382.         toHex: toHex,
  7383.         run: run,
  7384.         getAttribs: getAttribs,
  7385.         isEmpty: isEmpty,
  7386.         createRng: createRng,
  7387.         nodeIndex: findNodeIndex,
  7388.         split: split,
  7389.         bind: bind,
  7390.         unbind: unbind,
  7391.         fire: fire,
  7392.         getContentEditable: getContentEditable,
  7393.         getContentEditableParent: getContentEditableParent,
  7394.         destroy: destroy,
  7395.         isChildOf: isChildOf,
  7396.         dumpRng: dumpRng
  7397.       };
  7398.       var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7399.       return self;
  7400.     };
  7401.     DOMUtils.DOM = DOMUtils(document);
  7402.     DOMUtils.nodeIndex = findNodeIndex;
  7403.  
  7404.     var DOM$a = DOMUtils.DOM;
  7405.     var each$e = Tools.each, grep = Tools.grep;
  7406.     var QUEUED = 0;
  7407.     var LOADING = 1;
  7408.     var LOADED = 2;
  7409.     var FAILED = 3;
  7410.     var ScriptLoader = function () {
  7411.       function ScriptLoader(settings) {
  7412.         if (settings === void 0) {
  7413.           settings = {};
  7414.         }
  7415.         this.states = {};
  7416.         this.queue = [];
  7417.         this.scriptLoadedCallbacks = {};
  7418.         this.queueLoadedCallbacks = [];
  7419.         this.loading = 0;
  7420.         this.settings = settings;
  7421.       }
  7422.       ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7423.         this.settings.referrerPolicy = referrerPolicy;
  7424.       };
  7425.       ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7426.         var dom = DOM$a;
  7427.         var elm;
  7428.         var cleanup = function () {
  7429.           dom.remove(id);
  7430.           if (elm) {
  7431.             elm.onerror = elm.onload = elm = null;
  7432.           }
  7433.         };
  7434.         var done = function () {
  7435.           cleanup();
  7436.           success();
  7437.         };
  7438.         var error = function () {
  7439.           cleanup();
  7440.           if (isFunction(failure)) {
  7441.             failure();
  7442.           } else {
  7443.             if (typeof console !== 'undefined' && console.log) {
  7444.               console.log('Failed to load script: ' + url);
  7445.             }
  7446.           }
  7447.         };
  7448.         var id = dom.uniqueId();
  7449.         elm = document.createElement('script');
  7450.         elm.id = id;
  7451.         elm.type = 'text/javascript';
  7452.         elm.src = Tools._addCacheSuffix(url);
  7453.         if (this.settings.referrerPolicy) {
  7454.           dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7455.         }
  7456.         elm.onload = done;
  7457.         elm.onerror = error;
  7458.         (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7459.       };
  7460.       ScriptLoader.prototype.isDone = function (url) {
  7461.         return this.states[url] === LOADED;
  7462.       };
  7463.       ScriptLoader.prototype.markDone = function (url) {
  7464.         this.states[url] = LOADED;
  7465.       };
  7466.       ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7467.         var state = this.states[url];
  7468.         this.queue.push(url);
  7469.         if (state === undefined) {
  7470.           this.states[url] = QUEUED;
  7471.         }
  7472.         if (success) {
  7473.           if (!this.scriptLoadedCallbacks[url]) {
  7474.             this.scriptLoadedCallbacks[url] = [];
  7475.           }
  7476.           this.scriptLoadedCallbacks[url].push({
  7477.             success: success,
  7478.             failure: failure,
  7479.             scope: scope || this
  7480.           });
  7481.         }
  7482.       };
  7483.       ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7484.         return this.add(url, success, scope, failure);
  7485.       };
  7486.       ScriptLoader.prototype.remove = function (url) {
  7487.         delete this.states[url];
  7488.         delete this.scriptLoadedCallbacks[url];
  7489.       };
  7490.       ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7491.         this.loadScripts(this.queue, success, scope, failure);
  7492.       };
  7493.       ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7494.         var self = this;
  7495.         var failures = [];
  7496.         var execCallbacks = function (name, url) {
  7497.           each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7498.             if (isFunction(callback[name])) {
  7499.               callback[name].call(callback.scope);
  7500.             }
  7501.           });
  7502.           self.scriptLoadedCallbacks[url] = undefined;
  7503.         };
  7504.         self.queueLoadedCallbacks.push({
  7505.           success: success,
  7506.           failure: failure,
  7507.           scope: scope || this
  7508.         });
  7509.         var loadScripts = function () {
  7510.           var loadingScripts = grep(scripts);
  7511.           scripts.length = 0;
  7512.           each$e(loadingScripts, function (url) {
  7513.             if (self.states[url] === LOADED) {
  7514.               execCallbacks('success', url);
  7515.               return;
  7516.             }
  7517.             if (self.states[url] === FAILED) {
  7518.               execCallbacks('failure', url);
  7519.               return;
  7520.             }
  7521.             if (self.states[url] !== LOADING) {
  7522.               self.states[url] = LOADING;
  7523.               self.loading++;
  7524.               self.loadScript(url, function () {
  7525.                 self.states[url] = LOADED;
  7526.                 self.loading--;
  7527.                 execCallbacks('success', url);
  7528.                 loadScripts();
  7529.               }, function () {
  7530.                 self.states[url] = FAILED;
  7531.                 self.loading--;
  7532.                 failures.push(url);
  7533.                 execCallbacks('failure', url);
  7534.                 loadScripts();
  7535.               });
  7536.             }
  7537.           });
  7538.           if (!self.loading) {
  7539.             var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7540.             self.queueLoadedCallbacks.length = 0;
  7541.             each$e(notifyCallbacks, function (callback) {
  7542.               if (failures.length === 0) {
  7543.                 if (isFunction(callback.success)) {
  7544.                   callback.success.call(callback.scope);
  7545.                 }
  7546.               } else {
  7547.                 if (isFunction(callback.failure)) {
  7548.                   callback.failure.call(callback.scope, failures);
  7549.                 }
  7550.               }
  7551.             });
  7552.           }
  7553.         };
  7554.         loadScripts();
  7555.       };
  7556.       ScriptLoader.ScriptLoader = new ScriptLoader();
  7557.       return ScriptLoader;
  7558.     }();
  7559.  
  7560.     var Cell = function (initial) {
  7561.       var value = initial;
  7562.       var get = function () {
  7563.         return value;
  7564.       };
  7565.       var set = function (v) {
  7566.         value = v;
  7567.       };
  7568.       return {
  7569.         get: get,
  7570.         set: set
  7571.       };
  7572.     };
  7573.  
  7574.     var isRaw = function (str) {
  7575.       return isObject(str) && has$2(str, 'raw');
  7576.     };
  7577.     var isTokenised = function (str) {
  7578.       return isArray$1(str) && str.length > 1;
  7579.     };
  7580.     var data = {};
  7581.     var currentCode = Cell('en');
  7582.     var getLanguageData = function () {
  7583.       return get$9(data, currentCode.get());
  7584.     };
  7585.     var getData = function () {
  7586.       return map$2(data, function (value) {
  7587.         return __assign({}, value);
  7588.       });
  7589.     };
  7590.     var setCode = function (newCode) {
  7591.       if (newCode) {
  7592.         currentCode.set(newCode);
  7593.       }
  7594.     };
  7595.     var getCode = function () {
  7596.       return currentCode.get();
  7597.     };
  7598.     var add$4 = function (code, items) {
  7599.       var langData = data[code];
  7600.       if (!langData) {
  7601.         data[code] = langData = {};
  7602.       }
  7603.       each$j(items, function (translation, name) {
  7604.         langData[name.toLowerCase()] = translation;
  7605.       });
  7606.     };
  7607.     var translate = function (text) {
  7608.       var langData = getLanguageData().getOr({});
  7609.       var toString = function (obj) {
  7610.         if (isFunction(obj)) {
  7611.           return Object.prototype.toString.call(obj);
  7612.         }
  7613.         return !isEmpty(obj) ? '' + obj : '';
  7614.       };
  7615.       var isEmpty = function (text) {
  7616.         return text === '' || text === null || text === undefined;
  7617.       };
  7618.       var getLangData = function (text) {
  7619.         var textstr = toString(text);
  7620.         return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7621.       };
  7622.       var removeContext = function (str) {
  7623.         return str.replace(/{context:\w+}$/, '');
  7624.       };
  7625.       if (isEmpty(text)) {
  7626.         return '';
  7627.       }
  7628.       if (isRaw(text)) {
  7629.         return toString(text.raw);
  7630.       }
  7631.       if (isTokenised(text)) {
  7632.         var values_1 = text.slice(1);
  7633.         var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7634.           return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  7635.         });
  7636.         return removeContext(substitued);
  7637.       }
  7638.       return removeContext(getLangData(text));
  7639.     };
  7640.     var isRtl$1 = function () {
  7641.       return getLanguageData().bind(function (items) {
  7642.         return get$9(items, '_dir');
  7643.       }).exists(function (dir) {
  7644.         return dir === 'rtl';
  7645.       });
  7646.     };
  7647.     var hasCode = function (code) {
  7648.       return has$2(data, code);
  7649.     };
  7650.     var I18n = {
  7651.       getData: getData,
  7652.       setCode: setCode,
  7653.       getCode: getCode,
  7654.       add: add$4,
  7655.       translate: translate,
  7656.       isRtl: isRtl$1,
  7657.       hasCode: hasCode
  7658.     };
  7659.  
  7660.     var AddOnManager = function () {
  7661.       var items = [];
  7662.       var urls = {};
  7663.       var lookup = {};
  7664.       var _listeners = [];
  7665.       var runListeners = function (name, state) {
  7666.         var matchedListeners = filter$4(_listeners, function (listener) {
  7667.           return listener.name === name && listener.state === state;
  7668.         });
  7669.         each$k(matchedListeners, function (listener) {
  7670.           return listener.callback();
  7671.         });
  7672.       };
  7673.       var get = function (name) {
  7674.         if (lookup[name]) {
  7675.           return lookup[name].instance;
  7676.         }
  7677.         return undefined;
  7678.       };
  7679.       var dependencies = function (name) {
  7680.         var result;
  7681.         if (lookup[name]) {
  7682.           result = lookup[name].dependencies;
  7683.         }
  7684.         return result || [];
  7685.       };
  7686.       var requireLangPack = function (name, languages) {
  7687.         if (AddOnManager.languageLoad !== false) {
  7688.           waitFor(name, function () {
  7689.             var language = I18n.getCode();
  7690.             var wrappedLanguages = ',' + (languages || '') + ',';
  7691.             if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7692.               return;
  7693.             }
  7694.             ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7695.           }, 'loaded');
  7696.         }
  7697.       };
  7698.       var add = function (id, addOn, dependencies) {
  7699.         var addOnConstructor = addOn;
  7700.         items.push(addOnConstructor);
  7701.         lookup[id] = {
  7702.           instance: addOnConstructor,
  7703.           dependencies: dependencies
  7704.         };
  7705.         runListeners(id, 'added');
  7706.         return addOnConstructor;
  7707.       };
  7708.       var remove = function (name) {
  7709.         delete urls[name];
  7710.         delete lookup[name];
  7711.       };
  7712.       var createUrl = function (baseUrl, dep) {
  7713.         if (typeof dep === 'object') {
  7714.           return dep;
  7715.         }
  7716.         return typeof baseUrl === 'string' ? {
  7717.           prefix: '',
  7718.           resource: dep,
  7719.           suffix: ''
  7720.         } : {
  7721.           prefix: baseUrl.prefix,
  7722.           resource: dep,
  7723.           suffix: baseUrl.suffix
  7724.         };
  7725.       };
  7726.       var addComponents = function (pluginName, scripts) {
  7727.         var pluginUrl = urls[pluginName];
  7728.         each$k(scripts, function (script) {
  7729.           ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  7730.         });
  7731.       };
  7732.       var loadDependencies = function (name, addOnUrl, success, scope) {
  7733.         var deps = dependencies(name);
  7734.         each$k(deps, function (dep) {
  7735.           var newUrl = createUrl(addOnUrl, dep);
  7736.           load(newUrl.resource, newUrl, undefined, undefined);
  7737.         });
  7738.         if (success) {
  7739.           if (scope) {
  7740.             success.call(scope);
  7741.           } else {
  7742.             success.call(ScriptLoader);
  7743.           }
  7744.         }
  7745.       };
  7746.       var load = function (name, addOnUrl, success, scope, failure) {
  7747.         if (urls[name]) {
  7748.           return;
  7749.         }
  7750.         var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  7751.         if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  7752.           urlString = AddOnManager.baseURL + '/' + urlString;
  7753.         }
  7754.         urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  7755.         var done = function () {
  7756.           runListeners(name, 'loaded');
  7757.           loadDependencies(name, addOnUrl, success, scope);
  7758.         };
  7759.         if (lookup[name]) {
  7760.           done();
  7761.         } else {
  7762.           ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  7763.         }
  7764.       };
  7765.       var waitFor = function (name, callback, state) {
  7766.         if (state === void 0) {
  7767.           state = 'added';
  7768.         }
  7769.         if (has$2(lookup, name) && state === 'added') {
  7770.           callback();
  7771.         } else if (has$2(urls, name) && state === 'loaded') {
  7772.           callback();
  7773.         } else {
  7774.           _listeners.push({
  7775.             name: name,
  7776.             state: state,
  7777.             callback: callback
  7778.           });
  7779.         }
  7780.       };
  7781.       return {
  7782.         items: items,
  7783.         urls: urls,
  7784.         lookup: lookup,
  7785.         _listeners: _listeners,
  7786.         get: get,
  7787.         dependencies: dependencies,
  7788.         requireLangPack: requireLangPack,
  7789.         add: add,
  7790.         remove: remove,
  7791.         createUrl: createUrl,
  7792.         addComponents: addComponents,
  7793.         load: load,
  7794.         waitFor: waitFor
  7795.       };
  7796.     };
  7797.     AddOnManager.languageLoad = true;
  7798.     AddOnManager.baseURL = '';
  7799.     AddOnManager.PluginManager = AddOnManager();
  7800.     AddOnManager.ThemeManager = AddOnManager();
  7801.  
  7802.     var singleton = function (doRevoke) {
  7803.       var subject = Cell(Optional.none());
  7804.       var revoke = function () {
  7805.         return subject.get().each(doRevoke);
  7806.       };
  7807.       var clear = function () {
  7808.         revoke();
  7809.         subject.set(Optional.none());
  7810.       };
  7811.       var isSet = function () {
  7812.         return subject.get().isSome();
  7813.       };
  7814.       var get = function () {
  7815.         return subject.get();
  7816.       };
  7817.       var set = function (s) {
  7818.         revoke();
  7819.         subject.set(Optional.some(s));
  7820.       };
  7821.       return {
  7822.         clear: clear,
  7823.         isSet: isSet,
  7824.         get: get,
  7825.         set: set
  7826.       };
  7827.     };
  7828.     var value = function () {
  7829.       var subject = singleton(noop);
  7830.       var on = function (f) {
  7831.         return subject.get().each(f);
  7832.       };
  7833.       return __assign(__assign({}, subject), { on: on });
  7834.     };
  7835.  
  7836.     var first = function (fn, rate) {
  7837.       var timer = null;
  7838.       var cancel = function () {
  7839.         if (!isNull(timer)) {
  7840.           clearTimeout(timer);
  7841.           timer = null;
  7842.         }
  7843.       };
  7844.       var throttle = function () {
  7845.         var args = [];
  7846.         for (var _i = 0; _i < arguments.length; _i++) {
  7847.           args[_i] = arguments[_i];
  7848.         }
  7849.         if (isNull(timer)) {
  7850.           timer = setTimeout(function () {
  7851.             timer = null;
  7852.             fn.apply(null, args);
  7853.           }, rate);
  7854.         }
  7855.       };
  7856.       return {
  7857.         cancel: cancel,
  7858.         throttle: throttle
  7859.       };
  7860.     };
  7861.     var last = function (fn, rate) {
  7862.       var timer = null;
  7863.       var cancel = function () {
  7864.         if (!isNull(timer)) {
  7865.           clearTimeout(timer);
  7866.           timer = null;
  7867.         }
  7868.       };
  7869.       var throttle = function () {
  7870.         var args = [];
  7871.         for (var _i = 0; _i < arguments.length; _i++) {
  7872.           args[_i] = arguments[_i];
  7873.         }
  7874.         cancel();
  7875.         timer = setTimeout(function () {
  7876.           timer = null;
  7877.           fn.apply(null, args);
  7878.         }, rate);
  7879.       };
  7880.       return {
  7881.         cancel: cancel,
  7882.         throttle: throttle
  7883.       };
  7884.     };
  7885.  
  7886.     var read$4 = function (element, attr) {
  7887.       var value = get$6(element, attr);
  7888.       return value === undefined || value === '' ? [] : value.split(' ');
  7889.     };
  7890.     var add$3 = function (element, attr, id) {
  7891.       var old = read$4(element, attr);
  7892.       var nu = old.concat([id]);
  7893.       set$1(element, attr, nu.join(' '));
  7894.       return true;
  7895.     };
  7896.     var remove$5 = function (element, attr, id) {
  7897.       var nu = filter$4(read$4(element, attr), function (v) {
  7898.         return v !== id;
  7899.       });
  7900.       if (nu.length > 0) {
  7901.         set$1(element, attr, nu.join(' '));
  7902.       } else {
  7903.         remove$6(element, attr);
  7904.       }
  7905.       return false;
  7906.     };
  7907.  
  7908.     var supports = function (element) {
  7909.       return element.dom.classList !== undefined;
  7910.     };
  7911.     var get$4 = function (element) {
  7912.       return read$4(element, 'class');
  7913.     };
  7914.     var add$2 = function (element, clazz) {
  7915.       return add$3(element, 'class', clazz);
  7916.     };
  7917.     var remove$4 = function (element, clazz) {
  7918.       return remove$5(element, 'class', clazz);
  7919.     };
  7920.  
  7921.     var add$1 = function (element, clazz) {
  7922.       if (supports(element)) {
  7923.         element.dom.classList.add(clazz);
  7924.       } else {
  7925.         add$2(element, clazz);
  7926.       }
  7927.     };
  7928.     var cleanClass = function (element) {
  7929.       var classList = supports(element) ? element.dom.classList : get$4(element);
  7930.       if (classList.length === 0) {
  7931.         remove$6(element, 'class');
  7932.       }
  7933.     };
  7934.     var remove$3 = function (element, clazz) {
  7935.       if (supports(element)) {
  7936.         var classList = element.dom.classList;
  7937.         classList.remove(clazz);
  7938.       } else {
  7939.         remove$4(element, clazz);
  7940.       }
  7941.       cleanClass(element);
  7942.     };
  7943.     var has = function (element, clazz) {
  7944.       return supports(element) && element.dom.classList.contains(clazz);
  7945.     };
  7946.  
  7947.     var descendants$1 = function (scope, predicate) {
  7948.       var result = [];
  7949.       each$k(children(scope), function (x) {
  7950.         if (predicate(x)) {
  7951.           result = result.concat([x]);
  7952.         }
  7953.         result = result.concat(descendants$1(x, predicate));
  7954.       });
  7955.       return result;
  7956.     };
  7957.  
  7958.     var descendants = function (scope, selector) {
  7959.       return all(selector, scope);
  7960.     };
  7961.  
  7962.     var annotation = constant('mce-annotation');
  7963.     var dataAnnotation = constant('data-mce-annotation');
  7964.     var dataAnnotationId = constant('data-mce-annotation-uid');
  7965.  
  7966.     var identify = function (editor, annotationName) {
  7967.       var rng = editor.selection.getRng();
  7968.       var start = SugarElement.fromDom(rng.startContainer);
  7969.       var root = SugarElement.fromDom(editor.getBody());
  7970.       var selector = annotationName.fold(function () {
  7971.         return '.' + annotation();
  7972.       }, function (an) {
  7973.         return '[' + dataAnnotation() + '="' + an + '"]';
  7974.       });
  7975.       var newStart = child$1(start, rng.startOffset).getOr(start);
  7976.       var closest = closest$2(newStart, selector, function (n) {
  7977.         return eq(n, root);
  7978.       });
  7979.       var getAttr = function (c, property) {
  7980.         if (has$1(c, property)) {
  7981.           return Optional.some(get$6(c, property));
  7982.         } else {
  7983.           return Optional.none();
  7984.         }
  7985.       };
  7986.       return closest.bind(function (c) {
  7987.         return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  7988.           return getAttr(c, '' + dataAnnotation()).map(function (name) {
  7989.             var elements = findMarkers(editor, uid);
  7990.             return {
  7991.               uid: uid,
  7992.               name: name,
  7993.               elements: elements
  7994.             };
  7995.           });
  7996.         });
  7997.       });
  7998.     };
  7999.     var isAnnotation = function (elem) {
  8000.       return isElement$6(elem) && has(elem, annotation());
  8001.     };
  8002.     var findMarkers = function (editor, uid) {
  8003.       var body = SugarElement.fromDom(editor.getBody());
  8004.       return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  8005.     };
  8006.     var findAll = function (editor, name) {
  8007.       var body = SugarElement.fromDom(editor.getBody());
  8008.       var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  8009.       var directory = {};
  8010.       each$k(markers, function (m) {
  8011.         var uid = get$6(m, dataAnnotationId());
  8012.         var nodesAlready = get$9(directory, uid).getOr([]);
  8013.         directory[uid] = nodesAlready.concat([m]);
  8014.       });
  8015.       return directory;
  8016.     };
  8017.  
  8018.     var setup$n = function (editor, _registry) {
  8019.       var changeCallbacks = Cell({});
  8020.       var initData = function () {
  8021.         return {
  8022.           listeners: [],
  8023.           previous: value()
  8024.         };
  8025.       };
  8026.       var withCallbacks = function (name, f) {
  8027.         updateCallbacks(name, function (data) {
  8028.           f(data);
  8029.           return data;
  8030.         });
  8031.       };
  8032.       var updateCallbacks = function (name, f) {
  8033.         var callbackMap = changeCallbacks.get();
  8034.         var data = get$9(callbackMap, name).getOrThunk(initData);
  8035.         var outputData = f(data);
  8036.         callbackMap[name] = outputData;
  8037.         changeCallbacks.set(callbackMap);
  8038.       };
  8039.       var fireCallbacks = function (name, uid, elements) {
  8040.         withCallbacks(name, function (data) {
  8041.           each$k(data.listeners, function (f) {
  8042.             return f(true, name, {
  8043.               uid: uid,
  8044.               nodes: map$3(elements, function (elem) {
  8045.                 return elem.dom;
  8046.               })
  8047.             });
  8048.           });
  8049.         });
  8050.       };
  8051.       var fireNoAnnotation = function (name) {
  8052.         withCallbacks(name, function (data) {
  8053.           each$k(data.listeners, function (f) {
  8054.             return f(false, name);
  8055.           });
  8056.         });
  8057.       };
  8058.       var onNodeChange = last(function () {
  8059.         var callbackMap = changeCallbacks.get();
  8060.         var annotations = sort(keys(callbackMap));
  8061.         each$k(annotations, function (name) {
  8062.           updateCallbacks(name, function (data) {
  8063.             var prev = data.previous.get();
  8064.             identify(editor, Optional.some(name)).fold(function () {
  8065.               if (prev.isSome()) {
  8066.                 fireNoAnnotation(name);
  8067.                 data.previous.clear();
  8068.               }
  8069.             }, function (_a) {
  8070.               var uid = _a.uid, name = _a.name, elements = _a.elements;
  8071.               if (!is$1(prev, uid)) {
  8072.                 fireCallbacks(name, uid, elements);
  8073.                 data.previous.set(uid);
  8074.               }
  8075.             });
  8076.             return {
  8077.               previous: data.previous,
  8078.               listeners: data.listeners
  8079.             };
  8080.           });
  8081.         });
  8082.       }, 30);
  8083.       editor.on('remove', function () {
  8084.         onNodeChange.cancel();
  8085.       });
  8086.       editor.on('NodeChange', function () {
  8087.         onNodeChange.throttle();
  8088.       });
  8089.       var addListener = function (name, f) {
  8090.         updateCallbacks(name, function (data) {
  8091.           return {
  8092.             previous: data.previous,
  8093.             listeners: data.listeners.concat([f])
  8094.           };
  8095.         });
  8096.       };
  8097.       return { addListener: addListener };
  8098.     };
  8099.  
  8100.     var setup$m = function (editor, registry) {
  8101.       var identifyParserNode = function (span) {
  8102.         return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8103.       };
  8104.       editor.on('init', function () {
  8105.         editor.serializer.addNodeFilter('span', function (spans) {
  8106.           each$k(spans, function (span) {
  8107.             identifyParserNode(span).each(function (settings) {
  8108.               if (settings.persistent === false) {
  8109.                 span.unwrap();
  8110.               }
  8111.             });
  8112.           });
  8113.         });
  8114.       });
  8115.     };
  8116.  
  8117.     var create$7 = function () {
  8118.       var annotations = {};
  8119.       var register = function (name, settings) {
  8120.         annotations[name] = {
  8121.           name: name,
  8122.           settings: settings
  8123.         };
  8124.       };
  8125.       var lookup = function (name) {
  8126.         return get$9(annotations, name).map(function (a) {
  8127.           return a.settings;
  8128.         });
  8129.       };
  8130.       return {
  8131.         register: register,
  8132.         lookup: lookup
  8133.       };
  8134.     };
  8135.  
  8136.     var unique = 0;
  8137.     var generate = function (prefix) {
  8138.       var date = new Date();
  8139.       var time = date.getTime();
  8140.       var random = Math.floor(Math.random() * 1000000000);
  8141.       unique++;
  8142.       return prefix + '_' + random + unique + String(time);
  8143.     };
  8144.  
  8145.     var add = function (element, classes) {
  8146.       each$k(classes, function (x) {
  8147.         add$1(element, x);
  8148.       });
  8149.     };
  8150.  
  8151.     var fromHtml = function (html, scope) {
  8152.       var doc = scope || document;
  8153.       var div = doc.createElement('div');
  8154.       div.innerHTML = html;
  8155.       return children(SugarElement.fromDom(div));
  8156.     };
  8157.     var fromDom$1 = function (nodes) {
  8158.       return map$3(nodes, SugarElement.fromDom);
  8159.     };
  8160.  
  8161.     var get$3 = function (element) {
  8162.       return element.dom.innerHTML;
  8163.     };
  8164.     var set = function (element, content) {
  8165.       var owner = owner$1(element);
  8166.       var docDom = owner.dom;
  8167.       var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8168.       var contentElements = fromHtml(content, docDom);
  8169.       append(fragment, contentElements);
  8170.       empty(element);
  8171.       append$1(element, fragment);
  8172.     };
  8173.  
  8174.     var clone$1 = function (original, isDeep) {
  8175.       return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8176.     };
  8177.     var shallow = function (original) {
  8178.       return clone$1(original, false);
  8179.     };
  8180.     var deep$1 = function (original) {
  8181.       return clone$1(original, true);
  8182.     };
  8183.  
  8184.     var TextWalker = function (startNode, rootNode, isBoundary) {
  8185.       if (isBoundary === void 0) {
  8186.         isBoundary = never;
  8187.       }
  8188.       var walker = new DomTreeWalker(startNode, rootNode);
  8189.       var walk = function (direction) {
  8190.         var next;
  8191.         do {
  8192.           next = walker[direction]();
  8193.         } while (next && !isText$7(next) && !isBoundary(next));
  8194.         return Optional.from(next).filter(isText$7);
  8195.       };
  8196.       return {
  8197.         current: function () {
  8198.           return Optional.from(walker.current()).filter(isText$7);
  8199.         },
  8200.         next: function () {
  8201.           return walk('next');
  8202.         },
  8203.         prev: function () {
  8204.           return walk('prev');
  8205.         },
  8206.         prev2: function () {
  8207.           return walk('prev2');
  8208.         }
  8209.       };
  8210.     };
  8211.  
  8212.     var TextSeeker = function (dom, isBoundary) {
  8213.       var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8214.         return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8215.       };
  8216.       var walk = function (node, offset, walker, process) {
  8217.         if (isText$7(node)) {
  8218.           var newOffset = process(node, offset, node.data);
  8219.           if (newOffset !== -1) {
  8220.             return Optional.some({
  8221.               container: node,
  8222.               offset: newOffset
  8223.             });
  8224.           }
  8225.         }
  8226.         return walker().bind(function (next) {
  8227.           return walk(next.container, next.offset, walker, process);
  8228.         });
  8229.       };
  8230.       var backwards = function (node, offset, process, root) {
  8231.         var walker = TextWalker(node, root, isBlockBoundary);
  8232.         return walk(node, offset, function () {
  8233.           return walker.prev().map(function (prev) {
  8234.             return {
  8235.               container: prev,
  8236.               offset: prev.length
  8237.             };
  8238.           });
  8239.         }, process).getOrNull();
  8240.       };
  8241.       var forwards = function (node, offset, process, root) {
  8242.         var walker = TextWalker(node, root, isBlockBoundary);
  8243.         return walk(node, offset, function () {
  8244.           return walker.next().map(function (next) {
  8245.             return {
  8246.               container: next,
  8247.               offset: 0
  8248.             };
  8249.           });
  8250.         }, process).getOrNull();
  8251.       };
  8252.       return {
  8253.         backwards: backwards,
  8254.         forwards: forwards
  8255.       };
  8256.     };
  8257.  
  8258.     var round$2 = Math.round;
  8259.     var clone = function (rect) {
  8260.       if (!rect) {
  8261.         return {
  8262.           left: 0,
  8263.           top: 0,
  8264.           bottom: 0,
  8265.           right: 0,
  8266.           width: 0,
  8267.           height: 0
  8268.         };
  8269.       }
  8270.       return {
  8271.         left: round$2(rect.left),
  8272.         top: round$2(rect.top),
  8273.         bottom: round$2(rect.bottom),
  8274.         right: round$2(rect.right),
  8275.         width: round$2(rect.width),
  8276.         height: round$2(rect.height)
  8277.       };
  8278.     };
  8279.     var collapse = function (rect, toStart) {
  8280.       rect = clone(rect);
  8281.       if (toStart) {
  8282.         rect.right = rect.left;
  8283.       } else {
  8284.         rect.left = rect.left + rect.width;
  8285.         rect.right = rect.left;
  8286.       }
  8287.       rect.width = 0;
  8288.       return rect;
  8289.     };
  8290.     var isEqual = function (rect1, rect2) {
  8291.       return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8292.     };
  8293.     var isValidOverflow = function (overflowY, rect1, rect2) {
  8294.       return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8295.     };
  8296.     var isAbove$1 = function (rect1, rect2) {
  8297.       var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8298.       if (rect1.bottom - halfHeight < rect2.top) {
  8299.         return true;
  8300.       }
  8301.       if (rect1.top > rect2.bottom) {
  8302.         return false;
  8303.       }
  8304.       return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8305.     };
  8306.     var isBelow$1 = function (rect1, rect2) {
  8307.       if (rect1.top > rect2.bottom) {
  8308.         return true;
  8309.       }
  8310.       if (rect1.bottom < rect2.top) {
  8311.         return false;
  8312.       }
  8313.       return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8314.     };
  8315.     var containsXY = function (rect, clientX, clientY) {
  8316.       return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8317.     };
  8318.  
  8319.     var clamp$2 = function (value, min, max) {
  8320.       return Math.min(Math.max(value, min), max);
  8321.     };
  8322.  
  8323.     var getSelectedNode = function (range) {
  8324.       var startContainer = range.startContainer, startOffset = range.startOffset;
  8325.       if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8326.         return startContainer.childNodes[startOffset];
  8327.       }
  8328.       return null;
  8329.     };
  8330.     var getNode$1 = function (container, offset) {
  8331.       if (isElement$5(container) && container.hasChildNodes()) {
  8332.         var childNodes = container.childNodes;
  8333.         var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8334.         return childNodes[safeOffset];
  8335.       } else {
  8336.         return container;
  8337.       }
  8338.     };
  8339.     var getNodeUnsafe = function (container, offset) {
  8340.       if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8341.         return undefined;
  8342.       } else {
  8343.         return getNode$1(container, offset);
  8344.       }
  8345.     };
  8346.  
  8347.     var extendingChars = new RegExp('[\u0300-\u036f\u0483-\u0487\u0488-\u0489\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u0610-\u061a' + '\u064b-\u065f\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7-\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0' + '\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e3-\u0902\u093a\u093c' + '\u0941-\u0948\u094d\u0951-\u0957\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\u0c00\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55-\u0c56' + '\u0c62-\u0c63\u0c81\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc-\u0ccd\u0cd5-\u0cd6\u0ce2-\u0ce3\u0d01\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\u0f8d-\u0f97' + '\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039-\u103a\u103d-\u103e\u1058-\u1059\u105e-\u1060\u1071-\u1074' + '\u1082\u1085-\u1086\u108d\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752-\u1753\u1772-\u1773\u17b4-\u17b5' + '\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927-\u1928\u1932\u1939-\u193b\u1a17-\u1a18' + '\u1a1b\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1ab0-\u1abd\u1ABE\u1b00-\u1b03\u1b34' + '\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80-\u1b81\u1ba2-\u1ba5\u1ba8-\u1ba9\u1bab-\u1bad\u1be6\u1be8-\u1be9' + '\u1bed\u1bef-\u1bf1\u1c2c-\u1c33\u1c36-\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1cf4\u1cf8-\u1cf9' + '\u1dc0-\u1df5\u1dfc-\u1dff\u200c-\u200d\u20d0-\u20dc\u20DD-\u20E0\u20e1\u20E2-\u20E4\u20e5-\u20f0\u2cef-\u2cf1' + '\u2d7f\u2de0-\u2dff\u302a-\u302d\u302e-\u302f\u3099-\u309a\ua66f\uA670-\uA672\ua674-\ua67d\ua69e-\ua69f\ua6f0-\ua6f1' + '\ua802\ua806\ua80b\ua825-\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc' + '\ua9e5\uaa29-\uaa2e\uaa31-\uaa32\uaa35-\uaa36\uaa43\uaa4c\uaa7c\uaab0\uaab2-\uaab4\uaab7-\uaab8\uaabe-\uaabf\uaac1' + '\uaaec-\uaaed\uaaf6\uabe5\uabe8\uabed\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\uff9e-\uff9f]');
  8348.     var isExtendingChar = function (ch) {
  8349.       return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8350.     };
  8351.  
  8352.     var or = function () {
  8353.       var args = [];
  8354.       for (var _i = 0; _i < arguments.length; _i++) {
  8355.         args[_i] = arguments[_i];
  8356.       }
  8357.       return function (x) {
  8358.         for (var i = 0; i < args.length; i++) {
  8359.           if (args[i](x)) {
  8360.             return true;
  8361.           }
  8362.         }
  8363.         return false;
  8364.       };
  8365.     };
  8366.     var and = function () {
  8367.       var args = [];
  8368.       for (var _i = 0; _i < arguments.length; _i++) {
  8369.         args[_i] = arguments[_i];
  8370.       }
  8371.       return function (x) {
  8372.         for (var i = 0; i < args.length; i++) {
  8373.           if (!args[i](x)) {
  8374.             return false;
  8375.           }
  8376.         }
  8377.         return true;
  8378.       };
  8379.     };
  8380.  
  8381.     var isElement$3 = isElement$5;
  8382.     var isCaretCandidate$2 = isCaretCandidate$3;
  8383.     var isBlock$1 = matchStyleValues('display', 'block table');
  8384.     var isFloated = matchStyleValues('float', 'left right');
  8385.     var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8386.     var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8387.     var isText$4 = isText$7;
  8388.     var isBr$2 = isBr$5;
  8389.     var nodeIndex$1 = DOMUtils.nodeIndex;
  8390.     var resolveIndex$1 = getNodeUnsafe;
  8391.     var createRange$1 = function (doc) {
  8392.       return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8393.     };
  8394.     var isWhiteSpace$1 = function (chr) {
  8395.       return chr && /[\r\n\t ]/.test(chr);
  8396.     };
  8397.     var isRange = function (rng) {
  8398.       return !!rng.setStart && !!rng.setEnd;
  8399.     };
  8400.     var isHiddenWhiteSpaceRange = function (range) {
  8401.       var container = range.startContainer;
  8402.       var offset = range.startOffset;
  8403.       if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8404.         var text = container.data;
  8405.         if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8406.           return true;
  8407.         }
  8408.       }
  8409.       return false;
  8410.     };
  8411.     var getBrClientRect = function (brNode) {
  8412.       var doc = brNode.ownerDocument;
  8413.       var rng = createRange$1(doc);
  8414.       var nbsp$1 = doc.createTextNode(nbsp);
  8415.       var parentNode = brNode.parentNode;
  8416.       parentNode.insertBefore(nbsp$1, brNode);
  8417.       rng.setStart(nbsp$1, 0);
  8418.       rng.setEnd(nbsp$1, 1);
  8419.       var clientRect = clone(rng.getBoundingClientRect());
  8420.       parentNode.removeChild(nbsp$1);
  8421.       return clientRect;
  8422.     };
  8423.     var getBoundingClientRectWebKitText = function (rng) {
  8424.       var sc = rng.startContainer;
  8425.       var ec = rng.endContainer;
  8426.       var so = rng.startOffset;
  8427.       var eo = rng.endOffset;
  8428.       if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8429.         var newRng = rng.cloneRange();
  8430.         newRng.setEndAfter(ec);
  8431.         return getBoundingClientRect$1(newRng);
  8432.       } else {
  8433.         return null;
  8434.       }
  8435.     };
  8436.     var isZeroRect = function (r) {
  8437.       return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8438.     };
  8439.     var getBoundingClientRect$1 = function (item) {
  8440.       var clientRect;
  8441.       var clientRects = item.getClientRects();
  8442.       if (clientRects.length > 0) {
  8443.         clientRect = clone(clientRects[0]);
  8444.       } else {
  8445.         clientRect = clone(item.getBoundingClientRect());
  8446.       }
  8447.       if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8448.         return getBrClientRect(item);
  8449.       }
  8450.       if (isZeroRect(clientRect) && isRange(item)) {
  8451.         return getBoundingClientRectWebKitText(item);
  8452.       }
  8453.       return clientRect;
  8454.     };
  8455.     var collapseAndInflateWidth = function (clientRect, toStart) {
  8456.       var newClientRect = collapse(clientRect, toStart);
  8457.       newClientRect.width = 1;
  8458.       newClientRect.right = newClientRect.left + 1;
  8459.       return newClientRect;
  8460.     };
  8461.     var getCaretPositionClientRects = function (caretPosition) {
  8462.       var clientRects = [];
  8463.       var addUniqueAndValidRect = function (clientRect) {
  8464.         if (clientRect.height === 0) {
  8465.           return;
  8466.         }
  8467.         if (clientRects.length > 0) {
  8468.           if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8469.             return;
  8470.           }
  8471.         }
  8472.         clientRects.push(clientRect);
  8473.       };
  8474.       var addCharacterOffset = function (container, offset) {
  8475.         var range = createRange$1(container.ownerDocument);
  8476.         if (offset < container.data.length) {
  8477.           if (isExtendingChar(container.data[offset])) {
  8478.             return clientRects;
  8479.           }
  8480.           if (isExtendingChar(container.data[offset - 1])) {
  8481.             range.setStart(container, offset);
  8482.             range.setEnd(container, offset + 1);
  8483.             if (!isHiddenWhiteSpaceRange(range)) {
  8484.               addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8485.               return clientRects;
  8486.             }
  8487.           }
  8488.         }
  8489.         if (offset > 0) {
  8490.           range.setStart(container, offset - 1);
  8491.           range.setEnd(container, offset);
  8492.           if (!isHiddenWhiteSpaceRange(range)) {
  8493.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8494.           }
  8495.         }
  8496.         if (offset < container.data.length) {
  8497.           range.setStart(container, offset);
  8498.           range.setEnd(container, offset + 1);
  8499.           if (!isHiddenWhiteSpaceRange(range)) {
  8500.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8501.           }
  8502.         }
  8503.       };
  8504.       var container = caretPosition.container();
  8505.       var offset = caretPosition.offset();
  8506.       if (isText$4(container)) {
  8507.         addCharacterOffset(container, offset);
  8508.         return clientRects;
  8509.       }
  8510.       if (isElement$3(container)) {
  8511.         if (caretPosition.isAtEnd()) {
  8512.           var node = resolveIndex$1(container, offset);
  8513.           if (isText$4(node)) {
  8514.             addCharacterOffset(node, node.data.length);
  8515.           }
  8516.           if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8517.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8518.           }
  8519.         } else {
  8520.           var node = resolveIndex$1(container, offset);
  8521.           if (isText$4(node)) {
  8522.             addCharacterOffset(node, 0);
  8523.           }
  8524.           if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8525.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8526.             return clientRects;
  8527.           }
  8528.           var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8529.           if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8530.             if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8531.               addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8532.             }
  8533.           }
  8534.           if (isValidElementCaretCandidate(node)) {
  8535.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8536.           }
  8537.         }
  8538.       }
  8539.       return clientRects;
  8540.     };
  8541.     var CaretPosition = function (container, offset, clientRects) {
  8542.       var isAtStart = function () {
  8543.         if (isText$4(container)) {
  8544.           return offset === 0;
  8545.         }
  8546.         return offset === 0;
  8547.       };
  8548.       var isAtEnd = function () {
  8549.         if (isText$4(container)) {
  8550.           return offset >= container.data.length;
  8551.         }
  8552.         return offset >= container.childNodes.length;
  8553.       };
  8554.       var toRange = function () {
  8555.         var range = createRange$1(container.ownerDocument);
  8556.         range.setStart(container, offset);
  8557.         range.setEnd(container, offset);
  8558.         return range;
  8559.       };
  8560.       var getClientRects = function () {
  8561.         if (!clientRects) {
  8562.           clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8563.         }
  8564.         return clientRects;
  8565.       };
  8566.       var isVisible = function () {
  8567.         return getClientRects().length > 0;
  8568.       };
  8569.       var isEqual = function (caretPosition) {
  8570.         return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8571.       };
  8572.       var getNode = function (before) {
  8573.         return resolveIndex$1(container, before ? offset - 1 : offset);
  8574.       };
  8575.       return {
  8576.         container: constant(container),
  8577.         offset: constant(offset),
  8578.         toRange: toRange,
  8579.         getClientRects: getClientRects,
  8580.         isVisible: isVisible,
  8581.         isAtStart: isAtStart,
  8582.         isAtEnd: isAtEnd,
  8583.         isEqual: isEqual,
  8584.         getNode: getNode
  8585.       };
  8586.     };
  8587.     CaretPosition.fromRangeStart = function (range) {
  8588.       return CaretPosition(range.startContainer, range.startOffset);
  8589.     };
  8590.     CaretPosition.fromRangeEnd = function (range) {
  8591.       return CaretPosition(range.endContainer, range.endOffset);
  8592.     };
  8593.     CaretPosition.after = function (node) {
  8594.       return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8595.     };
  8596.     CaretPosition.before = function (node) {
  8597.       return CaretPosition(node.parentNode, nodeIndex$1(node));
  8598.     };
  8599.     CaretPosition.isAbove = function (pos1, pos2) {
  8600.       return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8601.     };
  8602.     CaretPosition.isBelow = function (pos1, pos2) {
  8603.       return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8604.     };
  8605.     CaretPosition.isAtStart = function (pos) {
  8606.       return pos ? pos.isAtStart() : false;
  8607.     };
  8608.     CaretPosition.isAtEnd = function (pos) {
  8609.       return pos ? pos.isAtEnd() : false;
  8610.     };
  8611.     CaretPosition.isTextPosition = function (pos) {
  8612.       return pos ? isText$7(pos.container()) : false;
  8613.     };
  8614.     CaretPosition.isElementPosition = function (pos) {
  8615.       return CaretPosition.isTextPosition(pos) === false;
  8616.     };
  8617.  
  8618.     var trimEmptyTextNode$1 = function (dom, node) {
  8619.       if (isText$7(node) && node.data.length === 0) {
  8620.         dom.remove(node);
  8621.       }
  8622.     };
  8623.     var insertNode = function (dom, rng, node) {
  8624.       rng.insertNode(node);
  8625.       trimEmptyTextNode$1(dom, node.previousSibling);
  8626.       trimEmptyTextNode$1(dom, node.nextSibling);
  8627.     };
  8628.     var insertFragment = function (dom, rng, frag) {
  8629.       var firstChild = Optional.from(frag.firstChild);
  8630.       var lastChild = Optional.from(frag.lastChild);
  8631.       rng.insertNode(frag);
  8632.       firstChild.each(function (child) {
  8633.         return trimEmptyTextNode$1(dom, child.previousSibling);
  8634.       });
  8635.       lastChild.each(function (child) {
  8636.         return trimEmptyTextNode$1(dom, child.nextSibling);
  8637.       });
  8638.     };
  8639.     var rangeInsertNode = function (dom, rng, node) {
  8640.       if (isDocumentFragment(node)) {
  8641.         insertFragment(dom, rng, node);
  8642.       } else {
  8643.         insertNode(dom, rng, node);
  8644.       }
  8645.     };
  8646.  
  8647.     var isText$3 = isText$7;
  8648.     var isBogus = isBogus$2;
  8649.     var nodeIndex = DOMUtils.nodeIndex;
  8650.     var normalizedParent = function (node) {
  8651.       var parentNode = node.parentNode;
  8652.       if (isBogus(parentNode)) {
  8653.         return normalizedParent(parentNode);
  8654.       }
  8655.       return parentNode;
  8656.     };
  8657.     var getChildNodes = function (node) {
  8658.       if (!node) {
  8659.         return [];
  8660.       }
  8661.       return reduce(node.childNodes, function (result, node) {
  8662.         if (isBogus(node) && node.nodeName !== 'BR') {
  8663.           result = result.concat(getChildNodes(node));
  8664.         } else {
  8665.           result.push(node);
  8666.         }
  8667.         return result;
  8668.       }, []);
  8669.     };
  8670.     var normalizedTextOffset = function (node, offset) {
  8671.       while (node = node.previousSibling) {
  8672.         if (!isText$3(node)) {
  8673.           break;
  8674.         }
  8675.         offset += node.data.length;
  8676.       }
  8677.       return offset;
  8678.     };
  8679.     var equal = function (a) {
  8680.       return function (b) {
  8681.         return a === b;
  8682.       };
  8683.     };
  8684.     var normalizedNodeIndex = function (node) {
  8685.       var nodes, index;
  8686.       nodes = getChildNodes(normalizedParent(node));
  8687.       index = findIndex$1(nodes, equal(node), node);
  8688.       nodes = nodes.slice(0, index + 1);
  8689.       var numTextFragments = reduce(nodes, function (result, node, i) {
  8690.         if (isText$3(node) && isText$3(nodes[i - 1])) {
  8691.           result++;
  8692.         }
  8693.         return result;
  8694.       }, 0);
  8695.       nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8696.       index = findIndex$1(nodes, equal(node), node);
  8697.       return index - numTextFragments;
  8698.     };
  8699.     var createPathItem = function (node) {
  8700.       var name;
  8701.       if (isText$3(node)) {
  8702.         name = 'text()';
  8703.       } else {
  8704.         name = node.nodeName.toLowerCase();
  8705.       }
  8706.       return name + '[' + normalizedNodeIndex(node) + ']';
  8707.     };
  8708.     var parentsUntil$1 = function (root, node, predicate) {
  8709.       var parents = [];
  8710.       for (node = node.parentNode; node !== root; node = node.parentNode) {
  8711.         if (predicate && predicate(node)) {
  8712.           break;
  8713.         }
  8714.         parents.push(node);
  8715.       }
  8716.       return parents;
  8717.     };
  8718.     var create$6 = function (root, caretPosition) {
  8719.       var container, offset, path = [], outputOffset, childNodes, parents;
  8720.       container = caretPosition.container();
  8721.       offset = caretPosition.offset();
  8722.       if (isText$3(container)) {
  8723.         outputOffset = normalizedTextOffset(container, offset);
  8724.       } else {
  8725.         childNodes = container.childNodes;
  8726.         if (offset >= childNodes.length) {
  8727.           outputOffset = 'after';
  8728.           offset = childNodes.length - 1;
  8729.         } else {
  8730.           outputOffset = 'before';
  8731.         }
  8732.         container = childNodes[offset];
  8733.       }
  8734.       path.push(createPathItem(container));
  8735.       parents = parentsUntil$1(root, container);
  8736.       parents = filter$2(parents, not(isBogus$2));
  8737.       path = path.concat(map$1(parents, function (node) {
  8738.         return createPathItem(node);
  8739.       }));
  8740.       return path.reverse().join('/') + ',' + outputOffset;
  8741.     };
  8742.     var resolvePathItem = function (node, name, index) {
  8743.       var nodes = getChildNodes(node);
  8744.       nodes = filter$2(nodes, function (node, index) {
  8745.         return !isText$3(node) || !isText$3(nodes[index - 1]);
  8746.       });
  8747.       nodes = filter$2(nodes, matchNodeNames([name]));
  8748.       return nodes[index];
  8749.     };
  8750.     var findTextPosition = function (container, offset) {
  8751.       var node = container, targetOffset = 0, dataLen;
  8752.       while (isText$3(node)) {
  8753.         dataLen = node.data.length;
  8754.         if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8755.           container = node;
  8756.           offset = offset - targetOffset;
  8757.           break;
  8758.         }
  8759.         if (!isText$3(node.nextSibling)) {
  8760.           container = node;
  8761.           offset = dataLen;
  8762.           break;
  8763.         }
  8764.         targetOffset += dataLen;
  8765.         node = node.nextSibling;
  8766.       }
  8767.       if (isText$3(container) && offset > container.data.length) {
  8768.         offset = container.data.length;
  8769.       }
  8770.       return CaretPosition(container, offset);
  8771.     };
  8772.     var resolve$2 = function (root, path) {
  8773.       var offset;
  8774.       if (!path) {
  8775.         return null;
  8776.       }
  8777.       var parts = path.split(',');
  8778.       var paths = parts[0].split('/');
  8779.       offset = parts.length > 1 ? parts[1] : 'before';
  8780.       var container = reduce(paths, function (result, value) {
  8781.         var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  8782.         if (!match) {
  8783.           return null;
  8784.         }
  8785.         if (match[1] === 'text()') {
  8786.           match[1] = '#text';
  8787.         }
  8788.         return resolvePathItem(result, match[1], parseInt(match[2], 10));
  8789.       }, root);
  8790.       if (!container) {
  8791.         return null;
  8792.       }
  8793.       if (!isText$3(container)) {
  8794.         if (offset === 'after') {
  8795.           offset = nodeIndex(container) + 1;
  8796.         } else {
  8797.           offset = nodeIndex(container);
  8798.         }
  8799.         return CaretPosition(container.parentNode, offset);
  8800.       }
  8801.       return findTextPosition(container, parseInt(offset, 10));
  8802.     };
  8803.  
  8804.     var isContentEditableFalse$9 = isContentEditableFalse$b;
  8805.     var getNormalizedTextOffset = function (trim, container, offset) {
  8806.       var node, trimmedOffset;
  8807.       trimmedOffset = trim(container.data.slice(0, offset)).length;
  8808.       for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  8809.         trimmedOffset += trim(node.data).length;
  8810.       }
  8811.       return trimmedOffset;
  8812.     };
  8813.     var getPoint = function (dom, trim, normalized, rng, start) {
  8814.       var container = rng[start ? 'startContainer' : 'endContainer'];
  8815.       var offset = rng[start ? 'startOffset' : 'endOffset'];
  8816.       var point = [];
  8817.       var childNodes, after = 0;
  8818.       var root = dom.getRoot();
  8819.       if (isText$7(container)) {
  8820.         point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  8821.       } else {
  8822.         childNodes = container.childNodes;
  8823.         if (offset >= childNodes.length && childNodes.length) {
  8824.           after = 1;
  8825.           offset = Math.max(0, childNodes.length - 1);
  8826.         }
  8827.         point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  8828.       }
  8829.       for (; container && container !== root; container = container.parentNode) {
  8830.         point.push(dom.nodeIndex(container, normalized));
  8831.       }
  8832.       return point;
  8833.     };
  8834.     var getLocation = function (trim, selection, normalized, rng) {
  8835.       var dom = selection.dom, bookmark = {};
  8836.       bookmark.start = getPoint(dom, trim, normalized, rng, true);
  8837.       if (!selection.isCollapsed()) {
  8838.         bookmark.end = getPoint(dom, trim, normalized, rng, false);
  8839.       }
  8840.       if (isRangeInCaretContainerBlock(rng)) {
  8841.         bookmark.isFakeCaret = true;
  8842.       }
  8843.       return bookmark;
  8844.     };
  8845.     var findIndex = function (dom, name, element) {
  8846.       var count = 0;
  8847.       Tools.each(dom.select(name), function (node) {
  8848.         if (node.getAttribute('data-mce-bogus') === 'all') {
  8849.           return;
  8850.         }
  8851.         if (node === element) {
  8852.           return false;
  8853.         }
  8854.         count++;
  8855.       });
  8856.       return count;
  8857.     };
  8858.     var moveEndPoint$1 = function (rng, start) {
  8859.       var container, offset, childNodes;
  8860.       var prefix = start ? 'start' : 'end';
  8861.       container = rng[prefix + 'Container'];
  8862.       offset = rng[prefix + 'Offset'];
  8863.       if (isElement$5(container) && container.nodeName === 'TR') {
  8864.         childNodes = container.childNodes;
  8865.         container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  8866.         if (container) {
  8867.           offset = start ? 0 : container.childNodes.length;
  8868.           rng['set' + (start ? 'Start' : 'End')](container, offset);
  8869.         }
  8870.       }
  8871.     };
  8872.     var normalizeTableCellSelection = function (rng) {
  8873.       moveEndPoint$1(rng, true);
  8874.       moveEndPoint$1(rng, false);
  8875.       return rng;
  8876.     };
  8877.     var findSibling = function (node, offset) {
  8878.       var sibling;
  8879.       if (isElement$5(node)) {
  8880.         node = getNode$1(node, offset);
  8881.         if (isContentEditableFalse$9(node)) {
  8882.           return node;
  8883.         }
  8884.       }
  8885.       if (isCaretContainer$2(node)) {
  8886.         if (isText$7(node) && isCaretContainerBlock$1(node)) {
  8887.           node = node.parentNode;
  8888.         }
  8889.         sibling = node.previousSibling;
  8890.         if (isContentEditableFalse$9(sibling)) {
  8891.           return sibling;
  8892.         }
  8893.         sibling = node.nextSibling;
  8894.         if (isContentEditableFalse$9(sibling)) {
  8895.           return sibling;
  8896.         }
  8897.       }
  8898.     };
  8899.     var findAdjacentContentEditableFalseElm = function (rng) {
  8900.       return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  8901.     };
  8902.     var getOffsetBookmark = function (trim, normalized, selection) {
  8903.       var element = selection.getNode();
  8904.       var name = element ? element.nodeName : null;
  8905.       var rng = selection.getRng();
  8906.       if (isContentEditableFalse$9(element) || name === 'IMG') {
  8907.         return {
  8908.           name: name,
  8909.           index: findIndex(selection.dom, name, element)
  8910.         };
  8911.       }
  8912.       var sibling = findAdjacentContentEditableFalseElm(rng);
  8913.       if (sibling) {
  8914.         name = sibling.tagName;
  8915.         return {
  8916.           name: name,
  8917.           index: findIndex(selection.dom, name, sibling)
  8918.         };
  8919.       }
  8920.       return getLocation(trim, selection, normalized, rng);
  8921.     };
  8922.     var getCaretBookmark = function (selection) {
  8923.       var rng = selection.getRng();
  8924.       return {
  8925.         start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  8926.         end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  8927.       };
  8928.     };
  8929.     var getRangeBookmark = function (selection) {
  8930.       return { rng: selection.getRng() };
  8931.     };
  8932.     var createBookmarkSpan = function (dom, id, filled) {
  8933.       var args = {
  8934.         'data-mce-type': 'bookmark',
  8935.         id: id,
  8936.         'style': 'overflow:hidden;line-height:0px'
  8937.       };
  8938.       return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  8939.     };
  8940.     var getPersistentBookmark = function (selection, filled) {
  8941.       var dom = selection.dom;
  8942.       var rng = selection.getRng();
  8943.       var id = dom.uniqueId();
  8944.       var collapsed = selection.isCollapsed();
  8945.       var element = selection.getNode();
  8946.       var name = element.nodeName;
  8947.       if (name === 'IMG') {
  8948.         return {
  8949.           name: name,
  8950.           index: findIndex(dom, name, element)
  8951.         };
  8952.       }
  8953.       var rng2 = normalizeTableCellSelection(rng.cloneRange());
  8954.       if (!collapsed) {
  8955.         rng2.collapse(false);
  8956.         var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  8957.         rangeInsertNode(dom, rng2, endBookmarkNode);
  8958.       }
  8959.       rng = normalizeTableCellSelection(rng);
  8960.       rng.collapse(true);
  8961.       var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  8962.       rangeInsertNode(dom, rng, startBookmarkNode);
  8963.       selection.moveToBookmark({
  8964.         id: id,
  8965.         keep: true
  8966.       });
  8967.       return { id: id };
  8968.     };
  8969.     var getBookmark$2 = function (selection, type, normalized) {
  8970.       if (type === 2) {
  8971.         return getOffsetBookmark(trim$2, normalized, selection);
  8972.       } else if (type === 3) {
  8973.         return getCaretBookmark(selection);
  8974.       } else if (type) {
  8975.         return getRangeBookmark(selection);
  8976.       } else {
  8977.         return getPersistentBookmark(selection, false);
  8978.       }
  8979.     };
  8980.     var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  8981.  
  8982.     var DOM$9 = DOMUtils.DOM;
  8983.     var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  8984.     var getBodySetting = function (editor, name, defaultValue) {
  8985.       var value = editor.getParam(name, defaultValue);
  8986.       if (value.indexOf('=') !== -1) {
  8987.         var bodyObj = editor.getParam(name, '', 'hash');
  8988.         return get$9(bodyObj, editor.id).getOr(defaultValue);
  8989.       } else {
  8990.         return value;
  8991.       }
  8992.     };
  8993.     var getIframeAttrs = function (editor) {
  8994.       return editor.getParam('iframe_attrs', {});
  8995.     };
  8996.     var getDocType = function (editor) {
  8997.       return editor.getParam('doctype', '<!DOCTYPE html>');
  8998.     };
  8999.     var getDocumentBaseUrl = function (editor) {
  9000.       return editor.getParam('document_base_url', '');
  9001.     };
  9002.     var getBodyId = function (editor) {
  9003.       return getBodySetting(editor, 'body_id', 'tinymce');
  9004.     };
  9005.     var getBodyClass = function (editor) {
  9006.       return getBodySetting(editor, 'body_class', '');
  9007.     };
  9008.     var getContentSecurityPolicy = function (editor) {
  9009.       return editor.getParam('content_security_policy', '');
  9010.     };
  9011.     var shouldPutBrInPre$1 = function (editor) {
  9012.       return editor.getParam('br_in_pre', true);
  9013.     };
  9014.     var getForcedRootBlock = function (editor) {
  9015.       if (editor.getParam('force_p_newlines', false)) {
  9016.         return 'p';
  9017.       }
  9018.       var block = editor.getParam('forced_root_block', 'p');
  9019.       if (block === false) {
  9020.         return '';
  9021.       } else if (block === true) {
  9022.         return 'p';
  9023.       } else {
  9024.         return block;
  9025.       }
  9026.     };
  9027.     var getForcedRootBlockAttrs = function (editor) {
  9028.       return editor.getParam('forced_root_block_attrs', {});
  9029.     };
  9030.     var getBrNewLineSelector = function (editor) {
  9031.       return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  9032.     };
  9033.     var getNoNewLineSelector = function (editor) {
  9034.       return editor.getParam('no_newline_selector', '');
  9035.     };
  9036.     var shouldKeepStyles = function (editor) {
  9037.       return editor.getParam('keep_styles', true);
  9038.     };
  9039.     var shouldEndContainerOnEmptyBlock = function (editor) {
  9040.       return editor.getParam('end_container_on_empty_block', false);
  9041.     };
  9042.     var getFontStyleValues = function (editor) {
  9043.       return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  9044.     };
  9045.     var getFontSizeClasses = function (editor) {
  9046.       return Tools.explode(editor.getParam('font_size_classes', ''));
  9047.     };
  9048.     var getImagesDataImgFilter = function (editor) {
  9049.       return editor.getParam('images_dataimg_filter', always, 'function');
  9050.     };
  9051.     var isAutomaticUploadsEnabled = function (editor) {
  9052.       return editor.getParam('automatic_uploads', true, 'boolean');
  9053.     };
  9054.     var shouldReuseFileName = function (editor) {
  9055.       return editor.getParam('images_reuse_filename', false, 'boolean');
  9056.     };
  9057.     var shouldReplaceBlobUris = function (editor) {
  9058.       return editor.getParam('images_replace_blob_uris', true, 'boolean');
  9059.     };
  9060.     var getIconPackName = function (editor) {
  9061.       return editor.getParam('icons', '', 'string');
  9062.     };
  9063.     var getIconsUrl = function (editor) {
  9064.       return editor.getParam('icons_url', '', 'string');
  9065.     };
  9066.     var getImageUploadUrl = function (editor) {
  9067.       return editor.getParam('images_upload_url', '', 'string');
  9068.     };
  9069.     var getImageUploadBasePath = function (editor) {
  9070.       return editor.getParam('images_upload_base_path', '', 'string');
  9071.     };
  9072.     var getImagesUploadCredentials = function (editor) {
  9073.       return editor.getParam('images_upload_credentials', false, 'boolean');
  9074.     };
  9075.     var getImagesUploadHandler = function (editor) {
  9076.       return editor.getParam('images_upload_handler', null, 'function');
  9077.     };
  9078.     var shouldUseContentCssCors = function (editor) {
  9079.       return editor.getParam('content_css_cors', false, 'boolean');
  9080.     };
  9081.     var getReferrerPolicy = function (editor) {
  9082.       return editor.getParam('referrer_policy', '', 'string');
  9083.     };
  9084.     var getLanguageCode = function (editor) {
  9085.       return editor.getParam('language', 'en', 'string');
  9086.     };
  9087.     var getLanguageUrl = function (editor) {
  9088.       return editor.getParam('language_url', '', 'string');
  9089.     };
  9090.     var shouldIndentUseMargin = function (editor) {
  9091.       return editor.getParam('indent_use_margin', false);
  9092.     };
  9093.     var getIndentation = function (editor) {
  9094.       return editor.getParam('indentation', '40px', 'string');
  9095.     };
  9096.     var getContentCss = function (editor) {
  9097.       var contentCss = editor.getParam('content_css');
  9098.       if (isString$1(contentCss)) {
  9099.         return map$3(contentCss.split(','), trim$4);
  9100.       } else if (isArray$1(contentCss)) {
  9101.         return contentCss;
  9102.       } else if (contentCss === false || editor.inline) {
  9103.         return [];
  9104.       } else {
  9105.         return ['default'];
  9106.       }
  9107.     };
  9108.     var getFontCss = function (editor) {
  9109.       var fontCss = editor.getParam('font_css', []);
  9110.       return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$4);
  9111.     };
  9112.     var getDirectionality = function (editor) {
  9113.       return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9114.     };
  9115.     var getInlineBoundarySelector = function (editor) {
  9116.       return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9117.     };
  9118.     var getObjectResizing = function (editor) {
  9119.       var selector = editor.getParam('object_resizing');
  9120.       if (selector === false || Env.iOS) {
  9121.         return false;
  9122.       } else {
  9123.         return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9124.       }
  9125.     };
  9126.     var getResizeImgProportional = function (editor) {
  9127.       return editor.getParam('resize_img_proportional', true, 'boolean');
  9128.     };
  9129.     var getPlaceholder = function (editor) {
  9130.       return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9131.     };
  9132.     var getEventRoot = function (editor) {
  9133.       return editor.getParam('event_root');
  9134.     };
  9135.     var getServiceMessage = function (editor) {
  9136.       return editor.getParam('service_message');
  9137.     };
  9138.     var getTheme = function (editor) {
  9139.       return editor.getParam('theme');
  9140.     };
  9141.     var shouldValidate = function (editor) {
  9142.       return editor.getParam('validate');
  9143.     };
  9144.     var isInlineBoundariesEnabled = function (editor) {
  9145.       return editor.getParam('inline_boundaries') !== false;
  9146.     };
  9147.     var getFormats = function (editor) {
  9148.       return editor.getParam('formats');
  9149.     };
  9150.     var getPreviewStyles = function (editor) {
  9151.       var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9152.       if (isString$1(style)) {
  9153.         return style;
  9154.       } else {
  9155.         return '';
  9156.       }
  9157.     };
  9158.     var canFormatEmptyLines = function (editor) {
  9159.       return editor.getParam('format_empty_lines', false, 'boolean');
  9160.     };
  9161.     var getCustomUiSelector = function (editor) {
  9162.       return editor.getParam('custom_ui_selector', '', 'string');
  9163.     };
  9164.     var getThemeUrl = function (editor) {
  9165.       return editor.getParam('theme_url');
  9166.     };
  9167.     var isInline = function (editor) {
  9168.       return editor.getParam('inline');
  9169.     };
  9170.     var hasHiddenInput = function (editor) {
  9171.       return editor.getParam('hidden_input');
  9172.     };
  9173.     var shouldPatchSubmit = function (editor) {
  9174.       return editor.getParam('submit_patch');
  9175.     };
  9176.     var isEncodingXml = function (editor) {
  9177.       return editor.getParam('encoding') === 'xml';
  9178.     };
  9179.     var shouldAddFormSubmitTrigger = function (editor) {
  9180.       return editor.getParam('add_form_submit_trigger');
  9181.     };
  9182.     var shouldAddUnloadTrigger = function (editor) {
  9183.       return editor.getParam('add_unload_trigger');
  9184.     };
  9185.     var hasForcedRootBlock = function (editor) {
  9186.       return getForcedRootBlock(editor) !== '';
  9187.     };
  9188.     var getCustomUndoRedoLevels = function (editor) {
  9189.       return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9190.     };
  9191.     var shouldDisableNodeChange = function (editor) {
  9192.       return editor.getParam('disable_nodechange');
  9193.     };
  9194.     var isReadOnly$1 = function (editor) {
  9195.       return editor.getParam('readonly');
  9196.     };
  9197.     var hasContentCssCors = function (editor) {
  9198.       return editor.getParam('content_css_cors');
  9199.     };
  9200.     var getPlugins = function (editor) {
  9201.       return editor.getParam('plugins', '', 'string');
  9202.     };
  9203.     var getExternalPlugins$1 = function (editor) {
  9204.       return editor.getParam('external_plugins');
  9205.     };
  9206.     var shouldBlockUnsupportedDrop = function (editor) {
  9207.       return editor.getParam('block_unsupported_drop', true, 'boolean');
  9208.     };
  9209.     var isVisualAidsEnabled = function (editor) {
  9210.       return editor.getParam('visual', true, 'boolean');
  9211.     };
  9212.     var getVisualAidsTableClass = function (editor) {
  9213.       return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9214.     };
  9215.     var getVisualAidsAnchorClass = function (editor) {
  9216.       return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9217.     };
  9218.     var getIframeAriaText = function (editor) {
  9219.       return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9220.     };
  9221.  
  9222.     var isElement$2 = isElement$5;
  9223.     var isText$2 = isText$7;
  9224.     var removeNode$1 = function (node) {
  9225.       var parentNode = node.parentNode;
  9226.       if (parentNode) {
  9227.         parentNode.removeChild(node);
  9228.       }
  9229.     };
  9230.     var trimCount = function (text) {
  9231.       var trimmedText = trim$2(text);
  9232.       return {
  9233.         count: text.length - trimmedText.length,
  9234.         text: trimmedText
  9235.       };
  9236.     };
  9237.     var deleteZwspChars = function (caretContainer) {
  9238.       var idx;
  9239.       while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9240.         caretContainer.deleteData(idx, 1);
  9241.       }
  9242.     };
  9243.     var removeUnchanged = function (caretContainer, pos) {
  9244.       remove$2(caretContainer);
  9245.       return pos;
  9246.     };
  9247.     var removeTextAndReposition = function (caretContainer, pos) {
  9248.       var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9249.       var after = trimCount(caretContainer.data.substr(pos.offset()));
  9250.       var text = before.text + after.text;
  9251.       if (text.length > 0) {
  9252.         deleteZwspChars(caretContainer);
  9253.         return CaretPosition(caretContainer, pos.offset() - before.count);
  9254.       } else {
  9255.         return pos;
  9256.       }
  9257.     };
  9258.     var removeElementAndReposition = function (caretContainer, pos) {
  9259.       var parentNode = pos.container();
  9260.       var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9261.         return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9262.       }).getOr(pos);
  9263.       remove$2(caretContainer);
  9264.       return newPosition;
  9265.     };
  9266.     var removeTextCaretContainer = function (caretContainer, pos) {
  9267.       return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9268.     };
  9269.     var removeElementCaretContainer = function (caretContainer, pos) {
  9270.       return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9271.     };
  9272.     var removeAndReposition = function (container, pos) {
  9273.       return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9274.     };
  9275.     var remove$2 = function (caretContainerNode) {
  9276.       if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9277.         if (hasContent(caretContainerNode)) {
  9278.           caretContainerNode.removeAttribute('data-mce-caret');
  9279.         } else {
  9280.           removeNode$1(caretContainerNode);
  9281.         }
  9282.       }
  9283.       if (isText$2(caretContainerNode)) {
  9284.         deleteZwspChars(caretContainerNode);
  9285.         if (caretContainerNode.data.length === 0) {
  9286.           removeNode$1(caretContainerNode);
  9287.         }
  9288.       }
  9289.     };
  9290.  
  9291.     var browser$2 = detect().browser;
  9292.     var isContentEditableFalse$8 = isContentEditableFalse$b;
  9293.     var isMedia$1 = isMedia$2;
  9294.     var isTableCell$3 = isTableCell$5;
  9295.     var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9296.     var getAbsoluteClientRect = function (root, element, before) {
  9297.       var clientRect = collapse(element.getBoundingClientRect(), before);
  9298.       var scrollX;
  9299.       var scrollY;
  9300.       if (root.tagName === 'BODY') {
  9301.         var docElm = root.ownerDocument.documentElement;
  9302.         scrollX = root.scrollLeft || docElm.scrollLeft;
  9303.         scrollY = root.scrollTop || docElm.scrollTop;
  9304.       } else {
  9305.         var rootRect = root.getBoundingClientRect();
  9306.         scrollX = root.scrollLeft - rootRect.left;
  9307.         scrollY = root.scrollTop - rootRect.top;
  9308.       }
  9309.       clientRect.left += scrollX;
  9310.       clientRect.right += scrollX;
  9311.       clientRect.top += scrollY;
  9312.       clientRect.bottom += scrollY;
  9313.       clientRect.width = 1;
  9314.       var margin = element.offsetWidth - element.clientWidth;
  9315.       if (margin > 0) {
  9316.         if (before) {
  9317.           margin *= -1;
  9318.         }
  9319.         clientRect.left += margin;
  9320.         clientRect.right += margin;
  9321.       }
  9322.       return clientRect;
  9323.     };
  9324.     var trimInlineCaretContainers = function (root) {
  9325.       var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9326.       for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9327.         var node = fakeCaretTargetNodes[i].dom;
  9328.         var sibling = node.previousSibling;
  9329.         if (endsWithCaretContainer$1(sibling)) {
  9330.           var data = sibling.data;
  9331.           if (data.length === 1) {
  9332.             sibling.parentNode.removeChild(sibling);
  9333.           } else {
  9334.             sibling.deleteData(data.length - 1, 1);
  9335.           }
  9336.         }
  9337.         sibling = node.nextSibling;
  9338.         if (startsWithCaretContainer$1(sibling)) {
  9339.           var data = sibling.data;
  9340.           if (data.length === 1) {
  9341.             sibling.parentNode.removeChild(sibling);
  9342.           } else {
  9343.             sibling.deleteData(0, 1);
  9344.           }
  9345.         }
  9346.       }
  9347.     };
  9348.     var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9349.       var lastVisualCaret = value();
  9350.       var cursorInterval;
  9351.       var caretContainerNode;
  9352.       var rootBlock = getForcedRootBlock(editor);
  9353.       var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9354.       var show = function (before, element) {
  9355.         var rng;
  9356.         hide();
  9357.         if (isTableCell$3(element)) {
  9358.           return null;
  9359.         }
  9360.         if (isBlock(element)) {
  9361.           caretContainerNode = insertBlock$1(caretBlock, element, before);
  9362.           var clientRect = getAbsoluteClientRect(root, element, before);
  9363.           DomQuery(caretContainerNode).css('top', clientRect.top);
  9364.           var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9365.           lastVisualCaret.set({
  9366.             caret: caret,
  9367.             element: element,
  9368.             before: before
  9369.           });
  9370.           if (before) {
  9371.             DomQuery(caret).addClass('mce-visual-caret-before');
  9372.           }
  9373.           startBlink();
  9374.           rng = element.ownerDocument.createRange();
  9375.           rng.setStart(caretContainerNode, 0);
  9376.           rng.setEnd(caretContainerNode, 0);
  9377.         } else {
  9378.           caretContainerNode = insertInline$1(element, before);
  9379.           rng = element.ownerDocument.createRange();
  9380.           if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9381.             rng.setStart(caretContainerNode, 0);
  9382.             rng.setEnd(caretContainerNode, 0);
  9383.           } else {
  9384.             rng.setStart(caretContainerNode, 1);
  9385.             rng.setEnd(caretContainerNode, 1);
  9386.           }
  9387.           return rng;
  9388.         }
  9389.         return rng;
  9390.       };
  9391.       var hide = function () {
  9392.         trimInlineCaretContainers(root);
  9393.         if (caretContainerNode) {
  9394.           remove$2(caretContainerNode);
  9395.           caretContainerNode = null;
  9396.         }
  9397.         lastVisualCaret.on(function (caretState) {
  9398.           DomQuery(caretState.caret).remove();
  9399.           lastVisualCaret.clear();
  9400.         });
  9401.         if (cursorInterval) {
  9402.           Delay.clearInterval(cursorInterval);
  9403.           cursorInterval = undefined;
  9404.         }
  9405.       };
  9406.       var startBlink = function () {
  9407.         cursorInterval = Delay.setInterval(function () {
  9408.           if (hasFocus()) {
  9409.             DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9410.           } else {
  9411.             DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9412.           }
  9413.         }, 500);
  9414.       };
  9415.       var reposition = function () {
  9416.         lastVisualCaret.on(function (caretState) {
  9417.           var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9418.           DomQuery(caretState.caret).css(__assign({}, clientRect));
  9419.         });
  9420.       };
  9421.       var destroy = function () {
  9422.         return Delay.clearInterval(cursorInterval);
  9423.       };
  9424.       var getCss = function () {
  9425.         return '.mce-visual-caret {' + 'position: absolute;' + 'background-color: black;' + 'background-color: currentcolor;' + '}' + '.mce-visual-caret-hidden {' + 'display: none;' + '}' + '*[data-mce-caret] {' + 'position: absolute;' + 'left: -1000px;' + 'right: auto;' + 'top: 0;' + 'margin: 0;' + 'padding: 0;' + '}';
  9426.       };
  9427.       return {
  9428.         show: show,
  9429.         hide: hide,
  9430.         getCss: getCss,
  9431.         reposition: reposition,
  9432.         destroy: destroy
  9433.       };
  9434.     };
  9435.     var isFakeCaretTableBrowser = function () {
  9436.       return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9437.     };
  9438.     var isInlineFakeCaretTarget = function (node) {
  9439.       return isContentEditableFalse$8(node) || isMedia$1(node);
  9440.     };
  9441.     var isFakeCaretTarget = function (node) {
  9442.       return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9443.     };
  9444.  
  9445.     var isContentEditableFalse$7 = isContentEditableFalse$b;
  9446.     var isMedia = isMedia$2;
  9447.     var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9448.     var isCaretContainer = isCaretContainer$2;
  9449.     var isCaretContainerBlock = isCaretContainerBlock$1;
  9450.     var isElement$1 = isElement$5;
  9451.     var isCaretCandidate$1 = isCaretCandidate$3;
  9452.     var isForwards = function (direction) {
  9453.       return direction > 0;
  9454.     };
  9455.     var isBackwards = function (direction) {
  9456.       return direction < 0;
  9457.     };
  9458.     var skipCaretContainers = function (walk, shallow) {
  9459.       var node;
  9460.       while (node = walk(shallow)) {
  9461.         if (!isCaretContainerBlock(node)) {
  9462.           return node;
  9463.         }
  9464.       }
  9465.       return null;
  9466.     };
  9467.     var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9468.       var walker = new DomTreeWalker(node, rootNode);
  9469.       var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9470.       if (isBackwards(direction)) {
  9471.         if (isCefOrCaretContainer) {
  9472.           node = skipCaretContainers(walker.prev.bind(walker), true);
  9473.           if (predicateFn(node)) {
  9474.             return node;
  9475.           }
  9476.         }
  9477.         while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9478.           if (predicateFn(node)) {
  9479.             return node;
  9480.           }
  9481.         }
  9482.       }
  9483.       if (isForwards(direction)) {
  9484.         if (isCefOrCaretContainer) {
  9485.           node = skipCaretContainers(walker.next.bind(walker), true);
  9486.           if (predicateFn(node)) {
  9487.             return node;
  9488.           }
  9489.         }
  9490.         while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9491.           if (predicateFn(node)) {
  9492.             return node;
  9493.           }
  9494.         }
  9495.       }
  9496.       return null;
  9497.     };
  9498.     var getParentBlock$2 = function (node, rootNode) {
  9499.       while (node && node !== rootNode) {
  9500.         if (isBlockLike(node)) {
  9501.           return node;
  9502.         }
  9503.         node = node.parentNode;
  9504.       }
  9505.       return null;
  9506.     };
  9507.     var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9508.       return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9509.     };
  9510.     var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9511.       if (!caretPosition) {
  9512.         return null;
  9513.       }
  9514.       var container = caretPosition.container();
  9515.       var offset = caretPosition.offset();
  9516.       if (!isElement$1(container)) {
  9517.         return null;
  9518.       }
  9519.       return container.childNodes[offset + relativeOffset];
  9520.     };
  9521.     var beforeAfter = function (before, node) {
  9522.       var range = node.ownerDocument.createRange();
  9523.       if (before) {
  9524.         range.setStartBefore(node);
  9525.         range.setEndBefore(node);
  9526.       } else {
  9527.         range.setStartAfter(node);
  9528.         range.setEndAfter(node);
  9529.       }
  9530.       return range;
  9531.     };
  9532.     var isNodesInSameBlock = function (root, node1, node2) {
  9533.       return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9534.     };
  9535.     var lean = function (left, root, node) {
  9536.       var siblingName = left ? 'previousSibling' : 'nextSibling';
  9537.       while (node && node !== root) {
  9538.         var sibling = node[siblingName];
  9539.         if (isCaretContainer(sibling)) {
  9540.           sibling = sibling[siblingName];
  9541.         }
  9542.         if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9543.           if (isNodesInSameBlock(root, sibling, node)) {
  9544.             return sibling;
  9545.           }
  9546.           break;
  9547.         }
  9548.         if (isCaretCandidate$1(sibling)) {
  9549.           break;
  9550.         }
  9551.         node = node.parentNode;
  9552.       }
  9553.       return null;
  9554.     };
  9555.     var before$2 = curry(beforeAfter, true);
  9556.     var after$2 = curry(beforeAfter, false);
  9557.     var normalizeRange = function (direction, root, range) {
  9558.       var node;
  9559.       var leanLeft = curry(lean, true, root);
  9560.       var leanRight = curry(lean, false, root);
  9561.       var container = range.startContainer;
  9562.       var offset = range.startOffset;
  9563.       if (isCaretContainerBlock$1(container)) {
  9564.         if (!isElement$1(container)) {
  9565.           container = container.parentNode;
  9566.         }
  9567.         var location_1 = container.getAttribute('data-mce-caret');
  9568.         if (location_1 === 'before') {
  9569.           node = container.nextSibling;
  9570.           if (isFakeCaretTarget(node)) {
  9571.             return before$2(node);
  9572.           }
  9573.         }
  9574.         if (location_1 === 'after') {
  9575.           node = container.previousSibling;
  9576.           if (isFakeCaretTarget(node)) {
  9577.             return after$2(node);
  9578.           }
  9579.         }
  9580.       }
  9581.       if (!range.collapsed) {
  9582.         return range;
  9583.       }
  9584.       if (isText$7(container)) {
  9585.         if (isCaretContainer(container)) {
  9586.           if (direction === 1) {
  9587.             node = leanRight(container);
  9588.             if (node) {
  9589.               return before$2(node);
  9590.             }
  9591.             node = leanLeft(container);
  9592.             if (node) {
  9593.               return after$2(node);
  9594.             }
  9595.           }
  9596.           if (direction === -1) {
  9597.             node = leanLeft(container);
  9598.             if (node) {
  9599.               return after$2(node);
  9600.             }
  9601.             node = leanRight(container);
  9602.             if (node) {
  9603.               return before$2(node);
  9604.             }
  9605.           }
  9606.           return range;
  9607.         }
  9608.         if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9609.           if (direction === 1) {
  9610.             node = leanRight(container);
  9611.             if (node) {
  9612.               return before$2(node);
  9613.             }
  9614.           }
  9615.           return range;
  9616.         }
  9617.         if (startsWithCaretContainer$1(container) && offset <= 1) {
  9618.           if (direction === -1) {
  9619.             node = leanLeft(container);
  9620.             if (node) {
  9621.               return after$2(node);
  9622.             }
  9623.           }
  9624.           return range;
  9625.         }
  9626.         if (offset === container.data.length) {
  9627.           node = leanRight(container);
  9628.           if (node) {
  9629.             return before$2(node);
  9630.           }
  9631.           return range;
  9632.         }
  9633.         if (offset === 0) {
  9634.           node = leanLeft(container);
  9635.           if (node) {
  9636.             return after$2(node);
  9637.           }
  9638.           return range;
  9639.         }
  9640.       }
  9641.       return range;
  9642.     };
  9643.     var getRelativeCefElm = function (forward, caretPosition) {
  9644.       return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9645.     };
  9646.     var getNormalizedRangeEndPoint = function (direction, root, range) {
  9647.       var normalizedRange = normalizeRange(direction, root, range);
  9648.       if (direction === -1) {
  9649.         return CaretPosition.fromRangeStart(normalizedRange);
  9650.       }
  9651.       return CaretPosition.fromRangeEnd(normalizedRange);
  9652.     };
  9653.     var getElementFromPosition = function (pos) {
  9654.       return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9655.     };
  9656.     var getElementFromPrevPosition = function (pos) {
  9657.       return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9658.     };
  9659.     var getVisualCaretPosition = function (walkFn, caretPosition) {
  9660.       while (caretPosition = walkFn(caretPosition)) {
  9661.         if (caretPosition.isVisible()) {
  9662.           return caretPosition;
  9663.         }
  9664.       }
  9665.       return caretPosition;
  9666.     };
  9667.     var isMoveInsideSameBlock = function (from, to) {
  9668.       var inSameBlock = isInSameBlock(from, to);
  9669.       if (!inSameBlock && isBr$5(from.getNode())) {
  9670.         return true;
  9671.       }
  9672.       return inSameBlock;
  9673.     };
  9674.  
  9675.     var HDirection;
  9676.     (function (HDirection) {
  9677.       HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9678.       HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9679.     }(HDirection || (HDirection = {})));
  9680.     var isContentEditableFalse$6 = isContentEditableFalse$b;
  9681.     var isText$1 = isText$7;
  9682.     var isElement = isElement$5;
  9683.     var isBr$1 = isBr$5;
  9684.     var isCaretCandidate = isCaretCandidate$3;
  9685.     var isAtomic = isAtomic$1;
  9686.     var isEditableCaretCandidate = isEditableCaretCandidate$1;
  9687.     var getParents$3 = function (node, root) {
  9688.       var parents = [];
  9689.       while (node && node !== root) {
  9690.         parents.push(node);
  9691.         node = node.parentNode;
  9692.       }
  9693.       return parents;
  9694.     };
  9695.     var nodeAtIndex = function (container, offset) {
  9696.       if (container.hasChildNodes() && offset < container.childNodes.length) {
  9697.         return container.childNodes[offset];
  9698.       }
  9699.       return null;
  9700.     };
  9701.     var getCaretCandidatePosition = function (direction, node) {
  9702.       if (isForwards(direction)) {
  9703.         if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  9704.           return CaretPosition.before(node);
  9705.         }
  9706.         if (isText$1(node)) {
  9707.           return CaretPosition(node, 0);
  9708.         }
  9709.       }
  9710.       if (isBackwards(direction)) {
  9711.         if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  9712.           return CaretPosition.after(node);
  9713.         }
  9714.         if (isText$1(node)) {
  9715.           return CaretPosition(node, node.data.length);
  9716.         }
  9717.       }
  9718.       if (isBackwards(direction)) {
  9719.         if (isBr$1(node)) {
  9720.           return CaretPosition.before(node);
  9721.         }
  9722.         return CaretPosition.after(node);
  9723.       }
  9724.       return CaretPosition.before(node);
  9725.     };
  9726.     var moveForwardFromBr = function (root, nextNode) {
  9727.       var nextSibling = nextNode.nextSibling;
  9728.       if (nextSibling && isCaretCandidate(nextSibling)) {
  9729.         if (isText$1(nextSibling)) {
  9730.           return CaretPosition(nextSibling, 0);
  9731.         } else {
  9732.           return CaretPosition.before(nextSibling);
  9733.         }
  9734.       } else {
  9735.         return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  9736.       }
  9737.     };
  9738.     var findCaretPosition$1 = function (direction, startPos, root) {
  9739.       var node;
  9740.       var nextNode;
  9741.       var innerNode;
  9742.       var caretPosition;
  9743.       if (!isElement(root) || !startPos) {
  9744.         return null;
  9745.       }
  9746.       if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  9747.         caretPosition = CaretPosition.after(root.lastChild);
  9748.         if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  9749.           return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  9750.         }
  9751.       } else {
  9752.         caretPosition = startPos;
  9753.       }
  9754.       var container = caretPosition.container();
  9755.       var offset = caretPosition.offset();
  9756.       if (isText$1(container)) {
  9757.         if (isBackwards(direction) && offset > 0) {
  9758.           return CaretPosition(container, --offset);
  9759.         }
  9760.         if (isForwards(direction) && offset < container.length) {
  9761.           return CaretPosition(container, ++offset);
  9762.         }
  9763.         node = container;
  9764.       } else {
  9765.         if (isBackwards(direction) && offset > 0) {
  9766.           nextNode = nodeAtIndex(container, offset - 1);
  9767.           if (isCaretCandidate(nextNode)) {
  9768.             if (!isAtomic(nextNode)) {
  9769.               innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9770.               if (innerNode) {
  9771.                 if (isText$1(innerNode)) {
  9772.                   return CaretPosition(innerNode, innerNode.data.length);
  9773.                 }
  9774.                 return CaretPosition.after(innerNode);
  9775.               }
  9776.             }
  9777.             if (isText$1(nextNode)) {
  9778.               return CaretPosition(nextNode, nextNode.data.length);
  9779.             }
  9780.             return CaretPosition.before(nextNode);
  9781.           }
  9782.         }
  9783.         if (isForwards(direction) && offset < container.childNodes.length) {
  9784.           nextNode = nodeAtIndex(container, offset);
  9785.           if (isCaretCandidate(nextNode)) {
  9786.             if (isBr$1(nextNode)) {
  9787.               return moveForwardFromBr(root, nextNode);
  9788.             }
  9789.             if (!isAtomic(nextNode)) {
  9790.               innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9791.               if (innerNode) {
  9792.                 if (isText$1(innerNode)) {
  9793.                   return CaretPosition(innerNode, 0);
  9794.                 }
  9795.                 return CaretPosition.before(innerNode);
  9796.               }
  9797.             }
  9798.             if (isText$1(nextNode)) {
  9799.               return CaretPosition(nextNode, 0);
  9800.             }
  9801.             return CaretPosition.after(nextNode);
  9802.           }
  9803.         }
  9804.         node = nextNode ? nextNode : caretPosition.getNode();
  9805.       }
  9806.       if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  9807.         node = findNode$1(node, direction, always, root, true);
  9808.         if (isEditableCaretCandidate(node, root)) {
  9809.           return getCaretCandidatePosition(direction, node);
  9810.         }
  9811.       }
  9812.       nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  9813.       var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  9814.       if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  9815.         if (isForwards(direction)) {
  9816.           caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  9817.         } else {
  9818.           caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  9819.         }
  9820.         return caretPosition;
  9821.       }
  9822.       if (nextNode) {
  9823.         return getCaretCandidatePosition(direction, nextNode);
  9824.       }
  9825.       return null;
  9826.     };
  9827.     var CaretWalker = function (root) {
  9828.       return {
  9829.         next: function (caretPosition) {
  9830.           return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  9831.         },
  9832.         prev: function (caretPosition) {
  9833.           return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  9834.         }
  9835.       };
  9836.     };
  9837.  
  9838.     var walkToPositionIn = function (forward, root, start) {
  9839.       var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  9840.       return fromPosition(forward, root, position);
  9841.     };
  9842.     var afterElement = function (node) {
  9843.       return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  9844.     };
  9845.     var isBeforeOrStart = function (position) {
  9846.       if (CaretPosition.isTextPosition(position)) {
  9847.         return position.offset() === 0;
  9848.       } else {
  9849.         return isCaretCandidate$3(position.getNode());
  9850.       }
  9851.     };
  9852.     var isAfterOrEnd = function (position) {
  9853.       if (CaretPosition.isTextPosition(position)) {
  9854.         var container = position.container();
  9855.         return position.offset() === container.data.length;
  9856.       } else {
  9857.         return isCaretCandidate$3(position.getNode(true));
  9858.       }
  9859.     };
  9860.     var isBeforeAfterSameElement = function (from, to) {
  9861.       return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  9862.     };
  9863.     var isAtBr = function (position) {
  9864.       return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  9865.     };
  9866.     var shouldSkipPosition = function (forward, from, to) {
  9867.       if (forward) {
  9868.         return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  9869.       } else {
  9870.         return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  9871.       }
  9872.     };
  9873.     var fromPosition = function (forward, root, pos) {
  9874.       var walker = CaretWalker(root);
  9875.       return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  9876.     };
  9877.     var navigate = function (forward, root, from) {
  9878.       return fromPosition(forward, root, from).bind(function (to) {
  9879.         if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  9880.           return fromPosition(forward, root, to);
  9881.         } else {
  9882.           return Optional.some(to);
  9883.         }
  9884.       });
  9885.     };
  9886.     var navigateIgnore = function (forward, root, from, ignoreFilter) {
  9887.       return navigate(forward, root, from).bind(function (pos) {
  9888.         return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  9889.       });
  9890.     };
  9891.     var positionIn = function (forward, element) {
  9892.       var startNode = forward ? element.firstChild : element.lastChild;
  9893.       if (isText$7(startNode)) {
  9894.         return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  9895.       } else if (startNode) {
  9896.         if (isCaretCandidate$3(startNode)) {
  9897.           return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  9898.         } else {
  9899.           return walkToPositionIn(forward, element, startNode);
  9900.         }
  9901.       } else {
  9902.         return Optional.none();
  9903.       }
  9904.     };
  9905.     var nextPosition = curry(fromPosition, true);
  9906.     var prevPosition = curry(fromPosition, false);
  9907.     var firstPositionIn = curry(positionIn, true);
  9908.     var lastPositionIn = curry(positionIn, false);
  9909.  
  9910.     var CARET_ID$1 = '_mce_caret';
  9911.     var isCaretNode = function (node) {
  9912.       return isElement$5(node) && node.id === CARET_ID$1;
  9913.     };
  9914.     var getParentCaretContainer = function (body, node) {
  9915.       while (node && node !== body) {
  9916.         if (node.id === CARET_ID$1) {
  9917.           return node;
  9918.         }
  9919.         node = node.parentNode;
  9920.       }
  9921.       return null;
  9922.     };
  9923.  
  9924.     var isStringPathBookmark = function (bookmark) {
  9925.       return isString$1(bookmark.start);
  9926.     };
  9927.     var isRangeBookmark = function (bookmark) {
  9928.       return has$2(bookmark, 'rng');
  9929.     };
  9930.     var isIdBookmark = function (bookmark) {
  9931.       return has$2(bookmark, 'id');
  9932.     };
  9933.     var isIndexBookmark = function (bookmark) {
  9934.       return has$2(bookmark, 'name');
  9935.     };
  9936.     var isPathBookmark = function (bookmark) {
  9937.       return Tools.isArray(bookmark.start);
  9938.     };
  9939.  
  9940.     var addBogus = function (dom, node) {
  9941.       if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  9942.         node.innerHTML = '<br data-mce-bogus="1" />';
  9943.       }
  9944.       return node;
  9945.     };
  9946.     var resolveCaretPositionBookmark = function (dom, bookmark) {
  9947.       var pos;
  9948.       var rng = dom.createRng();
  9949.       pos = resolve$2(dom.getRoot(), bookmark.start);
  9950.       rng.setStart(pos.container(), pos.offset());
  9951.       pos = resolve$2(dom.getRoot(), bookmark.end);
  9952.       rng.setEnd(pos.container(), pos.offset());
  9953.       return rng;
  9954.     };
  9955.     var insertZwsp = function (node, rng) {
  9956.       var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  9957.       node.appendChild(textNode);
  9958.       rng.setStart(textNode, 0);
  9959.       rng.setEnd(textNode, 0);
  9960.     };
  9961.     var isEmpty$1 = function (node) {
  9962.       return node.hasChildNodes() === false;
  9963.     };
  9964.     var tryFindRangePosition = function (node, rng) {
  9965.       return lastPositionIn(node).fold(never, function (pos) {
  9966.         rng.setStart(pos.container(), pos.offset());
  9967.         rng.setEnd(pos.container(), pos.offset());
  9968.         return true;
  9969.       });
  9970.     };
  9971.     var padEmptyCaretContainer = function (root, node, rng) {
  9972.       if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  9973.         insertZwsp(node, rng);
  9974.         return true;
  9975.       } else {
  9976.         return false;
  9977.       }
  9978.     };
  9979.     var setEndPoint = function (dom, start, bookmark, rng) {
  9980.       var point = bookmark[start ? 'start' : 'end'];
  9981.       var i, node, offset, children;
  9982.       var root = dom.getRoot();
  9983.       if (point) {
  9984.         offset = point[0];
  9985.         for (node = root, i = point.length - 1; i >= 1; i--) {
  9986.           children = node.childNodes;
  9987.           if (padEmptyCaretContainer(root, node, rng)) {
  9988.             return true;
  9989.           }
  9990.           if (point[i] > children.length - 1) {
  9991.             if (padEmptyCaretContainer(root, node, rng)) {
  9992.               return true;
  9993.             }
  9994.             return tryFindRangePosition(node, rng);
  9995.           }
  9996.           node = children[point[i]];
  9997.         }
  9998.         if (node.nodeType === 3) {
  9999.           offset = Math.min(point[0], node.nodeValue.length);
  10000.         }
  10001.         if (node.nodeType === 1) {
  10002.           offset = Math.min(point[0], node.childNodes.length);
  10003.         }
  10004.         if (start) {
  10005.           rng.setStart(node, offset);
  10006.         } else {
  10007.           rng.setEnd(node, offset);
  10008.         }
  10009.       }
  10010.       return true;
  10011.     };
  10012.     var isValidTextNode = function (node) {
  10013.       return isText$7(node) && node.data.length > 0;
  10014.     };
  10015.     var restoreEndPoint = function (dom, suffix, bookmark) {
  10016.       var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  10017.       var keep = bookmark.keep;
  10018.       var container, offset;
  10019.       if (marker) {
  10020.         node = marker.parentNode;
  10021.         if (suffix === 'start') {
  10022.           if (!keep) {
  10023.             idx = dom.nodeIndex(marker);
  10024.           } else {
  10025.             if (marker.hasChildNodes()) {
  10026.               node = marker.firstChild;
  10027.               idx = 1;
  10028.             } else if (isValidTextNode(marker.nextSibling)) {
  10029.               node = marker.nextSibling;
  10030.               idx = 0;
  10031.             } else if (isValidTextNode(marker.previousSibling)) {
  10032.               node = marker.previousSibling;
  10033.               idx = marker.previousSibling.data.length;
  10034.             } else {
  10035.               node = marker.parentNode;
  10036.               idx = dom.nodeIndex(marker) + 1;
  10037.             }
  10038.           }
  10039.           container = node;
  10040.           offset = idx;
  10041.         } else {
  10042.           if (!keep) {
  10043.             idx = dom.nodeIndex(marker);
  10044.           } else {
  10045.             if (marker.hasChildNodes()) {
  10046.               node = marker.firstChild;
  10047.               idx = 1;
  10048.             } else if (isValidTextNode(marker.previousSibling)) {
  10049.               node = marker.previousSibling;
  10050.               idx = marker.previousSibling.data.length;
  10051.             } else {
  10052.               node = marker.parentNode;
  10053.               idx = dom.nodeIndex(marker);
  10054.             }
  10055.           }
  10056.           container = node;
  10057.           offset = idx;
  10058.         }
  10059.         if (!keep) {
  10060.           prev = marker.previousSibling;
  10061.           next = marker.nextSibling;
  10062.           Tools.each(Tools.grep(marker.childNodes), function (node) {
  10063.             if (isText$7(node)) {
  10064.               node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  10065.             }
  10066.           });
  10067.           while (marker = dom.get(bookmark.id + '_' + suffix)) {
  10068.             dom.remove(marker, true);
  10069.           }
  10070.           if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  10071.             idx = prev.nodeValue.length;
  10072.             prev.appendData(next.nodeValue);
  10073.             dom.remove(next);
  10074.             container = prev;
  10075.             offset = idx;
  10076.           }
  10077.         }
  10078.         return Optional.some(CaretPosition(container, offset));
  10079.       } else {
  10080.         return Optional.none();
  10081.       }
  10082.     };
  10083.     var resolvePaths = function (dom, bookmark) {
  10084.       var rng = dom.createRng();
  10085.       if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  10086.         return Optional.some(rng);
  10087.       } else {
  10088.         return Optional.none();
  10089.       }
  10090.     };
  10091.     var resolveId = function (dom, bookmark) {
  10092.       var startPos = restoreEndPoint(dom, 'start', bookmark);
  10093.       var endPos = restoreEndPoint(dom, 'end', bookmark);
  10094.       return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  10095.         var rng = dom.createRng();
  10096.         rng.setStart(addBogus(dom, spos.container()), spos.offset());
  10097.         rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  10098.         return rng;
  10099.       });
  10100.     };
  10101.     var resolveIndex = function (dom, bookmark) {
  10102.       return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  10103.         var rng = dom.createRng();
  10104.         rng.selectNode(elm);
  10105.         return rng;
  10106.       });
  10107.     };
  10108.     var resolve$1 = function (selection, bookmark) {
  10109.       var dom = selection.dom;
  10110.       if (bookmark) {
  10111.         if (isPathBookmark(bookmark)) {
  10112.           return resolvePaths(dom, bookmark);
  10113.         } else if (isStringPathBookmark(bookmark)) {
  10114.           return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10115.         } else if (isIdBookmark(bookmark)) {
  10116.           return resolveId(dom, bookmark);
  10117.         } else if (isIndexBookmark(bookmark)) {
  10118.           return resolveIndex(dom, bookmark);
  10119.         } else if (isRangeBookmark(bookmark)) {
  10120.           return Optional.some(bookmark.rng);
  10121.         }
  10122.       }
  10123.       return Optional.none();
  10124.     };
  10125.  
  10126.     var getBookmark$1 = function (selection, type, normalized) {
  10127.       return getBookmark$2(selection, type, normalized);
  10128.     };
  10129.     var moveToBookmark = function (selection, bookmark) {
  10130.       resolve$1(selection, bookmark).each(function (rng) {
  10131.         selection.setRng(rng);
  10132.       });
  10133.     };
  10134.     var isBookmarkNode$1 = function (node) {
  10135.       return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10136.     };
  10137.  
  10138.     var is = function (expected) {
  10139.       return function (actual) {
  10140.         return expected === actual;
  10141.       };
  10142.     };
  10143.     var isNbsp = is(nbsp);
  10144.     var isWhiteSpace = function (chr) {
  10145.       return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10146.     };
  10147.     var isContent = function (chr) {
  10148.       return !isWhiteSpace(chr) && !isNbsp(chr);
  10149.     };
  10150.  
  10151.     var isNode = function (node) {
  10152.       return !!node.nodeType;
  10153.     };
  10154.     var isInlineBlock = function (node) {
  10155.       return node && /^(IMG)$/.test(node.nodeName);
  10156.     };
  10157.     var moveStart = function (dom, selection, rng) {
  10158.       var offset = rng.startOffset;
  10159.       var container = rng.startContainer;
  10160.       if (container === rng.endContainer) {
  10161.         if (isInlineBlock(container.childNodes[offset])) {
  10162.           return;
  10163.         }
  10164.       }
  10165.       if (isElement$5(container)) {
  10166.         var nodes = container.childNodes;
  10167.         var walker = void 0;
  10168.         if (offset < nodes.length) {
  10169.           container = nodes[offset];
  10170.           walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10171.         } else {
  10172.           container = nodes[nodes.length - 1];
  10173.           walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10174.           walker.next(true);
  10175.         }
  10176.         for (var node = walker.current(); node; node = walker.next()) {
  10177.           if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10178.             rng.setStart(node, 0);
  10179.             selection.setRng(rng);
  10180.             return;
  10181.           }
  10182.         }
  10183.       }
  10184.     };
  10185.     var getNonWhiteSpaceSibling = function (node, next, inc) {
  10186.       if (node) {
  10187.         var nextName = next ? 'nextSibling' : 'previousSibling';
  10188.         for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10189.           if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10190.             return node;
  10191.           }
  10192.         }
  10193.       }
  10194.     };
  10195.     var isTextBlock$1 = function (editor, name) {
  10196.       if (isNode(name)) {
  10197.         name = name.nodeName;
  10198.       }
  10199.       return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10200.     };
  10201.     var isValid = function (ed, parent, child) {
  10202.       return ed.schema.isValidChild(parent, child);
  10203.     };
  10204.     var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10205.       if (allowSpaces === void 0) {
  10206.         allowSpaces = false;
  10207.       }
  10208.       if (isNonNullable(node) && isText$7(node)) {
  10209.         var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10210.         return isWhitespaceText(data);
  10211.       } else {
  10212.         return false;
  10213.       }
  10214.     };
  10215.     var isEmptyTextNode$1 = function (node) {
  10216.       return isNonNullable(node) && isText$7(node) && node.length === 0;
  10217.     };
  10218.     var replaceVars = function (value, vars) {
  10219.       if (isFunction(value)) {
  10220.         value = value(vars);
  10221.       } else if (isNonNullable(vars)) {
  10222.         value = value.replace(/%(\w+)/g, function (str, name) {
  10223.           return vars[name] || str;
  10224.         });
  10225.       }
  10226.       return value;
  10227.     };
  10228.     var isEq$5 = function (str1, str2) {
  10229.       str1 = str1 || '';
  10230.       str2 = str2 || '';
  10231.       str1 = '' + (str1.nodeName || str1);
  10232.       str2 = '' + (str2.nodeName || str2);
  10233.       return str1.toLowerCase() === str2.toLowerCase();
  10234.     };
  10235.     var normalizeStyleValue = function (dom, value, name) {
  10236.       if (name === 'color' || name === 'backgroundColor') {
  10237.         value = dom.toHex(value);
  10238.       }
  10239.       if (name === 'fontWeight' && value === 700) {
  10240.         value = 'bold';
  10241.       }
  10242.       if (name === 'fontFamily') {
  10243.         value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10244.       }
  10245.       return '' + value;
  10246.     };
  10247.     var getStyle = function (dom, node, name) {
  10248.       return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10249.     };
  10250.     var getTextDecoration = function (dom, node) {
  10251.       var decoration;
  10252.       dom.getParent(node, function (n) {
  10253.         decoration = dom.getStyle(n, 'text-decoration');
  10254.         return decoration && decoration !== 'none';
  10255.       });
  10256.       return decoration;
  10257.     };
  10258.     var getParents$2 = function (dom, node, selector) {
  10259.       return dom.getParents(node, selector, dom.getRoot());
  10260.     };
  10261.     var isVariableFormatName = function (editor, formatName) {
  10262.       var hasVariableValues = function (format) {
  10263.         var isVariableValue = function (val) {
  10264.           return val.length > 1 && val.charAt(0) === '%';
  10265.         };
  10266.         return exists([
  10267.           'styles',
  10268.           'attributes'
  10269.         ], function (key) {
  10270.           return get$9(format, key).exists(function (field) {
  10271.             var fieldValues = isArray$1(field) ? field : values(field);
  10272.             return exists(fieldValues, isVariableValue);
  10273.           });
  10274.         });
  10275.       };
  10276.       return exists(editor.formatter.get(formatName), hasVariableValues);
  10277.     };
  10278.     var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10279.       var validKeys = [
  10280.         'inline',
  10281.         'block',
  10282.         'selector',
  10283.         'attributes',
  10284.         'styles',
  10285.         'classes'
  10286.       ];
  10287.       var filterObj = function (format) {
  10288.         return filter$3(format, function (_, key) {
  10289.           return exists(validKeys, function (validKey) {
  10290.             return validKey === key;
  10291.           });
  10292.         });
  10293.       };
  10294.       return exists(editor.formatter.get(formatName), function (fmt1) {
  10295.         var filteredFmt1 = filterObj(fmt1);
  10296.         return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10297.           var filteredFmt2 = filterObj(fmt2);
  10298.           return equal$1(filteredFmt1, filteredFmt2);
  10299.         });
  10300.       });
  10301.     };
  10302.     var isBlockFormat = function (format) {
  10303.       return hasNonNullableKey(format, 'block');
  10304.     };
  10305.     var isSelectorFormat = function (format) {
  10306.       return hasNonNullableKey(format, 'selector');
  10307.     };
  10308.     var isInlineFormat = function (format) {
  10309.       return hasNonNullableKey(format, 'inline');
  10310.     };
  10311.     var isMixedFormat = function (format) {
  10312.       return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10313.     };
  10314.     var shouldExpandToSelector = function (format) {
  10315.       return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10316.     };
  10317.  
  10318.     var isBookmarkNode = isBookmarkNode$1;
  10319.     var getParents$1 = getParents$2;
  10320.     var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10321.     var isTextBlock = isTextBlock$1;
  10322.     var isBogusBr = function (node) {
  10323.       return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10324.     };
  10325.     var findParentContentEditable = function (dom, node) {
  10326.       var parent = node;
  10327.       while (parent) {
  10328.         if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10329.           return dom.getContentEditable(parent) === 'false' ? parent : node;
  10330.         }
  10331.         parent = parent.parentNode;
  10332.       }
  10333.       return node;
  10334.     };
  10335.     var walkText = function (start, node, offset, predicate) {
  10336.       var str = node.data;
  10337.       for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10338.         if (predicate(str.charAt(i))) {
  10339.           return start ? i + 1 : i;
  10340.         }
  10341.       }
  10342.       return -1;
  10343.     };
  10344.     var findSpace = function (start, node, offset) {
  10345.       return walkText(start, node, offset, function (c) {
  10346.         return isNbsp(c) || isWhiteSpace(c);
  10347.       });
  10348.     };
  10349.     var findContent = function (start, node, offset) {
  10350.       return walkText(start, node, offset, isContent);
  10351.     };
  10352.     var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10353.       var lastTextNode;
  10354.       var rootNode = dom.getParent(container, dom.isBlock) || body;
  10355.       var walk = function (container, offset, pred) {
  10356.         var textSeeker = TextSeeker(dom);
  10357.         var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10358.         return Optional.from(walker(container, offset, function (text, textOffset) {
  10359.           if (isBookmarkNode(text.parentNode)) {
  10360.             return -1;
  10361.           } else {
  10362.             lastTextNode = text;
  10363.             return pred(start, text, textOffset);
  10364.           }
  10365.         }, rootNode));
  10366.       };
  10367.       var spaceResult = walk(container, offset, findSpace);
  10368.       return spaceResult.bind(function (result) {
  10369.         return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10370.       }).orThunk(function () {
  10371.         return lastTextNode ? Optional.some({
  10372.           container: lastTextNode,
  10373.           offset: start ? 0 : lastTextNode.length
  10374.         }) : Optional.none();
  10375.       });
  10376.     };
  10377.     var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10378.       if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10379.         container = container[siblingName];
  10380.       }
  10381.       var parents = getParents$1(dom, container);
  10382.       for (var i = 0; i < parents.length; i++) {
  10383.         for (var y = 0; y < formatList.length; y++) {
  10384.           var curFormat = formatList[y];
  10385.           if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10386.             continue;
  10387.           }
  10388.           if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10389.             return parents[i];
  10390.           }
  10391.         }
  10392.       }
  10393.       return container;
  10394.     };
  10395.     var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10396.       var node = container;
  10397.       var dom = editor.dom;
  10398.       var root = dom.getRoot();
  10399.       var format = formatList[0];
  10400.       if (isBlockFormat(format)) {
  10401.         node = format.wrapper ? null : dom.getParent(container, format.block, root);
  10402.       }
  10403.       if (!node) {
  10404.         var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10405.         node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10406.           return node !== root && isTextBlock(editor, node);
  10407.         }, scopeRoot);
  10408.       }
  10409.       if (node && isBlockFormat(format) && format.wrapper) {
  10410.         node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10411.       }
  10412.       if (!node) {
  10413.         node = container;
  10414.         while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10415.           node = node[siblingName];
  10416.           if (isEq$5(node, 'br')) {
  10417.             break;
  10418.           }
  10419.         }
  10420.       }
  10421.       return node || container;
  10422.     };
  10423.     var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10424.       var parent = container.parentNode;
  10425.       if (isNonNullable(container[siblingName])) {
  10426.         return false;
  10427.       } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10428.         return true;
  10429.       } else {
  10430.         return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10431.       }
  10432.     };
  10433.     var findParentContainer = function (dom, formatList, container, offset, start) {
  10434.       var parent = container;
  10435.       var siblingName = start ? 'previousSibling' : 'nextSibling';
  10436.       var root = dom.getRoot();
  10437.       if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10438.         if (start ? offset > 0 : offset < container.data.length) {
  10439.           return container;
  10440.         }
  10441.       }
  10442.       while (true) {
  10443.         if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10444.           return parent;
  10445.         }
  10446.         for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10447.           var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10448.           if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10449.             return parent;
  10450.           }
  10451.         }
  10452.         if (parent === root || parent.parentNode === root) {
  10453.           container = parent;
  10454.           break;
  10455.         }
  10456.         parent = parent.parentNode;
  10457.       }
  10458.       return container;
  10459.     };
  10460.     var isSelfOrParentBookmark = function (container) {
  10461.       return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10462.     };
  10463.     var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10464.       if (includeTrailingSpace === void 0) {
  10465.         includeTrailingSpace = false;
  10466.       }
  10467.       var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10468.       var dom = editor.dom;
  10469.       var format = formatList[0];
  10470.       if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10471.         startContainer = getNode$1(startContainer, startOffset);
  10472.         if (isText$7(startContainer)) {
  10473.           startOffset = 0;
  10474.         }
  10475.       }
  10476.       if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10477.         endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10478.         if (isText$7(endContainer)) {
  10479.           endOffset = endContainer.nodeValue.length;
  10480.         }
  10481.       }
  10482.       startContainer = findParentContentEditable(dom, startContainer);
  10483.       endContainer = findParentContentEditable(dom, endContainer);
  10484.       if (isSelfOrParentBookmark(startContainer)) {
  10485.         startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10486.         if (rng.collapsed) {
  10487.           startContainer = startContainer.previousSibling || startContainer;
  10488.         } else {
  10489.           startContainer = startContainer.nextSibling || startContainer;
  10490.         }
  10491.         if (isText$7(startContainer)) {
  10492.           startOffset = rng.collapsed ? startContainer.length : 0;
  10493.         }
  10494.       }
  10495.       if (isSelfOrParentBookmark(endContainer)) {
  10496.         endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10497.         if (rng.collapsed) {
  10498.           endContainer = endContainer.nextSibling || endContainer;
  10499.         } else {
  10500.           endContainer = endContainer.previousSibling || endContainer;
  10501.         }
  10502.         if (isText$7(endContainer)) {
  10503.           endOffset = rng.collapsed ? 0 : endContainer.length;
  10504.         }
  10505.       }
  10506.       if (rng.collapsed) {
  10507.         var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10508.         startPoint.each(function (_a) {
  10509.           var container = _a.container, offset = _a.offset;
  10510.           startContainer = container;
  10511.           startOffset = offset;
  10512.         });
  10513.         var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10514.         endPoint.each(function (_a) {
  10515.           var container = _a.container, offset = _a.offset;
  10516.           endContainer = container;
  10517.           endOffset = offset;
  10518.         });
  10519.       }
  10520.       if (isInlineFormat(format) || format.block_expand) {
  10521.         if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10522.           startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10523.         }
  10524.         if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10525.           endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10526.         }
  10527.       }
  10528.       if (shouldExpandToSelector(format)) {
  10529.         startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10530.         endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10531.       }
  10532.       if (isBlockFormat(format) || isSelectorFormat(format)) {
  10533.         startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10534.         endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10535.         if (isBlockFormat(format)) {
  10536.           if (!dom.isBlock(startContainer)) {
  10537.             startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10538.           }
  10539.           if (!dom.isBlock(endContainer)) {
  10540.             endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10541.           }
  10542.         }
  10543.       }
  10544.       if (isElement$5(startContainer)) {
  10545.         startOffset = dom.nodeIndex(startContainer);
  10546.         startContainer = startContainer.parentNode;
  10547.       }
  10548.       if (isElement$5(endContainer)) {
  10549.         endOffset = dom.nodeIndex(endContainer) + 1;
  10550.         endContainer = endContainer.parentNode;
  10551.       }
  10552.       return {
  10553.         startContainer: startContainer,
  10554.         startOffset: startOffset,
  10555.         endContainer: endContainer,
  10556.         endOffset: endOffset
  10557.       };
  10558.     };
  10559.  
  10560.     var walk$2 = function (dom, rng, callback) {
  10561.       var startOffset = rng.startOffset;
  10562.       var startContainer = getNode$1(rng.startContainer, startOffset);
  10563.       var endOffset = rng.endOffset;
  10564.       var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10565.       var exclude = function (nodes) {
  10566.         var firstNode = nodes[0];
  10567.         if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10568.           nodes.splice(0, 1);
  10569.         }
  10570.         var lastNode = nodes[nodes.length - 1];
  10571.         if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10572.           nodes.splice(nodes.length - 1, 1);
  10573.         }
  10574.         return nodes;
  10575.       };
  10576.       var collectSiblings = function (node, name, endNode) {
  10577.         var siblings = [];
  10578.         for (; node && node !== endNode; node = node[name]) {
  10579.           siblings.push(node);
  10580.         }
  10581.         return siblings;
  10582.       };
  10583.       var findEndPoint = function (node, root) {
  10584.         return dom.getParent(node, function (node) {
  10585.           return node.parentNode === root;
  10586.         }, root);
  10587.       };
  10588.       var walkBoundary = function (startNode, endNode, next) {
  10589.         var siblingName = next ? 'nextSibling' : 'previousSibling';
  10590.         for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10591.           parent_1 = node.parentNode;
  10592.           var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10593.           if (siblings_1.length) {
  10594.             if (!next) {
  10595.               siblings_1.reverse();
  10596.             }
  10597.             callback(exclude(siblings_1));
  10598.           }
  10599.         }
  10600.       };
  10601.       if (startContainer === endContainer) {
  10602.         return callback(exclude([startContainer]));
  10603.       }
  10604.       var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10605.       if (dom.isChildOf(startContainer, endContainer)) {
  10606.         return walkBoundary(startContainer, ancestor, true);
  10607.       }
  10608.       if (dom.isChildOf(endContainer, startContainer)) {
  10609.         return walkBoundary(endContainer, ancestor);
  10610.       }
  10611.       var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10612.       var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10613.       walkBoundary(startContainer, startPoint, true);
  10614.       var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10615.       if (siblings.length) {
  10616.         callback(exclude(siblings));
  10617.       }
  10618.       walkBoundary(endContainer, endPoint);
  10619.     };
  10620.  
  10621.     var getRanges = function (selection) {
  10622.       var ranges = [];
  10623.       if (selection) {
  10624.         for (var i = 0; i < selection.rangeCount; i++) {
  10625.           ranges.push(selection.getRangeAt(i));
  10626.         }
  10627.       }
  10628.       return ranges;
  10629.     };
  10630.     var getSelectedNodes = function (ranges) {
  10631.       return bind(ranges, function (range) {
  10632.         var node = getSelectedNode(range);
  10633.         return node ? [SugarElement.fromDom(node)] : [];
  10634.       });
  10635.     };
  10636.     var hasMultipleRanges = function (selection) {
  10637.       return getRanges(selection).length > 1;
  10638.     };
  10639.  
  10640.     var getCellsFromRanges = function (ranges) {
  10641.       return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10642.     };
  10643.     var getCellsFromElement = function (elm) {
  10644.       return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10645.     };
  10646.     var getCellsFromElementOrRanges = function (ranges, element) {
  10647.       var selectedCells = getCellsFromElement(element);
  10648.       return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10649.     };
  10650.     var getCellsFromEditor = function (editor) {
  10651.       return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10652.     };
  10653.     var getClosestTable = function (cell, isRoot) {
  10654.       return ancestor$2(cell, 'table', isRoot);
  10655.     };
  10656.  
  10657.     var getStartNode = function (rng) {
  10658.       var sc = rng.startContainer, so = rng.startOffset;
  10659.       if (isText$7(sc)) {
  10660.         return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10661.       } else {
  10662.         return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10663.       }
  10664.     };
  10665.     var getEndNode = function (rng) {
  10666.       var ec = rng.endContainer, eo = rng.endOffset;
  10667.       if (isText$7(ec)) {
  10668.         return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10669.       } else {
  10670.         return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10671.       }
  10672.     };
  10673.     var getFirstChildren = function (node) {
  10674.       return firstChild(node).fold(constant([node]), function (child) {
  10675.         return [node].concat(getFirstChildren(child));
  10676.       });
  10677.     };
  10678.     var getLastChildren$1 = function (node) {
  10679.       return lastChild(node).fold(constant([node]), function (child) {
  10680.         if (name(child) === 'br') {
  10681.           return prevSibling(child).map(function (sibling) {
  10682.             return [node].concat(getLastChildren$1(sibling));
  10683.           }).getOr([]);
  10684.         } else {
  10685.           return [node].concat(getLastChildren$1(child));
  10686.         }
  10687.       });
  10688.     };
  10689.     var hasAllContentsSelected = function (elm, rng) {
  10690.       return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10691.         var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  10692.         var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  10693.         return start.isSome() && end.isSome();
  10694.       }).getOr(false);
  10695.     };
  10696.     var moveEndPoint = function (dom, rng, node, start) {
  10697.       var root = node, walker = new DomTreeWalker(node, root);
  10698.       var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10699.         return !contains$3([
  10700.           'td',
  10701.           'th',
  10702.           'table'
  10703.         ], name.toLowerCase());
  10704.       });
  10705.       do {
  10706.         if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  10707.           if (start) {
  10708.             rng.setStart(node, 0);
  10709.           } else {
  10710.             rng.setEnd(node, node.nodeValue.length);
  10711.           }
  10712.           return;
  10713.         }
  10714.         if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10715.           if (start) {
  10716.             rng.setStartBefore(node);
  10717.           } else {
  10718.             if (node.nodeName === 'BR') {
  10719.               rng.setEndBefore(node);
  10720.             } else {
  10721.               rng.setEndAfter(node);
  10722.             }
  10723.           }
  10724.           return;
  10725.         }
  10726.       } while (node = start ? walker.next() : walker.prev());
  10727.       if (root.nodeName === 'BODY') {
  10728.         if (start) {
  10729.           rng.setStart(root, 0);
  10730.         } else {
  10731.           rng.setEnd(root, root.childNodes.length);
  10732.         }
  10733.       }
  10734.     };
  10735.     var hasAnyRanges = function (editor) {
  10736.       var sel = editor.selection.getSel();
  10737.       return sel && sel.rangeCount > 0;
  10738.     };
  10739.     var runOnRanges = function (editor, executor) {
  10740.       var fakeSelectionNodes = getCellsFromEditor(editor);
  10741.       if (fakeSelectionNodes.length > 0) {
  10742.         each$k(fakeSelectionNodes, function (elem) {
  10743.           var node = elem.dom;
  10744.           var fakeNodeRng = editor.dom.createRng();
  10745.           fakeNodeRng.setStartBefore(node);
  10746.           fakeNodeRng.setEndAfter(node);
  10747.           executor(fakeNodeRng, true);
  10748.         });
  10749.       } else {
  10750.         executor(editor.selection.getRng(), false);
  10751.       }
  10752.     };
  10753.     var preserve = function (selection, fillBookmark, executor) {
  10754.       var bookmark = getPersistentBookmark(selection, fillBookmark);
  10755.       executor(bookmark);
  10756.       selection.moveToBookmark(bookmark);
  10757.     };
  10758.  
  10759.     var NodeValue = function (is, name) {
  10760.       var get = function (element) {
  10761.         if (!is(element)) {
  10762.           throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10763.         }
  10764.         return getOption(element).getOr('');
  10765.       };
  10766.       var getOption = function (element) {
  10767.         return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10768.       };
  10769.       var set = function (element, value) {
  10770.         if (!is(element)) {
  10771.           throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10772.         }
  10773.         element.dom.nodeValue = value;
  10774.       };
  10775.       return {
  10776.         get: get,
  10777.         getOption: getOption,
  10778.         set: set
  10779.       };
  10780.     };
  10781.  
  10782.     var api$1 = NodeValue(isText$8, 'text');
  10783.     var get$2 = function (element) {
  10784.       return api$1.get(element);
  10785.     };
  10786.  
  10787.     var isZeroWidth = function (elem) {
  10788.       return isText$8(elem) && get$2(elem) === ZWSP$1;
  10789.     };
  10790.     var context = function (editor, elem, wrapName, nodeName) {
  10791.       return parent(elem).fold(function () {
  10792.         return 'skipping';
  10793.       }, function (parent) {
  10794.         if (nodeName === 'br' || isZeroWidth(elem)) {
  10795.           return 'valid';
  10796.         } else if (isAnnotation(elem)) {
  10797.           return 'existing';
  10798.         } else if (isCaretNode(elem.dom)) {
  10799.           return 'caret';
  10800.         } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10801.           return 'invalid-child';
  10802.         } else {
  10803.           return 'valid';
  10804.         }
  10805.       });
  10806.     };
  10807.  
  10808.     var applyWordGrab = function (editor, rng) {
  10809.       var r = expandRng(editor, rng, [{ inline: 'span' }]);
  10810.       rng.setStart(r.startContainer, r.startOffset);
  10811.       rng.setEnd(r.endContainer, r.endOffset);
  10812.       editor.selection.setRng(rng);
  10813.     };
  10814.     var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  10815.       var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  10816.       var master = SugarElement.fromTag('span', eDoc);
  10817.       add$1(master, annotation());
  10818.       set$1(master, '' + dataAnnotationId(), uid);
  10819.       set$1(master, '' + dataAnnotation(), annotationName);
  10820.       var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  10821.       setAll$1(master, attributes);
  10822.       add(master, classes);
  10823.       return master;
  10824.     };
  10825.     var annotate = function (editor, rng, annotationName, decorate, data) {
  10826.       var newWrappers = [];
  10827.       var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  10828.       var wrapper = value();
  10829.       var finishWrapper = function () {
  10830.         wrapper.clear();
  10831.       };
  10832.       var getOrOpenWrapper = function () {
  10833.         return wrapper.get().getOrThunk(function () {
  10834.           var nu = shallow(master);
  10835.           newWrappers.push(nu);
  10836.           wrapper.set(nu);
  10837.           return nu;
  10838.         });
  10839.       };
  10840.       var processElements = function (elems) {
  10841.         each$k(elems, processElement);
  10842.       };
  10843.       var processElement = function (elem) {
  10844.         var ctx = context(editor, elem, 'span', name(elem));
  10845.         switch (ctx) {
  10846.         case 'invalid-child': {
  10847.             finishWrapper();
  10848.             var children$1 = children(elem);
  10849.             processElements(children$1);
  10850.             finishWrapper();
  10851.             break;
  10852.           }
  10853.         case 'valid': {
  10854.             var w = getOrOpenWrapper();
  10855.             wrap$3(elem, w);
  10856.             break;
  10857.           }
  10858.         }
  10859.       };
  10860.       var processNodes = function (nodes) {
  10861.         var elems = map$3(nodes, SugarElement.fromDom);
  10862.         processElements(elems);
  10863.       };
  10864.       walk$2(editor.dom, rng, function (nodes) {
  10865.         finishWrapper();
  10866.         processNodes(nodes);
  10867.       });
  10868.       return newWrappers;
  10869.     };
  10870.     var annotateWithBookmark = function (editor, name, settings, data) {
  10871.       editor.undoManager.transact(function () {
  10872.         var selection = editor.selection;
  10873.         var initialRng = selection.getRng();
  10874.         var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  10875.         if (initialRng.collapsed && !hasFakeSelection) {
  10876.           applyWordGrab(editor, initialRng);
  10877.         }
  10878.         if (selection.getRng().collapsed && !hasFakeSelection) {
  10879.           var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  10880.           set(wrapper, nbsp);
  10881.           selection.getRng().insertNode(wrapper.dom);
  10882.           selection.select(wrapper.dom);
  10883.         } else {
  10884.           preserve(selection, false, function () {
  10885.             runOnRanges(editor, function (selectionRng) {
  10886.               annotate(editor, selectionRng, name, settings.decorate, data);
  10887.             });
  10888.           });
  10889.         }
  10890.       });
  10891.     };
  10892.  
  10893.     var Annotator = function (editor) {
  10894.       var registry = create$7();
  10895.       setup$m(editor, registry);
  10896.       var changes = setup$n(editor);
  10897.       return {
  10898.         register: function (name, settings) {
  10899.           registry.register(name, settings);
  10900.         },
  10901.         annotate: function (name, data) {
  10902.           registry.lookup(name).each(function (settings) {
  10903.             annotateWithBookmark(editor, name, settings, data);
  10904.           });
  10905.         },
  10906.         annotationChanged: function (name, callback) {
  10907.           changes.addListener(name, callback);
  10908.         },
  10909.         remove: function (name) {
  10910.           identify(editor, Optional.some(name)).each(function (_a) {
  10911.             var elements = _a.elements;
  10912.             each$k(elements, unwrap);
  10913.           });
  10914.         },
  10915.         getAll: function (name) {
  10916.           var directory = findAll(editor, name);
  10917.           return map$2(directory, function (elems) {
  10918.             return map$3(elems, function (elem) {
  10919.               return elem.dom;
  10920.             });
  10921.           });
  10922.         }
  10923.       };
  10924.     };
  10925.  
  10926.     var BookmarkManager = function (selection) {
  10927.       return {
  10928.         getBookmark: curry(getBookmark$1, selection),
  10929.         moveToBookmark: curry(moveToBookmark, selection)
  10930.       };
  10931.     };
  10932.     BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  10933.  
  10934.     var getContentEditableRoot$1 = function (root, node) {
  10935.       while (node && node !== root) {
  10936.         if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  10937.           return node;
  10938.         }
  10939.         node = node.parentNode;
  10940.       }
  10941.       return null;
  10942.     };
  10943.  
  10944.     var isXYWithinRange = function (clientX, clientY, range) {
  10945.       if (range.collapsed) {
  10946.         return false;
  10947.       }
  10948.       if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  10949.         var elm = range.startContainer.childNodes[range.startOffset];
  10950.         if (isElement$5(elm)) {
  10951.           return exists(elm.getClientRects(), function (rect) {
  10952.             return containsXY(rect, clientX, clientY);
  10953.           });
  10954.         }
  10955.       }
  10956.       return exists(range.getClientRects(), function (rect) {
  10957.         return containsXY(rect, clientX, clientY);
  10958.       });
  10959.     };
  10960.  
  10961.     var firePreProcess = function (editor, args) {
  10962.       return editor.fire('PreProcess', args);
  10963.     };
  10964.     var firePostProcess = function (editor, args) {
  10965.       return editor.fire('PostProcess', args);
  10966.     };
  10967.     var fireRemove = function (editor) {
  10968.       return editor.fire('remove');
  10969.     };
  10970.     var fireDetach = function (editor) {
  10971.       return editor.fire('detach');
  10972.     };
  10973.     var fireSwitchMode = function (editor, mode) {
  10974.       return editor.fire('SwitchMode', { mode: mode });
  10975.     };
  10976.     var fireObjectResizeStart = function (editor, target, width, height, origin) {
  10977.       editor.fire('ObjectResizeStart', {
  10978.         target: target,
  10979.         width: width,
  10980.         height: height,
  10981.         origin: origin
  10982.       });
  10983.     };
  10984.     var fireObjectResized = function (editor, target, width, height, origin) {
  10985.       editor.fire('ObjectResized', {
  10986.         target: target,
  10987.         width: width,
  10988.         height: height,
  10989.         origin: origin
  10990.       });
  10991.     };
  10992.     var firePreInit = function (editor) {
  10993.       return editor.fire('PreInit');
  10994.     };
  10995.     var firePostRender = function (editor) {
  10996.       return editor.fire('PostRender');
  10997.     };
  10998.     var fireInit = function (editor) {
  10999.       return editor.fire('Init');
  11000.     };
  11001.     var firePlaceholderToggle = function (editor, state) {
  11002.       return editor.fire('PlaceholderToggle', { state: state });
  11003.     };
  11004.     var fireError = function (editor, errorType, error) {
  11005.       return editor.fire(errorType, error);
  11006.     };
  11007.     var fireFormatApply = function (editor, format, node, vars) {
  11008.       return editor.fire('FormatApply', {
  11009.         format: format,
  11010.         node: node,
  11011.         vars: vars
  11012.       });
  11013.     };
  11014.     var fireFormatRemove = function (editor, format, node, vars) {
  11015.       return editor.fire('FormatRemove', {
  11016.         format: format,
  11017.         node: node,
  11018.         vars: vars
  11019.       });
  11020.     };
  11021.  
  11022.     var VK = {
  11023.       BACKSPACE: 8,
  11024.       DELETE: 46,
  11025.       DOWN: 40,
  11026.       ENTER: 13,
  11027.       ESC: 27,
  11028.       LEFT: 37,
  11029.       RIGHT: 39,
  11030.       SPACEBAR: 32,
  11031.       TAB: 9,
  11032.       UP: 38,
  11033.       PAGE_UP: 33,
  11034.       PAGE_DOWN: 34,
  11035.       END: 35,
  11036.       HOME: 36,
  11037.       modifierPressed: function (e) {
  11038.         return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  11039.       },
  11040.       metaKeyPressed: function (e) {
  11041.         return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  11042.       }
  11043.     };
  11044.  
  11045.     var isContentEditableFalse$5 = isContentEditableFalse$b;
  11046.     var ControlSelection = function (selection, editor) {
  11047.       var elementSelectionAttr = 'data-mce-selected';
  11048.       var dom = editor.dom, each = Tools.each;
  11049.       var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  11050.       var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  11051.       var width, height;
  11052.       var editableDoc = editor.getDoc(), rootDocument = document;
  11053.       var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  11054.       var startScrollWidth, startScrollHeight;
  11055.       var resizeHandles = {
  11056.         nw: [
  11057.           0,
  11058.           0,
  11059.           -1,
  11060.           -1
  11061.         ],
  11062.         ne: [
  11063.           1,
  11064.           0,
  11065.           1,
  11066.           -1
  11067.         ],
  11068.         se: [
  11069.           1,
  11070.           1,
  11071.           1,
  11072.           1
  11073.         ],
  11074.         sw: [
  11075.           0,
  11076.           1,
  11077.           -1,
  11078.           1
  11079.         ]
  11080.       };
  11081.       var isImage = function (elm) {
  11082.         return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  11083.       };
  11084.       var isMedia = function (elm) {
  11085.         return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  11086.       };
  11087.       var isEventOnImageOutsideRange = function (evt, range) {
  11088.         if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  11089.           var touch = evt.touches[0];
  11090.           return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  11091.         } else {
  11092.           return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  11093.         }
  11094.       };
  11095.       var contextMenuSelectImage = function (evt) {
  11096.         var target = evt.target;
  11097.         if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  11098.           editor.selection.select(target);
  11099.         }
  11100.       };
  11101.       var getResizeTargets = function (elm) {
  11102.         if (dom.is(elm, 'figure.image')) {
  11103.           return [elm.querySelector('img')];
  11104.         } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  11105.           return [
  11106.             elm,
  11107.             elm.firstElementChild
  11108.           ];
  11109.         } else {
  11110.           return [elm];
  11111.         }
  11112.       };
  11113.       var isResizable = function (elm) {
  11114.         var selector = getObjectResizing(editor);
  11115.         if (!selector) {
  11116.           return false;
  11117.         }
  11118.         if (elm.getAttribute('data-mce-resize') === 'false') {
  11119.           return false;
  11120.         }
  11121.         if (elm === editor.getBody()) {
  11122.           return false;
  11123.         }
  11124.         if (dom.hasClass(elm, 'mce-preview-object')) {
  11125.           return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  11126.         } else {
  11127.           return is$2(SugarElement.fromDom(elm), selector);
  11128.         }
  11129.       };
  11130.       var createGhostElement = function (elm) {
  11131.         if (isMedia(elm)) {
  11132.           return dom.create('img', { src: Env.transparentSrc });
  11133.         } else {
  11134.           return elm.cloneNode(true);
  11135.         }
  11136.       };
  11137.       var setSizeProp = function (element, name, value) {
  11138.         if (isNonNullable(value)) {
  11139.           var targets = getResizeTargets(element);
  11140.           each$k(targets, function (target) {
  11141.             if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11142.               dom.setStyle(target, name, value);
  11143.             } else {
  11144.               dom.setAttrib(target, name, '' + value);
  11145.             }
  11146.           });
  11147.         }
  11148.       };
  11149.       var setGhostElmSize = function (ghostElm, width, height) {
  11150.         setSizeProp(ghostElm, 'width', width);
  11151.         setSizeProp(ghostElm, 'height', height);
  11152.       };
  11153.       var resizeGhostElement = function (e) {
  11154.         var deltaX, deltaY, proportional;
  11155.         var resizeHelperX, resizeHelperY;
  11156.         deltaX = e.screenX - startX;
  11157.         deltaY = e.screenY - startY;
  11158.         width = deltaX * selectedHandle[2] + startW;
  11159.         height = deltaY * selectedHandle[3] + startH;
  11160.         width = width < 5 ? 5 : width;
  11161.         height = height < 5 ? 5 : height;
  11162.         if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11163.           proportional = !VK.modifierPressed(e);
  11164.         } else {
  11165.           proportional = VK.modifierPressed(e);
  11166.         }
  11167.         if (proportional) {
  11168.           if (abs(deltaX) > abs(deltaY)) {
  11169.             height = round(width * ratio);
  11170.             width = round(height / ratio);
  11171.           } else {
  11172.             width = round(height / ratio);
  11173.             height = round(width * ratio);
  11174.           }
  11175.         }
  11176.         setGhostElmSize(selectedElmGhost, width, height);
  11177.         resizeHelperX = selectedHandle.startPos.x + deltaX;
  11178.         resizeHelperY = selectedHandle.startPos.y + deltaY;
  11179.         resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11180.         resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11181.         dom.setStyles(resizeHelper, {
  11182.           left: resizeHelperX,
  11183.           top: resizeHelperY,
  11184.           display: 'block'
  11185.         });
  11186.         resizeHelper.innerHTML = width + ' &times; ' + height;
  11187.         if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11188.           dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11189.         }
  11190.         if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11191.           dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11192.         }
  11193.         deltaX = rootElement.scrollWidth - startScrollWidth;
  11194.         deltaY = rootElement.scrollHeight - startScrollHeight;
  11195.         if (deltaX + deltaY !== 0) {
  11196.           dom.setStyles(resizeHelper, {
  11197.             left: resizeHelperX - deltaX,
  11198.             top: resizeHelperY - deltaY
  11199.           });
  11200.         }
  11201.         if (!resizeStarted) {
  11202.           fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11203.           resizeStarted = true;
  11204.         }
  11205.       };
  11206.       var endGhostResize = function () {
  11207.         var wasResizeStarted = resizeStarted;
  11208.         resizeStarted = false;
  11209.         if (wasResizeStarted) {
  11210.           setSizeProp(selectedElm, 'width', width);
  11211.           setSizeProp(selectedElm, 'height', height);
  11212.         }
  11213.         dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11214.         dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11215.         if (rootDocument !== editableDoc) {
  11216.           dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11217.           dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11218.         }
  11219.         dom.remove(selectedElmGhost);
  11220.         dom.remove(resizeHelper);
  11221.         dom.remove(resizeBackdrop);
  11222.         showResizeRect(selectedElm);
  11223.         if (wasResizeStarted) {
  11224.           fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11225.           dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11226.         }
  11227.         editor.nodeChanged();
  11228.       };
  11229.       var showResizeRect = function (targetElm) {
  11230.         unbindResizeHandleEvents();
  11231.         var position = dom.getPos(targetElm, rootElement);
  11232.         var selectedElmX = position.x;
  11233.         var selectedElmY = position.y;
  11234.         var rect = targetElm.getBoundingClientRect();
  11235.         var targetWidth = rect.width || rect.right - rect.left;
  11236.         var targetHeight = rect.height || rect.bottom - rect.top;
  11237.         if (selectedElm !== targetElm) {
  11238.           hideResizeRect();
  11239.           selectedElm = targetElm;
  11240.           width = height = 0;
  11241.         }
  11242.         var e = editor.fire('ObjectSelected', { target: targetElm });
  11243.         var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11244.         if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11245.           each(resizeHandles, function (handle, name) {
  11246.             var handleElm;
  11247.             var startDrag = function (e) {
  11248.               var target = getResizeTargets(selectedElm)[0];
  11249.               startX = e.screenX;
  11250.               startY = e.screenY;
  11251.               startW = target.clientWidth;
  11252.               startH = target.clientHeight;
  11253.               ratio = startH / startW;
  11254.               selectedHandle = handle;
  11255.               selectedHandle.name = name;
  11256.               selectedHandle.startPos = {
  11257.                 x: targetWidth * handle[0] + selectedElmX,
  11258.                 y: targetHeight * handle[1] + selectedElmY
  11259.               };
  11260.               startScrollWidth = rootElement.scrollWidth;
  11261.               startScrollHeight = rootElement.scrollHeight;
  11262.               resizeBackdrop = dom.add(rootElement, 'div', {
  11263.                 'class': 'mce-resize-backdrop',
  11264.                 'data-mce-bogus': 'all'
  11265.               });
  11266.               dom.setStyles(resizeBackdrop, {
  11267.                 position: 'fixed',
  11268.                 left: '0',
  11269.                 top: '0',
  11270.                 width: '100%',
  11271.                 height: '100%'
  11272.               });
  11273.               selectedElmGhost = createGhostElement(selectedElm);
  11274.               dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11275.               dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11276.               selectedElmGhost.contentEditable = 'false';
  11277.               dom.setStyles(selectedElmGhost, {
  11278.                 left: selectedElmX,
  11279.                 top: selectedElmY,
  11280.                 margin: 0
  11281.               });
  11282.               setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11283.               selectedElmGhost.removeAttribute(elementSelectionAttr);
  11284.               rootElement.appendChild(selectedElmGhost);
  11285.               dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11286.               dom.bind(editableDoc, 'mouseup', endGhostResize);
  11287.               if (rootDocument !== editableDoc) {
  11288.                 dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11289.                 dom.bind(rootDocument, 'mouseup', endGhostResize);
  11290.               }
  11291.               resizeHelper = dom.add(rootElement, 'div', {
  11292.                 'class': 'mce-resize-helper',
  11293.                 'data-mce-bogus': 'all'
  11294.               }, startW + ' &times; ' + startH);
  11295.             };
  11296.             handleElm = dom.get('mceResizeHandle' + name);
  11297.             if (handleElm) {
  11298.               dom.remove(handleElm);
  11299.             }
  11300.             handleElm = dom.add(rootElement, 'div', {
  11301.               'id': 'mceResizeHandle' + name,
  11302.               'data-mce-bogus': 'all',
  11303.               'class': 'mce-resizehandle',
  11304.               'unselectable': true,
  11305.               'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11306.             });
  11307.             if (Env.ie === 11) {
  11308.               handleElm.contentEditable = false;
  11309.             }
  11310.             dom.bind(handleElm, 'mousedown', function (e) {
  11311.               e.stopImmediatePropagation();
  11312.               e.preventDefault();
  11313.               startDrag(e);
  11314.             });
  11315.             handle.elm = handleElm;
  11316.             dom.setStyles(handleElm, {
  11317.               left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11318.               top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11319.             });
  11320.           });
  11321.         } else {
  11322.           hideResizeRect();
  11323.         }
  11324.         if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11325.           selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11326.         }
  11327.       };
  11328.       var hideResizeRect = function () {
  11329.         unbindResizeHandleEvents();
  11330.         if (selectedElm) {
  11331.           selectedElm.removeAttribute(elementSelectionAttr);
  11332.         }
  11333.         each$j(resizeHandles, function (value, name) {
  11334.           var handleElm = dom.get('mceResizeHandle' + name);
  11335.           if (handleElm) {
  11336.             dom.unbind(handleElm);
  11337.             dom.remove(handleElm);
  11338.           }
  11339.         });
  11340.       };
  11341.       var updateResizeRect = function (e) {
  11342.         var startElm, controlElm;
  11343.         var isChildOrEqual = function (node, parent) {
  11344.           if (node) {
  11345.             do {
  11346.               if (node === parent) {
  11347.                 return true;
  11348.               }
  11349.             } while (node = node.parentNode);
  11350.           }
  11351.         };
  11352.         if (resizeStarted || editor.removed) {
  11353.           return;
  11354.         }
  11355.         each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11356.           img.removeAttribute(elementSelectionAttr);
  11357.         });
  11358.         controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11359.         controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11360.         if (isChildOrEqual(controlElm, rootElement)) {
  11361.           disableGeckoResize();
  11362.           startElm = selection.getStart(true);
  11363.           if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11364.             showResizeRect(controlElm);
  11365.             return;
  11366.           }
  11367.         }
  11368.         hideResizeRect();
  11369.       };
  11370.       var isWithinContentEditableFalse = function (elm) {
  11371.         return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11372.       };
  11373.       var unbindResizeHandleEvents = function () {
  11374.         each$j(resizeHandles, function (handle) {
  11375.           if (handle.elm) {
  11376.             dom.unbind(handle.elm);
  11377.             delete handle.elm;
  11378.           }
  11379.         });
  11380.       };
  11381.       var disableGeckoResize = function () {
  11382.         try {
  11383.           editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11384.         } catch (ex) {
  11385.         }
  11386.       };
  11387.       editor.on('init', function () {
  11388.         disableGeckoResize();
  11389.         if (Env.browser.isIE() || Env.browser.isEdge()) {
  11390.           editor.on('mousedown click', function (e) {
  11391.             var target = e.target, nodeName = target.nodeName;
  11392.             if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11393.               if (e.button !== 2) {
  11394.                 editor.selection.select(target, nodeName === 'TABLE');
  11395.               }
  11396.               if (e.type === 'mousedown') {
  11397.                 editor.nodeChanged();
  11398.               }
  11399.             }
  11400.           });
  11401.           var handleMSControlSelect_1 = function (e) {
  11402.             var delayedSelect = function (node) {
  11403.               Delay.setEditorTimeout(editor, function () {
  11404.                 return editor.selection.select(node);
  11405.               });
  11406.             };
  11407.             if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11408.               e.preventDefault();
  11409.               delayedSelect(e.target);
  11410.               return;
  11411.             }
  11412.             if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11413.               e.preventDefault();
  11414.               if (e.target.tagName === 'IMG') {
  11415.                 delayedSelect(e.target);
  11416.               }
  11417.             }
  11418.           };
  11419.           dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11420.           editor.on('remove', function () {
  11421.             return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11422.           });
  11423.         }
  11424.         var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11425.           if (!editor.composing) {
  11426.             updateResizeRect(e);
  11427.           }
  11428.         });
  11429.         editor.on('nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged', throttledUpdateResizeRect);
  11430.         editor.on('keyup compositionend', function (e) {
  11431.           if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11432.             throttledUpdateResizeRect(e);
  11433.           }
  11434.         });
  11435.         editor.on('hide blur', hideResizeRect);
  11436.         editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11437.       });
  11438.       editor.on('remove', unbindResizeHandleEvents);
  11439.       var destroy = function () {
  11440.         selectedElm = selectedElmGhost = resizeBackdrop = null;
  11441.       };
  11442.       return {
  11443.         isResizable: isResizable,
  11444.         showResizeRect: showResizeRect,
  11445.         hideResizeRect: hideResizeRect,
  11446.         updateResizeRect: updateResizeRect,
  11447.         destroy: destroy
  11448.       };
  11449.     };
  11450.  
  11451.     var hasCeProperty = function (node) {
  11452.       return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11453.     };
  11454.     var findParent$1 = function (node, rootNode, predicate) {
  11455.       while (node && node !== rootNode) {
  11456.         if (predicate(node)) {
  11457.           return node;
  11458.         }
  11459.         node = node.parentNode;
  11460.       }
  11461.       return null;
  11462.     };
  11463.     var findClosestIeRange = function (clientX, clientY, doc) {
  11464.       var rects;
  11465.       var element = doc.elementFromPoint(clientX, clientY);
  11466.       var rng = doc.body.createTextRange();
  11467.       if (!element || element.tagName === 'HTML') {
  11468.         element = doc.body;
  11469.       }
  11470.       rng.moveToElementText(element);
  11471.       rects = Tools.toArray(rng.getClientRects());
  11472.       rects = rects.sort(function (a, b) {
  11473.         a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11474.         b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11475.         return a - b;
  11476.       });
  11477.       if (rects.length > 0) {
  11478.         clientY = (rects[0].bottom + rects[0].top) / 2;
  11479.         try {
  11480.           rng.moveToPoint(clientX, clientY);
  11481.           rng.collapse(true);
  11482.           return rng;
  11483.         } catch (ex) {
  11484.         }
  11485.       }
  11486.       return null;
  11487.     };
  11488.     var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11489.       var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11490.       return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11491.     };
  11492.     var fromPoint = function (clientX, clientY, doc) {
  11493.       var rng, point;
  11494.       var pointDoc = doc;
  11495.       if (pointDoc.caretPositionFromPoint) {
  11496.         point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11497.         if (point) {
  11498.           rng = doc.createRange();
  11499.           rng.setStart(point.offsetNode, point.offset);
  11500.           rng.collapse(true);
  11501.         }
  11502.       } else if (pointDoc.caretRangeFromPoint) {
  11503.         rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11504.       } else if (pointDoc.body.createTextRange) {
  11505.         rng = pointDoc.body.createTextRange();
  11506.         try {
  11507.           rng.moveToPoint(clientX, clientY);
  11508.           rng.collapse(true);
  11509.         } catch (ex) {
  11510.           rng = findClosestIeRange(clientX, clientY, doc);
  11511.         }
  11512.         return moveOutOfContentEditableFalse(rng, doc.body);
  11513.       }
  11514.       return rng;
  11515.     };
  11516.  
  11517.     var isEq$4 = function (rng1, rng2) {
  11518.       return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11519.     };
  11520.  
  11521.     var findParent = function (node, rootNode, predicate) {
  11522.       while (node && node !== rootNode) {
  11523.         if (predicate(node)) {
  11524.           return node;
  11525.         }
  11526.         node = node.parentNode;
  11527.       }
  11528.       return null;
  11529.     };
  11530.     var hasParent$1 = function (node, rootNode, predicate) {
  11531.       return findParent(node, rootNode, predicate) !== null;
  11532.     };
  11533.     var hasParentWithName = function (node, rootNode, name) {
  11534.       return hasParent$1(node, rootNode, function (node) {
  11535.         return node.nodeName === name;
  11536.       });
  11537.     };
  11538.     var isTable = function (node) {
  11539.       return node && node.nodeName === 'TABLE';
  11540.     };
  11541.     var isTableCell$2 = function (node) {
  11542.       return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11543.     };
  11544.     var isCeFalseCaretContainer = function (node, rootNode) {
  11545.       return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11546.     };
  11547.     var hasBrBeforeAfter = function (dom, node, left) {
  11548.       var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11549.       while (node = walker[left ? 'prev' : 'next']()) {
  11550.         if (isBr$5(node)) {
  11551.           return true;
  11552.         }
  11553.       }
  11554.     };
  11555.     var isPrevNode = function (node, name) {
  11556.       return node.previousSibling && node.previousSibling.nodeName === name;
  11557.     };
  11558.     var hasContentEditableFalseParent = function (body, node) {
  11559.       while (node && node !== body) {
  11560.         if (isContentEditableFalse$b(node)) {
  11561.           return true;
  11562.         }
  11563.         node = node.parentNode;
  11564.       }
  11565.       return false;
  11566.     };
  11567.     var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11568.       var lastInlineElement;
  11569.       var body = dom.getRoot();
  11570.       var node;
  11571.       var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11572.       var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11573.       if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11574.         return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11575.       }
  11576.       var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11577.       while (node = walker[left ? 'prev' : 'next']()) {
  11578.         if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11579.           return Optional.none();
  11580.         }
  11581.         if (isText$7(node) && node.nodeValue.length > 0) {
  11582.           if (hasParentWithName(node, body, 'A') === false) {
  11583.             return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11584.           }
  11585.           return Optional.none();
  11586.         }
  11587.         if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11588.           return Optional.none();
  11589.         }
  11590.         lastInlineElement = node;
  11591.       }
  11592.       if (collapsed && lastInlineElement) {
  11593.         return Optional.some(CaretPosition(lastInlineElement, 0));
  11594.       }
  11595.       return Optional.none();
  11596.     };
  11597.     var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11598.       var container, offset;
  11599.       var body = dom.getRoot();
  11600.       var node;
  11601.       var directionLeft, normalized = false;
  11602.       container = rng[(start ? 'start' : 'end') + 'Container'];
  11603.       offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11604.       var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11605.       var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11606.       directionLeft = start;
  11607.       if (isCaretContainer$2(container)) {
  11608.         return Optional.none();
  11609.       }
  11610.       if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11611.         directionLeft = false;
  11612.       }
  11613.       if (isDocument$1(container)) {
  11614.         container = body;
  11615.         offset = 0;
  11616.       }
  11617.       if (container === body) {
  11618.         if (directionLeft) {
  11619.           node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11620.           if (node) {
  11621.             if (isCaretContainer$2(node)) {
  11622.               return Optional.none();
  11623.             }
  11624.             if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11625.               return Optional.none();
  11626.             }
  11627.           }
  11628.         }
  11629.         if (container.hasChildNodes()) {
  11630.           offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11631.           container = container.childNodes[offset];
  11632.           offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11633.           if (!collapsed && container === body.lastChild && isTable(container)) {
  11634.             return Optional.none();
  11635.           }
  11636.           if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11637.             return Optional.none();
  11638.           }
  11639.           if (container.hasChildNodes() && isTable(container) === false) {
  11640.             node = container;
  11641.             var walker = new DomTreeWalker(container, body);
  11642.             do {
  11643.               if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11644.                 normalized = false;
  11645.                 break;
  11646.               }
  11647.               if (isText$7(node) && node.nodeValue.length > 0) {
  11648.                 offset = directionLeft ? 0 : node.nodeValue.length;
  11649.                 container = node;
  11650.                 normalized = true;
  11651.                 break;
  11652.               }
  11653.               if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11654.                 offset = dom.nodeIndex(node);
  11655.                 container = node.parentNode;
  11656.                 if (!directionLeft) {
  11657.                   offset++;
  11658.                 }
  11659.                 normalized = true;
  11660.                 break;
  11661.               }
  11662.             } while (node = directionLeft ? walker.next() : walker.prev());
  11663.           }
  11664.         }
  11665.       }
  11666.       if (collapsed) {
  11667.         if (isText$7(container) && offset === 0) {
  11668.           findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11669.             container = pos.container();
  11670.             offset = pos.offset();
  11671.             normalized = true;
  11672.           });
  11673.         }
  11674.         if (isElement$5(container)) {
  11675.           node = container.childNodes[offset];
  11676.           if (!node) {
  11677.             node = container.childNodes[offset - 1];
  11678.           }
  11679.           if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11680.             findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11681.               container = pos.container();
  11682.               offset = pos.offset();
  11683.               normalized = true;
  11684.             });
  11685.           }
  11686.         }
  11687.       }
  11688.       if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11689.         findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11690.           container = pos.container();
  11691.           offset = pos.offset();
  11692.           normalized = true;
  11693.         });
  11694.       }
  11695.       return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11696.     };
  11697.     var normalize$2 = function (dom, rng) {
  11698.       var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11699.       var startPos = CaretPosition.fromRangeStart(rng);
  11700.       normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11701.         if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11702.           normRng.setStart(pos.container(), pos.offset());
  11703.         }
  11704.       });
  11705.       if (!collapsed) {
  11706.         normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11707.           normRng.setEnd(pos.container(), pos.offset());
  11708.         });
  11709.       }
  11710.       if (collapsed) {
  11711.         normRng.collapse(true);
  11712.       }
  11713.       return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11714.     };
  11715.  
  11716.     var splitText = function (node, offset) {
  11717.       return node.splitText(offset);
  11718.     };
  11719.     var split = function (rng) {
  11720.       var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11721.       if (startContainer === endContainer && isText$7(startContainer)) {
  11722.         if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11723.           endContainer = splitText(startContainer, startOffset);
  11724.           startContainer = endContainer.previousSibling;
  11725.           if (endOffset > startOffset) {
  11726.             endOffset = endOffset - startOffset;
  11727.             startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11728.             endOffset = endContainer.nodeValue.length;
  11729.             startOffset = 0;
  11730.           } else {
  11731.             endOffset = 0;
  11732.           }
  11733.         }
  11734.       } else {
  11735.         if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11736.           startContainer = splitText(startContainer, startOffset);
  11737.           startOffset = 0;
  11738.         }
  11739.         if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11740.           endContainer = splitText(endContainer, endOffset).previousSibling;
  11741.           endOffset = endContainer.nodeValue.length;
  11742.         }
  11743.       }
  11744.       return {
  11745.         startContainer: startContainer,
  11746.         startOffset: startOffset,
  11747.         endContainer: endContainer,
  11748.         endOffset: endOffset
  11749.       };
  11750.     };
  11751.  
  11752.     var RangeUtils = function (dom) {
  11753.       var walk = function (rng, callback) {
  11754.         return walk$2(dom, rng, callback);
  11755.       };
  11756.       var split$1 = split;
  11757.       var normalize = function (rng) {
  11758.         return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  11759.           rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11760.           rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11761.           return true;
  11762.         });
  11763.       };
  11764.       return {
  11765.         walk: walk,
  11766.         split: split$1,
  11767.         normalize: normalize
  11768.       };
  11769.     };
  11770.     RangeUtils.compareRanges = isEq$4;
  11771.     RangeUtils.getCaretRangeFromPoint = fromPoint;
  11772.     RangeUtils.getSelectedNode = getSelectedNode;
  11773.     RangeUtils.getNode = getNode$1;
  11774.  
  11775.     var Dimension = function (name, getOffset) {
  11776.       var set = function (element, h) {
  11777.         if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11778.           throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11779.         }
  11780.         var dom = element.dom;
  11781.         if (isSupported(dom)) {
  11782.           dom.style[name] = h + 'px';
  11783.         }
  11784.       };
  11785.       var get = function (element) {
  11786.         var r = getOffset(element);
  11787.         if (r <= 0 || r === null) {
  11788.           var css = get$5(element, name);
  11789.           return parseFloat(css) || 0;
  11790.         }
  11791.         return r;
  11792.       };
  11793.       var getOuter = get;
  11794.       var aggregate = function (element, properties) {
  11795.         return foldl(properties, function (acc, property) {
  11796.           var val = get$5(element, property);
  11797.           var value = val === undefined ? 0 : parseInt(val, 10);
  11798.           return isNaN(value) ? acc : acc + value;
  11799.         }, 0);
  11800.       };
  11801.       var max = function (element, value, properties) {
  11802.         var cumulativeInclusions = aggregate(element, properties);
  11803.         var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11804.         return absoluteMax;
  11805.       };
  11806.       return {
  11807.         set: set,
  11808.         get: get,
  11809.         getOuter: getOuter,
  11810.         aggregate: aggregate,
  11811.         max: max
  11812.       };
  11813.     };
  11814.  
  11815.     var api = Dimension('height', function (element) {
  11816.       var dom = element.dom;
  11817.       return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11818.     });
  11819.     var get$1 = function (element) {
  11820.       return api.get(element);
  11821.     };
  11822.  
  11823.     var walkUp = function (navigation, doc) {
  11824.       var frame = navigation.view(doc);
  11825.       return frame.fold(constant([]), function (f) {
  11826.         var parent = navigation.owner(f);
  11827.         var rest = walkUp(navigation, parent);
  11828.         return [f].concat(rest);
  11829.       });
  11830.     };
  11831.     var pathTo = function (element, navigation) {
  11832.       var d = navigation.owner(element);
  11833.       return walkUp(navigation, d);
  11834.     };
  11835.  
  11836.     var view = function (doc) {
  11837.       var _a;
  11838.       var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11839.       return element.map(SugarElement.fromDom);
  11840.     };
  11841.     var owner = function (element) {
  11842.       return documentOrOwner(element);
  11843.     };
  11844.  
  11845.     var Navigation = /*#__PURE__*/Object.freeze({
  11846.         __proto__: null,
  11847.         view: view,
  11848.         owner: owner
  11849.     });
  11850.  
  11851.     var find$1 = function (element) {
  11852.       var doc = SugarElement.fromDom(document);
  11853.       var scroll = get$8(doc);
  11854.       var frames = pathTo(element, Navigation);
  11855.       var offset = viewport(element);
  11856.       var r = foldr(frames, function (b, a) {
  11857.         var loc = viewport(a);
  11858.         return {
  11859.           left: b.left + loc.left,
  11860.           top: b.top + loc.top
  11861.         };
  11862.       }, {
  11863.         left: 0,
  11864.         top: 0
  11865.       });
  11866.       return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11867.     };
  11868.  
  11869.     var excludeFromDescend = function (element) {
  11870.       return name(element) === 'textarea';
  11871.     };
  11872.     var fireScrollIntoViewEvent = function (editor, data) {
  11873.       var scrollEvent = editor.fire('ScrollIntoView', data);
  11874.       return scrollEvent.isDefaultPrevented();
  11875.     };
  11876.     var fireAfterScrollIntoViewEvent = function (editor, data) {
  11877.       editor.fire('AfterScrollIntoView', data);
  11878.     };
  11879.     var descend = function (element, offset) {
  11880.       var children$1 = children(element);
  11881.       if (children$1.length === 0 || excludeFromDescend(element)) {
  11882.         return {
  11883.           element: element,
  11884.           offset: offset
  11885.         };
  11886.       } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  11887.         return {
  11888.           element: children$1[offset],
  11889.           offset: 0
  11890.         };
  11891.       } else {
  11892.         var last = children$1[children$1.length - 1];
  11893.         if (excludeFromDescend(last)) {
  11894.           return {
  11895.             element: element,
  11896.             offset: offset
  11897.           };
  11898.         } else {
  11899.           if (name(last) === 'img') {
  11900.             return {
  11901.               element: last,
  11902.               offset: 1
  11903.             };
  11904.           } else if (isText$8(last)) {
  11905.             return {
  11906.               element: last,
  11907.               offset: get$2(last).length
  11908.             };
  11909.           } else {
  11910.             return {
  11911.               element: last,
  11912.               offset: children(last).length
  11913.             };
  11914.           }
  11915.         }
  11916.       }
  11917.     };
  11918.     var markerInfo = function (element, cleanupFun) {
  11919.       var pos = absolute(element);
  11920.       var height = get$1(element);
  11921.       return {
  11922.         element: element,
  11923.         bottom: pos.top + height,
  11924.         height: height,
  11925.         pos: pos,
  11926.         cleanup: cleanupFun
  11927.       };
  11928.     };
  11929.     var createMarker = function (element, offset) {
  11930.       var startPoint = descend(element, offset);
  11931.       var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  11932.       before$4(startPoint.element, span);
  11933.       return markerInfo(span, function () {
  11934.         return remove$7(span);
  11935.       });
  11936.     };
  11937.     var elementMarker = function (element) {
  11938.       return markerInfo(SugarElement.fromDom(element), noop);
  11939.     };
  11940.     var withMarker = function (editor, f, rng, alignToTop) {
  11941.       preserveWith(editor, function (_s, _e) {
  11942.         return applyWithMarker(editor, f, rng, alignToTop);
  11943.       }, rng);
  11944.     };
  11945.     var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  11946.       var data = {
  11947.         elm: marker.element.dom,
  11948.         alignToTop: alignToTop
  11949.       };
  11950.       if (fireScrollIntoViewEvent(editor, data)) {
  11951.         return;
  11952.       }
  11953.       var scrollTop = get$8(doc).top;
  11954.       f(doc, scrollTop, marker, alignToTop);
  11955.       fireAfterScrollIntoViewEvent(editor, data);
  11956.     };
  11957.     var applyWithMarker = function (editor, f, rng, alignToTop) {
  11958.       var body = SugarElement.fromDom(editor.getBody());
  11959.       var doc = SugarElement.fromDom(editor.getDoc());
  11960.       reflow(body);
  11961.       var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  11962.       withScrollEvents(editor, doc, f, marker, alignToTop);
  11963.       marker.cleanup();
  11964.     };
  11965.     var withElement = function (editor, element, f, alignToTop) {
  11966.       var doc = SugarElement.fromDom(editor.getDoc());
  11967.       withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  11968.     };
  11969.     var preserveWith = function (editor, f, rng) {
  11970.       var startElement = rng.startContainer;
  11971.       var startOffset = rng.startOffset;
  11972.       var endElement = rng.endContainer;
  11973.       var endOffset = rng.endOffset;
  11974.       f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  11975.       var newRng = editor.dom.createRng();
  11976.       newRng.setStart(startElement, startOffset);
  11977.       newRng.setEnd(endElement, endOffset);
  11978.       editor.selection.setRng(rng);
  11979.     };
  11980.     var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  11981.       var pos = marker.pos;
  11982.       if (alignToTop) {
  11983.         to(pos.left, pos.top, doc);
  11984.       } else {
  11985.         var y = pos.top - viewHeight + marker.height;
  11986.         to(pos.left, y, doc);
  11987.       }
  11988.     };
  11989.     var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  11990.       var viewportBottom = viewHeight + scrollTop;
  11991.       var markerTop = marker.pos.top;
  11992.       var markerBottom = marker.bottom;
  11993.       var largerThanViewport = markerBottom - markerTop >= viewHeight;
  11994.       if (markerTop < scrollTop) {
  11995.         scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  11996.       } else if (markerTop > viewportBottom) {
  11997.         var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  11998.         scrollToMarker(marker, viewHeight, align, doc);
  11999.       } else if (markerBottom > viewportBottom && !largerThanViewport) {
  12000.         scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  12001.       }
  12002.     };
  12003.     var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  12004.       var viewHeight = doc.dom.defaultView.innerHeight;
  12005.       intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  12006.     };
  12007.     var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  12008.       var frameViewHeight = doc.dom.defaultView.innerHeight;
  12009.       intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  12010.       var op = find$1(marker.element);
  12011.       var viewportBounds = getBounds(window);
  12012.       if (op.top < viewportBounds.y) {
  12013.         intoView(marker.element, alignToTop !== false);
  12014.       } else if (op.top > viewportBounds.bottom) {
  12015.         intoView(marker.element, alignToTop === true);
  12016.       }
  12017.     };
  12018.     var rangeIntoWindow = function (editor, rng, alignToTop) {
  12019.       return withMarker(editor, intoWindow, rng, alignToTop);
  12020.     };
  12021.     var elementIntoWindow = function (editor, element, alignToTop) {
  12022.       return withElement(editor, element, intoWindow, alignToTop);
  12023.     };
  12024.     var rangeIntoFrame = function (editor, rng, alignToTop) {
  12025.       return withMarker(editor, intoFrame, rng, alignToTop);
  12026.     };
  12027.     var elementIntoFrame = function (editor, element, alignToTop) {
  12028.       return withElement(editor, element, intoFrame, alignToTop);
  12029.     };
  12030.     var scrollElementIntoView = function (editor, element, alignToTop) {
  12031.       var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  12032.       scroller(editor, element, alignToTop);
  12033.     };
  12034.     var scrollRangeIntoView = function (editor, rng, alignToTop) {
  12035.       var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  12036.       scroller(editor, rng, alignToTop);
  12037.     };
  12038.  
  12039.     var getDocument = function () {
  12040.       return SugarElement.fromDom(document);
  12041.     };
  12042.  
  12043.     var focus$1 = function (element) {
  12044.       return element.dom.focus();
  12045.     };
  12046.     var hasFocus$1 = function (element) {
  12047.       var root = getRootNode(element).dom;
  12048.       return element.dom === root.activeElement;
  12049.     };
  12050.     var active = function (root) {
  12051.       if (root === void 0) {
  12052.         root = getDocument();
  12053.       }
  12054.       return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  12055.     };
  12056.     var search = function (element) {
  12057.       return active(getRootNode(element)).filter(function (e) {
  12058.         return element.dom.contains(e.dom);
  12059.       });
  12060.     };
  12061.  
  12062.     var create$5 = function (start, soffset, finish, foffset) {
  12063.       return {
  12064.         start: start,
  12065.         soffset: soffset,
  12066.         finish: finish,
  12067.         foffset: foffset
  12068.       };
  12069.     };
  12070.     var SimRange = { create: create$5 };
  12071.  
  12072.     var adt$1 = Adt.generate([
  12073.       { before: ['element'] },
  12074.       {
  12075.         on: [
  12076.           'element',
  12077.           'offset'
  12078.         ]
  12079.       },
  12080.       { after: ['element'] }
  12081.     ]);
  12082.     var cata = function (subject, onBefore, onOn, onAfter) {
  12083.       return subject.fold(onBefore, onOn, onAfter);
  12084.     };
  12085.     var getStart$2 = function (situ) {
  12086.       return situ.fold(identity, identity, identity);
  12087.     };
  12088.     var before$1 = adt$1.before;
  12089.     var on = adt$1.on;
  12090.     var after$1 = adt$1.after;
  12091.     var Situ = {
  12092.       before: before$1,
  12093.       on: on,
  12094.       after: after$1,
  12095.       cata: cata,
  12096.       getStart: getStart$2
  12097.     };
  12098.  
  12099.     var adt = Adt.generate([
  12100.       { domRange: ['rng'] },
  12101.       {
  12102.         relative: [
  12103.           'startSitu',
  12104.           'finishSitu'
  12105.         ]
  12106.       },
  12107.       {
  12108.         exact: [
  12109.           'start',
  12110.           'soffset',
  12111.           'finish',
  12112.           'foffset'
  12113.         ]
  12114.       }
  12115.     ]);
  12116.     var exactFromRange = function (simRange) {
  12117.       return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  12118.     };
  12119.     var getStart$1 = function (selection) {
  12120.       return selection.match({
  12121.         domRange: function (rng) {
  12122.           return SugarElement.fromDom(rng.startContainer);
  12123.         },
  12124.         relative: function (startSitu, _finishSitu) {
  12125.           return Situ.getStart(startSitu);
  12126.         },
  12127.         exact: function (start, _soffset, _finish, _foffset) {
  12128.           return start;
  12129.         }
  12130.       });
  12131.     };
  12132.     var domRange = adt.domRange;
  12133.     var relative = adt.relative;
  12134.     var exact = adt.exact;
  12135.     var getWin = function (selection) {
  12136.       var start = getStart$1(selection);
  12137.       return defaultView(start);
  12138.     };
  12139.     var range = SimRange.create;
  12140.     var SimSelection = {
  12141.       domRange: domRange,
  12142.       relative: relative,
  12143.       exact: exact,
  12144.       exactFromRange: exactFromRange,
  12145.       getWin: getWin,
  12146.       range: range
  12147.     };
  12148.  
  12149.     var browser$1 = detect().browser;
  12150.     var clamp$1 = function (offset, element) {
  12151.       var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  12152.       if (offset > max) {
  12153.         return max;
  12154.       } else if (offset < 0) {
  12155.         return 0;
  12156.       }
  12157.       return offset;
  12158.     };
  12159.     var normalizeRng = function (rng) {
  12160.       return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12161.     };
  12162.     var isOrContains = function (root, elm) {
  12163.       return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12164.     };
  12165.     var isRngInRoot = function (root) {
  12166.       return function (rng) {
  12167.         return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12168.       };
  12169.     };
  12170.     var shouldStore = function (editor) {
  12171.       return editor.inline === true || browser$1.isIE();
  12172.     };
  12173.     var nativeRangeToSelectionRange = function (r) {
  12174.       return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12175.     };
  12176.     var readRange = function (win) {
  12177.       var selection = win.getSelection();
  12178.       var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12179.       return rng.map(nativeRangeToSelectionRange);
  12180.     };
  12181.     var getBookmark = function (root) {
  12182.       var win = defaultView(root);
  12183.       return readRange(win.dom).filter(isRngInRoot(root));
  12184.     };
  12185.     var validate = function (root, bookmark) {
  12186.       return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12187.     };
  12188.     var bookmarkToNativeRng = function (bookmark) {
  12189.       var rng = document.createRange();
  12190.       try {
  12191.         rng.setStart(bookmark.start.dom, bookmark.soffset);
  12192.         rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12193.         return Optional.some(rng);
  12194.       } catch (_) {
  12195.         return Optional.none();
  12196.       }
  12197.     };
  12198.     var store = function (editor) {
  12199.       var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12200.       editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12201.     };
  12202.     var storeNative = function (editor, rng) {
  12203.       var root = SugarElement.fromDom(editor.getBody());
  12204.       var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12205.       var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12206.       editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12207.     };
  12208.     var getRng = function (editor) {
  12209.       var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12210.       return bookmark.bind(function (x) {
  12211.         return validate(SugarElement.fromDom(editor.getBody()), x);
  12212.       }).bind(bookmarkToNativeRng);
  12213.     };
  12214.     var restore = function (editor) {
  12215.       getRng(editor).each(function (rng) {
  12216.         return editor.selection.setRng(rng);
  12217.       });
  12218.     };
  12219.  
  12220.     var isEditorUIElement$1 = function (elm) {
  12221.       var className = elm.className.toString();
  12222.       return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12223.     };
  12224.     var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12225.  
  12226.     var isManualNodeChange = function (e) {
  12227.       return e.type === 'nodechange' && e.selectionChange;
  12228.     };
  12229.     var registerPageMouseUp = function (editor, throttledStore) {
  12230.       var mouseUpPage = function () {
  12231.         throttledStore.throttle();
  12232.       };
  12233.       DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12234.       editor.on('remove', function () {
  12235.         DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12236.       });
  12237.     };
  12238.     var registerFocusOut = function (editor) {
  12239.       editor.on('focusout', function () {
  12240.         store(editor);
  12241.       });
  12242.     };
  12243.     var registerMouseUp = function (editor, throttledStore) {
  12244.       editor.on('mouseup touchend', function (_e) {
  12245.         throttledStore.throttle();
  12246.       });
  12247.     };
  12248.     var registerEditorEvents = function (editor, throttledStore) {
  12249.       var browser = detect().browser;
  12250.       if (browser.isIE()) {
  12251.         registerFocusOut(editor);
  12252.       } else {
  12253.         registerMouseUp(editor, throttledStore);
  12254.       }
  12255.       editor.on('keyup NodeChange', function (e) {
  12256.         if (!isManualNodeChange(e)) {
  12257.           store(editor);
  12258.         }
  12259.       });
  12260.     };
  12261.     var register$3 = function (editor) {
  12262.       var throttledStore = first(function () {
  12263.         store(editor);
  12264.       }, 0);
  12265.       editor.on('init', function () {
  12266.         if (editor.inline) {
  12267.           registerPageMouseUp(editor, throttledStore);
  12268.         }
  12269.         registerEditorEvents(editor, throttledStore);
  12270.       });
  12271.       editor.on('remove', function () {
  12272.         throttledStore.cancel();
  12273.       });
  12274.     };
  12275.  
  12276.     var documentFocusInHandler;
  12277.     var DOM$8 = DOMUtils.DOM;
  12278.     var isEditorUIElement = function (elm) {
  12279.       return FocusManager.isEditorUIElement(elm);
  12280.     };
  12281.     var isEditorContentAreaElement = function (elm) {
  12282.       var classList = elm.classList;
  12283.       if (classList !== undefined) {
  12284.         return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12285.       } else {
  12286.         return false;
  12287.       }
  12288.     };
  12289.     var isUIElement = function (editor, elm) {
  12290.       var customSelector = getCustomUiSelector(editor);
  12291.       var parent = DOM$8.getParent(elm, function (elm) {
  12292.         return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12293.       });
  12294.       return parent !== null;
  12295.     };
  12296.     var getActiveElement = function (editor) {
  12297.       try {
  12298.         var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12299.         return active(root).fold(function () {
  12300.           return document.body;
  12301.         }, function (x) {
  12302.           return x.dom;
  12303.         });
  12304.       } catch (ex) {
  12305.         return document.body;
  12306.       }
  12307.     };
  12308.     var registerEvents$1 = function (editorManager, e) {
  12309.       var editor = e.editor;
  12310.       register$3(editor);
  12311.       editor.on('focusin', function () {
  12312.         var focusedEditor = editorManager.focusedEditor;
  12313.         if (focusedEditor !== editor) {
  12314.           if (focusedEditor) {
  12315.             focusedEditor.fire('blur', { focusedEditor: editor });
  12316.           }
  12317.           editorManager.setActive(editor);
  12318.           editorManager.focusedEditor = editor;
  12319.           editor.fire('focus', { blurredEditor: focusedEditor });
  12320.           editor.focus(true);
  12321.         }
  12322.       });
  12323.       editor.on('focusout', function () {
  12324.         Delay.setEditorTimeout(editor, function () {
  12325.           var focusedEditor = editorManager.focusedEditor;
  12326.           if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12327.             editor.fire('blur', { focusedEditor: null });
  12328.             editorManager.focusedEditor = null;
  12329.           }
  12330.         });
  12331.       });
  12332.       if (!documentFocusInHandler) {
  12333.         documentFocusInHandler = function (e) {
  12334.           var activeEditor = editorManager.activeEditor;
  12335.           if (activeEditor) {
  12336.             getOriginalEventTarget(e).each(function (target) {
  12337.               if (target.ownerDocument === document) {
  12338.                 if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12339.                   activeEditor.fire('blur', { focusedEditor: null });
  12340.                   editorManager.focusedEditor = null;
  12341.                 }
  12342.               }
  12343.             });
  12344.           }
  12345.         };
  12346.         DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12347.       }
  12348.     };
  12349.     var unregisterDocumentEvents = function (editorManager, e) {
  12350.       if (editorManager.focusedEditor === e.editor) {
  12351.         editorManager.focusedEditor = null;
  12352.       }
  12353.       if (!editorManager.activeEditor) {
  12354.         DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12355.         documentFocusInHandler = null;
  12356.       }
  12357.     };
  12358.     var setup$l = function (editorManager) {
  12359.       editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12360.       editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12361.     };
  12362.  
  12363.     var getContentEditableHost = function (editor, node) {
  12364.       return editor.dom.getParent(node, function (node) {
  12365.         return editor.dom.getContentEditable(node) === 'true';
  12366.       });
  12367.     };
  12368.     var getCollapsedNode = function (rng) {
  12369.       return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12370.     };
  12371.     var getFocusInElement = function (root, rng) {
  12372.       return getCollapsedNode(rng).bind(function (node) {
  12373.         if (isTableSection(node)) {
  12374.           return Optional.some(node);
  12375.         } else if (contains$1(root, node) === false) {
  12376.           return Optional.some(root);
  12377.         } else {
  12378.           return Optional.none();
  12379.         }
  12380.       });
  12381.     };
  12382.     var normalizeSelection$1 = function (editor, rng) {
  12383.       getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12384.         return firstPositionIn(elm.dom);
  12385.       }).fold(function () {
  12386.         editor.selection.normalize();
  12387.         return;
  12388.       }, function (caretPos) {
  12389.         return editor.selection.setRng(caretPos.toRange());
  12390.       });
  12391.     };
  12392.     var focusBody = function (body) {
  12393.       if (body.setActive) {
  12394.         try {
  12395.           body.setActive();
  12396.         } catch (ex) {
  12397.           body.focus();
  12398.         }
  12399.       } else {
  12400.         body.focus();
  12401.       }
  12402.     };
  12403.     var hasElementFocus = function (elm) {
  12404.       return hasFocus$1(elm) || search(elm).isSome();
  12405.     };
  12406.     var hasIframeFocus = function (editor) {
  12407.       return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12408.     };
  12409.     var hasInlineFocus = function (editor) {
  12410.       var rawBody = editor.getBody();
  12411.       return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12412.     };
  12413.     var hasUiFocus = function (editor) {
  12414.       var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12415.       return active(dos).filter(function (elem) {
  12416.         return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12417.       }).isSome();
  12418.     };
  12419.     var hasFocus = function (editor) {
  12420.       return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12421.     };
  12422.     var hasEditorOrUiFocus = function (editor) {
  12423.       return hasFocus(editor) || hasUiFocus(editor);
  12424.     };
  12425.     var focusEditor = function (editor) {
  12426.       var selection = editor.selection;
  12427.       var body = editor.getBody();
  12428.       var rng = selection.getRng();
  12429.       editor.quirks.refreshContentEditable();
  12430.       if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12431.         getRng(editor).each(function (bookmarkRng) {
  12432.           editor.selection.setRng(bookmarkRng);
  12433.           rng = bookmarkRng;
  12434.         });
  12435.       }
  12436.       var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12437.       if (editor.$.contains(body, contentEditableHost)) {
  12438.         focusBody(contentEditableHost);
  12439.         normalizeSelection$1(editor, rng);
  12440.         activateEditor(editor);
  12441.         return;
  12442.       }
  12443.       if (!editor.inline) {
  12444.         if (!Env.opera) {
  12445.           focusBody(body);
  12446.         }
  12447.         editor.getWin().focus();
  12448.       }
  12449.       if (Env.gecko || editor.inline) {
  12450.         focusBody(body);
  12451.         normalizeSelection$1(editor, rng);
  12452.       }
  12453.       activateEditor(editor);
  12454.     };
  12455.     var activateEditor = function (editor) {
  12456.       return editor.editorManager.setActive(editor);
  12457.     };
  12458.     var focus = function (editor, skipFocus) {
  12459.       if (editor.removed) {
  12460.         return;
  12461.       }
  12462.       if (skipFocus) {
  12463.         activateEditor(editor);
  12464.       } else {
  12465.         focusEditor(editor);
  12466.       }
  12467.     };
  12468.  
  12469.     var getEndpointElement = function (root, rng, start, real, resolve) {
  12470.       var container = start ? rng.startContainer : rng.endContainer;
  12471.       var offset = start ? rng.startOffset : rng.endOffset;
  12472.       return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12473.         return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12474.       }).bind(function (elm) {
  12475.         return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12476.       }).map(function (elm) {
  12477.         return elm.dom;
  12478.       }).getOr(root);
  12479.     };
  12480.     var getStart = function (root, rng, real) {
  12481.       return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12482.         return Math.min(childNodesCount(elm), offset);
  12483.       });
  12484.     };
  12485.     var getEnd = function (root, rng, real) {
  12486.       return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12487.         return offset > 0 ? offset - 1 : offset;
  12488.       });
  12489.     };
  12490.     var skipEmptyTextNodes = function (node, forwards) {
  12491.       var orig = node;
  12492.       while (node && isText$7(node) && node.length === 0) {
  12493.         node = forwards ? node.nextSibling : node.previousSibling;
  12494.       }
  12495.       return node || orig;
  12496.     };
  12497.     var getNode = function (root, rng) {
  12498.       var elm, startContainer, endContainer;
  12499.       if (!rng) {
  12500.         return root;
  12501.       }
  12502.       startContainer = rng.startContainer;
  12503.       endContainer = rng.endContainer;
  12504.       var startOffset = rng.startOffset;
  12505.       var endOffset = rng.endOffset;
  12506.       elm = rng.commonAncestorContainer;
  12507.       if (!rng.collapsed) {
  12508.         if (startContainer === endContainer) {
  12509.           if (endOffset - startOffset < 2) {
  12510.             if (startContainer.hasChildNodes()) {
  12511.               elm = startContainer.childNodes[startOffset];
  12512.             }
  12513.           }
  12514.         }
  12515.         if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12516.           if (startContainer.length === startOffset) {
  12517.             startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12518.           } else {
  12519.             startContainer = startContainer.parentNode;
  12520.           }
  12521.           if (endOffset === 0) {
  12522.             endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12523.           } else {
  12524.             endContainer = endContainer.parentNode;
  12525.           }
  12526.           if (startContainer && startContainer === endContainer) {
  12527.             return startContainer;
  12528.           }
  12529.         }
  12530.       }
  12531.       if (elm && elm.nodeType === 3) {
  12532.         return elm.parentNode;
  12533.       }
  12534.       return elm;
  12535.     };
  12536.     var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12537.       var node;
  12538.       var selectedBlocks = [];
  12539.       var root = dom.getRoot();
  12540.       startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12541.       endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12542.       if (startElm && startElm !== root) {
  12543.         selectedBlocks.push(startElm);
  12544.       }
  12545.       if (startElm && endElm && startElm !== endElm) {
  12546.         node = startElm;
  12547.         var walker = new DomTreeWalker(startElm, root);
  12548.         while ((node = walker.next()) && node !== endElm) {
  12549.           if (dom.isBlock(node)) {
  12550.             selectedBlocks.push(node);
  12551.           }
  12552.         }
  12553.       }
  12554.       if (endElm && startElm !== endElm && endElm !== root) {
  12555.         selectedBlocks.push(endElm);
  12556.       }
  12557.       return selectedBlocks;
  12558.     };
  12559.     var select = function (dom, node, content) {
  12560.       return Optional.from(node).map(function (node) {
  12561.         var idx = dom.nodeIndex(node);
  12562.         var rng = dom.createRng();
  12563.         rng.setStart(node.parentNode, idx);
  12564.         rng.setEnd(node.parentNode, idx + 1);
  12565.         if (content) {
  12566.           moveEndPoint(dom, rng, node, true);
  12567.           moveEndPoint(dom, rng, node, false);
  12568.         }
  12569.         return rng;
  12570.       });
  12571.     };
  12572.  
  12573.     var processRanges = function (editor, ranges) {
  12574.       return map$3(ranges, function (range) {
  12575.         var evt = editor.fire('GetSelectionRange', { range: range });
  12576.         return evt.range !== range ? evt.range : range;
  12577.       });
  12578.     };
  12579.  
  12580.     var typeLookup = {
  12581.       '#text': 3,
  12582.       '#comment': 8,
  12583.       '#cdata': 4,
  12584.       '#pi': 7,
  12585.       '#doctype': 10,
  12586.       '#document-fragment': 11
  12587.     };
  12588.     var walk$1 = function (node, root, prev) {
  12589.       var startName = prev ? 'lastChild' : 'firstChild';
  12590.       var siblingName = prev ? 'prev' : 'next';
  12591.       if (node[startName]) {
  12592.         return node[startName];
  12593.       }
  12594.       if (node !== root) {
  12595.         var sibling = node[siblingName];
  12596.         if (sibling) {
  12597.           return sibling;
  12598.         }
  12599.         for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12600.           sibling = parent_1[siblingName];
  12601.           if (sibling) {
  12602.             return sibling;
  12603.           }
  12604.         }
  12605.       }
  12606.     };
  12607.     var isEmptyTextNode = function (node) {
  12608.       if (!isWhitespaceText(node.value)) {
  12609.         return false;
  12610.       }
  12611.       var parentNode = node.parent;
  12612.       if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12613.         return false;
  12614.       }
  12615.       return true;
  12616.     };
  12617.     var isNonEmptyElement = function (node) {
  12618.       var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12619.       return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12620.     };
  12621.     var AstNode = function () {
  12622.       function AstNode(name, type) {
  12623.         this.name = name;
  12624.         this.type = type;
  12625.         if (type === 1) {
  12626.           this.attributes = [];
  12627.           this.attributes.map = {};
  12628.         }
  12629.       }
  12630.       AstNode.create = function (name, attrs) {
  12631.         var node = new AstNode(name, typeLookup[name] || 1);
  12632.         if (attrs) {
  12633.           each$j(attrs, function (value, attrName) {
  12634.             node.attr(attrName, value);
  12635.           });
  12636.         }
  12637.         return node;
  12638.       };
  12639.       AstNode.prototype.replace = function (node) {
  12640.         var self = this;
  12641.         if (node.parent) {
  12642.           node.remove();
  12643.         }
  12644.         self.insert(node, self);
  12645.         self.remove();
  12646.         return self;
  12647.       };
  12648.       AstNode.prototype.attr = function (name, value) {
  12649.         var self = this;
  12650.         var attrs;
  12651.         if (typeof name !== 'string') {
  12652.           if (name !== undefined && name !== null) {
  12653.             each$j(name, function (value, key) {
  12654.               self.attr(key, value);
  12655.             });
  12656.           }
  12657.           return self;
  12658.         }
  12659.         if (attrs = self.attributes) {
  12660.           if (value !== undefined) {
  12661.             if (value === null) {
  12662.               if (name in attrs.map) {
  12663.                 delete attrs.map[name];
  12664.                 var i = attrs.length;
  12665.                 while (i--) {
  12666.                   if (attrs[i].name === name) {
  12667.                     attrs.splice(i, 1);
  12668.                     return self;
  12669.                   }
  12670.                 }
  12671.               }
  12672.               return self;
  12673.             }
  12674.             if (name in attrs.map) {
  12675.               var i = attrs.length;
  12676.               while (i--) {
  12677.                 if (attrs[i].name === name) {
  12678.                   attrs[i].value = value;
  12679.                   break;
  12680.                 }
  12681.               }
  12682.             } else {
  12683.               attrs.push({
  12684.                 name: name,
  12685.                 value: value
  12686.               });
  12687.             }
  12688.             attrs.map[name] = value;
  12689.             return self;
  12690.           }
  12691.           return attrs.map[name];
  12692.         }
  12693.       };
  12694.       AstNode.prototype.clone = function () {
  12695.         var self = this;
  12696.         var clone = new AstNode(self.name, self.type);
  12697.         var selfAttrs;
  12698.         if (selfAttrs = self.attributes) {
  12699.           var cloneAttrs = [];
  12700.           cloneAttrs.map = {};
  12701.           for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12702.             var selfAttr = selfAttrs[i];
  12703.             if (selfAttr.name !== 'id') {
  12704.               cloneAttrs[cloneAttrs.length] = {
  12705.                 name: selfAttr.name,
  12706.                 value: selfAttr.value
  12707.               };
  12708.               cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12709.             }
  12710.           }
  12711.           clone.attributes = cloneAttrs;
  12712.         }
  12713.         clone.value = self.value;
  12714.         clone.shortEnded = self.shortEnded;
  12715.         return clone;
  12716.       };
  12717.       AstNode.prototype.wrap = function (wrapper) {
  12718.         var self = this;
  12719.         self.parent.insert(wrapper, self);
  12720.         wrapper.append(self);
  12721.         return self;
  12722.       };
  12723.       AstNode.prototype.unwrap = function () {
  12724.         var self = this;
  12725.         for (var node = self.firstChild; node;) {
  12726.           var next = node.next;
  12727.           self.insert(node, self, true);
  12728.           node = next;
  12729.         }
  12730.         self.remove();
  12731.       };
  12732.       AstNode.prototype.remove = function () {
  12733.         var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12734.         if (parent) {
  12735.           if (parent.firstChild === self) {
  12736.             parent.firstChild = next;
  12737.             if (next) {
  12738.               next.prev = null;
  12739.             }
  12740.           } else {
  12741.             prev.next = next;
  12742.           }
  12743.           if (parent.lastChild === self) {
  12744.             parent.lastChild = prev;
  12745.             if (prev) {
  12746.               prev.next = null;
  12747.             }
  12748.           } else {
  12749.             next.prev = prev;
  12750.           }
  12751.           self.parent = self.next = self.prev = null;
  12752.         }
  12753.         return self;
  12754.       };
  12755.       AstNode.prototype.append = function (node) {
  12756.         var self = this;
  12757.         if (node.parent) {
  12758.           node.remove();
  12759.         }
  12760.         var last = self.lastChild;
  12761.         if (last) {
  12762.           last.next = node;
  12763.           node.prev = last;
  12764.           self.lastChild = node;
  12765.         } else {
  12766.           self.lastChild = self.firstChild = node;
  12767.         }
  12768.         node.parent = self;
  12769.         return node;
  12770.       };
  12771.       AstNode.prototype.insert = function (node, refNode, before) {
  12772.         if (node.parent) {
  12773.           node.remove();
  12774.         }
  12775.         var parent = refNode.parent || this;
  12776.         if (before) {
  12777.           if (refNode === parent.firstChild) {
  12778.             parent.firstChild = node;
  12779.           } else {
  12780.             refNode.prev.next = node;
  12781.           }
  12782.           node.prev = refNode.prev;
  12783.           node.next = refNode;
  12784.           refNode.prev = node;
  12785.         } else {
  12786.           if (refNode === parent.lastChild) {
  12787.             parent.lastChild = node;
  12788.           } else {
  12789.             refNode.next.prev = node;
  12790.           }
  12791.           node.next = refNode.next;
  12792.           node.prev = refNode;
  12793.           refNode.next = node;
  12794.         }
  12795.         node.parent = parent;
  12796.         return node;
  12797.       };
  12798.       AstNode.prototype.getAll = function (name) {
  12799.         var self = this;
  12800.         var collection = [];
  12801.         for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12802.           if (node.name === name) {
  12803.             collection.push(node);
  12804.           }
  12805.         }
  12806.         return collection;
  12807.       };
  12808.       AstNode.prototype.children = function () {
  12809.         var self = this;
  12810.         var collection = [];
  12811.         for (var node = self.firstChild; node; node = node.next) {
  12812.           collection.push(node);
  12813.         }
  12814.         return collection;
  12815.       };
  12816.       AstNode.prototype.empty = function () {
  12817.         var self = this;
  12818.         if (self.firstChild) {
  12819.           var nodes = [];
  12820.           for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12821.             nodes.push(node);
  12822.           }
  12823.           var i = nodes.length;
  12824.           while (i--) {
  12825.             var node = nodes[i];
  12826.             node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12827.           }
  12828.         }
  12829.         self.firstChild = self.lastChild = null;
  12830.         return self;
  12831.       };
  12832.       AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12833.         if (whitespace === void 0) {
  12834.           whitespace = {};
  12835.         }
  12836.         var self = this;
  12837.         var node = self.firstChild;
  12838.         if (isNonEmptyElement(self)) {
  12839.           return false;
  12840.         }
  12841.         if (node) {
  12842.           do {
  12843.             if (node.type === 1) {
  12844.               if (node.attr('data-mce-bogus')) {
  12845.                 continue;
  12846.               }
  12847.               if (elements[node.name]) {
  12848.                 return false;
  12849.               }
  12850.               if (isNonEmptyElement(node)) {
  12851.                 return false;
  12852.               }
  12853.             }
  12854.             if (node.type === 8) {
  12855.               return false;
  12856.             }
  12857.             if (node.type === 3 && !isEmptyTextNode(node)) {
  12858.               return false;
  12859.             }
  12860.             if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12861.               return false;
  12862.             }
  12863.             if (predicate && predicate(node)) {
  12864.               return false;
  12865.             }
  12866.           } while (node = walk$1(node, self));
  12867.         }
  12868.         return true;
  12869.       };
  12870.       AstNode.prototype.walk = function (prev) {
  12871.         return walk$1(this, null, prev);
  12872.       };
  12873.       return AstNode;
  12874.     }();
  12875.  
  12876.     var extractBase64DataUris = function (html) {
  12877.       var dataImageUri = /data:[^;]+;base64,([a-z0-9\+\/=\s]+)/gi;
  12878.       var chunks = [];
  12879.       var uris = {};
  12880.       var prefix = generate('img');
  12881.       var matches;
  12882.       var index = 0;
  12883.       var count = 0;
  12884.       while (matches = dataImageUri.exec(html)) {
  12885.         var uri = matches[0];
  12886.         var imageId = prefix + '_' + count++;
  12887.         uris[imageId] = uri;
  12888.         if (index < matches.index) {
  12889.           chunks.push(html.substr(index, matches.index - index));
  12890.         }
  12891.         chunks.push(imageId);
  12892.         index = matches.index + uri.length;
  12893.       }
  12894.       var re = new RegExp(prefix + '_[0-9]+', 'g');
  12895.       if (index === 0) {
  12896.         return {
  12897.           prefix: prefix,
  12898.           uris: uris,
  12899.           html: html,
  12900.           re: re
  12901.         };
  12902.       } else {
  12903.         if (index < html.length) {
  12904.           chunks.push(html.substr(index));
  12905.         }
  12906.         return {
  12907.           prefix: prefix,
  12908.           uris: uris,
  12909.           html: chunks.join(''),
  12910.           re: re
  12911.         };
  12912.       }
  12913.     };
  12914.     var restoreDataUris = function (html, result) {
  12915.       return html.replace(result.re, function (imageId) {
  12916.         return get$9(result.uris, imageId).getOr(imageId);
  12917.       });
  12918.     };
  12919.     var parseDataUri$1 = function (uri) {
  12920.       var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  12921.       if (matches) {
  12922.         return Optional.some({
  12923.           type: matches[1],
  12924.           data: decodeURIComponent(matches[2])
  12925.         });
  12926.       } else {
  12927.         return Optional.none();
  12928.       }
  12929.     };
  12930.  
  12931.     var each$d = Tools.each, trim = Tools.trim;
  12932.     var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  12933.     var DEFAULT_PORTS = {
  12934.       ftp: 21,
  12935.       http: 80,
  12936.       https: 443,
  12937.       mailto: 25
  12938.     };
  12939.     var safeSvgDataUrlElements = [
  12940.       'img',
  12941.       'video'
  12942.     ];
  12943.     var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  12944.       if (isNonNullable(allowSvgDataUrls)) {
  12945.         return !allowSvgDataUrls;
  12946.       } else {
  12947.         return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
  12948.       }
  12949.     };
  12950.     var isInvalidUri = function (settings, uri, tagName) {
  12951.       if (settings.allow_html_data_urls) {
  12952.         return false;
  12953.       } else if (/^data:image\//i.test(uri)) {
  12954.         return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  12955.       } else {
  12956.         return /^data:/i.test(uri);
  12957.       }
  12958.     };
  12959.     var URI = function () {
  12960.       function URI(url, settings) {
  12961.         url = trim(url);
  12962.         this.settings = settings || {};
  12963.         var baseUri = this.settings.base_uri;
  12964.         var self = this;
  12965.         if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  12966.           self.source = url;
  12967.           return;
  12968.         }
  12969.         var isProtocolRelative = url.indexOf('//') === 0;
  12970.         if (url.indexOf('/') === 0 && !isProtocolRelative) {
  12971.           url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  12972.         }
  12973.         if (!/^[\w\-]*:?\/\//.test(url)) {
  12974.           var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  12975.           if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  12976.             url = '//mce_host' + self.toAbsPath(baseUrl, url);
  12977.           } else {
  12978.             var match = /([^#?]*)([#?]?.*)/.exec(url);
  12979.             url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  12980.           }
  12981.         }
  12982.         url = url.replace(/@@/g, '(mce_at)');
  12983.         var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  12984.         each$d(queryParts, function (v, i) {
  12985.           var part = urlMatch[i];
  12986.           if (part) {
  12987.             part = part.replace(/\(mce_at\)/g, '@@');
  12988.           }
  12989.           self[v] = part;
  12990.         });
  12991.         if (baseUri) {
  12992.           if (!self.protocol) {
  12993.             self.protocol = baseUri.protocol;
  12994.           }
  12995.           if (!self.userInfo) {
  12996.             self.userInfo = baseUri.userInfo;
  12997.           }
  12998.           if (!self.port && self.host === 'mce_host') {
  12999.             self.port = baseUri.port;
  13000.           }
  13001.           if (!self.host || self.host === 'mce_host') {
  13002.             self.host = baseUri.host;
  13003.           }
  13004.           self.source = '';
  13005.         }
  13006.         if (isProtocolRelative) {
  13007.           self.protocol = '';
  13008.         }
  13009.       }
  13010.       URI.parseDataUri = function (uri) {
  13011.         var type;
  13012.         var uriComponents = decodeURIComponent(uri).split(',');
  13013.         var matches = /data:([^;]+)/.exec(uriComponents[0]);
  13014.         if (matches) {
  13015.           type = matches[1];
  13016.         }
  13017.         return {
  13018.           type: type,
  13019.           data: uriComponents[1]
  13020.         };
  13021.       };
  13022.       URI.isDomSafe = function (uri, context, options) {
  13023.         if (options === void 0) {
  13024.           options = {};
  13025.         }
  13026.         if (options.allow_script_urls) {
  13027.           return true;
  13028.         } else {
  13029.           var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  13030.           try {
  13031.             decodedUri = decodeURIComponent(decodedUri);
  13032.           } catch (ex) {
  13033.             decodedUri = unescape(decodedUri);
  13034.           }
  13035.           if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  13036.             return false;
  13037.           }
  13038.           return !isInvalidUri(options, decodedUri, context);
  13039.         }
  13040.       };
  13041.       URI.getDocumentBaseUrl = function (loc) {
  13042.         var baseUrl;
  13043.         if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  13044.           baseUrl = loc.href;
  13045.         } else {
  13046.           baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  13047.         }
  13048.         if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  13049.           baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  13050.           if (!/[\/\\]$/.test(baseUrl)) {
  13051.             baseUrl += '/';
  13052.           }
  13053.         }
  13054.         return baseUrl;
  13055.       };
  13056.       URI.prototype.setPath = function (path) {
  13057.         var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  13058.         this.path = pathMatch[0];
  13059.         this.directory = pathMatch[1];
  13060.         this.file = pathMatch[2];
  13061.         this.source = '';
  13062.         this.getURI();
  13063.       };
  13064.       URI.prototype.toRelative = function (uri) {
  13065.         var output;
  13066.         if (uri === './') {
  13067.           return uri;
  13068.         }
  13069.         var relativeUri = new URI(uri, { base_uri: this });
  13070.         if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  13071.           return relativeUri.getURI();
  13072.         }
  13073.         var tu = this.getURI(), uu = relativeUri.getURI();
  13074.         if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  13075.           return tu;
  13076.         }
  13077.         output = this.toRelPath(this.path, relativeUri.path);
  13078.         if (relativeUri.query) {
  13079.           output += '?' + relativeUri.query;
  13080.         }
  13081.         if (relativeUri.anchor) {
  13082.           output += '#' + relativeUri.anchor;
  13083.         }
  13084.         return output;
  13085.       };
  13086.       URI.prototype.toAbsolute = function (uri, noHost) {
  13087.         var absoluteUri = new URI(uri, { base_uri: this });
  13088.         return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  13089.       };
  13090.       URI.prototype.isSameOrigin = function (uri) {
  13091.         if (this.host == uri.host && this.protocol == uri.protocol) {
  13092.           if (this.port == uri.port) {
  13093.             return true;
  13094.           }
  13095.           var defaultPort = DEFAULT_PORTS[this.protocol];
  13096.           if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  13097.             return true;
  13098.           }
  13099.         }
  13100.         return false;
  13101.       };
  13102.       URI.prototype.toRelPath = function (base, path) {
  13103.         var breakPoint = 0, out = '', i, l;
  13104.         var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  13105.         var items = path.split('/');
  13106.         if (normalizedBase.length >= items.length) {
  13107.           for (i = 0, l = normalizedBase.length; i < l; i++) {
  13108.             if (i >= items.length || normalizedBase[i] !== items[i]) {
  13109.               breakPoint = i + 1;
  13110.               break;
  13111.             }
  13112.           }
  13113.         }
  13114.         if (normalizedBase.length < items.length) {
  13115.           for (i = 0, l = items.length; i < l; i++) {
  13116.             if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  13117.               breakPoint = i + 1;
  13118.               break;
  13119.             }
  13120.           }
  13121.         }
  13122.         if (breakPoint === 1) {
  13123.           return path;
  13124.         }
  13125.         for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  13126.           out += '../';
  13127.         }
  13128.         for (i = breakPoint - 1, l = items.length; i < l; i++) {
  13129.           if (i !== breakPoint - 1) {
  13130.             out += '/' + items[i];
  13131.           } else {
  13132.             out += items[i];
  13133.           }
  13134.         }
  13135.         return out;
  13136.       };
  13137.       URI.prototype.toAbsPath = function (base, path) {
  13138.         var i, nb = 0, o = [], outPath;
  13139.         var tr = /\/$/.test(path) ? '/' : '';
  13140.         var normalizedBase = base.split('/');
  13141.         var normalizedPath = path.split('/');
  13142.         each$d(normalizedBase, function (k) {
  13143.           if (k) {
  13144.             o.push(k);
  13145.           }
  13146.         });
  13147.         normalizedBase = o;
  13148.         for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  13149.           if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  13150.             continue;
  13151.           }
  13152.           if (normalizedPath[i] === '..') {
  13153.             nb++;
  13154.             continue;
  13155.           }
  13156.           if (nb > 0) {
  13157.             nb--;
  13158.             continue;
  13159.           }
  13160.           o.push(normalizedPath[i]);
  13161.         }
  13162.         i = normalizedBase.length - nb;
  13163.         if (i <= 0) {
  13164.           outPath = reverse(o).join('/');
  13165.         } else {
  13166.           outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  13167.         }
  13168.         if (outPath.indexOf('/') !== 0) {
  13169.           outPath = '/' + outPath;
  13170.         }
  13171.         if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  13172.           outPath += tr;
  13173.         }
  13174.         return outPath;
  13175.       };
  13176.       URI.prototype.getURI = function (noProtoHost) {
  13177.         if (noProtoHost === void 0) {
  13178.           noProtoHost = false;
  13179.         }
  13180.         var s;
  13181.         if (!this.source || noProtoHost) {
  13182.           s = '';
  13183.           if (!noProtoHost) {
  13184.             if (this.protocol) {
  13185.               s += this.protocol + '://';
  13186.             } else {
  13187.               s += '//';
  13188.             }
  13189.             if (this.userInfo) {
  13190.               s += this.userInfo + '@';
  13191.             }
  13192.             if (this.host) {
  13193.               s += this.host;
  13194.             }
  13195.             if (this.port) {
  13196.               s += ':' + this.port;
  13197.             }
  13198.           }
  13199.           if (this.path) {
  13200.             s += this.path;
  13201.           }
  13202.           if (this.query) {
  13203.             s += '?' + this.query;
  13204.           }
  13205.           if (this.anchor) {
  13206.             s += '#' + this.anchor;
  13207.           }
  13208.           this.source = s;
  13209.         }
  13210.         return this.source;
  13211.       };
  13212.       return URI;
  13213.     }();
  13214.  
  13215.     var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  13216.     var isValidPrefixAttrName = function (name) {
  13217.       return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  13218.     };
  13219.     var findMatchingEndTagIndex = function (schema, html, startIndex) {
  13220.       var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  13221.       var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  13222.       var shortEndedElements = schema.getShortEndedElements();
  13223.       var count = 1, index = startIndex;
  13224.       while (count !== 0) {
  13225.         startTagRegExp.lastIndex = index;
  13226.         while (true) {
  13227.           var startMatch = startTagRegExp.exec(html);
  13228.           if (startMatch === null) {
  13229.             return index;
  13230.           } else if (startMatch[1] === '!') {
  13231.             if (startsWith(startMatch[2], '--')) {
  13232.               index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  13233.             } else {
  13234.               index = findCommentEndIndex(html, true, startMatch.index + 1);
  13235.             }
  13236.             break;
  13237.           } else {
  13238.             endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  13239.             var endMatch = endTagRegExp.exec(html);
  13240.             if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  13241.               continue;
  13242.             }
  13243.             if (startMatch[1] === '/') {
  13244.               count -= 1;
  13245.             } else if (!has$2(shortEndedElements, startMatch[2])) {
  13246.               count += 1;
  13247.             }
  13248.             index = startTagRegExp.lastIndex + endMatch[0].length;
  13249.             break;
  13250.           }
  13251.         }
  13252.       }
  13253.       return index;
  13254.     };
  13255.     var isConditionalComment = function (html, startIndex) {
  13256.       return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  13257.     };
  13258.     var findCommentEndIndex = function (html, isBogus, startIndex) {
  13259.       if (startIndex === void 0) {
  13260.         startIndex = 0;
  13261.       }
  13262.       var lcHtml = html.toLowerCase();
  13263.       if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  13264.         var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  13265.         return lcHtml.indexOf('>', endIfIndex);
  13266.       } else {
  13267.         if (isBogus) {
  13268.           var endIndex = lcHtml.indexOf('>', startIndex);
  13269.           return endIndex !== -1 ? endIndex : lcHtml.length;
  13270.         } else {
  13271.           var endCommentRegexp = /--!?>/g;
  13272.           endCommentRegexp.lastIndex = startIndex;
  13273.           var match = endCommentRegexp.exec(html);
  13274.           return match ? match.index + match[0].length : lcHtml.length;
  13275.         }
  13276.       }
  13277.     };
  13278.     var checkBogusAttribute = function (regExp, attrString) {
  13279.       var matches = regExp.exec(attrString);
  13280.       if (matches) {
  13281.         var name_1 = matches[1];
  13282.         var value = matches[2];
  13283.         return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  13284.       } else {
  13285.         return null;
  13286.       }
  13287.     };
  13288.     var SaxParser = function (settings, schema) {
  13289.       var _a;
  13290.       if (schema === void 0) {
  13291.         schema = Schema();
  13292.       }
  13293.       settings = settings || {};
  13294.       var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  13295.       var form = doc.createElement('form');
  13296.       if (settings.fix_self_closing !== false) {
  13297.         settings.fix_self_closing = true;
  13298.       }
  13299.       var comment = settings.comment ? settings.comment : noop;
  13300.       var cdata = settings.cdata ? settings.cdata : noop;
  13301.       var text = settings.text ? settings.text : noop;
  13302.       var start = settings.start ? settings.start : noop;
  13303.       var end = settings.end ? settings.end : noop;
  13304.       var pi = settings.pi ? settings.pi : noop;
  13305.       var doctype = settings.doctype ? settings.doctype : noop;
  13306.       var parseInternal = function (base64Extract, format) {
  13307.         if (format === void 0) {
  13308.           format = 'html';
  13309.         }
  13310.         var html = base64Extract.html;
  13311.         var matches, index = 0, value, endRegExp;
  13312.         var stack = [];
  13313.         var attrList, i, textData, name;
  13314.         var isInternalElement, isShortEnded;
  13315.         var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  13316.         var attributesRequired, attributesDefault, attributesForced;
  13317.         var anyAttributesRequired, attrValue, idCount = 0;
  13318.         var decode = Entities.decode;
  13319.         var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  13320.         var parsingMode = format === 'html' ? 0 : 1;
  13321.         var processEndTag = function (name) {
  13322.           var pos, i;
  13323.           pos = stack.length;
  13324.           while (pos--) {
  13325.             if (stack[pos].name === name) {
  13326.               break;
  13327.             }
  13328.           }
  13329.           if (pos >= 0) {
  13330.             for (i = stack.length - 1; i >= pos; i--) {
  13331.               name = stack[i];
  13332.               if (name.valid) {
  13333.                 end(name.name);
  13334.               }
  13335.             }
  13336.             stack.length = pos;
  13337.           }
  13338.         };
  13339.         var processText = function (value, raw) {
  13340.           return text(restoreDataUris(value, base64Extract), raw);
  13341.         };
  13342.         var processComment = function (value) {
  13343.           if (value === '') {
  13344.             return;
  13345.           }
  13346.           if (value.charAt(0) === '>') {
  13347.             value = ' ' + value;
  13348.           }
  13349.           if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  13350.             value = ' ' + value;
  13351.           }
  13352.           comment(restoreDataUris(value, base64Extract));
  13353.         };
  13354.         var processAttr = function (value) {
  13355.           return restoreDataUris(value, base64Extract);
  13356.         };
  13357.         var processMalformedComment = function (value, startIndex) {
  13358.           var startTag = value || '';
  13359.           var isBogus = !startsWith(startTag, '--');
  13360.           var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  13361.           value = html.substr(startIndex, endIndex - startIndex);
  13362.           processComment(isBogus ? startTag + value : value);
  13363.           return endIndex + 1;
  13364.         };
  13365.         var parseAttribute = function (tagName, name, value, val2, val3) {
  13366.           name = name.toLowerCase();
  13367.           value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  13368.           if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  13369.             var attrRule = validAttributesMap[name];
  13370.             if (!attrRule && validAttributePatterns) {
  13371.               var i_1 = validAttributePatterns.length;
  13372.               while (i_1--) {
  13373.                 attrRule = validAttributePatterns[i_1];
  13374.                 if (attrRule.pattern.test(name)) {
  13375.                   break;
  13376.                 }
  13377.               }
  13378.               if (i_1 === -1) {
  13379.                 attrRule = null;
  13380.               }
  13381.             }
  13382.             if (!attrRule) {
  13383.               return;
  13384.             }
  13385.             if (attrRule.validValues && !(value in attrRule.validValues)) {
  13386.               return;
  13387.             }
  13388.           }
  13389.           var isNameOrId = name === 'name' || name === 'id';
  13390.           if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  13391.             return;
  13392.           }
  13393.           if (filteredUrlAttrs[name] && !URI.isDomSafe(value, tagName, settings)) {
  13394.             return;
  13395.           }
  13396.           if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  13397.             return;
  13398.           }
  13399.           attrList.map[name] = value;
  13400.           attrList.push({
  13401.             name: name,
  13402.             value: value
  13403.           });
  13404.         };
  13405.         var tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)--!?>)|' + '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + '(?:![Dd][Oo][Cc][Tt][Yy][Pp][Ee]([\\w\\W]*?)>)|' + '(?:!(--)?)|' + '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + '(?:\\/([A-Za-z][A-Za-z0-9\\-_\\:\\.]*)>)|' + '(?:([A-Za-z][A-Za-z0-9\\-_:.]*)(\\s(?:[^\'">]+(?:"[^"]*"|\'[^\']*\'))*[^"\'>]*(?:"[^">]*|\'[^\'>]*)?|\\s*|\\/)>)' + ')', 'g');
  13406.         var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  13407.         var shortEndedElements = schema.getShortEndedElements();
  13408.         var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  13409.         var fillAttrsMap = schema.getBoolAttrs();
  13410.         var validate = settings.validate;
  13411.         var removeInternalElements = settings.remove_internals;
  13412.         var fixSelfClosing = settings.fix_self_closing;
  13413.         var specialElements = schema.getSpecialElements();
  13414.         var processHtml = html + '>';
  13415.         while (matches = tokenRegExp.exec(processHtml)) {
  13416.           var matchText = matches[0];
  13417.           if (index < matches.index) {
  13418.             processText(decode(html.substr(index, matches.index - index)));
  13419.           }
  13420.           if (value = matches[7]) {
  13421.             value = value.toLowerCase();
  13422.             if (value.charAt(0) === ':') {
  13423.               value = value.substr(1);
  13424.             }
  13425.             processEndTag(value);
  13426.           } else if (value = matches[8]) {
  13427.             if (matches.index + matchText.length > html.length) {
  13428.               processText(decode(html.substr(matches.index)));
  13429.               index = matches.index + matchText.length;
  13430.               continue;
  13431.             }
  13432.             value = value.toLowerCase();
  13433.             if (value.charAt(0) === ':') {
  13434.               value = value.substr(1);
  13435.             }
  13436.             isShortEnded = value in shortEndedElements;
  13437.             if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  13438.               processEndTag(value);
  13439.             }
  13440.             var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  13441.             if (bogusValue !== null) {
  13442.               if (bogusValue === 'all') {
  13443.                 index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13444.                 tokenRegExp.lastIndex = index;
  13445.                 continue;
  13446.               }
  13447.               isValidElement = false;
  13448.             }
  13449.             if (!validate || (elementRule = schema.getElementRule(value))) {
  13450.               isValidElement = true;
  13451.               if (validate) {
  13452.                 validAttributesMap = elementRule.attributes;
  13453.                 validAttributePatterns = elementRule.attributePatterns;
  13454.               }
  13455.               if (attribsValue = matches[9]) {
  13456.                 isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  13457.                 if (isInternalElement && removeInternalElements) {
  13458.                   isValidElement = false;
  13459.                 }
  13460.                 attrList = [];
  13461.                 attrList.map = {};
  13462.                 attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  13463.                   parseAttribute(value, name, val, val2, val3);
  13464.                   return '';
  13465.                 });
  13466.               } else {
  13467.                 attrList = [];
  13468.                 attrList.map = {};
  13469.               }
  13470.               if (validate && !isInternalElement) {
  13471.                 attributesRequired = elementRule.attributesRequired;
  13472.                 attributesDefault = elementRule.attributesDefault;
  13473.                 attributesForced = elementRule.attributesForced;
  13474.                 anyAttributesRequired = elementRule.removeEmptyAttrs;
  13475.                 if (anyAttributesRequired && !attrList.length) {
  13476.                   isValidElement = false;
  13477.                 }
  13478.                 if (attributesForced) {
  13479.                   i = attributesForced.length;
  13480.                   while (i--) {
  13481.                     attr = attributesForced[i];
  13482.                     name = attr.name;
  13483.                     attrValue = attr.value;
  13484.                     if (attrValue === '{$uid}') {
  13485.                       attrValue = 'mce_' + idCount++;
  13486.                     }
  13487.                     attrList.map[name] = attrValue;
  13488.                     attrList.push({
  13489.                       name: name,
  13490.                       value: attrValue
  13491.                     });
  13492.                   }
  13493.                 }
  13494.                 if (attributesDefault) {
  13495.                   i = attributesDefault.length;
  13496.                   while (i--) {
  13497.                     attr = attributesDefault[i];
  13498.                     name = attr.name;
  13499.                     if (!(name in attrList.map)) {
  13500.                       attrValue = attr.value;
  13501.                       if (attrValue === '{$uid}') {
  13502.                         attrValue = 'mce_' + idCount++;
  13503.                       }
  13504.                       attrList.map[name] = attrValue;
  13505.                       attrList.push({
  13506.                         name: name,
  13507.                         value: attrValue
  13508.                       });
  13509.                     }
  13510.                   }
  13511.                 }
  13512.                 if (attributesRequired) {
  13513.                   i = attributesRequired.length;
  13514.                   while (i--) {
  13515.                     if (attributesRequired[i] in attrList.map) {
  13516.                       break;
  13517.                     }
  13518.                   }
  13519.                   if (i === -1) {
  13520.                     isValidElement = false;
  13521.                   }
  13522.                 }
  13523.                 if (attr = attrList.map['data-mce-bogus']) {
  13524.                   if (attr === 'all') {
  13525.                     index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  13526.                     tokenRegExp.lastIndex = index;
  13527.                     continue;
  13528.                   }
  13529.                   isValidElement = false;
  13530.                 }
  13531.               }
  13532.               if (isValidElement) {
  13533.                 start(value, attrList, isShortEnded);
  13534.               }
  13535.             } else {
  13536.               isValidElement = false;
  13537.             }
  13538.             if (endRegExp = specialElements[value]) {
  13539.               endRegExp.lastIndex = index = matches.index + matchText.length;
  13540.               if (matches = endRegExp.exec(html)) {
  13541.                 if (isValidElement) {
  13542.                   textData = html.substr(index, matches.index - index);
  13543.                 }
  13544.                 index = matches.index + matches[0].length;
  13545.               } else {
  13546.                 textData = html.substr(index);
  13547.                 index = html.length;
  13548.               }
  13549.               if (isValidElement) {
  13550.                 if (textData.length > 0) {
  13551.                   processText(textData, true);
  13552.                 }
  13553.                 end(value);
  13554.               }
  13555.               tokenRegExp.lastIndex = index;
  13556.               continue;
  13557.             }
  13558.             if (!isShortEnded) {
  13559.               if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  13560.                 stack.push({
  13561.                   name: value,
  13562.                   valid: isValidElement
  13563.                 });
  13564.               } else if (isValidElement) {
  13565.                 end(value);
  13566.               }
  13567.             }
  13568.           } else if (value = matches[1]) {
  13569.             processComment(value);
  13570.           } else if (value = matches[2]) {
  13571.             var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  13572.             if (isValidCdataSection) {
  13573.               cdata(value);
  13574.             } else {
  13575.               index = processMalformedComment('', matches.index + 2);
  13576.               tokenRegExp.lastIndex = index;
  13577.               continue;
  13578.             }
  13579.           } else if (value = matches[3]) {
  13580.             doctype(value);
  13581.           } else if ((value = matches[4]) || matchText === '<!') {
  13582.             index = processMalformedComment(value, matches.index + matchText.length);
  13583.             tokenRegExp.lastIndex = index;
  13584.             continue;
  13585.           } else if (value = matches[5]) {
  13586.             if (parsingMode === 1) {
  13587.               pi(value, matches[6]);
  13588.             } else {
  13589.               index = processMalformedComment('?', matches.index + 2);
  13590.               tokenRegExp.lastIndex = index;
  13591.               continue;
  13592.             }
  13593.           }
  13594.           index = matches.index + matchText.length;
  13595.         }
  13596.         if (index < html.length) {
  13597.           processText(decode(html.substr(index)));
  13598.         }
  13599.         for (i = stack.length - 1; i >= 0; i--) {
  13600.           value = stack[i];
  13601.           if (value.valid) {
  13602.             end(value.name);
  13603.           }
  13604.         }
  13605.       };
  13606.       var parse = function (html, format) {
  13607.         if (format === void 0) {
  13608.           format = 'html';
  13609.         }
  13610.         parseInternal(extractBase64DataUris(html), format);
  13611.       };
  13612.       return { parse: parse };
  13613.     };
  13614.     SaxParser.findEndTag = findMatchingEndTagIndex;
  13615.  
  13616.     var trimHtml = function (tempAttrs, html) {
  13617.       var trimContentRegExp = new RegExp(['\\s?(' + tempAttrs.join('|') + ')="[^"]+"'].join('|'), 'gi');
  13618.       return html.replace(trimContentRegExp, '');
  13619.     };
  13620.     var trimInternal = function (serializer, html) {
  13621.       var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
  13622.       var schema = serializer.schema;
  13623.       var content = trimHtml(serializer.getTempAttrs(), html);
  13624.       var shortEndedElements = schema.getShortEndedElements();
  13625.       var matches;
  13626.       while (matches = bogusAllRegExp.exec(content)) {
  13627.         var index = bogusAllRegExp.lastIndex;
  13628.         var matchLength = matches[0].length;
  13629.         var endTagIndex = void 0;
  13630.         if (shortEndedElements[matches[1]]) {
  13631.           endTagIndex = index;
  13632.         } else {
  13633.           endTagIndex = SaxParser.findEndTag(schema, content, index);
  13634.         }
  13635.         content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
  13636.         bogusAllRegExp.lastIndex = index - matchLength;
  13637.       }
  13638.       return trim$2(content);
  13639.     };
  13640.     var trimExternal = trimInternal;
  13641.  
  13642.     var trimEmptyContents = function (editor, html) {
  13643.       var blockName = getForcedRootBlock(editor);
  13644.       var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  13645.       return html.replace(emptyRegExp, '');
  13646.     };
  13647.     var setupArgs$3 = function (args, format) {
  13648.       return __assign(__assign({}, args), {
  13649.         format: format,
  13650.         get: true,
  13651.         getInner: true
  13652.       });
  13653.     };
  13654.     var getContentFromBody = function (editor, args, format, body) {
  13655.       var defaultedArgs = setupArgs$3(args, format);
  13656.       var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeGetContent', defaultedArgs);
  13657.       var content;
  13658.       if (updatedArgs.format === 'raw') {
  13659.         content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
  13660.       } else if (updatedArgs.format === 'text') {
  13661.         content = editor.dom.isEmpty(body) ? '' : trim$2(body.innerText || body.textContent);
  13662.       } else if (updatedArgs.format === 'tree') {
  13663.         content = editor.serializer.serialize(body, updatedArgs);
  13664.       } else {
  13665.         content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  13666.       }
  13667.       if (!contains$3([
  13668.           'text',
  13669.           'tree'
  13670.         ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  13671.         updatedArgs.content = Tools.trim(content);
  13672.       } else {
  13673.         updatedArgs.content = content;
  13674.       }
  13675.       if (updatedArgs.no_events) {
  13676.         return updatedArgs.content;
  13677.       } else {
  13678.         return editor.fire('GetContent', updatedArgs).content;
  13679.       }
  13680.     };
  13681.     var getContentInternal = function (editor, args, format) {
  13682.       return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  13683.         return getContentFromBody(editor, args, format, body);
  13684.       });
  13685.     };
  13686.  
  13687.     var each$c = Tools.each;
  13688.     var ElementUtils = function (dom) {
  13689.       var compare = function (node1, node2) {
  13690.         if (node1.nodeName !== node2.nodeName) {
  13691.           return false;
  13692.         }
  13693.         var getAttribs = function (node) {
  13694.           var attribs = {};
  13695.           each$c(dom.getAttribs(node), function (attr) {
  13696.             var name = attr.nodeName.toLowerCase();
  13697.             if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13698.               attribs[name] = dom.getAttrib(node, name);
  13699.             }
  13700.           });
  13701.           return attribs;
  13702.         };
  13703.         var compareObjects = function (obj1, obj2) {
  13704.           var value, name;
  13705.           for (name in obj1) {
  13706.             if (has$2(obj1, name)) {
  13707.               value = obj2[name];
  13708.               if (typeof value === 'undefined') {
  13709.                 return false;
  13710.               }
  13711.               if (obj1[name] !== value) {
  13712.                 return false;
  13713.               }
  13714.               delete obj2[name];
  13715.             }
  13716.           }
  13717.           for (name in obj2) {
  13718.             if (has$2(obj2, name)) {
  13719.               return false;
  13720.             }
  13721.           }
  13722.           return true;
  13723.         };
  13724.         if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13725.           return false;
  13726.         }
  13727.         if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13728.           return false;
  13729.         }
  13730.         return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13731.       };
  13732.       return { compare: compare };
  13733.     };
  13734.  
  13735.     var makeMap$1 = Tools.makeMap;
  13736.     var Writer = function (settings) {
  13737.       var html = [];
  13738.       settings = settings || {};
  13739.       var indent = settings.indent;
  13740.       var indentBefore = makeMap$1(settings.indent_before || '');
  13741.       var indentAfter = makeMap$1(settings.indent_after || '');
  13742.       var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13743.       var htmlOutput = settings.element_format === 'html';
  13744.       return {
  13745.         start: function (name, attrs, empty) {
  13746.           var i, l, attr, value;
  13747.           if (indent && indentBefore[name] && html.length > 0) {
  13748.             value = html[html.length - 1];
  13749.             if (value.length > 0 && value !== '\n') {
  13750.               html.push('\n');
  13751.             }
  13752.           }
  13753.           html.push('<', name);
  13754.           if (attrs) {
  13755.             for (i = 0, l = attrs.length; i < l; i++) {
  13756.               attr = attrs[i];
  13757.               html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13758.             }
  13759.           }
  13760.           if (!empty || htmlOutput) {
  13761.             html[html.length] = '>';
  13762.           } else {
  13763.             html[html.length] = ' />';
  13764.           }
  13765.           if (empty && indent && indentAfter[name] && html.length > 0) {
  13766.             value = html[html.length - 1];
  13767.             if (value.length > 0 && value !== '\n') {
  13768.               html.push('\n');
  13769.             }
  13770.           }
  13771.         },
  13772.         end: function (name) {
  13773.           var value;
  13774.           html.push('</', name, '>');
  13775.           if (indent && indentAfter[name] && html.length > 0) {
  13776.             value = html[html.length - 1];
  13777.             if (value.length > 0 && value !== '\n') {
  13778.               html.push('\n');
  13779.             }
  13780.           }
  13781.         },
  13782.         text: function (text, raw) {
  13783.           if (text.length > 0) {
  13784.             html[html.length] = raw ? text : encode(text);
  13785.           }
  13786.         },
  13787.         cdata: function (text) {
  13788.           html.push('<![CDATA[', text, ']]>');
  13789.         },
  13790.         comment: function (text) {
  13791.           html.push('<!--', text, '-->');
  13792.         },
  13793.         pi: function (name, text) {
  13794.           if (text) {
  13795.             html.push('<?', name, ' ', encode(text), '?>');
  13796.           } else {
  13797.             html.push('<?', name, '?>');
  13798.           }
  13799.           if (indent) {
  13800.             html.push('\n');
  13801.           }
  13802.         },
  13803.         doctype: function (text) {
  13804.           html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13805.         },
  13806.         reset: function () {
  13807.           html.length = 0;
  13808.         },
  13809.         getContent: function () {
  13810.           return html.join('').replace(/\n$/, '');
  13811.         }
  13812.       };
  13813.     };
  13814.  
  13815.     var HtmlSerializer = function (settings, schema) {
  13816.       if (schema === void 0) {
  13817.         schema = Schema();
  13818.       }
  13819.       var writer = Writer(settings);
  13820.       settings = settings || {};
  13821.       settings.validate = 'validate' in settings ? settings.validate : true;
  13822.       var serialize = function (node) {
  13823.         var validate = settings.validate;
  13824.         var handlers = {
  13825.           3: function (node) {
  13826.             writer.text(node.value, node.raw);
  13827.           },
  13828.           8: function (node) {
  13829.             writer.comment(node.value);
  13830.           },
  13831.           7: function (node) {
  13832.             writer.pi(node.name, node.value);
  13833.           },
  13834.           10: function (node) {
  13835.             writer.doctype(node.value);
  13836.           },
  13837.           4: function (node) {
  13838.             writer.cdata(node.value);
  13839.           },
  13840.           11: function (node) {
  13841.             if (node = node.firstChild) {
  13842.               do {
  13843.                 walk(node);
  13844.               } while (node = node.next);
  13845.             }
  13846.           }
  13847.         };
  13848.         writer.reset();
  13849.         var walk = function (node) {
  13850.           var handler = handlers[node.type];
  13851.           if (!handler) {
  13852.             var name_1 = node.name;
  13853.             var isEmpty = node.shortEnded;
  13854.             var attrs = node.attributes;
  13855.             if (validate && attrs && attrs.length > 1) {
  13856.               var sortedAttrs = [];
  13857.               sortedAttrs.map = {};
  13858.               var elementRule = schema.getElementRule(node.name);
  13859.               if (elementRule) {
  13860.                 for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13861.                   var attrName = elementRule.attributesOrder[i];
  13862.                   if (attrName in attrs.map) {
  13863.                     var attrValue = attrs.map[attrName];
  13864.                     sortedAttrs.map[attrName] = attrValue;
  13865.                     sortedAttrs.push({
  13866.                       name: attrName,
  13867.                       value: attrValue
  13868.                     });
  13869.                   }
  13870.                 }
  13871.                 for (var i = 0, l = attrs.length; i < l; i++) {
  13872.                   var attrName = attrs[i].name;
  13873.                   if (!(attrName in sortedAttrs.map)) {
  13874.                     var attrValue = attrs.map[attrName];
  13875.                     sortedAttrs.map[attrName] = attrValue;
  13876.                     sortedAttrs.push({
  13877.                       name: attrName,
  13878.                       value: attrValue
  13879.                     });
  13880.                   }
  13881.                 }
  13882.                 attrs = sortedAttrs;
  13883.               }
  13884.             }
  13885.             writer.start(node.name, attrs, isEmpty);
  13886.             if (!isEmpty) {
  13887.               if (node = node.firstChild) {
  13888.                 do {
  13889.                   walk(node);
  13890.                 } while (node = node.next);
  13891.               }
  13892.               writer.end(name_1);
  13893.             }
  13894.           } else {
  13895.             handler(node);
  13896.           }
  13897.         };
  13898.         if (node.type === 1 && !settings.inner) {
  13899.           walk(node);
  13900.         } else {
  13901.           handlers[11](node);
  13902.         }
  13903.         return writer.getContent();
  13904.       };
  13905.       return { serialize: serialize };
  13906.     };
  13907.  
  13908.     var nonInheritableStyles = new Set();
  13909.     (function () {
  13910.       var nonInheritableStylesArr = [
  13911.         'margin',
  13912.         'margin-left',
  13913.         'margin-right',
  13914.         'margin-top',
  13915.         'margin-bottom',
  13916.         'padding',
  13917.         'padding-left',
  13918.         'padding-right',
  13919.         'padding-top',
  13920.         'padding-bottom',
  13921.         'border',
  13922.         'border-width',
  13923.         'border-style',
  13924.         'border-color',
  13925.         'background',
  13926.         'background-attachment',
  13927.         'background-clip',
  13928.         'background-color',
  13929.         'background-image',
  13930.         'background-origin',
  13931.         'background-position',
  13932.         'background-repeat',
  13933.         'background-size',
  13934.         'float',
  13935.         'position',
  13936.         'left',
  13937.         'right',
  13938.         'top',
  13939.         'bottom',
  13940.         'z-index',
  13941.         'display',
  13942.         'transform',
  13943.         'width',
  13944.         'max-width',
  13945.         'min-width',
  13946.         'height',
  13947.         'max-height',
  13948.         'min-height',
  13949.         'overflow',
  13950.         'overflow-x',
  13951.         'overflow-y',
  13952.         'text-overflow',
  13953.         'vertical-align',
  13954.         'transition',
  13955.         'transition-delay',
  13956.         'transition-duration',
  13957.         'transition-property',
  13958.         'transition-timing-function'
  13959.       ];
  13960.       each$k(nonInheritableStylesArr, function (style) {
  13961.         nonInheritableStyles.add(style);
  13962.       });
  13963.     }());
  13964.     var shorthandStyleProps = [
  13965.       'font',
  13966.       'text-decoration',
  13967.       'text-emphasis'
  13968.     ];
  13969.     var getStyleProps = function (dom, node) {
  13970.       return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13971.     };
  13972.     var isNonInheritableStyle = function (style) {
  13973.       return nonInheritableStyles.has(style);
  13974.     };
  13975.     var hasInheritableStyles = function (dom, node) {
  13976.       return forall(getStyleProps(dom, node), function (style) {
  13977.         return !isNonInheritableStyle(style);
  13978.       });
  13979.     };
  13980.     var getLonghandStyleProps = function (styles) {
  13981.       return filter$4(styles, function (style) {
  13982.         return exists(shorthandStyleProps, function (prop) {
  13983.           return startsWith(style, prop);
  13984.         });
  13985.       });
  13986.     };
  13987.     var hasStyleConflict = function (dom, node, parentNode) {
  13988.       var nodeStyleProps = getStyleProps(dom, node);
  13989.       var parentNodeStyleProps = getStyleProps(dom, parentNode);
  13990.       var valueMismatch = function (prop) {
  13991.         var nodeValue = dom.getStyle(node, prop);
  13992.         var parentValue = dom.getStyle(parentNode, prop);
  13993.         return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  13994.       };
  13995.       return exists(nodeStyleProps, function (nodeStyleProp) {
  13996.         var propExists = function (props) {
  13997.           return exists(props, function (prop) {
  13998.             return prop === nodeStyleProp;
  13999.           });
  14000.         };
  14001.         if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  14002.           var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  14003.           return exists(longhandProps, valueMismatch);
  14004.         } else {
  14005.           return valueMismatch(nodeStyleProp);
  14006.         }
  14007.       });
  14008.     };
  14009.  
  14010.     var isChar = function (forward, predicate, pos) {
  14011.       return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  14012.         var delta = forward ? 0 : -1;
  14013.         return predicate(text.data.charAt(pos.offset() + delta));
  14014.       });
  14015.     };
  14016.     var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  14017.     var isAfterSpace = curry(isChar, false, isWhiteSpace);
  14018.     var isEmptyText = function (pos) {
  14019.       var container = pos.container();
  14020.       return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  14021.     };
  14022.     var matchesElementPosition = function (before, predicate) {
  14023.       return function (pos) {
  14024.         return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  14025.       };
  14026.     };
  14027.     var isImageBlock = function (node) {
  14028.       return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  14029.     };
  14030.     var isCefNode = function (node) {
  14031.       return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  14032.     };
  14033.     var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  14034.     var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  14035.     var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  14036.     var isAfterMedia = matchesElementPosition(false, isMedia$2);
  14037.     var isBeforeTable = matchesElementPosition(true, isTable$3);
  14038.     var isAfterTable = matchesElementPosition(false, isTable$3);
  14039.     var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  14040.     var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  14041.  
  14042.     var getLastChildren = function (elm) {
  14043.       var children = [];
  14044.       var rawNode = elm.dom;
  14045.       while (rawNode) {
  14046.         children.push(SugarElement.fromDom(rawNode));
  14047.         rawNode = rawNode.lastChild;
  14048.       }
  14049.       return children;
  14050.     };
  14051.     var removeTrailingBr = function (elm) {
  14052.       var allBrs = descendants(elm, 'br');
  14053.       var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  14054.       if (allBrs.length === brs.length) {
  14055.         each$k(brs, remove$7);
  14056.       }
  14057.     };
  14058.     var fillWithPaddingBr = function (elm) {
  14059.       empty(elm);
  14060.       append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  14061.     };
  14062.     var trimBlockTrailingBr = function (elm) {
  14063.       lastChild(elm).each(function (lastChild) {
  14064.         prevSibling(lastChild).each(function (lastChildPrevSibling) {
  14065.           if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  14066.             remove$7(lastChild);
  14067.           }
  14068.         });
  14069.       });
  14070.     };
  14071.  
  14072.     var dropLast = function (xs) {
  14073.       return xs.slice(0, -1);
  14074.     };
  14075.     var parentsUntil = function (start, root, predicate) {
  14076.       if (contains$1(root, start)) {
  14077.         return dropLast(parents$1(start, function (elm) {
  14078.           return predicate(elm) || eq(elm, root);
  14079.         }));
  14080.       } else {
  14081.         return [];
  14082.       }
  14083.     };
  14084.     var parents = function (start, root) {
  14085.       return parentsUntil(start, root, never);
  14086.     };
  14087.     var parentsAndSelf = function (start, root) {
  14088.       return [start].concat(parents(start, root));
  14089.     };
  14090.  
  14091.     var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  14092.       return navigateIgnore(forward, root, from, isEmptyText);
  14093.     };
  14094.     var getClosestBlock$1 = function (root, pos) {
  14095.       return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14096.     };
  14097.     var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  14098.       return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14099.         return getClosestBlock$1(root, pos).fold(function () {
  14100.           return isInSameBlock(newPos, pos, root.dom) === false;
  14101.         }, function (fromBlock) {
  14102.           return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  14103.         });
  14104.       });
  14105.     };
  14106.     var isAtBlockBoundary = function (forward, root, pos) {
  14107.       return getClosestBlock$1(root, pos).fold(function () {
  14108.         return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  14109.           return isInSameBlock(newPos, pos, root.dom) === false;
  14110.         });
  14111.       }, function (parent) {
  14112.         return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  14113.       });
  14114.     };
  14115.     var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  14116.     var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  14117.     var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  14118.     var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  14119.  
  14120.     var isBr = function (pos) {
  14121.       return getElementFromPosition(pos).exists(isBr$4);
  14122.     };
  14123.     var findBr = function (forward, root, pos) {
  14124.       var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14125.       var scope = head(parentBlocks).getOr(root);
  14126.       return fromPosition(forward, scope.dom, pos).filter(isBr);
  14127.     };
  14128.     var isBeforeBr$1 = function (root, pos) {
  14129.       return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  14130.     };
  14131.     var isAfterBr = function (root, pos) {
  14132.       return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  14133.     };
  14134.     var findPreviousBr = curry(findBr, false);
  14135.     var findNextBr = curry(findBr, true);
  14136.  
  14137.     var isInMiddleOfText = function (pos) {
  14138.       return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  14139.     };
  14140.     var getClosestBlock = function (root, pos) {
  14141.       var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  14142.       return head(parentBlocks).getOr(root);
  14143.     };
  14144.     var hasSpaceBefore = function (root, pos) {
  14145.       if (isInMiddleOfText(pos)) {
  14146.         return isAfterSpace(pos);
  14147.       } else {
  14148.         return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  14149.       }
  14150.     };
  14151.     var hasSpaceAfter = function (root, pos) {
  14152.       if (isInMiddleOfText(pos)) {
  14153.         return isBeforeSpace(pos);
  14154.       } else {
  14155.         return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  14156.       }
  14157.     };
  14158.     var isPreValue = function (value) {
  14159.       return contains$3([
  14160.         'pre',
  14161.         'pre-wrap'
  14162.       ], value);
  14163.     };
  14164.     var isInPre = function (pos) {
  14165.       return getElementFromPosition(pos).bind(function (elm) {
  14166.         return closest$3(elm, isElement$6);
  14167.       }).exists(function (elm) {
  14168.         return isPreValue(get$5(elm, 'white-space'));
  14169.       });
  14170.     };
  14171.     var isAtBeginningOfBody = function (root, pos) {
  14172.       return prevPosition(root.dom, pos).isNone();
  14173.     };
  14174.     var isAtEndOfBody = function (root, pos) {
  14175.       return nextPosition(root.dom, pos).isNone();
  14176.     };
  14177.     var isAtLineBoundary = function (root, pos) {
  14178.       return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  14179.     };
  14180.     var needsToHaveNbsp = function (root, pos) {
  14181.       if (isInPre(pos)) {
  14182.         return false;
  14183.       } else {
  14184.         return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  14185.       }
  14186.     };
  14187.     var needsToBeNbspLeft = function (root, pos) {
  14188.       if (isInPre(pos)) {
  14189.         return false;
  14190.       } else {
  14191.         return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  14192.       }
  14193.     };
  14194.     var leanRight = function (pos) {
  14195.       var container = pos.container();
  14196.       var offset = pos.offset();
  14197.       if (isText$7(container) && offset < container.data.length) {
  14198.         return CaretPosition(container, offset + 1);
  14199.       } else {
  14200.         return pos;
  14201.       }
  14202.     };
  14203.     var needsToBeNbspRight = function (root, pos) {
  14204.       if (isInPre(pos)) {
  14205.         return false;
  14206.       } else {
  14207.         return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  14208.       }
  14209.     };
  14210.     var needsToBeNbsp = function (root, pos) {
  14211.       return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  14212.     };
  14213.     var isNbspAt = function (text, offset) {
  14214.       return isNbsp(text.charAt(offset));
  14215.     };
  14216.     var hasNbsp = function (pos) {
  14217.       var container = pos.container();
  14218.       return isText$7(container) && contains$2(container.data, nbsp);
  14219.     };
  14220.     var normalizeNbspMiddle = function (text) {
  14221.       var chars = text.split('');
  14222.       return map$3(chars, function (chr, i) {
  14223.         if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  14224.           return ' ';
  14225.         } else {
  14226.           return chr;
  14227.         }
  14228.       }).join('');
  14229.     };
  14230.     var normalizeNbspAtStart = function (root, node) {
  14231.       var text = node.data;
  14232.       var firstPos = CaretPosition(node, 0);
  14233.       if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  14234.         node.data = ' ' + text.slice(1);
  14235.         return true;
  14236.       } else {
  14237.         return false;
  14238.       }
  14239.     };
  14240.     var normalizeNbspInMiddleOfTextNode = function (node) {
  14241.       var text = node.data;
  14242.       var newText = normalizeNbspMiddle(text);
  14243.       if (newText !== text) {
  14244.         node.data = newText;
  14245.         return true;
  14246.       } else {
  14247.         return false;
  14248.       }
  14249.     };
  14250.     var normalizeNbspAtEnd = function (root, node) {
  14251.       var text = node.data;
  14252.       var lastPos = CaretPosition(node, text.length - 1);
  14253.       if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  14254.         node.data = text.slice(0, -1) + ' ';
  14255.         return true;
  14256.       } else {
  14257.         return false;
  14258.       }
  14259.     };
  14260.     var normalizeNbsps = function (root, pos) {
  14261.       return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  14262.         var container = pos.container();
  14263.         var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  14264.         return normalized ? Optional.some(pos) : Optional.none();
  14265.       });
  14266.     };
  14267.     var normalizeNbspsInEditor = function (editor) {
  14268.       var root = SugarElement.fromDom(editor.getBody());
  14269.       if (editor.selection.isCollapsed()) {
  14270.         normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  14271.           editor.selection.setRng(pos.toRange());
  14272.         });
  14273.       }
  14274.     };
  14275.  
  14276.     var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  14277.       var result = foldl(content, function (acc, c) {
  14278.         if (isWhiteSpace(c) || isNbsp(c)) {
  14279.           if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  14280.             return {
  14281.               previousCharIsSpace: false,
  14282.               str: acc.str + nbsp
  14283.             };
  14284.           } else {
  14285.             return {
  14286.               previousCharIsSpace: true,
  14287.               str: acc.str + ' '
  14288.             };
  14289.           }
  14290.         } else {
  14291.           return {
  14292.             previousCharIsSpace: false,
  14293.             str: acc.str + c
  14294.           };
  14295.         }
  14296.       }, {
  14297.         previousCharIsSpace: false,
  14298.         str: ''
  14299.       });
  14300.       return result.str;
  14301.     };
  14302.     var normalize$1 = function (node, offset, count) {
  14303.       if (count === 0) {
  14304.         return;
  14305.       }
  14306.       var elm = SugarElement.fromDom(node);
  14307.       var root = ancestor$3(elm, isBlock$2).getOr(elm);
  14308.       var whitespace = node.data.slice(offset, offset + count);
  14309.       var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  14310.       var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  14311.       node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  14312.     };
  14313.     var normalizeWhitespaceAfter = function (node, offset) {
  14314.       var content = node.data.slice(offset);
  14315.       var whitespaceCount = content.length - lTrim(content).length;
  14316.       normalize$1(node, offset, whitespaceCount);
  14317.     };
  14318.     var normalizeWhitespaceBefore = function (node, offset) {
  14319.       var content = node.data.slice(0, offset);
  14320.       var whitespaceCount = content.length - rTrim(content).length;
  14321.       normalize$1(node, offset - whitespaceCount, whitespaceCount);
  14322.     };
  14323.     var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  14324.       if (mergeToPrev === void 0) {
  14325.         mergeToPrev = true;
  14326.       }
  14327.       var whitespaceOffset = rTrim(prevNode.data).length;
  14328.       var newNode = mergeToPrev ? prevNode : nextNode;
  14329.       var removeNode = mergeToPrev ? nextNode : prevNode;
  14330.       if (mergeToPrev) {
  14331.         newNode.appendData(removeNode.data);
  14332.       } else {
  14333.         newNode.insertData(0, removeNode.data);
  14334.       }
  14335.       remove$7(SugarElement.fromDom(removeNode));
  14336.       if (normalizeWhitespace) {
  14337.         normalizeWhitespaceAfter(newNode, whitespaceOffset);
  14338.       }
  14339.       return newNode;
  14340.     };
  14341.  
  14342.     var needsReposition = function (pos, elm) {
  14343.       var container = pos.container();
  14344.       var offset = pos.offset();
  14345.       return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  14346.     };
  14347.     var reposition = function (elm, pos) {
  14348.       return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  14349.     };
  14350.     var beforeOrStartOf = function (node) {
  14351.       return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  14352.     };
  14353.     var afterOrEndOf = function (node) {
  14354.       return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  14355.     };
  14356.     var getPreviousSiblingCaretPosition = function (elm) {
  14357.       if (isCaretCandidate$3(elm.previousSibling)) {
  14358.         return Optional.some(afterOrEndOf(elm.previousSibling));
  14359.       } else {
  14360.         return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  14361.       }
  14362.     };
  14363.     var getNextSiblingCaretPosition = function (elm) {
  14364.       if (isCaretCandidate$3(elm.nextSibling)) {
  14365.         return Optional.some(beforeOrStartOf(elm.nextSibling));
  14366.       } else {
  14367.         return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  14368.       }
  14369.     };
  14370.     var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  14371.       var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  14372.       return prevPosition(rootElement, startPosition).fold(function () {
  14373.         return nextPosition(rootElement, CaretPosition.after(elm));
  14374.       }, Optional.some);
  14375.     };
  14376.     var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  14377.       return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  14378.         return prevPosition(rootElement, CaretPosition.before(elm));
  14379.       }, Optional.some);
  14380.     };
  14381.     var findCaretPositionBackwards = function (rootElement, elm) {
  14382.       return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  14383.         return getNextSiblingCaretPosition(elm);
  14384.       }).orThunk(function () {
  14385.         return findCaretPositionBackwardsFromElm(rootElement, elm);
  14386.       });
  14387.     };
  14388.     var findCaretPositionForward = function (rootElement, elm) {
  14389.       return getNextSiblingCaretPosition(elm).orThunk(function () {
  14390.         return getPreviousSiblingCaretPosition(elm);
  14391.       }).orThunk(function () {
  14392.         return findCaretPositionForwardsFromElm(rootElement, elm);
  14393.       });
  14394.     };
  14395.     var findCaretPosition = function (forward, rootElement, elm) {
  14396.       return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  14397.     };
  14398.     var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  14399.       return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  14400.     };
  14401.     var setSelection$1 = function (editor, forward, pos) {
  14402.       pos.fold(function () {
  14403.         editor.focus();
  14404.       }, function (pos) {
  14405.         editor.selection.setRng(pos.toRange(), forward);
  14406.       });
  14407.     };
  14408.     var eqRawNode = function (rawNode) {
  14409.       return function (elm) {
  14410.         return elm.dom === rawNode;
  14411.       };
  14412.     };
  14413.     var isBlock = function (editor, elm) {
  14414.       return elm && has$2(editor.schema.getBlockElements(), name(elm));
  14415.     };
  14416.     var paddEmptyBlock = function (elm) {
  14417.       if (isEmpty$2(elm)) {
  14418.         var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  14419.         empty(elm);
  14420.         append$1(elm, br);
  14421.         return Optional.some(CaretPosition.before(br.dom));
  14422.       } else {
  14423.         return Optional.none();
  14424.       }
  14425.     };
  14426.     var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  14427.       var prevTextOpt = prevSibling(elm).filter(isText$8);
  14428.       var nextTextOpt = nextSibling(elm).filter(isText$8);
  14429.       remove$7(elm);
  14430.       return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  14431.         var prevNode = prev.dom, nextNode = next.dom;
  14432.         var offset = prevNode.data.length;
  14433.         mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  14434.         return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  14435.       }).orThunk(function () {
  14436.         if (normalizeWhitespace) {
  14437.           prevTextOpt.each(function (elm) {
  14438.             return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  14439.           });
  14440.           nextTextOpt.each(function (elm) {
  14441.             return normalizeWhitespaceAfter(elm.dom, 0);
  14442.           });
  14443.         }
  14444.         return afterDeletePosOpt;
  14445.       });
  14446.     };
  14447.     var isInlineElement = function (editor, element) {
  14448.       return has$2(editor.schema.getTextInlineElements(), name(element));
  14449.     };
  14450.     var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  14451.       if (moveCaret === void 0) {
  14452.         moveCaret = true;
  14453.       }
  14454.       var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  14455.       var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  14456.       var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  14457.       if (editor.dom.isEmpty(editor.getBody())) {
  14458.         editor.setContent('');
  14459.         editor.selection.setCursorLocation();
  14460.       } else {
  14461.         parentBlock.bind(paddEmptyBlock).fold(function () {
  14462.           if (moveCaret) {
  14463.             setSelection$1(editor, forward, normalizedAfterDeletePos);
  14464.           }
  14465.         }, function (paddPos) {
  14466.           if (moveCaret) {
  14467.             setSelection$1(editor, forward, Optional.some(paddPos));
  14468.           }
  14469.         });
  14470.       }
  14471.     };
  14472.  
  14473.     var isRootFromElement = function (root) {
  14474.       return function (cur) {
  14475.         return eq(root, cur);
  14476.       };
  14477.     };
  14478.     var getTableCells = function (table) {
  14479.       return descendants(table, 'td,th');
  14480.     };
  14481.     var getTableDetailsFromRange = function (rng, isRoot) {
  14482.       var getTable = function (node) {
  14483.         return getClosestTable(SugarElement.fromDom(node), isRoot);
  14484.       };
  14485.       var startTable = getTable(rng.startContainer);
  14486.       var endTable = getTable(rng.endContainer);
  14487.       var isStartInTable = startTable.isSome();
  14488.       var isEndInTable = endTable.isSome();
  14489.       var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  14490.       var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  14491.       return {
  14492.         startTable: startTable,
  14493.         endTable: endTable,
  14494.         isStartInTable: isStartInTable,
  14495.         isEndInTable: isEndInTable,
  14496.         isSameTable: isSameTable,
  14497.         isMultiTable: isMultiTable
  14498.       };
  14499.     };
  14500.  
  14501.     var tableCellRng = function (start, end) {
  14502.       return {
  14503.         start: start,
  14504.         end: end
  14505.       };
  14506.     };
  14507.     var tableSelection = function (rng, table, cells) {
  14508.       return {
  14509.         rng: rng,
  14510.         table: table,
  14511.         cells: cells
  14512.       };
  14513.     };
  14514.     var deleteAction = Adt.generate([
  14515.       {
  14516.         singleCellTable: [
  14517.           'rng',
  14518.           'cell'
  14519.         ]
  14520.       },
  14521.       { fullTable: ['table'] },
  14522.       {
  14523.         partialTable: [
  14524.           'cells',
  14525.           'outsideDetails'
  14526.         ]
  14527.       },
  14528.       {
  14529.         multiTable: [
  14530.           'startTableCells',
  14531.           'endTableCells',
  14532.           'betweenRng'
  14533.         ]
  14534.       }
  14535.     ]);
  14536.     var getClosestCell$1 = function (container, isRoot) {
  14537.       return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  14538.     };
  14539.     var isExpandedCellRng = function (cellRng) {
  14540.       return !eq(cellRng.start, cellRng.end);
  14541.     };
  14542.     var getTableFromCellRng = function (cellRng, isRoot) {
  14543.       return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  14544.         return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  14545.           return someIf(eq(startParentTable, endParentTable), startParentTable);
  14546.         });
  14547.       });
  14548.     };
  14549.     var isSingleCellTable = function (cellRng, isRoot) {
  14550.       return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  14551.         var rows = table.dom.rows;
  14552.         return rows.length === 1 && rows[0].cells.length === 1;
  14553.       });
  14554.     };
  14555.     var getCellRng = function (rng, isRoot) {
  14556.       var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14557.       var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14558.       return lift2(startCell, endCell, tableCellRng);
  14559.     };
  14560.     var getCellRangeFromStartTable = function (isRoot) {
  14561.       return function (startCell) {
  14562.         return getClosestTable(startCell, isRoot).bind(function (table) {
  14563.           return last$2(getTableCells(table)).map(function (endCell) {
  14564.             return tableCellRng(startCell, endCell);
  14565.           });
  14566.         });
  14567.       };
  14568.     };
  14569.     var getCellRangeFromEndTable = function (isRoot) {
  14570.       return function (endCell) {
  14571.         return getClosestTable(endCell, isRoot).bind(function (table) {
  14572.           return head(getTableCells(table)).map(function (startCell) {
  14573.             return tableCellRng(startCell, endCell);
  14574.           });
  14575.         });
  14576.       };
  14577.     };
  14578.     var getTableSelectionFromCellRng = function (isRoot) {
  14579.       return function (cellRng) {
  14580.         return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  14581.           return tableSelection(cellRng, table, getTableCells(table));
  14582.         });
  14583.       };
  14584.     };
  14585.     var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  14586.       if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  14587.         return Optional.none();
  14588.       } else if (selectionDetails.isSameTable) {
  14589.         var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  14590.         return Optional.some({
  14591.           start: sameTableSelection,
  14592.           end: sameTableSelection
  14593.         });
  14594.       } else {
  14595.         var startCell = getClosestCell$1(rng.startContainer, isRoot);
  14596.         var endCell = getClosestCell$1(rng.endContainer, isRoot);
  14597.         var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14598.         var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  14599.         return Optional.some({
  14600.           start: startTableSelection,
  14601.           end: endTableSelection
  14602.         });
  14603.       }
  14604.     };
  14605.     var getCellIndex = function (cells, cell) {
  14606.       return findIndex$2(cells, function (x) {
  14607.         return eq(x, cell);
  14608.       });
  14609.     };
  14610.     var getSelectedCells = function (tableSelection) {
  14611.       return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  14612.         return tableSelection.cells.slice(startIndex, endIndex + 1);
  14613.       });
  14614.     };
  14615.     var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  14616.       return optCellRng.exists(function (cellRng) {
  14617.         return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  14618.       });
  14619.     };
  14620.     var unselectCells = function (rng, selectionDetails) {
  14621.       var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  14622.       var otherContentRng = rng.cloneRange();
  14623.       startTable.each(function (table) {
  14624.         return otherContentRng.setStartAfter(table.dom);
  14625.       });
  14626.       endTable.each(function (table) {
  14627.         return otherContentRng.setEndBefore(table.dom);
  14628.       });
  14629.       return otherContentRng;
  14630.     };
  14631.     var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  14632.       return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14633.         var start = _a.start, end = _a.end;
  14634.         return start.or(end);
  14635.       }).bind(function (tableSelection) {
  14636.         var isSameTable = selectionDetails.isSameTable;
  14637.         var selectedCells = getSelectedCells(tableSelection).getOr([]);
  14638.         if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  14639.           return Optional.some(deleteAction.fullTable(tableSelection.table));
  14640.         } else if (selectedCells.length > 0) {
  14641.           if (isSameTable) {
  14642.             return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  14643.           } else {
  14644.             var otherContentRng = unselectCells(rng, selectionDetails);
  14645.             return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  14646.           }
  14647.         } else {
  14648.           return Optional.none();
  14649.         }
  14650.       });
  14651.     };
  14652.     var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  14653.       return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  14654.         var start = _a.start, end = _a.end;
  14655.         var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  14656.         var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  14657.         if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  14658.           var otherContentRng = unselectCells(rng, selectionDetails);
  14659.           return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  14660.         } else {
  14661.           return Optional.none();
  14662.         }
  14663.       });
  14664.     };
  14665.     var getActionFromRange = function (root, rng) {
  14666.       var isRoot = isRootFromElement(root);
  14667.       var optCellRng = getCellRng(rng, isRoot);
  14668.       var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  14669.       if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  14670.         return optCellRng.map(function (cellRng) {
  14671.           return deleteAction.singleCellTable(rng, cellRng.start);
  14672.         });
  14673.       } else if (selectionDetails.isMultiTable) {
  14674.         return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  14675.       } else {
  14676.         return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  14677.       }
  14678.     };
  14679.  
  14680.     var freefallRtl = function (root) {
  14681.       var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  14682.       return child.bind(freefallRtl).orThunk(function () {
  14683.         return Optional.some(root);
  14684.       });
  14685.     };
  14686.     var cleanCells = function (cells) {
  14687.       return each$k(cells, function (cell) {
  14688.         remove$6(cell, 'contenteditable');
  14689.         fillWithPaddingBr(cell);
  14690.       });
  14691.     };
  14692.     var getOutsideBlock = function (editor, container) {
  14693.       return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14694.     };
  14695.     var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14696.       emptyBlock.each(function (block) {
  14697.         if (startInTable) {
  14698.           remove$7(block);
  14699.         } else {
  14700.           fillWithPaddingBr(block);
  14701.           editor.selection.setCursorLocation(block.dom, 0);
  14702.         }
  14703.       });
  14704.     };
  14705.     var deleteContentInsideCell = function (editor, cell, rng, isFirstCellInSelection) {
  14706.       var insideTableRng = rng.cloneRange();
  14707.       if (isFirstCellInSelection) {
  14708.         insideTableRng.setStart(rng.startContainer, rng.startOffset);
  14709.         insideTableRng.setEndAfter(cell.dom.lastChild);
  14710.       } else {
  14711.         insideTableRng.setStartBefore(cell.dom.firstChild);
  14712.         insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  14713.       }
  14714.       deleteCellContents(editor, insideTableRng, cell, false);
  14715.     };
  14716.     var collapseAndRestoreCellSelection = function (editor) {
  14717.       var selectedCells = getCellsFromEditor(editor);
  14718.       var selectedNode = SugarElement.fromDom(editor.selection.getNode());
  14719.       if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  14720.         editor.selection.setCursorLocation(selectedNode.dom, 0);
  14721.       } else {
  14722.         editor.selection.collapse(true);
  14723.       }
  14724.       if (selectedCells.length > 1 && exists(selectedCells, function (cell) {
  14725.           return eq(cell, selectedNode);
  14726.         })) {
  14727.         set$1(selectedNode, 'data-mce-selected', '1');
  14728.       }
  14729.     };
  14730.     var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14731.       var editorRng = editor.selection.getRng();
  14732.       var cellsToClean = outsideDetails.bind(function (_a) {
  14733.         var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14734.         var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14735.         rng.deleteContents();
  14736.         handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14737.         var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  14738.         deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  14739.         if (!isEmpty$2(endPointCell)) {
  14740.           return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  14741.         } else {
  14742.           return Optional.none();
  14743.         }
  14744.       }).getOr(cells);
  14745.       cleanCells(cellsToClean);
  14746.       collapseAndRestoreCellSelection(editor);
  14747.       return true;
  14748.     };
  14749.     var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14750.       var rng = editor.selection.getRng();
  14751.       var startCell = startTableCells[0];
  14752.       var endCell = endTableCells[endTableCells.length - 1];
  14753.       deleteContentInsideCell(editor, startCell, rng, true);
  14754.       deleteContentInsideCell(editor, endCell, rng, false);
  14755.       var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  14756.       var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  14757.       cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  14758.       betweenRng.deleteContents();
  14759.       collapseAndRestoreCellSelection(editor);
  14760.       return true;
  14761.     };
  14762.     var deleteCellContents = function (editor, rng, cell, moveSelection) {
  14763.       if (moveSelection === void 0) {
  14764.         moveSelection = true;
  14765.       }
  14766.       rng.deleteContents();
  14767.       var lastNode = freefallRtl(cell).getOr(cell);
  14768.       var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14769.       if (isEmpty$2(lastBlock)) {
  14770.         fillWithPaddingBr(lastBlock);
  14771.         if (moveSelection) {
  14772.           editor.selection.setCursorLocation(lastBlock.dom, 0);
  14773.         }
  14774.       }
  14775.       if (!eq(cell, lastBlock)) {
  14776.         var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14777.         each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14778.           if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
  14779.             remove$7(node);
  14780.           }
  14781.         });
  14782.       }
  14783.       return true;
  14784.     };
  14785.     var deleteTableElement = function (editor, table) {
  14786.       deleteElement$2(editor, false, table);
  14787.       return true;
  14788.     };
  14789.     var deleteCellRange = function (editor, rootElm, rng) {
  14790.       return getActionFromRange(rootElm, rng).map(function (action) {
  14791.         return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14792.       });
  14793.     };
  14794.     var deleteCaptionRange = function (editor, caption) {
  14795.       return emptyElement(editor, caption);
  14796.     };
  14797.     var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14798.       return getParentCaption(rootElm, startElm).fold(function () {
  14799.         return deleteCellRange(editor, rootElm, rng);
  14800.       }, function (caption) {
  14801.         return deleteCaptionRange(editor, caption);
  14802.       }).getOr(false);
  14803.     };
  14804.     var deleteRange$2 = function (editor, startElm, selectedCells) {
  14805.       var rootNode = SugarElement.fromDom(editor.getBody());
  14806.       var rng = editor.selection.getRng();
  14807.       return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14808.     };
  14809.     var getParentCell = function (rootElm, elm) {
  14810.       return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14811.     };
  14812.     var getParentCaption = function (rootElm, elm) {
  14813.       return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14814.     };
  14815.     var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14816.       return navigate(forward, editor.getBody(), from).bind(function (to) {
  14817.         return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14818.           return eq(toCell, fromCell) === false;
  14819.         });
  14820.       });
  14821.     };
  14822.     var emptyElement = function (editor, elm) {
  14823.       fillWithPaddingBr(elm);
  14824.       editor.selection.setCursorLocation(elm.dom, 0);
  14825.       return Optional.some(true);
  14826.     };
  14827.     var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14828.       return firstPositionIn(fromCaption.dom).bind(function (first) {
  14829.         return lastPositionIn(fromCaption.dom).map(function (last) {
  14830.           return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14831.         });
  14832.       }).getOr(true);
  14833.     };
  14834.     var emptyCaretCaption = function (editor, elm) {
  14835.       return emptyElement(editor, elm);
  14836.     };
  14837.     var validateCaretCaption = function (rootElm, fromCaption, to) {
  14838.       return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14839.         return eq(toCaption, fromCaption) === false;
  14840.       });
  14841.     };
  14842.     var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14843.       return navigate(forward, editor.getBody(), from).bind(function (to) {
  14844.         return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14845.       }).or(Optional.some(true));
  14846.     };
  14847.     var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14848.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14849.       return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14850.         return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14851.       }).getOr(false);
  14852.     };
  14853.     var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14854.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14855.       return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14856.     };
  14857.     var isNearTable = function (forward, pos) {
  14858.       return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14859.     };
  14860.     var isBeforeOrAfterTable = function (editor, forward) {
  14861.       var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14862.       return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14863.         return isNearTable(forward, pos);
  14864.       });
  14865.     };
  14866.     var deleteCaret$3 = function (editor, forward, startElm) {
  14867.       var rootElm = SugarElement.fromDom(editor.getBody());
  14868.       return getParentCaption(rootElm, startElm).fold(function () {
  14869.         return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14870.       }, function (fromCaption) {
  14871.         return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14872.       });
  14873.     };
  14874.     var backspaceDelete$9 = function (editor, forward) {
  14875.       var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14876.       var cells = getCellsFromEditor(editor);
  14877.       return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14878.     };
  14879.  
  14880.     var createRange = function (sc, so, ec, eo) {
  14881.       var rng = document.createRange();
  14882.       rng.setStart(sc, so);
  14883.       rng.setEnd(ec, eo);
  14884.       return rng;
  14885.     };
  14886.     var normalizeBlockSelectionRange = function (rng) {
  14887.       var startPos = CaretPosition.fromRangeStart(rng);
  14888.       var endPos = CaretPosition.fromRangeEnd(rng);
  14889.       var rootNode = rng.commonAncestorContainer;
  14890.       return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14891.         if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14892.           return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14893.         } else {
  14894.           return rng;
  14895.         }
  14896.       }).getOr(rng);
  14897.     };
  14898.     var normalize = function (rng) {
  14899.       return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14900.     };
  14901.  
  14902.     var hasOnlyOneChild$1 = function (node) {
  14903.       return node.firstChild && node.firstChild === node.lastChild;
  14904.     };
  14905.     var isPaddingNode = function (node) {
  14906.       return node.name === 'br' || node.value === nbsp;
  14907.     };
  14908.     var isPaddedEmptyBlock = function (schema, node) {
  14909.       var blockElements = schema.getBlockElements();
  14910.       return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14911.     };
  14912.     var isEmptyFragmentElement = function (schema, node) {
  14913.       var nonEmptyElements = schema.getNonEmptyElements();
  14914.       return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14915.     };
  14916.     var isListFragment = function (schema, fragment) {
  14917.       var firstChild = fragment.firstChild;
  14918.       var lastChild = fragment.lastChild;
  14919.       if (firstChild && firstChild.name === 'meta') {
  14920.         firstChild = firstChild.next;
  14921.       }
  14922.       if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14923.         lastChild = lastChild.prev;
  14924.       }
  14925.       if (isEmptyFragmentElement(schema, lastChild)) {
  14926.         lastChild = lastChild.prev;
  14927.       }
  14928.       if (!firstChild || firstChild !== lastChild) {
  14929.         return false;
  14930.       }
  14931.       return firstChild.name === 'ul' || firstChild.name === 'ol';
  14932.     };
  14933.     var cleanupDomFragment = function (domFragment) {
  14934.       var firstChild = domFragment.firstChild;
  14935.       var lastChild = domFragment.lastChild;
  14936.       if (firstChild && firstChild.nodeName === 'META') {
  14937.         firstChild.parentNode.removeChild(firstChild);
  14938.       }
  14939.       if (lastChild && lastChild.id === 'mce_marker') {
  14940.         lastChild.parentNode.removeChild(lastChild);
  14941.       }
  14942.       return domFragment;
  14943.     };
  14944.     var toDomFragment = function (dom, serializer, fragment) {
  14945.       var html = serializer.serialize(fragment);
  14946.       var domFragment = dom.createFragment(html);
  14947.       return cleanupDomFragment(domFragment);
  14948.     };
  14949.     var listItems = function (elm) {
  14950.       return filter$4(elm.childNodes, function (child) {
  14951.         return child.nodeName === 'LI';
  14952.       });
  14953.     };
  14954.     var isPadding = function (node) {
  14955.       return node.data === nbsp || isBr$5(node);
  14956.     };
  14957.     var isListItemPadded = function (node) {
  14958.       return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14959.     };
  14960.     var isEmptyOrPadded = function (elm) {
  14961.       return !elm.firstChild || isListItemPadded(elm);
  14962.     };
  14963.     var trimListItems = function (elms) {
  14964.       return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14965.     };
  14966.     var getParentLi = function (dom, node) {
  14967.       var parentBlock = dom.getParent(node, dom.isBlock);
  14968.       return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14969.     };
  14970.     var isParentBlockLi = function (dom, node) {
  14971.       return !!getParentLi(dom, node);
  14972.     };
  14973.     var getSplit = function (parentNode, rng) {
  14974.       var beforeRng = rng.cloneRange();
  14975.       var afterRng = rng.cloneRange();
  14976.       beforeRng.setStartBefore(parentNode);
  14977.       afterRng.setEndAfter(parentNode);
  14978.       return [
  14979.         beforeRng.cloneContents(),
  14980.         afterRng.cloneContents()
  14981.       ];
  14982.     };
  14983.     var findFirstIn = function (node, rootNode) {
  14984.       var caretPos = CaretPosition.before(node);
  14985.       var caretWalker = CaretWalker(rootNode);
  14986.       var newCaretPos = caretWalker.next(caretPos);
  14987.       return newCaretPos ? newCaretPos.toRange() : null;
  14988.     };
  14989.     var findLastOf = function (node, rootNode) {
  14990.       var caretPos = CaretPosition.after(node);
  14991.       var caretWalker = CaretWalker(rootNode);
  14992.       var newCaretPos = caretWalker.prev(caretPos);
  14993.       return newCaretPos ? newCaretPos.toRange() : null;
  14994.     };
  14995.     var insertMiddle = function (target, elms, rootNode, rng) {
  14996.       var parts = getSplit(target, rng);
  14997.       var parentElm = target.parentNode;
  14998.       parentElm.insertBefore(parts[0], target);
  14999.       Tools.each(elms, function (li) {
  15000.         parentElm.insertBefore(li, target);
  15001.       });
  15002.       parentElm.insertBefore(parts[1], target);
  15003.       parentElm.removeChild(target);
  15004.       return findLastOf(elms[elms.length - 1], rootNode);
  15005.     };
  15006.     var insertBefore$1 = function (target, elms, rootNode) {
  15007.       var parentElm = target.parentNode;
  15008.       Tools.each(elms, function (elm) {
  15009.         parentElm.insertBefore(elm, target);
  15010.       });
  15011.       return findFirstIn(target, rootNode);
  15012.     };
  15013.     var insertAfter$1 = function (target, elms, rootNode, dom) {
  15014.       dom.insertAfter(elms.reverse(), target);
  15015.       return findLastOf(elms[0], rootNode);
  15016.     };
  15017.     var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  15018.       var domFragment = toDomFragment(dom, serializer, fragment);
  15019.       var liTarget = getParentLi(dom, rng.startContainer);
  15020.       var liElms = trimListItems(listItems(domFragment.firstChild));
  15021.       var BEGINNING = 1, END = 2;
  15022.       var rootNode = dom.getRoot();
  15023.       var isAt = function (location) {
  15024.         var caretPos = CaretPosition.fromRangeStart(rng);
  15025.         var caretWalker = CaretWalker(dom.getRoot());
  15026.         var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  15027.         return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  15028.       };
  15029.       if (isAt(BEGINNING)) {
  15030.         return insertBefore$1(liTarget, liElms, rootNode);
  15031.       } else if (isAt(END)) {
  15032.         return insertAfter$1(liTarget, liElms, rootNode, dom);
  15033.       }
  15034.       return insertMiddle(liTarget, liElms, rootNode, rng);
  15035.     };
  15036.  
  15037.     var trimOrPadLeftRight = function (dom, rng, html) {
  15038.       var root = SugarElement.fromDom(dom.getRoot());
  15039.       if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  15040.         html = html.replace(/^ /, '&nbsp;');
  15041.       } else {
  15042.         html = html.replace(/^&nbsp;/, ' ');
  15043.       }
  15044.       if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  15045.         html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  15046.       } else {
  15047.         html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  15048.       }
  15049.       return html;
  15050.     };
  15051.  
  15052.     var isTableCell$1 = isTableCell$5;
  15053.     var isTableCellContentSelected = function (dom, rng, cell) {
  15054.       if (cell !== null) {
  15055.         var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  15056.         return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  15057.       } else {
  15058.         return false;
  15059.       }
  15060.     };
  15061.     var validInsertion = function (editor, value, parentNode) {
  15062.       if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  15063.         parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  15064.       } else {
  15065.         var node = parentNode.firstChild;
  15066.         var node2 = parentNode.lastChild;
  15067.         if (!node || node === node2 && node.nodeName === 'BR') {
  15068.           editor.dom.setHTML(parentNode, value);
  15069.         } else {
  15070.           editor.selection.setContent(value);
  15071.         }
  15072.       }
  15073.     };
  15074.     var trimBrsFromTableCell = function (dom, elm) {
  15075.       Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  15076.     };
  15077.     var reduceInlineTextElements = function (editor, merge) {
  15078.       var textInlineElements = editor.schema.getTextInlineElements();
  15079.       var dom = editor.dom;
  15080.       if (merge) {
  15081.         var root_1 = editor.getBody();
  15082.         var elementUtils_1 = ElementUtils(dom);
  15083.         Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  15084.           var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  15085.           if (isInline && hasInheritableStyles(dom, node)) {
  15086.             for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  15087.               var styleConflict = hasStyleConflict(dom, node, parentNode);
  15088.               if (styleConflict) {
  15089.                 break;
  15090.               }
  15091.               if (elementUtils_1.compare(parentNode, node)) {
  15092.                 dom.remove(node, true);
  15093.                 break;
  15094.               }
  15095.             }
  15096.           }
  15097.         });
  15098.       }
  15099.     };
  15100.     var markFragmentElements = function (fragment) {
  15101.       var node = fragment;
  15102.       while (node = node.walk()) {
  15103.         if (node.type === 1) {
  15104.           node.attr('data-mce-fragment', '1');
  15105.         }
  15106.       }
  15107.     };
  15108.     var unmarkFragmentElements = function (elm) {
  15109.       Tools.each(elm.getElementsByTagName('*'), function (elm) {
  15110.         elm.removeAttribute('data-mce-fragment');
  15111.       });
  15112.     };
  15113.     var isPartOfFragment = function (node) {
  15114.       return !!node.getAttribute('data-mce-fragment');
  15115.     };
  15116.     var canHaveChildren = function (editor, node) {
  15117.       return node && !editor.schema.getShortEndedElements()[node.nodeName];
  15118.     };
  15119.     var moveSelectionToMarker = function (editor, marker) {
  15120.       var nextRng;
  15121.       var dom = editor.dom;
  15122.       var selection = editor.selection;
  15123.       if (!marker) {
  15124.         return;
  15125.       }
  15126.       selection.scrollIntoView(marker);
  15127.       var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  15128.       if (dom.getContentEditable(parentEditableElm) === 'false') {
  15129.         dom.remove(marker);
  15130.         selection.select(parentEditableElm);
  15131.         return;
  15132.       }
  15133.       var rng = dom.createRng();
  15134.       var node = marker.previousSibling;
  15135.       if (isText$7(node)) {
  15136.         rng.setStart(node, node.nodeValue.length);
  15137.         if (!Env.ie) {
  15138.           var node2 = marker.nextSibling;
  15139.           if (isText$7(node2)) {
  15140.             node.appendData(node2.data);
  15141.             node2.parentNode.removeChild(node2);
  15142.           }
  15143.         }
  15144.       } else {
  15145.         rng.setStartBefore(marker);
  15146.         rng.setEndBefore(marker);
  15147.       }
  15148.       var findNextCaretRng = function (rng) {
  15149.         var caretPos = CaretPosition.fromRangeStart(rng);
  15150.         var caretWalker = CaretWalker(editor.getBody());
  15151.         caretPos = caretWalker.next(caretPos);
  15152.         if (caretPos) {
  15153.           return caretPos.toRange();
  15154.         }
  15155.       };
  15156.       var parentBlock = dom.getParent(marker, dom.isBlock);
  15157.       dom.remove(marker);
  15158.       if (parentBlock && dom.isEmpty(parentBlock)) {
  15159.         editor.$(parentBlock).empty();
  15160.         rng.setStart(parentBlock, 0);
  15161.         rng.setEnd(parentBlock, 0);
  15162.         if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  15163.           rng = nextRng;
  15164.           dom.remove(parentBlock);
  15165.         } else {
  15166.           dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  15167.         }
  15168.       }
  15169.       selection.setRng(rng);
  15170.     };
  15171.     var deleteSelectedContent = function (editor) {
  15172.       var dom = editor.dom;
  15173.       var rng = normalize(editor.selection.getRng());
  15174.       editor.selection.setRng(rng);
  15175.       var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  15176.       if (isTableCellContentSelected(dom, rng, startCell)) {
  15177.         deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  15178.       } else {
  15179.         editor.getDoc().execCommand('Delete', false, null);
  15180.       }
  15181.     };
  15182.     var insertHtmlAtCaret = function (editor, value, details) {
  15183.       var parentNode;
  15184.       var rng, node;
  15185.       var selection = editor.selection;
  15186.       var dom = editor.dom;
  15187.       if (/^ | $/.test(value)) {
  15188.         value = trimOrPadLeftRight(dom, selection.getRng(), value);
  15189.       }
  15190.       var parser = editor.parser;
  15191.       var merge = details.merge;
  15192.       var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  15193.       var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  15194.       var args = editor.fire('BeforeSetContent', {
  15195.         content: value,
  15196.         format: 'html',
  15197.         selection: true,
  15198.         paste: details.paste
  15199.       });
  15200.       if (args.isDefaultPrevented()) {
  15201.         editor.fire('SetContent', {
  15202.           content: args.content,
  15203.           format: 'html',
  15204.           selection: true,
  15205.           paste: details.paste
  15206.         });
  15207.         return;
  15208.       }
  15209.       value = args.content;
  15210.       if (value.indexOf('{$caret}') === -1) {
  15211.         value += '{$caret}';
  15212.       }
  15213.       value = value.replace(/\{\$caret\}/, bookmarkHtml);
  15214.       rng = selection.getRng();
  15215.       var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  15216.       var body = editor.getBody();
  15217.       if (caretElement === body && selection.isCollapsed()) {
  15218.         if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  15219.           rng = dom.createRng();
  15220.           rng.setStart(body.firstChild, 0);
  15221.           rng.setEnd(body.firstChild, 0);
  15222.           selection.setRng(rng);
  15223.         }
  15224.       }
  15225.       if (!selection.isCollapsed()) {
  15226.         deleteSelectedContent(editor);
  15227.       }
  15228.       parentNode = selection.getNode();
  15229.       var parserArgs = {
  15230.         context: parentNode.nodeName.toLowerCase(),
  15231.         data: details.data,
  15232.         insert: true
  15233.       };
  15234.       var fragment = parser.parse(value, parserArgs);
  15235.       if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  15236.         rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  15237.         selection.setRng(rng);
  15238.         editor.fire('SetContent', args);
  15239.         return;
  15240.       }
  15241.       markFragmentElements(fragment);
  15242.       node = fragment.lastChild;
  15243.       if (node.attr('id') === 'mce_marker') {
  15244.         var marker = node;
  15245.         for (node = node.prev; node; node = node.walk(true)) {
  15246.           if (node.type === 3 || !dom.isBlock(node.name)) {
  15247.             if (editor.schema.isValidChild(node.parent.name, 'span')) {
  15248.               node.parent.insert(marker, node, node.name === 'br');
  15249.             }
  15250.             break;
  15251.           }
  15252.         }
  15253.       }
  15254.       editor._selectionOverrides.showBlockCaretContainer(parentNode);
  15255.       if (!parserArgs.invalid) {
  15256.         value = serializer.serialize(fragment);
  15257.         validInsertion(editor, value, parentNode);
  15258.       } else {
  15259.         editor.selection.setContent(bookmarkHtml);
  15260.         parentNode = selection.getNode();
  15261.         var rootNode = editor.getBody();
  15262.         if (parentNode.nodeType === 9) {
  15263.           parentNode = node = rootNode;
  15264.         } else {
  15265.           node = parentNode;
  15266.         }
  15267.         while (node !== rootNode) {
  15268.           parentNode = node;
  15269.           node = node.parentNode;
  15270.         }
  15271.         value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  15272.         value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  15273.           return serializer.serialize(fragment);
  15274.         })));
  15275.         if (parentNode === rootNode) {
  15276.           dom.setHTML(rootNode, value);
  15277.         } else {
  15278.           dom.setOuterHTML(parentNode, value);
  15279.         }
  15280.       }
  15281.       reduceInlineTextElements(editor, merge);
  15282.       moveSelectionToMarker(editor, dom.get('mce_marker'));
  15283.       unmarkFragmentElements(editor.getBody());
  15284.       trimBrsFromTableCell(dom, selection.getStart());
  15285.       editor.fire('SetContent', args);
  15286.       editor.addVisual();
  15287.     };
  15288.  
  15289.     var traverse = function (node, fn) {
  15290.       fn(node);
  15291.       if (node.firstChild) {
  15292.         traverse(node.firstChild, fn);
  15293.       }
  15294.       if (node.next) {
  15295.         traverse(node.next, fn);
  15296.       }
  15297.     };
  15298.     var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  15299.       var nodeMatches = {};
  15300.       var attrMatches = {};
  15301.       var matches = [];
  15302.       if (node.firstChild) {
  15303.         traverse(node.firstChild, function (node) {
  15304.           each$k(nodeFilters, function (filter) {
  15305.             if (filter.name === node.name) {
  15306.               if (nodeMatches[filter.name]) {
  15307.                 nodeMatches[filter.name].nodes.push(node);
  15308.               } else {
  15309.                 nodeMatches[filter.name] = {
  15310.                   filter: filter,
  15311.                   nodes: [node]
  15312.                 };
  15313.               }
  15314.             }
  15315.           });
  15316.           each$k(attributeFilters, function (filter) {
  15317.             if (typeof node.attr(filter.name) === 'string') {
  15318.               if (attrMatches[filter.name]) {
  15319.                 attrMatches[filter.name].nodes.push(node);
  15320.               } else {
  15321.                 attrMatches[filter.name] = {
  15322.                   filter: filter,
  15323.                   nodes: [node]
  15324.                 };
  15325.               }
  15326.             }
  15327.           });
  15328.         });
  15329.       }
  15330.       for (var name_1 in nodeMatches) {
  15331.         if (has$2(nodeMatches, name_1)) {
  15332.           matches.push(nodeMatches[name_1]);
  15333.         }
  15334.       }
  15335.       for (var name_2 in attrMatches) {
  15336.         if (has$2(attrMatches, name_2)) {
  15337.           matches.push(attrMatches[name_2]);
  15338.         }
  15339.       }
  15340.       return matches;
  15341.     };
  15342.     var filter$1 = function (nodeFilters, attributeFilters, node) {
  15343.       var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  15344.       each$k(matches, function (match) {
  15345.         each$k(match.filter.callbacks, function (callback) {
  15346.           callback(match.nodes, match.filter.name, {});
  15347.         });
  15348.       });
  15349.     };
  15350.  
  15351.     var defaultFormat$1 = 'html';
  15352.     var isTreeNode = function (content) {
  15353.       return content instanceof AstNode;
  15354.     };
  15355.     var moveSelection = function (editor) {
  15356.       if (hasFocus(editor)) {
  15357.         firstPositionIn(editor.getBody()).each(function (pos) {
  15358.           var node = pos.getNode();
  15359.           var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  15360.           editor.selection.setRng(caretPos.toRange());
  15361.         });
  15362.       }
  15363.     };
  15364.     var setEditorHtml = function (editor, html, noSelection) {
  15365.       editor.dom.setHTML(editor.getBody(), html);
  15366.       if (noSelection !== true) {
  15367.         moveSelection(editor);
  15368.       }
  15369.     };
  15370.     var setContentString = function (editor, body, content, args) {
  15371.       if (content.length === 0 || /^\s+$/.test(content)) {
  15372.         var padd = '<br data-mce-bogus="1">';
  15373.         if (body.nodeName === 'TABLE') {
  15374.           content = '<tr><td>' + padd + '</td></tr>';
  15375.         } else if (/^(UL|OL)$/.test(body.nodeName)) {
  15376.           content = '<li>' + padd + '</li>';
  15377.         }
  15378.         var forcedRootBlockName = getForcedRootBlock(editor);
  15379.         if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  15380.           content = padd;
  15381.           content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  15382.         } else if (!content) {
  15383.           content = '<br data-mce-bogus="1">';
  15384.         }
  15385.         setEditorHtml(editor, content, args.no_selection);
  15386.         editor.fire('SetContent', args);
  15387.       } else {
  15388.         if (args.format !== 'raw') {
  15389.           content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  15390.             isRootContent: true,
  15391.             insert: true
  15392.           }));
  15393.         }
  15394.         args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  15395.         setEditorHtml(editor, args.content, args.no_selection);
  15396.         if (!args.no_events) {
  15397.           editor.fire('SetContent', args);
  15398.         }
  15399.       }
  15400.       return args.content;
  15401.     };
  15402.     var setContentTree = function (editor, body, content, args) {
  15403.       filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  15404.       var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  15405.       args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  15406.       setEditorHtml(editor, args.content, args.no_selection);
  15407.       if (!args.no_events) {
  15408.         editor.fire('SetContent', args);
  15409.       }
  15410.       return content;
  15411.     };
  15412.     var setupArgs$2 = function (args, content) {
  15413.       return __assign(__assign({ format: defaultFormat$1 }, args), {
  15414.         set: true,
  15415.         content: isTreeNode(content) ? '' : content
  15416.       });
  15417.     };
  15418.     var setContentInternal = function (editor, content, args) {
  15419.       var defaultedArgs = setupArgs$2(args, content);
  15420.       var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeSetContent', defaultedArgs);
  15421.       if (!isTreeNode(content)) {
  15422.         content = updatedArgs.content;
  15423.       }
  15424.       return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  15425.         return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  15426.       });
  15427.     };
  15428.  
  15429.     var sibling = function (scope, predicate) {
  15430.       return sibling$2(scope, predicate).isSome();
  15431.     };
  15432.  
  15433.     var ensureIsRoot = function (isRoot) {
  15434.       return isFunction(isRoot) ? isRoot : never;
  15435.     };
  15436.     var ancestor = function (scope, transform, isRoot) {
  15437.       var element = scope.dom;
  15438.       var stop = ensureIsRoot(isRoot);
  15439.       while (element.parentNode) {
  15440.         element = element.parentNode;
  15441.         var el = SugarElement.fromDom(element);
  15442.         var transformed = transform(el);
  15443.         if (transformed.isSome()) {
  15444.           return transformed;
  15445.         } else if (stop(el)) {
  15446.           break;
  15447.         }
  15448.       }
  15449.       return Optional.none();
  15450.     };
  15451.     var closest$1 = function (scope, transform, isRoot) {
  15452.       var current = transform(scope);
  15453.       var stop = ensureIsRoot(isRoot);
  15454.       return current.orThunk(function () {
  15455.         return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  15456.       });
  15457.     };
  15458.  
  15459.     var isEq$3 = isEq$5;
  15460.     var matchesUnInheritedFormatSelector = function (ed, node, name) {
  15461.       var formatList = ed.formatter.get(name);
  15462.       if (formatList) {
  15463.         for (var i = 0; i < formatList.length; i++) {
  15464.           var format = formatList[i];
  15465.           if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  15466.             return true;
  15467.           }
  15468.         }
  15469.       }
  15470.       return false;
  15471.     };
  15472.     var matchParents = function (editor, node, name, vars, similar) {
  15473.       var root = editor.dom.getRoot();
  15474.       if (node === root) {
  15475.         return false;
  15476.       }
  15477.       node = editor.dom.getParent(node, function (node) {
  15478.         if (matchesUnInheritedFormatSelector(editor, node, name)) {
  15479.           return true;
  15480.         }
  15481.         return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  15482.       });
  15483.       return !!matchNode(editor, node, name, vars, similar);
  15484.     };
  15485.     var matchName$1 = function (dom, node, format) {
  15486.       if (isEq$3(node, format.inline)) {
  15487.         return true;
  15488.       }
  15489.       if (isEq$3(node, format.block)) {
  15490.         return true;
  15491.       }
  15492.       if (format.selector) {
  15493.         return node.nodeType === 1 && dom.is(node, format.selector);
  15494.       }
  15495.     };
  15496.     var matchItems = function (dom, node, format, itemName, similar, vars) {
  15497.       var items = format[itemName];
  15498.       if (isFunction(format.onmatch)) {
  15499.         return format.onmatch(node, format, itemName);
  15500.       }
  15501.       if (items) {
  15502.         if (isUndefined(items.length)) {
  15503.           for (var key in items) {
  15504.             if (has$2(items, key)) {
  15505.               var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  15506.               var expectedValue = replaceVars(items[key], vars);
  15507.               var isEmptyValue = isNullable(value) || isEmpty$3(value);
  15508.               if (isEmptyValue && isNullable(expectedValue)) {
  15509.                 continue;
  15510.               }
  15511.               if (similar && isEmptyValue && !format.exact) {
  15512.                 return false;
  15513.               }
  15514.               if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  15515.                 return false;
  15516.               }
  15517.             }
  15518.           }
  15519.         } else {
  15520.           for (var i = 0; i < items.length; i++) {
  15521.             if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  15522.               return true;
  15523.             }
  15524.           }
  15525.         }
  15526.       }
  15527.       return true;
  15528.     };
  15529.     var matchNode = function (ed, node, name, vars, similar) {
  15530.       var formatList = ed.formatter.get(name);
  15531.       var dom = ed.dom;
  15532.       if (formatList && node) {
  15533.         for (var i = 0; i < formatList.length; i++) {
  15534.           var format = formatList[i];
  15535.           if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  15536.             var classes = format.classes;
  15537.             if (classes) {
  15538.               for (var x = 0; x < classes.length; x++) {
  15539.                 if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  15540.                   return;
  15541.                 }
  15542.               }
  15543.             }
  15544.             return format;
  15545.           }
  15546.         }
  15547.       }
  15548.     };
  15549.     var match$2 = function (editor, name, vars, node, similar) {
  15550.       if (node) {
  15551.         return matchParents(editor, node, name, vars, similar);
  15552.       }
  15553.       node = editor.selection.getNode();
  15554.       if (matchParents(editor, node, name, vars, similar)) {
  15555.         return true;
  15556.       }
  15557.       var startNode = editor.selection.getStart();
  15558.       if (startNode !== node) {
  15559.         if (matchParents(editor, startNode, name, vars, similar)) {
  15560.           return true;
  15561.         }
  15562.       }
  15563.       return false;
  15564.     };
  15565.     var matchAll = function (editor, names, vars) {
  15566.       var matchedFormatNames = [];
  15567.       var checkedMap = {};
  15568.       var startElement = editor.selection.getStart();
  15569.       editor.dom.getParent(startElement, function (node) {
  15570.         for (var i = 0; i < names.length; i++) {
  15571.           var name_1 = names[i];
  15572.           if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  15573.             checkedMap[name_1] = true;
  15574.             matchedFormatNames.push(name_1);
  15575.           }
  15576.         }
  15577.       }, editor.dom.getRoot());
  15578.       return matchedFormatNames;
  15579.     };
  15580.     var closest = function (editor, names) {
  15581.       var isRoot = function (elm) {
  15582.         return eq(elm, SugarElement.fromDom(editor.getBody()));
  15583.       };
  15584.       var match = function (elm, name) {
  15585.         return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  15586.       };
  15587.       return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  15588.         return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  15589.           return findMap(names, function (name) {
  15590.             return match(elm, name);
  15591.           });
  15592.         }, isRoot);
  15593.       }).getOrNull();
  15594.     };
  15595.     var canApply = function (editor, name) {
  15596.       var formatList = editor.formatter.get(name);
  15597.       var dom = editor.dom;
  15598.       if (formatList) {
  15599.         var startNode = editor.selection.getStart();
  15600.         var parents = getParents$2(dom, startNode);
  15601.         for (var x = formatList.length - 1; x >= 0; x--) {
  15602.           var format = formatList[x];
  15603.           if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  15604.             return true;
  15605.           }
  15606.           for (var i = parents.length - 1; i >= 0; i--) {
  15607.             if (dom.is(parents[i], format.selector)) {
  15608.               return true;
  15609.             }
  15610.           }
  15611.         }
  15612.       }
  15613.       return false;
  15614.     };
  15615.     var matchAllOnNode = function (editor, node, formatNames) {
  15616.       return foldl(formatNames, function (acc, name) {
  15617.         var matchSimilar = isVariableFormatName(editor, name);
  15618.         if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  15619.           return acc.concat([name]);
  15620.         } else {
  15621.           return acc;
  15622.         }
  15623.       }, []);
  15624.     };
  15625.  
  15626.     var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  15627.     var importNode = function (ownerDocument, node) {
  15628.       return ownerDocument.importNode(node, true);
  15629.     };
  15630.     var getEmptyCaretContainers = function (node) {
  15631.       var nodes = [];
  15632.       while (node) {
  15633.         if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  15634.           return [];
  15635.         }
  15636.         if (node.nodeType === 1) {
  15637.           nodes.push(node);
  15638.         }
  15639.         node = node.firstChild;
  15640.       }
  15641.       return nodes;
  15642.     };
  15643.     var isCaretContainerEmpty = function (node) {
  15644.       return getEmptyCaretContainers(node).length > 0;
  15645.     };
  15646.     var findFirstTextNode = function (node) {
  15647.       if (node) {
  15648.         var walker = new DomTreeWalker(node, node);
  15649.         for (node = walker.current(); node; node = walker.next()) {
  15650.           if (isText$7(node)) {
  15651.             return node;
  15652.           }
  15653.         }
  15654.       }
  15655.       return null;
  15656.     };
  15657.     var createCaretContainer = function (fill) {
  15658.       var caretContainer = SugarElement.fromTag('span');
  15659.       setAll$1(caretContainer, {
  15660.         'id': CARET_ID,
  15661.         'data-mce-bogus': '1',
  15662.         'data-mce-type': 'format-caret'
  15663.       });
  15664.       if (fill) {
  15665.         append$1(caretContainer, SugarElement.fromText(ZWSP));
  15666.       }
  15667.       return caretContainer;
  15668.     };
  15669.     var trimZwspFromCaretContainer = function (caretContainerNode) {
  15670.       var textNode = findFirstTextNode(caretContainerNode);
  15671.       if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  15672.         textNode.deleteData(0, 1);
  15673.       }
  15674.       return textNode;
  15675.     };
  15676.     var removeCaretContainerNode = function (editor, node, moveCaret) {
  15677.       if (moveCaret === void 0) {
  15678.         moveCaret = true;
  15679.       }
  15680.       var dom = editor.dom, selection = editor.selection;
  15681.       if (isCaretContainerEmpty(node)) {
  15682.         deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  15683.       } else {
  15684.         var rng = selection.getRng();
  15685.         var block = dom.getParent(node, dom.isBlock);
  15686.         var startContainer = rng.startContainer;
  15687.         var startOffset = rng.startOffset;
  15688.         var endContainer = rng.endContainer;
  15689.         var endOffset = rng.endOffset;
  15690.         var textNode = trimZwspFromCaretContainer(node);
  15691.         dom.remove(node, true);
  15692.         if (startContainer === textNode && startOffset > 0) {
  15693.           rng.setStart(textNode, startOffset - 1);
  15694.         }
  15695.         if (endContainer === textNode && endOffset > 0) {
  15696.           rng.setEnd(textNode, endOffset - 1);
  15697.         }
  15698.         if (block && dom.isEmpty(block)) {
  15699.           fillWithPaddingBr(SugarElement.fromDom(block));
  15700.         }
  15701.         selection.setRng(rng);
  15702.       }
  15703.     };
  15704.     var removeCaretContainer = function (editor, node, moveCaret) {
  15705.       if (moveCaret === void 0) {
  15706.         moveCaret = true;
  15707.       }
  15708.       var dom = editor.dom, selection = editor.selection;
  15709.       if (!node) {
  15710.         node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15711.         if (!node) {
  15712.           while (node = dom.get(CARET_ID)) {
  15713.             removeCaretContainerNode(editor, node, false);
  15714.           }
  15715.         }
  15716.       } else {
  15717.         removeCaretContainerNode(editor, node, moveCaret);
  15718.       }
  15719.     };
  15720.     var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15721.       var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15722.       if (block && dom.isEmpty(block)) {
  15723.         formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15724.       } else {
  15725.         removeTrailingBr(SugarElement.fromDom(formatNode));
  15726.         if (dom.isEmpty(formatNode)) {
  15727.           formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15728.         } else {
  15729.           dom.insertAfter(caretContainer, formatNode);
  15730.         }
  15731.       }
  15732.     };
  15733.     var appendNode = function (parentNode, node) {
  15734.       parentNode.appendChild(node);
  15735.       return node;
  15736.     };
  15737.     var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15738.       var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15739.         return appendNode(parentNode, formatNode.cloneNode(false));
  15740.       }, caretContainer);
  15741.       return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15742.     };
  15743.     var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15744.       var formatter = editor.formatter;
  15745.       var dom = editor.dom;
  15746.       var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15747.         return formatName !== name && !contains$2(formatName, 'removeformat');
  15748.       });
  15749.       var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15750.       var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15751.         return !areSimilarFormats(editor, fmtName, name);
  15752.       });
  15753.       if (uniqueFormats.length > 0) {
  15754.         var clonedFormatNode = formatNode.cloneNode(false);
  15755.         dom.add(caretContainer, clonedFormatNode);
  15756.         formatter.remove(name, vars, clonedFormatNode, similar);
  15757.         dom.remove(clonedFormatNode);
  15758.         return Optional.some(clonedFormatNode);
  15759.       } else {
  15760.         return Optional.none();
  15761.       }
  15762.     };
  15763.     var applyCaretFormat = function (editor, name, vars) {
  15764.       var caretContainer, textNode;
  15765.       var selection = editor.selection;
  15766.       var selectionRng = selection.getRng();
  15767.       var offset = selectionRng.startOffset;
  15768.       var container = selectionRng.startContainer;
  15769.       var text = container.nodeValue;
  15770.       caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15771.       if (caretContainer) {
  15772.         textNode = findFirstTextNode(caretContainer);
  15773.       }
  15774.       var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15775.       if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15776.         var bookmark = selection.getBookmark();
  15777.         selectionRng.collapse(true);
  15778.         var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15779.         rng = split(rng);
  15780.         editor.formatter.apply(name, vars, rng);
  15781.         selection.moveToBookmark(bookmark);
  15782.       } else {
  15783.         if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15784.           caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15785.           textNode = caretContainer.firstChild;
  15786.           selectionRng.insertNode(caretContainer);
  15787.           offset = 1;
  15788.           editor.formatter.apply(name, vars, caretContainer);
  15789.         } else {
  15790.           editor.formatter.apply(name, vars, caretContainer);
  15791.         }
  15792.         selection.setCursorLocation(textNode, offset);
  15793.       }
  15794.     };
  15795.     var removeCaretFormat = function (editor, name, vars, similar) {
  15796.       var dom = editor.dom;
  15797.       var selection = editor.selection;
  15798.       var hasContentAfter, node, formatNode;
  15799.       var parents = [];
  15800.       var rng = selection.getRng();
  15801.       var container = rng.startContainer;
  15802.       var offset = rng.startOffset;
  15803.       node = container;
  15804.       if (container.nodeType === 3) {
  15805.         if (offset !== container.nodeValue.length) {
  15806.           hasContentAfter = true;
  15807.         }
  15808.         node = node.parentNode;
  15809.       }
  15810.       while (node) {
  15811.         if (matchNode(editor, node, name, vars, similar)) {
  15812.           formatNode = node;
  15813.           break;
  15814.         }
  15815.         if (node.nextSibling) {
  15816.           hasContentAfter = true;
  15817.         }
  15818.         parents.push(node);
  15819.         node = node.parentNode;
  15820.       }
  15821.       if (!formatNode) {
  15822.         return;
  15823.       }
  15824.       if (hasContentAfter) {
  15825.         var bookmark = selection.getBookmark();
  15826.         rng.collapse(true);
  15827.         var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15828.         expandedRng = split(expandedRng);
  15829.         editor.formatter.remove(name, vars, expandedRng, similar);
  15830.         selection.moveToBookmark(bookmark);
  15831.       } else {
  15832.         var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15833.         var newCaretContainer = createCaretContainer(false).dom;
  15834.         insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15835.         var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15836.         var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15837.         removeCaretContainerNode(editor, caretContainer, false);
  15838.         selection.setCursorLocation(caretTextNode, 1);
  15839.         if (dom.isEmpty(formatNode)) {
  15840.           dom.remove(formatNode);
  15841.         }
  15842.       }
  15843.     };
  15844.     var disableCaretContainer = function (editor, keyCode) {
  15845.       var selection = editor.selection, body = editor.getBody();
  15846.       removeCaretContainer(editor, null, false);
  15847.       if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15848.         removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15849.       }
  15850.       if (keyCode === 37 || keyCode === 39) {
  15851.         removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15852.       }
  15853.     };
  15854.     var setup$k = function (editor) {
  15855.       editor.on('mouseup keydown', function (e) {
  15856.         disableCaretContainer(editor, e.keyCode);
  15857.       });
  15858.     };
  15859.     var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15860.       var caretContainer = createCaretContainer(false);
  15861.       var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15862.       before$4(SugarElement.fromDom(targetNode), caretContainer);
  15863.       remove$7(SugarElement.fromDom(targetNode));
  15864.       return CaretPosition(innerMost, 0);
  15865.     };
  15866.     var isFormatElement = function (editor, element) {
  15867.       var inlineElements = editor.schema.getTextInlineElements();
  15868.       return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15869.     };
  15870.     var isEmptyCaretFormatElement = function (element) {
  15871.       return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15872.     };
  15873.  
  15874.     var postProcessHooks = {};
  15875.     var filter = filter$2;
  15876.     var each$b = each$i;
  15877.     var addPostProcessHook = function (name, hook) {
  15878.       var hooks = postProcessHooks[name];
  15879.       if (!hooks) {
  15880.         postProcessHooks[name] = [];
  15881.       }
  15882.       postProcessHooks[name].push(hook);
  15883.     };
  15884.     var postProcess$1 = function (name, editor) {
  15885.       each$b(postProcessHooks[name], function (hook) {
  15886.         hook(editor);
  15887.       });
  15888.     };
  15889.     addPostProcessHook('pre', function (editor) {
  15890.       var rng = editor.selection.getRng();
  15891.       var blocks;
  15892.       var hasPreSibling = function (pre) {
  15893.         return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15894.       };
  15895.       var joinPre = function (pre1, pre2) {
  15896.         DomQuery(pre2).remove();
  15897.         DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15898.       };
  15899.       var isPre = matchNodeNames(['pre']);
  15900.       if (!rng.collapsed) {
  15901.         blocks = editor.selection.getSelectedBlocks();
  15902.         each$b(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15903.           joinPre(pre.previousSibling, pre);
  15904.         });
  15905.       }
  15906.     });
  15907.  
  15908.     var each$a = Tools.each;
  15909.     var isElementNode$1 = function (node) {
  15910.       return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15911.     };
  15912.     var findElementSibling = function (node, siblingName) {
  15913.       for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15914.         if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15915.           return node;
  15916.         }
  15917.         if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15918.           return sibling;
  15919.         }
  15920.       }
  15921.       return node;
  15922.     };
  15923.     var mergeSiblingsNodes = function (dom, prev, next) {
  15924.       var elementUtils = ElementUtils(dom);
  15925.       if (prev && next) {
  15926.         prev = findElementSibling(prev, 'previousSibling');
  15927.         next = findElementSibling(next, 'nextSibling');
  15928.         if (elementUtils.compare(prev, next)) {
  15929.           for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15930.             var tmpSibling = sibling;
  15931.             sibling = sibling.nextSibling;
  15932.             prev.appendChild(tmpSibling);
  15933.           }
  15934.           dom.remove(next);
  15935.           Tools.each(Tools.grep(next.childNodes), function (node) {
  15936.             prev.appendChild(node);
  15937.           });
  15938.           return prev;
  15939.         }
  15940.       }
  15941.       return next;
  15942.     };
  15943.     var mergeSiblings = function (dom, format, vars, node) {
  15944.       if (node && format.merge_siblings !== false) {
  15945.         var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15946.         mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15947.       }
  15948.     };
  15949.     var clearChildStyles = function (dom, format, node) {
  15950.       if (format.clear_child_styles) {
  15951.         var selector = format.links ? '*:not(a)' : '*';
  15952.         each$a(dom.select(selector, node), function (node) {
  15953.           if (isElementNode$1(node)) {
  15954.             each$a(format.styles, function (value, name) {
  15955.               dom.setStyle(node, name, '');
  15956.             });
  15957.           }
  15958.         });
  15959.       }
  15960.     };
  15961.     var processChildElements = function (node, filter, process) {
  15962.       each$a(node.childNodes, function (node) {
  15963.         if (isElementNode$1(node)) {
  15964.           if (filter(node)) {
  15965.             process(node);
  15966.           }
  15967.           if (node.hasChildNodes()) {
  15968.             processChildElements(node, filter, process);
  15969.           }
  15970.         }
  15971.       });
  15972.     };
  15973.     var unwrapEmptySpan = function (dom, node) {
  15974.       if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15975.         dom.remove(node, true);
  15976.       }
  15977.     };
  15978.     var hasStyle = function (dom, name) {
  15979.       return function (node) {
  15980.         return !!(node && getStyle(dom, node, name));
  15981.       };
  15982.     };
  15983.     var applyStyle = function (dom, name, value) {
  15984.       return function (node) {
  15985.         dom.setStyle(node, name, value);
  15986.         if (node.getAttribute('style') === '') {
  15987.           node.removeAttribute('style');
  15988.         }
  15989.         unwrapEmptySpan(dom, node);
  15990.       };
  15991.     };
  15992.  
  15993.     var removeResult = Adt.generate([
  15994.       { keep: [] },
  15995.       { rename: ['name'] },
  15996.       { removed: [] }
  15997.     ]);
  15998.     var MCE_ATTR_RE = /^(src|href|style)$/;
  15999.     var each$9 = Tools.each;
  16000.     var isEq$2 = isEq$5;
  16001.     var isTableCellOrRow = function (node) {
  16002.       return /^(TR|TH|TD)$/.test(node.nodeName);
  16003.     };
  16004.     var isChildOfInlineParent = function (dom, node, parent) {
  16005.       return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  16006.     };
  16007.     var getContainer = function (ed, rng, start) {
  16008.       var container = rng[start ? 'startContainer' : 'endContainer'];
  16009.       var offset = rng[start ? 'startOffset' : 'endOffset'];
  16010.       if (isElement$5(container)) {
  16011.         var lastIdx = container.childNodes.length - 1;
  16012.         if (!start && offset) {
  16013.           offset--;
  16014.         }
  16015.         container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  16016.       }
  16017.       if (isText$7(container) && start && offset >= container.nodeValue.length) {
  16018.         container = new DomTreeWalker(container, ed.getBody()).next() || container;
  16019.       }
  16020.       if (isText$7(container) && !start && offset === 0) {
  16021.         container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  16022.       }
  16023.       return container;
  16024.     };
  16025.     var normalizeTableSelection = function (node, start) {
  16026.       var prop = start ? 'firstChild' : 'lastChild';
  16027.       if (isTableCellOrRow(node) && node[prop]) {
  16028.         var childNode = node[prop];
  16029.         if (node.nodeName === 'TR') {
  16030.           return childNode[prop] || childNode;
  16031.         } else {
  16032.           return childNode;
  16033.         }
  16034.       }
  16035.       return node;
  16036.     };
  16037.     var wrap$1 = function (dom, node, name, attrs) {
  16038.       var wrapper = dom.create(name, attrs);
  16039.       node.parentNode.insertBefore(wrapper, node);
  16040.       wrapper.appendChild(node);
  16041.       return wrapper;
  16042.     };
  16043.     var wrapWithSiblings = function (dom, node, next, name, attrs) {
  16044.       var start = SugarElement.fromDom(node);
  16045.       var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  16046.       var siblings = next ? nextSiblings(start) : prevSiblings(start);
  16047.       append(wrapper, siblings);
  16048.       if (next) {
  16049.         before$4(start, wrapper);
  16050.         prepend(wrapper, start);
  16051.       } else {
  16052.         after$3(start, wrapper);
  16053.         append$1(wrapper, start);
  16054.       }
  16055.       return wrapper.dom;
  16056.     };
  16057.     var matchName = function (dom, node, format) {
  16058.       if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  16059.         return true;
  16060.       }
  16061.       if (isBlockFormat(format) && isEq$2(node, format.block)) {
  16062.         return true;
  16063.       }
  16064.       if (isSelectorFormat(format)) {
  16065.         return isElement$5(node) && dom.is(node, format.selector);
  16066.       }
  16067.     };
  16068.     var isColorFormatAndAnchor = function (node, format) {
  16069.       return format.links && node.nodeName === 'A';
  16070.     };
  16071.     var find = function (dom, node, next, inc) {
  16072.       var sibling = getNonWhiteSpaceSibling(node, next, inc);
  16073.       return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  16074.     };
  16075.     var removeNode = function (ed, node, format) {
  16076.       var parentNode = node.parentNode;
  16077.       var rootBlockElm;
  16078.       var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  16079.       if (isBlockFormat(format)) {
  16080.         if (!forcedRootBlock) {
  16081.           if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  16082.             if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  16083.               node.insertBefore(dom.create('br'), node.firstChild);
  16084.             }
  16085.             if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  16086.               node.appendChild(dom.create('br'));
  16087.             }
  16088.           }
  16089.         } else {
  16090.           if (parentNode === dom.getRoot()) {
  16091.             if (!format.list_block || !isEq$2(node, format.list_block)) {
  16092.               each$k(from(node.childNodes), function (node) {
  16093.                 if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  16094.                   if (!rootBlockElm) {
  16095.                     rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  16096.                     dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  16097.                   } else {
  16098.                     rootBlockElm.appendChild(node);
  16099.                   }
  16100.                 } else {
  16101.                   rootBlockElm = null;
  16102.                 }
  16103.               });
  16104.             }
  16105.           }
  16106.         }
  16107.       }
  16108.       if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  16109.         return;
  16110.       }
  16111.       dom.remove(node, true);
  16112.     };
  16113.     var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  16114.       var stylesModified;
  16115.       var dom = ed.dom;
  16116.       if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  16117.         return removeResult.keep();
  16118.       }
  16119.       var elm = node;
  16120.       if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  16121.         var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  16122.           return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  16123.         });
  16124.         dom.removeAllAttribs(elm);
  16125.         each$k(attrsToPreserve, function (attr) {
  16126.           return dom.setAttrib(elm, attr.name, attr.value);
  16127.         });
  16128.         if (attrsToPreserve.length > 0) {
  16129.           return removeResult.rename('span');
  16130.         }
  16131.       }
  16132.       if (format.remove !== 'all') {
  16133.         each$9(format.styles, function (value, name) {
  16134.           value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  16135.           if (isNumber(name)) {
  16136.             name = value;
  16137.             compareNode = null;
  16138.           }
  16139.           if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  16140.             dom.setStyle(elm, name, '');
  16141.           }
  16142.           stylesModified = true;
  16143.         });
  16144.         if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  16145.           elm.removeAttribute('style');
  16146.           elm.removeAttribute('data-mce-style');
  16147.         }
  16148.         each$9(format.attributes, function (value, name) {
  16149.           var valueOut;
  16150.           value = replaceVars(value, vars);
  16151.           if (isNumber(name)) {
  16152.             name = value;
  16153.             compareNode = null;
  16154.           }
  16155.           if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  16156.             if (name === 'class') {
  16157.               value = dom.getAttrib(elm, name);
  16158.               if (value) {
  16159.                 valueOut = '';
  16160.                 each$k(value.split(/\s+/), function (cls) {
  16161.                   if (/mce\-\w+/.test(cls)) {
  16162.                     valueOut += (valueOut ? ' ' : '') + cls;
  16163.                   }
  16164.                 });
  16165.                 if (valueOut) {
  16166.                   dom.setAttrib(elm, name, valueOut);
  16167.                   return;
  16168.                 }
  16169.               }
  16170.             }
  16171.             if (MCE_ATTR_RE.test(name)) {
  16172.               elm.removeAttribute('data-mce-' + name);
  16173.             }
  16174.             if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  16175.               elm.removeAttribute(name);
  16176.               dom.setStyle(elm, 'list-style-type', 'none');
  16177.               return;
  16178.             }
  16179.             if (name === 'class') {
  16180.               elm.removeAttribute('className');
  16181.             }
  16182.             elm.removeAttribute(name);
  16183.           }
  16184.         });
  16185.         each$9(format.classes, function (value) {
  16186.           value = replaceVars(value, vars);
  16187.           if (!compareNode || dom.hasClass(compareNode, value)) {
  16188.             dom.removeClass(elm, value);
  16189.           }
  16190.         });
  16191.         var attrs = dom.getAttribs(elm);
  16192.         for (var i = 0; i < attrs.length; i++) {
  16193.           var attrName = attrs[i].nodeName;
  16194.           if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  16195.             return removeResult.keep();
  16196.           }
  16197.         }
  16198.       }
  16199.       if (format.remove !== 'none') {
  16200.         removeNode(ed, elm, format);
  16201.         return removeResult.removed();
  16202.       }
  16203.       return removeResult.keep();
  16204.     };
  16205.     var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  16206.       return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  16207.         ed.dom.rename(node, newName);
  16208.         return true;
  16209.       }, always);
  16210.     };
  16211.     var findFormatRoot = function (editor, container, name, vars, similar) {
  16212.       var formatRoot;
  16213.       each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  16214.         if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  16215.           var format = matchNode(editor, parent, name, vars, similar);
  16216.           if (format && format.split !== false) {
  16217.             formatRoot = parent;
  16218.           }
  16219.         }
  16220.       });
  16221.       return formatRoot;
  16222.     };
  16223.     var removeFormatFromClone = function (editor, format, vars, clone) {
  16224.       return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  16225.         var fragment = editor.dom.createFragment();
  16226.         fragment.appendChild(clone);
  16227.         return editor.dom.rename(clone, newName);
  16228.       }, constant(null));
  16229.     };
  16230.     var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  16231.       var clone, lastClone, firstClone;
  16232.       var dom = editor.dom;
  16233.       if (formatRoot) {
  16234.         var formatRootParent = formatRoot.parentNode;
  16235.         for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  16236.           clone = dom.clone(parent_1, false);
  16237.           for (var i = 0; i < formatList.length; i++) {
  16238.             clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  16239.             if (clone === null) {
  16240.               break;
  16241.             }
  16242.           }
  16243.           if (clone) {
  16244.             if (lastClone) {
  16245.               clone.appendChild(lastClone);
  16246.             }
  16247.             if (!firstClone) {
  16248.               firstClone = clone;
  16249.             }
  16250.             lastClone = clone;
  16251.           }
  16252.         }
  16253.         if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  16254.           container = dom.split(formatRoot, container);
  16255.         }
  16256.         if (lastClone) {
  16257.           target.parentNode.insertBefore(lastClone, target);
  16258.           firstClone.appendChild(target);
  16259.           if (isInlineFormat(format)) {
  16260.             mergeSiblings(dom, format, vars, lastClone);
  16261.           }
  16262.         }
  16263.       }
  16264.       return container;
  16265.     };
  16266.     var remove$1 = function (ed, name, vars, node, similar) {
  16267.       var formatList = ed.formatter.get(name);
  16268.       var format = formatList[0];
  16269.       var contentEditable = true;
  16270.       var dom = ed.dom;
  16271.       var selection = ed.selection;
  16272.       var splitToFormatRoot = function (container) {
  16273.         var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  16274.         return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  16275.       };
  16276.       var isRemoveBookmarkNode = function (node) {
  16277.         return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  16278.       };
  16279.       var removeNodeFormat = function (node) {
  16280.         return exists(formatList, function (fmt) {
  16281.           return removeFormat$1(ed, fmt, vars, node, node);
  16282.         });
  16283.       };
  16284.       var process = function (node) {
  16285.         var lastContentEditable = true;
  16286.         var hasContentEditableState = false;
  16287.         if (isElement$5(node) && dom.getContentEditable(node)) {
  16288.           lastContentEditable = contentEditable;
  16289.           contentEditable = dom.getContentEditable(node) === 'true';
  16290.           hasContentEditableState = true;
  16291.         }
  16292.         var children = from(node.childNodes);
  16293.         if (contentEditable && !hasContentEditableState) {
  16294.           var removed = removeNodeFormat(node);
  16295.           var parentNode = node.parentNode;
  16296.           if (!removed && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16297.             removeNodeFormat(parentNode);
  16298.           }
  16299.         }
  16300.         if (format.deep) {
  16301.           if (children.length) {
  16302.             for (var i = 0; i < children.length; i++) {
  16303.               process(children[i]);
  16304.             }
  16305.             if (hasContentEditableState) {
  16306.               contentEditable = lastContentEditable;
  16307.             }
  16308.           }
  16309.         }
  16310.         var textDecorations = [
  16311.           'underline',
  16312.           'line-through',
  16313.           'overline'
  16314.         ];
  16315.         each$k(textDecorations, function (decoration) {
  16316.           if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  16317.             removeFormat$1(ed, {
  16318.               deep: false,
  16319.               exact: true,
  16320.               inline: 'span',
  16321.               styles: { textDecoration: decoration }
  16322.             }, null, node);
  16323.           }
  16324.         });
  16325.       };
  16326.       var unwrap = function (start) {
  16327.         var node = dom.get(start ? '_start' : '_end');
  16328.         var out = node[start ? 'firstChild' : 'lastChild'];
  16329.         if (isRemoveBookmarkNode(out)) {
  16330.           out = out[start ? 'firstChild' : 'lastChild'];
  16331.         }
  16332.         if (isText$7(out) && out.data.length === 0) {
  16333.           out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  16334.         }
  16335.         dom.remove(node, true);
  16336.         return out;
  16337.       };
  16338.       var removeRngStyle = function (rng) {
  16339.         var startContainer, endContainer;
  16340.         var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  16341.         if (format.split) {
  16342.           expandedRng = split(expandedRng);
  16343.           startContainer = getContainer(ed, expandedRng, true);
  16344.           endContainer = getContainer(ed, expandedRng);
  16345.           if (startContainer !== endContainer) {
  16346.             startContainer = normalizeTableSelection(startContainer, true);
  16347.             endContainer = normalizeTableSelection(endContainer, false);
  16348.             if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  16349.               var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  16350.               splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  16351.                 'id': '_start',
  16352.                 'data-mce-type': 'bookmark'
  16353.               }));
  16354.               unwrap(true);
  16355.               return;
  16356.             }
  16357.             if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  16358.               var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  16359.               splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  16360.                 'id': '_end',
  16361.                 'data-mce-type': 'bookmark'
  16362.               }));
  16363.               unwrap(false);
  16364.               return;
  16365.             }
  16366.             startContainer = wrap$1(dom, startContainer, 'span', {
  16367.               'id': '_start',
  16368.               'data-mce-type': 'bookmark'
  16369.             });
  16370.             endContainer = wrap$1(dom, endContainer, 'span', {
  16371.               'id': '_end',
  16372.               'data-mce-type': 'bookmark'
  16373.             });
  16374.             var newRng = dom.createRng();
  16375.             newRng.setStartAfter(startContainer);
  16376.             newRng.setEndBefore(endContainer);
  16377.             walk$2(dom, newRng, function (nodes) {
  16378.               each$k(nodes, function (n) {
  16379.                 if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  16380.                   splitToFormatRoot(n);
  16381.                 }
  16382.               });
  16383.             });
  16384.             splitToFormatRoot(startContainer);
  16385.             splitToFormatRoot(endContainer);
  16386.             startContainer = unwrap(true);
  16387.             endContainer = unwrap();
  16388.           } else {
  16389.             startContainer = endContainer = splitToFormatRoot(startContainer);
  16390.           }
  16391.           expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  16392.           expandedRng.startOffset = dom.nodeIndex(startContainer);
  16393.           expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  16394.           expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  16395.         }
  16396.         walk$2(dom, expandedRng, function (nodes) {
  16397.           each$k(nodes, process);
  16398.         });
  16399.       };
  16400.       if (node) {
  16401.         if (isNode(node)) {
  16402.           var rng = dom.createRng();
  16403.           rng.setStartBefore(node);
  16404.           rng.setEndAfter(node);
  16405.           removeRngStyle(rng);
  16406.         } else {
  16407.           removeRngStyle(node);
  16408.         }
  16409.         fireFormatRemove(ed, name, node, vars);
  16410.         return;
  16411.       }
  16412.       if (dom.getContentEditable(selection.getNode()) === 'false') {
  16413.         node = selection.getNode();
  16414.         for (var i = 0; i < formatList.length; i++) {
  16415.           if (formatList[i].ceFalseOverride) {
  16416.             if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  16417.               break;
  16418.             }
  16419.           }
  16420.         }
  16421.         fireFormatRemove(ed, name, node, vars);
  16422.         return;
  16423.       }
  16424.       if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16425.         preserve(selection, true, function () {
  16426.           runOnRanges(ed, removeRngStyle);
  16427.         });
  16428.         if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  16429.           moveStart(dom, selection, selection.getRng());
  16430.         }
  16431.         ed.nodeChanged();
  16432.       } else {
  16433.         removeCaretFormat(ed, name, vars, similar);
  16434.       }
  16435.       fireFormatRemove(ed, name, node, vars);
  16436.     };
  16437.  
  16438.     var each$8 = Tools.each;
  16439.     var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  16440.       var processTextDecorationsAndColor = function (n) {
  16441.         if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  16442.           var textDecoration = getTextDecoration(dom, n.parentNode);
  16443.           if (dom.getStyle(n, 'color') && textDecoration) {
  16444.             dom.setStyle(n, 'text-decoration', textDecoration);
  16445.           } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  16446.             dom.setStyle(n, 'text-decoration', null);
  16447.           }
  16448.         }
  16449.       };
  16450.       if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  16451.         Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  16452.         processTextDecorationsAndColor(node);
  16453.       }
  16454.     };
  16455.     var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  16456.       if (format.styles && format.styles.backgroundColor) {
  16457.         processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  16458.       }
  16459.     };
  16460.     var mergeSubSup = function (dom, format, vars, node) {
  16461.       if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  16462.         processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  16463.         dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  16464.       }
  16465.     };
  16466.     var mergeWithChildren = function (editor, formatList, vars, node) {
  16467.       each$8(formatList, function (format) {
  16468.         if (isInlineFormat(format)) {
  16469.           each$8(editor.dom.select(format.inline, node), function (child) {
  16470.             if (!isElementNode$1(child)) {
  16471.               return;
  16472.             }
  16473.             removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  16474.           });
  16475.         }
  16476.         clearChildStyles(editor.dom, format, node);
  16477.       });
  16478.     };
  16479.     var mergeWithParents = function (editor, format, name, vars, node) {
  16480.       if (matchNode(editor, node.parentNode, name, vars)) {
  16481.         if (removeFormat$1(editor, format, vars, node)) {
  16482.           return;
  16483.         }
  16484.       }
  16485.       if (format.merge_with_parents) {
  16486.         editor.dom.getParent(node.parentNode, function (parent) {
  16487.           if (matchNode(editor, parent, name, vars)) {
  16488.             removeFormat$1(editor, format, vars, node);
  16489.             return true;
  16490.           }
  16491.         });
  16492.       }
  16493.     };
  16494.  
  16495.     var each$7 = Tools.each;
  16496.     var isElementNode = function (node) {
  16497.       return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  16498.     };
  16499.     var canFormatBR = function (editor, format, node, parentName) {
  16500.       if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  16501.         var validBRParentElements = __assign(__assign({}, editor.schema.getTextBlockElements()), {
  16502.           td: {},
  16503.           th: {},
  16504.           li: {},
  16505.           dt: {},
  16506.           dd: {},
  16507.           figcaption: {},
  16508.           caption: {},
  16509.           details: {},
  16510.           summary: {}
  16511.         });
  16512.         var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  16513.           return isCaretNode(sibling.dom);
  16514.         });
  16515.         return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  16516.       } else {
  16517.         return false;
  16518.       }
  16519.     };
  16520.     var applyFormat$1 = function (ed, name, vars, node) {
  16521.       var formatList = ed.formatter.get(name);
  16522.       var format = formatList[0];
  16523.       var isCollapsed = !node && ed.selection.isCollapsed();
  16524.       var dom = ed.dom;
  16525.       var selection = ed.selection;
  16526.       var setElementFormat = function (elm, fmt) {
  16527.         if (fmt === void 0) {
  16528.           fmt = format;
  16529.         }
  16530.         if (isFunction(fmt.onformat)) {
  16531.           fmt.onformat(elm, fmt, vars, node);
  16532.         }
  16533.         each$7(fmt.styles, function (value, name) {
  16534.           dom.setStyle(elm, name, replaceVars(value, vars));
  16535.         });
  16536.         if (fmt.styles) {
  16537.           var styleVal = dom.getAttrib(elm, 'style');
  16538.           if (styleVal) {
  16539.             dom.setAttrib(elm, 'data-mce-style', styleVal);
  16540.           }
  16541.         }
  16542.         each$7(fmt.attributes, function (value, name) {
  16543.           dom.setAttrib(elm, name, replaceVars(value, vars));
  16544.         });
  16545.         each$7(fmt.classes, function (value) {
  16546.           value = replaceVars(value, vars);
  16547.           if (!dom.hasClass(elm, value)) {
  16548.             dom.addClass(elm, value);
  16549.           }
  16550.         });
  16551.       };
  16552.       var applyNodeStyle = function (formatList, node) {
  16553.         var found = false;
  16554.         each$7(formatList, function (format) {
  16555.           if (!isSelectorFormat(format)) {
  16556.             return false;
  16557.           }
  16558.           if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  16559.             return;
  16560.           }
  16561.           if (dom.is(node, format.selector) && !isCaretNode(node)) {
  16562.             setElementFormat(node, format);
  16563.             found = true;
  16564.             return false;
  16565.           }
  16566.         });
  16567.         return found;
  16568.       };
  16569.       var createWrapElement = function (wrapName) {
  16570.         if (isString$1(wrapName)) {
  16571.           var wrapElm = dom.create(wrapName);
  16572.           setElementFormat(wrapElm);
  16573.           return wrapElm;
  16574.         } else {
  16575.           return null;
  16576.         }
  16577.       };
  16578.       var applyRngStyle = function (dom, rng, nodeSpecific) {
  16579.         var newWrappers = [];
  16580.         var contentEditable = true;
  16581.         var wrapName = format.inline || format.block;
  16582.         var wrapElm = createWrapElement(wrapName);
  16583.         walk$2(dom, rng, function (nodes) {
  16584.           var currentWrapElm;
  16585.           var process = function (node) {
  16586.             var hasContentEditableState = false;
  16587.             var lastContentEditable = contentEditable;
  16588.             var nodeName = node.nodeName.toLowerCase();
  16589.             var parentNode = node.parentNode;
  16590.             var parentName = parentNode.nodeName.toLowerCase();
  16591.             if (isElement$5(node) && dom.getContentEditable(node)) {
  16592.               lastContentEditable = contentEditable;
  16593.               contentEditable = dom.getContentEditable(node) === 'true';
  16594.               hasContentEditableState = true;
  16595.             }
  16596.             if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  16597.               currentWrapElm = null;
  16598.               if (isBlockFormat(format)) {
  16599.                 dom.remove(node);
  16600.               }
  16601.               return;
  16602.             }
  16603.             if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  16604.               currentWrapElm = null;
  16605.               return;
  16606.             }
  16607.             if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  16608.               var elm = dom.rename(node, wrapName);
  16609.               setElementFormat(elm);
  16610.               newWrappers.push(elm);
  16611.               currentWrapElm = null;
  16612.               return;
  16613.             }
  16614.             if (isSelectorFormat(format)) {
  16615.               var found = applyNodeStyle(formatList, node);
  16616.               if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  16617.                 found = applyNodeStyle(formatList, parentNode);
  16618.               }
  16619.               if (!isInlineFormat(format) || found) {
  16620.                 currentWrapElm = null;
  16621.                 return;
  16622.               }
  16623.             }
  16624.             if (contentEditable && !hasContentEditableState && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$7(node) && isZwsp(node.data)) && !isCaretNode(node) && (!isInlineFormat(format) || !dom.isBlock(node))) {
  16625.               if (!currentWrapElm) {
  16626.                 currentWrapElm = dom.clone(wrapElm, false);
  16627.                 node.parentNode.insertBefore(currentWrapElm, node);
  16628.                 newWrappers.push(currentWrapElm);
  16629.               }
  16630.               currentWrapElm.appendChild(node);
  16631.             } else {
  16632.               currentWrapElm = null;
  16633.               each$k(from(node.childNodes), process);
  16634.               if (hasContentEditableState) {
  16635.                 contentEditable = lastContentEditable;
  16636.               }
  16637.               currentWrapElm = null;
  16638.             }
  16639.           };
  16640.           each$k(nodes, process);
  16641.         });
  16642.         if (format.links === true) {
  16643.           each$k(newWrappers, function (node) {
  16644.             var process = function (node) {
  16645.               if (node.nodeName === 'A') {
  16646.                 setElementFormat(node, format);
  16647.               }
  16648.               each$k(from(node.childNodes), process);
  16649.             };
  16650.             process(node);
  16651.           });
  16652.         }
  16653.         each$k(newWrappers, function (node) {
  16654.           var getChildCount = function (node) {
  16655.             var count = 0;
  16656.             each$k(node.childNodes, function (node) {
  16657.               if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  16658.                 count++;
  16659.               }
  16660.             });
  16661.             return count;
  16662.           };
  16663.           var mergeStyles = function (node) {
  16664.             var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  16665.               return matchName$1(dom, child, format);
  16666.             });
  16667.             return childElement.map(function (child) {
  16668.               var clone = dom.clone(child, false);
  16669.               setElementFormat(clone);
  16670.               dom.replace(clone, node, true);
  16671.               dom.remove(child, true);
  16672.               return clone;
  16673.             }).getOr(node);
  16674.           };
  16675.           var childCount = getChildCount(node);
  16676.           if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  16677.             dom.remove(node, true);
  16678.             return;
  16679.           }
  16680.           if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  16681.             if (!format.exact && childCount === 1) {
  16682.               node = mergeStyles(node);
  16683.             }
  16684.             mergeWithChildren(ed, formatList, vars, node);
  16685.             mergeWithParents(ed, format, name, vars, node);
  16686.             mergeBackgroundColorAndFontSize(dom, format, vars, node);
  16687.             mergeTextDecorationsAndColor(dom, format, vars, node);
  16688.             mergeSubSup(dom, format, vars, node);
  16689.             mergeSiblings(dom, format, vars, node);
  16690.           }
  16691.         });
  16692.       };
  16693.       if (dom.getContentEditable(selection.getNode()) === 'false') {
  16694.         node = selection.getNode();
  16695.         for (var i = 0, l = formatList.length; i < l; i++) {
  16696.           var formatItem = formatList[i];
  16697.           if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  16698.             setElementFormat(node, formatItem);
  16699.             break;
  16700.           }
  16701.         }
  16702.         fireFormatApply(ed, name, node, vars);
  16703.         return;
  16704.       }
  16705.       if (format) {
  16706.         if (node) {
  16707.           if (isNode(node)) {
  16708.             if (!applyNodeStyle(formatList, node)) {
  16709.               var rng = dom.createRng();
  16710.               rng.setStartBefore(node);
  16711.               rng.setEndAfter(node);
  16712.               applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16713.             }
  16714.           } else {
  16715.             applyRngStyle(dom, node, true);
  16716.           }
  16717.         } else {
  16718.           if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16719.             var curSelNode = selection.getNode();
  16720.             var firstFormat = formatList[0];
  16721.             if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16722.               applyFormat$1(ed, firstFormat.defaultBlock);
  16723.             }
  16724.             selection.setRng(normalize(selection.getRng()));
  16725.             preserve(selection, true, function () {
  16726.               runOnRanges(ed, function (selectionRng, fake) {
  16727.                 var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16728.                 applyRngStyle(dom, expandedRng, false);
  16729.               });
  16730.             });
  16731.             moveStart(dom, selection, selection.getRng());
  16732.             ed.nodeChanged();
  16733.           } else {
  16734.             applyCaretFormat(ed, name, vars);
  16735.           }
  16736.         }
  16737.         postProcess$1(name, ed);
  16738.       }
  16739.       fireFormatApply(ed, name, node, vars);
  16740.     };
  16741.  
  16742.     var hasVars = function (value) {
  16743.       return has$2(value, 'vars');
  16744.     };
  16745.     var setup$j = function (registeredFormatListeners, editor) {
  16746.       registeredFormatListeners.set({});
  16747.       editor.on('NodeChange', function (e) {
  16748.         updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16749.       });
  16750.       editor.on('FormatApply FormatRemove', function (e) {
  16751.         var element = Optional.from(e.node).map(function (nodeOrRange) {
  16752.           return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16753.         }).bind(function (node) {
  16754.           return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16755.         }).getOrThunk(function () {
  16756.           return fallbackElement(editor);
  16757.         });
  16758.         updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16759.       });
  16760.     };
  16761.     var fallbackElement = function (editor) {
  16762.       return editor.selection.getStart();
  16763.     };
  16764.     var matchingNode = function (editor, parents, format, similar, vars) {
  16765.       var isMatchingNode = function (node) {
  16766.         var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16767.         return !isUndefined(matchingFormat);
  16768.       };
  16769.       var isUnableToMatch = function (node) {
  16770.         if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16771.           return true;
  16772.         } else {
  16773.           if (!similar) {
  16774.             return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16775.           } else {
  16776.             return false;
  16777.           }
  16778.         }
  16779.       };
  16780.       return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16781.     };
  16782.     var getParents = function (editor, elm) {
  16783.       var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16784.       return filter$4(getParents$2(editor.dom, element), function (node) {
  16785.         return isElement$5(node) && !isBogus$2(node);
  16786.       });
  16787.     };
  16788.     var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16789.       var parents = getParents(editor, elm);
  16790.       each$j(registeredCallbacks, function (data, format) {
  16791.         var runIfChanged = function (spec) {
  16792.           var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16793.           var isSet = match.isSome();
  16794.           if (spec.state.get() !== isSet) {
  16795.             spec.state.set(isSet);
  16796.             var node_1 = match.getOr(elm);
  16797.             if (hasVars(spec)) {
  16798.               spec.callback(isSet, {
  16799.                 node: node_1,
  16800.                 format: format,
  16801.                 parents: parents
  16802.               });
  16803.             } else {
  16804.               each$k(spec.callbacks, function (callback) {
  16805.                 return callback(isSet, {
  16806.                   node: node_1,
  16807.                   format: format,
  16808.                   parents: parents
  16809.                 });
  16810.               });
  16811.             }
  16812.           }
  16813.         };
  16814.         each$k([
  16815.           data.withSimilar,
  16816.           data.withoutSimilar
  16817.         ], runIfChanged);
  16818.         each$k(data.withVars, runIfChanged);
  16819.       });
  16820.     };
  16821.     var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16822.       var formatChangeItems = registeredFormatListeners.get();
  16823.       each$k(formats.split(','), function (format) {
  16824.         var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16825.           var base = {
  16826.             withSimilar: {
  16827.               state: Cell(false),
  16828.               similar: true,
  16829.               callbacks: []
  16830.             },
  16831.             withoutSimilar: {
  16832.               state: Cell(false),
  16833.               similar: false,
  16834.               callbacks: []
  16835.             },
  16836.             withVars: []
  16837.           };
  16838.           formatChangeItems[format] = base;
  16839.           return base;
  16840.         });
  16841.         var getCurrent = function () {
  16842.           var parents = getParents(editor);
  16843.           return matchingNode(editor, parents, format, similar, vars).isSome();
  16844.         };
  16845.         if (isUndefined(vars)) {
  16846.           var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16847.           toAppendTo.callbacks.push(callback);
  16848.           if (toAppendTo.callbacks.length === 1) {
  16849.             toAppendTo.state.set(getCurrent());
  16850.           }
  16851.         } else {
  16852.           group.withVars.push({
  16853.             state: Cell(getCurrent()),
  16854.             similar: similar,
  16855.             vars: vars,
  16856.             callback: callback
  16857.           });
  16858.         }
  16859.       });
  16860.       registeredFormatListeners.set(formatChangeItems);
  16861.     };
  16862.     var removeListeners = function (registeredFormatListeners, formats, callback) {
  16863.       var formatChangeItems = registeredFormatListeners.get();
  16864.       each$k(formats.split(','), function (format) {
  16865.         return get$9(formatChangeItems, format).each(function (group) {
  16866.           formatChangeItems[format] = {
  16867.             withSimilar: __assign(__assign({}, group.withSimilar), {
  16868.               callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16869.                 return cb !== callback;
  16870.               })
  16871.             }),
  16872.             withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16873.               callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16874.                 return cb !== callback;
  16875.               })
  16876.             }),
  16877.             withVars: filter$4(group.withVars, function (item) {
  16878.               return item.callback !== callback;
  16879.             })
  16880.           };
  16881.         });
  16882.       });
  16883.       registeredFormatListeners.set(formatChangeItems);
  16884.     };
  16885.     var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16886.       if (registeredFormatListeners.get() === null) {
  16887.         setup$j(registeredFormatListeners, editor);
  16888.       }
  16889.       addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16890.       return {
  16891.         unbind: function () {
  16892.           return removeListeners(registeredFormatListeners, formats, callback);
  16893.         }
  16894.       };
  16895.     };
  16896.  
  16897.     var toggle = function (editor, name, vars, node) {
  16898.       var fmt = editor.formatter.get(name);
  16899.       if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16900.         remove$1(editor, name, vars, node);
  16901.       } else {
  16902.         applyFormat$1(editor, name, vars, node);
  16903.       }
  16904.     };
  16905.  
  16906.     var fromElements = function (elements, scope) {
  16907.       var doc = scope || document;
  16908.       var fragment = doc.createDocumentFragment();
  16909.       each$k(elements, function (element) {
  16910.         fragment.appendChild(element.dom);
  16911.       });
  16912.       return SugarElement.fromDom(fragment);
  16913.     };
  16914.  
  16915.     var tableModel = function (element, width, rows) {
  16916.       return {
  16917.         element: element,
  16918.         width: width,
  16919.         rows: rows
  16920.       };
  16921.     };
  16922.     var tableRow = function (element, cells) {
  16923.       return {
  16924.         element: element,
  16925.         cells: cells
  16926.       };
  16927.     };
  16928.     var cellPosition = function (x, y) {
  16929.       return {
  16930.         x: x,
  16931.         y: y
  16932.       };
  16933.     };
  16934.     var getSpan = function (td, key) {
  16935.       var value = parseInt(get$6(td, key), 10);
  16936.       return isNaN(value) ? 1 : value;
  16937.     };
  16938.     var fillout = function (table, x, y, tr, td) {
  16939.       var rowspan = getSpan(td, 'rowspan');
  16940.       var colspan = getSpan(td, 'colspan');
  16941.       var rows = table.rows;
  16942.       for (var y2 = y; y2 < y + rowspan; y2++) {
  16943.         if (!rows[y2]) {
  16944.           rows[y2] = tableRow(deep$1(tr), []);
  16945.         }
  16946.         for (var x2 = x; x2 < x + colspan; x2++) {
  16947.           var cells = rows[y2].cells;
  16948.           cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16949.         }
  16950.       }
  16951.     };
  16952.     var cellExists = function (table, x, y) {
  16953.       var rows = table.rows;
  16954.       var cells = rows[y] ? rows[y].cells : [];
  16955.       return !!cells[x];
  16956.     };
  16957.     var skipCellsX = function (table, x, y) {
  16958.       while (cellExists(table, x, y)) {
  16959.         x++;
  16960.       }
  16961.       return x;
  16962.     };
  16963.     var getWidth = function (rows) {
  16964.       return foldl(rows, function (acc, row) {
  16965.         return row.cells.length > acc ? row.cells.length : acc;
  16966.       }, 0);
  16967.     };
  16968.     var findElementPos = function (table, element) {
  16969.       var rows = table.rows;
  16970.       for (var y = 0; y < rows.length; y++) {
  16971.         var cells = rows[y].cells;
  16972.         for (var x = 0; x < cells.length; x++) {
  16973.           if (eq(cells[x], element)) {
  16974.             return Optional.some(cellPosition(x, y));
  16975.           }
  16976.         }
  16977.       }
  16978.       return Optional.none();
  16979.     };
  16980.     var extractRows = function (table, sx, sy, ex, ey) {
  16981.       var newRows = [];
  16982.       var rows = table.rows;
  16983.       for (var y = sy; y <= ey; y++) {
  16984.         var cells = rows[y].cells;
  16985.         var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16986.         newRows.push(tableRow(rows[y].element, slice));
  16987.       }
  16988.       return newRows;
  16989.     };
  16990.     var subTable = function (table, startPos, endPos) {
  16991.       var sx = startPos.x, sy = startPos.y;
  16992.       var ex = endPos.x, ey = endPos.y;
  16993.       var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16994.       return tableModel(table.element, getWidth(newRows), newRows);
  16995.     };
  16996.     var createDomTable = function (table, rows) {
  16997.       var tableElement = shallow(table.element);
  16998.       var tableBody = SugarElement.fromTag('tbody');
  16999.       append(tableBody, rows);
  17000.       append$1(tableElement, tableBody);
  17001.       return tableElement;
  17002.     };
  17003.     var modelRowsToDomRows = function (table) {
  17004.       return map$3(table.rows, function (row) {
  17005.         var cells = map$3(row.cells, function (cell) {
  17006.           var td = deep$1(cell);
  17007.           remove$6(td, 'colspan');
  17008.           remove$6(td, 'rowspan');
  17009.           return td;
  17010.         });
  17011.         var tr = shallow(row.element);
  17012.         append(tr, cells);
  17013.         return tr;
  17014.       });
  17015.     };
  17016.     var fromDom = function (tableElm) {
  17017.       var table = tableModel(shallow(tableElm), 0, []);
  17018.       each$k(descendants(tableElm, 'tr'), function (tr, y) {
  17019.         each$k(descendants(tr, 'td,th'), function (td, x) {
  17020.           fillout(table, skipCellsX(table, x, y), y, tr, td);
  17021.         });
  17022.       });
  17023.       return tableModel(table.element, getWidth(table.rows), table.rows);
  17024.     };
  17025.     var toDom = function (table) {
  17026.       return createDomTable(table, modelRowsToDomRows(table));
  17027.     };
  17028.     var subsection = function (table, startElement, endElement) {
  17029.       return findElementPos(table, startElement).bind(function (startPos) {
  17030.         return findElementPos(table, endElement).map(function (endPos) {
  17031.           return subTable(table, startPos, endPos);
  17032.         });
  17033.       });
  17034.     };
  17035.  
  17036.     var findParentListContainer = function (parents) {
  17037.       return find$3(parents, function (elm) {
  17038.         return name(elm) === 'ul' || name(elm) === 'ol';
  17039.       });
  17040.     };
  17041.     var getFullySelectedListWrappers = function (parents, rng) {
  17042.       return find$3(parents, function (elm) {
  17043.         return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  17044.       }).fold(constant([]), function (_li) {
  17045.         return findParentListContainer(parents).map(function (listCont) {
  17046.           var listElm = SugarElement.fromTag(name(listCont));
  17047.           var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  17048.             return startsWith(name, 'list-style');
  17049.           });
  17050.           setAll(listElm, listStyles);
  17051.           return [
  17052.             SugarElement.fromTag('li'),
  17053.             listElm
  17054.           ];
  17055.         }).getOr([]);
  17056.       });
  17057.     };
  17058.     var wrap = function (innerElm, elms) {
  17059.       var wrapped = foldl(elms, function (acc, elm) {
  17060.         append$1(elm, acc);
  17061.         return elm;
  17062.       }, innerElm);
  17063.       return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  17064.     };
  17065.     var directListWrappers = function (commonAnchorContainer) {
  17066.       if (isListItem(commonAnchorContainer)) {
  17067.         return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  17068.           return [
  17069.             commonAnchorContainer,
  17070.             listElm
  17071.           ];
  17072.         });
  17073.       } else {
  17074.         return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  17075.       }
  17076.     };
  17077.     var getWrapElements = function (rootNode, rng) {
  17078.       var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  17079.       var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  17080.       var wrapElements = filter$4(parents, function (elm) {
  17081.         return isInline$1(elm) || isHeading(elm);
  17082.       });
  17083.       var listWrappers = getFullySelectedListWrappers(parents, rng);
  17084.       var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  17085.       return map$3(allWrappers, shallow);
  17086.     };
  17087.     var emptyFragment = function () {
  17088.       return fromElements([]);
  17089.     };
  17090.     var getFragmentFromRange = function (rootNode, rng) {
  17091.       return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  17092.     };
  17093.     var getParentTable = function (rootElm, cell) {
  17094.       return ancestor$2(cell, 'table', curry(eq, rootElm));
  17095.     };
  17096.     var getTableFragment = function (rootNode, selectedTableCells) {
  17097.       return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  17098.         var firstCell = selectedTableCells[0];
  17099.         var lastCell = selectedTableCells[selectedTableCells.length - 1];
  17100.         var fullTableModel = fromDom(tableElm);
  17101.         return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  17102.           return fromElements([toDom(sectionedTableModel)]);
  17103.         });
  17104.       }).getOrThunk(emptyFragment);
  17105.     };
  17106.     var getSelectionFragment = function (rootNode, ranges) {
  17107.       return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  17108.     };
  17109.     var read$3 = function (rootNode, ranges) {
  17110.       var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  17111.       return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  17112.     };
  17113.  
  17114.     var trimLeadingCollapsibleText = function (text) {
  17115.       return text.replace(/^[ \f\n\r\t\v]+/, '');
  17116.     };
  17117.     var isCollapsibleWhitespace = function (text, index) {
  17118.       return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  17119.     };
  17120.     var getInnerText = function (bin, shouldTrim) {
  17121.       var text = trim$2(bin.innerText);
  17122.       return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  17123.     };
  17124.     var getContextNodeName = function (parentBlockOpt) {
  17125.       return parentBlockOpt.map(function (block) {
  17126.         return block.nodeName;
  17127.       }).getOr('div').toLowerCase();
  17128.     };
  17129.     var getTextContent = function (editor) {
  17130.       return Optional.from(editor.selection.getRng()).map(function (rng) {
  17131.         var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  17132.         var body = editor.getBody();
  17133.         var contextNodeName = getContextNodeName(parentBlockOpt);
  17134.         var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  17135.         var bin = editor.dom.add(body, contextNodeName, {
  17136.           'data-mce-bogus': 'all',
  17137.           'style': 'overflow: hidden; opacity: 0;'
  17138.         }, rng.cloneContents());
  17139.         var text = getInnerText(bin, shouldTrimSpaces);
  17140.         var nonRenderedText = trim$2(bin.textContent);
  17141.         editor.dom.remove(bin);
  17142.         if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  17143.           var parentBlock = parentBlockOpt.getOr(body);
  17144.           var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  17145.           var textIndex = parentBlockText.indexOf(text);
  17146.           if (textIndex === -1) {
  17147.             return text;
  17148.           } else {
  17149.             var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  17150.             var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  17151.             return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  17152.           }
  17153.         } else {
  17154.           return text;
  17155.         }
  17156.       }).getOr('');
  17157.     };
  17158.     var getSerializedContent = function (editor, args) {
  17159.       var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  17160.       var sel = editor.selection.getSel();
  17161.       var ranges = processRanges(editor, getRanges(sel));
  17162.       var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  17163.       if (fragment) {
  17164.         tmpElm.appendChild(fragment);
  17165.       }
  17166.       return editor.selection.serializer.serialize(tmpElm, args);
  17167.     };
  17168.     var setupArgs$1 = function (args, format) {
  17169.       return __assign(__assign({}, args), {
  17170.         format: format,
  17171.         get: true,
  17172.         selection: true
  17173.       });
  17174.     };
  17175.     var getSelectedContentInternal = function (editor, format, args) {
  17176.       if (args === void 0) {
  17177.         args = {};
  17178.       }
  17179.       var defaultedArgs = setupArgs$1(args, format);
  17180.       var updatedArgs = editor.fire('BeforeGetContent', defaultedArgs);
  17181.       if (updatedArgs.isDefaultPrevented()) {
  17182.         editor.fire('GetContent', updatedArgs);
  17183.         return updatedArgs.content;
  17184.       }
  17185.       if (updatedArgs.format === 'text') {
  17186.         return getTextContent(editor);
  17187.       } else {
  17188.         updatedArgs.getInner = true;
  17189.         var content = getSerializedContent(editor, updatedArgs);
  17190.         if (updatedArgs.format === 'tree') {
  17191.           return content;
  17192.         } else {
  17193.           updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  17194.           editor.fire('GetContent', updatedArgs);
  17195.           return updatedArgs.content;
  17196.         }
  17197.       }
  17198.     };
  17199.  
  17200.     var KEEP = 0, INSERT = 1, DELETE = 2;
  17201.     var diff = function (left, right) {
  17202.       var size = left.length + right.length + 2;
  17203.       var vDown = new Array(size);
  17204.       var vUp = new Array(size);
  17205.       var snake = function (start, end, diag) {
  17206.         return {
  17207.           start: start,
  17208.           end: end,
  17209.           diag: diag
  17210.         };
  17211.       };
  17212.       var buildScript = function (start1, end1, start2, end2, script) {
  17213.         var middle = getMiddleSnake(start1, end1, start2, end2);
  17214.         if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  17215.           var i = start1;
  17216.           var j = start2;
  17217.           while (i < end1 || j < end2) {
  17218.             if (i < end1 && j < end2 && left[i] === right[j]) {
  17219.               script.push([
  17220.                 KEEP,
  17221.                 left[i]
  17222.               ]);
  17223.               ++i;
  17224.               ++j;
  17225.             } else {
  17226.               if (end1 - start1 > end2 - start2) {
  17227.                 script.push([
  17228.                   DELETE,
  17229.                   left[i]
  17230.                 ]);
  17231.                 ++i;
  17232.               } else {
  17233.                 script.push([
  17234.                   INSERT,
  17235.                   right[j]
  17236.                 ]);
  17237.                 ++j;
  17238.               }
  17239.             }
  17240.           }
  17241.         } else {
  17242.           buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  17243.           for (var i2 = middle.start; i2 < middle.end; ++i2) {
  17244.             script.push([
  17245.               KEEP,
  17246.               left[i2]
  17247.             ]);
  17248.           }
  17249.           buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  17250.         }
  17251.       };
  17252.       var buildSnake = function (start, diag, end1, end2) {
  17253.         var end = start;
  17254.         while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  17255.           ++end;
  17256.         }
  17257.         return snake(start, end, diag);
  17258.       };
  17259.       var getMiddleSnake = function (start1, end1, start2, end2) {
  17260.         var m = end1 - start1;
  17261.         var n = end2 - start2;
  17262.         if (m === 0 || n === 0) {
  17263.           return null;
  17264.         }
  17265.         var delta = m - n;
  17266.         var sum = n + m;
  17267.         var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  17268.         vDown[1 + offset] = start1;
  17269.         vUp[1 + offset] = end1 + 1;
  17270.         var d, k, i, x, y;
  17271.         for (d = 0; d <= offset; ++d) {
  17272.           for (k = -d; k <= d; k += 2) {
  17273.             i = k + offset;
  17274.             if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  17275.               vDown[i] = vDown[i + 1];
  17276.             } else {
  17277.               vDown[i] = vDown[i - 1] + 1;
  17278.             }
  17279.             x = vDown[i];
  17280.             y = x - start1 + start2 - k;
  17281.             while (x < end1 && y < end2 && left[x] === right[y]) {
  17282.               vDown[i] = ++x;
  17283.               ++y;
  17284.             }
  17285.             if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  17286.               if (vUp[i - delta] <= vDown[i]) {
  17287.                 return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  17288.               }
  17289.             }
  17290.           }
  17291.           for (k = delta - d; k <= delta + d; k += 2) {
  17292.             i = k + offset - delta;
  17293.             if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  17294.               vUp[i] = vUp[i + 1] - 1;
  17295.             } else {
  17296.               vUp[i] = vUp[i - 1];
  17297.             }
  17298.             x = vUp[i] - 1;
  17299.             y = x - start1 + start2 - k;
  17300.             while (x >= start1 && y >= start2 && left[x] === right[y]) {
  17301.               vUp[i] = x--;
  17302.               y--;
  17303.             }
  17304.             if (delta % 2 === 0 && -d <= k && k <= d) {
  17305.               if (vUp[i] <= vDown[i + delta]) {
  17306.                 return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  17307.               }
  17308.             }
  17309.           }
  17310.         }
  17311.       };
  17312.       var script = [];
  17313.       buildScript(0, left.length, 0, right.length, script);
  17314.       return script;
  17315.     };
  17316.  
  17317.     var getOuterHtml = function (elm) {
  17318.       if (isElement$5(elm)) {
  17319.         return elm.outerHTML;
  17320.       } else if (isText$7(elm)) {
  17321.         return Entities.encodeRaw(elm.data, false);
  17322.       } else if (isComment(elm)) {
  17323.         return '<!--' + elm.data + '-->';
  17324.       }
  17325.       return '';
  17326.     };
  17327.     var createFragment = function (html) {
  17328.       var node;
  17329.       var container = document.createElement('div');
  17330.       var frag = document.createDocumentFragment();
  17331.       if (html) {
  17332.         container.innerHTML = html;
  17333.       }
  17334.       while (node = container.firstChild) {
  17335.         frag.appendChild(node);
  17336.       }
  17337.       return frag;
  17338.     };
  17339.     var insertAt = function (elm, html, index) {
  17340.       var fragment = createFragment(html);
  17341.       if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17342.         var target = elm.childNodes[index];
  17343.         target.parentNode.insertBefore(fragment, target);
  17344.       } else {
  17345.         elm.appendChild(fragment);
  17346.       }
  17347.     };
  17348.     var removeAt = function (elm, index) {
  17349.       if (elm.hasChildNodes() && index < elm.childNodes.length) {
  17350.         var target = elm.childNodes[index];
  17351.         target.parentNode.removeChild(target);
  17352.       }
  17353.     };
  17354.     var applyDiff = function (diff, elm) {
  17355.       var index = 0;
  17356.       each$k(diff, function (action) {
  17357.         if (action[0] === KEEP) {
  17358.           index++;
  17359.         } else if (action[0] === INSERT) {
  17360.           insertAt(elm, action[1], index);
  17361.           index++;
  17362.         } else if (action[0] === DELETE) {
  17363.           removeAt(elm, index);
  17364.         }
  17365.       });
  17366.     };
  17367.     var read$2 = function (elm) {
  17368.       return filter$4(map$3(from(elm.childNodes), getOuterHtml), function (item) {
  17369.         return item.length > 0;
  17370.       });
  17371.     };
  17372.     var write = function (fragments, elm) {
  17373.       var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  17374.       applyDiff(diff(currentFragments, fragments), elm);
  17375.       return elm;
  17376.     };
  17377.  
  17378.     var lazyTempDocument = cached(function () {
  17379.       return document.implementation.createHTMLDocument('undo');
  17380.     });
  17381.     var hasIframes = function (html) {
  17382.       return html.indexOf('</iframe>') !== -1;
  17383.     };
  17384.     var createFragmentedLevel = function (fragments) {
  17385.       return {
  17386.         type: 'fragmented',
  17387.         fragments: fragments,
  17388.         content: '',
  17389.         bookmark: null,
  17390.         beforeBookmark: null
  17391.       };
  17392.     };
  17393.     var createCompleteLevel = function (content) {
  17394.       return {
  17395.         type: 'complete',
  17396.         fragments: null,
  17397.         content: content,
  17398.         bookmark: null,
  17399.         beforeBookmark: null
  17400.       };
  17401.     };
  17402.     var createFromEditor = function (editor) {
  17403.       var fragments = read$2(editor.getBody());
  17404.       var trimmedFragments = bind(fragments, function (html) {
  17405.         var trimmed = trimInternal(editor.serializer, html);
  17406.         return trimmed.length > 0 ? [trimmed] : [];
  17407.       });
  17408.       var content = trimmedFragments.join('');
  17409.       return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
  17410.     };
  17411.     var applyToEditor = function (editor, level, before) {
  17412.       var bookmark = before ? level.beforeBookmark : level.bookmark;
  17413.       if (level.type === 'fragmented') {
  17414.         write(level.fragments, editor.getBody());
  17415.       } else {
  17416.         editor.setContent(level.content, {
  17417.           format: 'raw',
  17418.           no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  17419.         });
  17420.       }
  17421.       editor.selection.moveToBookmark(bookmark);
  17422.     };
  17423.     var getLevelContent = function (level) {
  17424.       return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  17425.     };
  17426.     var getCleanLevelContent = function (level) {
  17427.       var elm = SugarElement.fromTag('body', lazyTempDocument());
  17428.       set(elm, getLevelContent(level));
  17429.       each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  17430.       return get$3(elm);
  17431.     };
  17432.     var hasEqualContent = function (level1, level2) {
  17433.       return getLevelContent(level1) === getLevelContent(level2);
  17434.     };
  17435.     var hasEqualCleanedContent = function (level1, level2) {
  17436.       return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  17437.     };
  17438.     var isEq$1 = function (level1, level2) {
  17439.       if (!level1 || !level2) {
  17440.         return false;
  17441.       } else if (hasEqualContent(level1, level2)) {
  17442.         return true;
  17443.       } else {
  17444.         return hasEqualCleanedContent(level1, level2);
  17445.       }
  17446.     };
  17447.  
  17448.     var isUnlocked = function (locks) {
  17449.       return locks.get() === 0;
  17450.     };
  17451.  
  17452.     var setTyping = function (undoManager, typing, locks) {
  17453.       if (isUnlocked(locks)) {
  17454.         undoManager.typing = typing;
  17455.       }
  17456.     };
  17457.     var endTyping = function (undoManager, locks) {
  17458.       if (undoManager.typing) {
  17459.         setTyping(undoManager, false, locks);
  17460.         undoManager.add();
  17461.       }
  17462.     };
  17463.     var endTypingLevelIgnoreLocks = function (undoManager) {
  17464.       if (undoManager.typing) {
  17465.         undoManager.typing = false;
  17466.         undoManager.add();
  17467.       }
  17468.     };
  17469.  
  17470.     var beforeChange$1 = function (editor, locks, beforeBookmark) {
  17471.       if (isUnlocked(locks)) {
  17472.         beforeBookmark.set(getUndoBookmark(editor.selection));
  17473.       }
  17474.     };
  17475.     var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17476.       var currentLevel = createFromEditor(editor);
  17477.       level = level || {};
  17478.       level = Tools.extend(level, currentLevel);
  17479.       if (isUnlocked(locks) === false || editor.removed) {
  17480.         return null;
  17481.       }
  17482.       var lastLevel = undoManager.data[index.get()];
  17483.       if (editor.fire('BeforeAddUndo', {
  17484.           level: level,
  17485.           lastLevel: lastLevel,
  17486.           originalEvent: event
  17487.         }).isDefaultPrevented()) {
  17488.         return null;
  17489.       }
  17490.       if (lastLevel && isEq$1(lastLevel, level)) {
  17491.         return null;
  17492.       }
  17493.       if (undoManager.data[index.get()]) {
  17494.         beforeBookmark.get().each(function (bm) {
  17495.           undoManager.data[index.get()].beforeBookmark = bm;
  17496.         });
  17497.       }
  17498.       var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  17499.       if (customUndoRedoLevels) {
  17500.         if (undoManager.data.length > customUndoRedoLevels) {
  17501.           for (var i = 0; i < undoManager.data.length - 1; i++) {
  17502.             undoManager.data[i] = undoManager.data[i + 1];
  17503.           }
  17504.           undoManager.data.length--;
  17505.           index.set(undoManager.data.length);
  17506.         }
  17507.       }
  17508.       level.bookmark = getUndoBookmark(editor.selection);
  17509.       if (index.get() < undoManager.data.length - 1) {
  17510.         undoManager.data.length = index.get() + 1;
  17511.       }
  17512.       undoManager.data.push(level);
  17513.       index.set(undoManager.data.length - 1);
  17514.       var args = {
  17515.         level: level,
  17516.         lastLevel: lastLevel,
  17517.         originalEvent: event
  17518.       };
  17519.       if (index.get() > 0) {
  17520.         editor.setDirty(true);
  17521.         editor.fire('AddUndo', args);
  17522.         editor.fire('change', args);
  17523.       } else {
  17524.         editor.fire('AddUndo', args);
  17525.       }
  17526.       return level;
  17527.     };
  17528.     var clear$1 = function (editor, undoManager, index) {
  17529.       undoManager.data = [];
  17530.       index.set(0);
  17531.       undoManager.typing = false;
  17532.       editor.fire('ClearUndos');
  17533.     };
  17534.     var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  17535.       if (undoManager.transact(callback1)) {
  17536.         var bookmark = undoManager.data[index.get()].bookmark;
  17537.         var lastLevel = undoManager.data[index.get() - 1];
  17538.         applyToEditor(editor, lastLevel, true);
  17539.         if (undoManager.transact(callback2)) {
  17540.           undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  17541.         }
  17542.       }
  17543.     };
  17544.     var redo$1 = function (editor, index, data) {
  17545.       var level;
  17546.       if (index.get() < data.length - 1) {
  17547.         index.set(index.get() + 1);
  17548.         level = data[index.get()];
  17549.         applyToEditor(editor, level, false);
  17550.         editor.setDirty(true);
  17551.         editor.fire('Redo', { level: level });
  17552.       }
  17553.       return level;
  17554.     };
  17555.     var undo$1 = function (editor, undoManager, locks, index) {
  17556.       var level;
  17557.       if (undoManager.typing) {
  17558.         undoManager.add();
  17559.         undoManager.typing = false;
  17560.         setTyping(undoManager, false, locks);
  17561.       }
  17562.       if (index.get() > 0) {
  17563.         index.set(index.get() - 1);
  17564.         level = undoManager.data[index.get()];
  17565.         applyToEditor(editor, level, true);
  17566.         editor.setDirty(true);
  17567.         editor.fire('Undo', { level: level });
  17568.       }
  17569.       return level;
  17570.     };
  17571.     var reset$1 = function (undoManager) {
  17572.       undoManager.clear();
  17573.       undoManager.add();
  17574.     };
  17575.     var hasUndo$1 = function (editor, undoManager, index) {
  17576.       return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  17577.     };
  17578.     var hasRedo$1 = function (undoManager, index) {
  17579.       return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  17580.     };
  17581.     var transact$1 = function (undoManager, locks, callback) {
  17582.       endTyping(undoManager, locks);
  17583.       undoManager.beforeChange();
  17584.       undoManager.ignore(callback);
  17585.       return undoManager.add();
  17586.     };
  17587.     var ignore$1 = function (locks, callback) {
  17588.       try {
  17589.         locks.set(locks.get() + 1);
  17590.         callback();
  17591.       } finally {
  17592.         locks.set(locks.get() - 1);
  17593.       }
  17594.     };
  17595.  
  17596.     var addVisualInternal = function (editor, elm) {
  17597.       var dom = editor.dom;
  17598.       var scope = isNonNullable(elm) ? elm : editor.getBody();
  17599.       if (isUndefined(editor.hasVisual)) {
  17600.         editor.hasVisual = isVisualAidsEnabled(editor);
  17601.       }
  17602.       each$k(dom.select('table,a', scope), function (matchedElm) {
  17603.         switch (matchedElm.nodeName) {
  17604.         case 'TABLE':
  17605.           var cls = getVisualAidsTableClass(editor);
  17606.           var value = dom.getAttrib(matchedElm, 'border');
  17607.           if ((!value || value === '0') && editor.hasVisual) {
  17608.             dom.addClass(matchedElm, cls);
  17609.           } else {
  17610.             dom.removeClass(matchedElm, cls);
  17611.           }
  17612.           break;
  17613.         case 'A':
  17614.           if (!dom.getAttrib(matchedElm, 'href')) {
  17615.             var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  17616.             var cls_1 = getVisualAidsAnchorClass(editor);
  17617.             if (value_1 && editor.hasVisual) {
  17618.               dom.addClass(matchedElm, cls_1);
  17619.             } else {
  17620.               dom.removeClass(matchedElm, cls_1);
  17621.             }
  17622.           }
  17623.           break;
  17624.         }
  17625.       });
  17626.       editor.fire('VisualAid', {
  17627.         element: elm,
  17628.         hasVisual: editor.hasVisual
  17629.       });
  17630.     };
  17631.  
  17632.     var makePlainAdaptor = function (editor) {
  17633.       return {
  17634.         undoManager: {
  17635.           beforeChange: function (locks, beforeBookmark) {
  17636.             return beforeChange$1(editor, locks, beforeBookmark);
  17637.           },
  17638.           add: function (undoManager, index, locks, beforeBookmark, level, event) {
  17639.             return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  17640.           },
  17641.           undo: function (undoManager, locks, index) {
  17642.             return undo$1(editor, undoManager, locks, index);
  17643.           },
  17644.           redo: function (index, data) {
  17645.             return redo$1(editor, index, data);
  17646.           },
  17647.           clear: function (undoManager, index) {
  17648.             return clear$1(editor, undoManager, index);
  17649.           },
  17650.           reset: function (undoManager) {
  17651.             return reset$1(undoManager);
  17652.           },
  17653.           hasUndo: function (undoManager, index) {
  17654.             return hasUndo$1(editor, undoManager, index);
  17655.           },
  17656.           hasRedo: function (undoManager, index) {
  17657.             return hasRedo$1(undoManager, index);
  17658.           },
  17659.           transact: function (undoManager, locks, callback) {
  17660.             return transact$1(undoManager, locks, callback);
  17661.           },
  17662.           ignore: function (locks, callback) {
  17663.             return ignore$1(locks, callback);
  17664.           },
  17665.           extra: function (undoManager, index, callback1, callback2) {
  17666.             return extra$1(editor, undoManager, index, callback1, callback2);
  17667.           }
  17668.         },
  17669.         formatter: {
  17670.           match: function (name, vars, node, similar) {
  17671.             return match$2(editor, name, vars, node, similar);
  17672.           },
  17673.           matchAll: function (names, vars) {
  17674.             return matchAll(editor, names, vars);
  17675.           },
  17676.           matchNode: function (node, name, vars, similar) {
  17677.             return matchNode(editor, node, name, vars, similar);
  17678.           },
  17679.           canApply: function (name) {
  17680.             return canApply(editor, name);
  17681.           },
  17682.           closest: function (names) {
  17683.             return closest(editor, names);
  17684.           },
  17685.           apply: function (name, vars, node) {
  17686.             return applyFormat$1(editor, name, vars, node);
  17687.           },
  17688.           remove: function (name, vars, node, similar) {
  17689.             return remove$1(editor, name, vars, node, similar);
  17690.           },
  17691.           toggle: function (name, vars, node) {
  17692.             return toggle(editor, name, vars, node);
  17693.           },
  17694.           formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  17695.             return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  17696.           }
  17697.         },
  17698.         editor: {
  17699.           getContent: function (args, format) {
  17700.             return getContentInternal(editor, args, format);
  17701.           },
  17702.           setContent: function (content, args) {
  17703.             return setContentInternal(editor, content, args);
  17704.           },
  17705.           insertContent: function (value, details) {
  17706.             return insertHtmlAtCaret(editor, value, details);
  17707.           },
  17708.           addVisual: function (elm) {
  17709.             return addVisualInternal(editor, elm);
  17710.           }
  17711.         },
  17712.         selection: {
  17713.           getContent: function (format, args) {
  17714.             return getSelectedContentInternal(editor, format, args);
  17715.           }
  17716.         },
  17717.         raw: {
  17718.           getModel: function () {
  17719.             return Optional.none();
  17720.           }
  17721.         }
  17722.       };
  17723.     };
  17724.     var makeRtcAdaptor = function (rtcEditor) {
  17725.       var defaultVars = function (vars) {
  17726.         return isObject(vars) ? vars : {};
  17727.       };
  17728.       var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17729.       return {
  17730.         undoManager: {
  17731.           beforeChange: undoManager.beforeChange,
  17732.           add: undoManager.add,
  17733.           undo: undoManager.undo,
  17734.           redo: undoManager.redo,
  17735.           clear: undoManager.clear,
  17736.           reset: undoManager.reset,
  17737.           hasUndo: undoManager.hasUndo,
  17738.           hasRedo: undoManager.hasRedo,
  17739.           transact: function (_undoManager, _locks, fn) {
  17740.             return undoManager.transact(fn);
  17741.           },
  17742.           ignore: function (_locks, callback) {
  17743.             return undoManager.ignore(callback);
  17744.           },
  17745.           extra: function (_undoManager, _index, callback1, callback2) {
  17746.             return undoManager.extra(callback1, callback2);
  17747.           }
  17748.         },
  17749.         formatter: {
  17750.           match: function (name, vars, _node, similar) {
  17751.             return formatter.match(name, defaultVars(vars), similar);
  17752.           },
  17753.           matchAll: formatter.matchAll,
  17754.           matchNode: formatter.matchNode,
  17755.           canApply: function (name) {
  17756.             return formatter.canApply(name);
  17757.           },
  17758.           closest: function (names) {
  17759.             return formatter.closest(names);
  17760.           },
  17761.           apply: function (name, vars, _node) {
  17762.             return formatter.apply(name, defaultVars(vars));
  17763.           },
  17764.           remove: function (name, vars, _node, _similar) {
  17765.             return formatter.remove(name, defaultVars(vars));
  17766.           },
  17767.           toggle: function (name, vars, _node) {
  17768.             return formatter.toggle(name, defaultVars(vars));
  17769.           },
  17770.           formatChanged: function (_rfl, formats, callback, similar, vars) {
  17771.             return formatter.formatChanged(formats, callback, similar, vars);
  17772.           }
  17773.         },
  17774.         editor: {
  17775.           getContent: function (args, _format) {
  17776.             return editor.getContent(args);
  17777.           },
  17778.           setContent: function (content, args) {
  17779.             return editor.setContent(content, args);
  17780.           },
  17781.           insertContent: function (content, _details) {
  17782.             return editor.insertContent(content);
  17783.           },
  17784.           addVisual: editor.addVisual
  17785.         },
  17786.         selection: {
  17787.           getContent: function (_format, args) {
  17788.             return selection.getContent(args);
  17789.           }
  17790.         },
  17791.         raw: {
  17792.           getModel: function () {
  17793.             return Optional.some(raw.getRawModel());
  17794.           }
  17795.         }
  17796.       };
  17797.     };
  17798.     var makeNoopAdaptor = function () {
  17799.       var nul = constant(null);
  17800.       var empty = constant('');
  17801.       return {
  17802.         undoManager: {
  17803.           beforeChange: noop,
  17804.           add: nul,
  17805.           undo: nul,
  17806.           redo: nul,
  17807.           clear: noop,
  17808.           reset: noop,
  17809.           hasUndo: never,
  17810.           hasRedo: never,
  17811.           transact: nul,
  17812.           ignore: noop,
  17813.           extra: noop
  17814.         },
  17815.         formatter: {
  17816.           match: never,
  17817.           matchAll: constant([]),
  17818.           matchNode: constant(undefined),
  17819.           canApply: never,
  17820.           closest: empty,
  17821.           apply: noop,
  17822.           remove: noop,
  17823.           toggle: noop,
  17824.           formatChanged: constant({ unbind: noop })
  17825.         },
  17826.         editor: {
  17827.           getContent: empty,
  17828.           setContent: empty,
  17829.           insertContent: noop,
  17830.           addVisual: noop
  17831.         },
  17832.         selection: { getContent: empty },
  17833.         raw: { getModel: constant(Optional.none()) }
  17834.       };
  17835.     };
  17836.     var isRtc = function (editor) {
  17837.       return has$2(editor.plugins, 'rtc');
  17838.     };
  17839.     var getRtcSetup = function (editor) {
  17840.       return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17841.         return Optional.from(rtcPlugin.setup);
  17842.       });
  17843.     };
  17844.     var setup$i = function (editor) {
  17845.       var editorCast = editor;
  17846.       return getRtcSetup(editor).fold(function () {
  17847.         editorCast.rtcInstance = makePlainAdaptor(editor);
  17848.         return Optional.none();
  17849.       }, function (setup) {
  17850.         editorCast.rtcInstance = makeNoopAdaptor();
  17851.         return Optional.some(function () {
  17852.           return setup().then(function (rtcEditor) {
  17853.             editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17854.             return rtcEditor.rtc.isRemote;
  17855.           });
  17856.         });
  17857.       });
  17858.     };
  17859.     var getRtcInstanceWithFallback = function (editor) {
  17860.       return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17861.     };
  17862.     var getRtcInstanceWithError = function (editor) {
  17863.       var rtcInstance = editor.rtcInstance;
  17864.       if (!rtcInstance) {
  17865.         throw new Error('Failed to get RTC instance not yet initialized.');
  17866.       } else {
  17867.         return rtcInstance;
  17868.       }
  17869.     };
  17870.     var beforeChange = function (editor, locks, beforeBookmark) {
  17871.       getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17872.     };
  17873.     var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17874.       return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17875.     };
  17876.     var undo = function (editor, undoManager, locks, index) {
  17877.       return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17878.     };
  17879.     var redo = function (editor, index, data) {
  17880.       return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17881.     };
  17882.     var clear = function (editor, undoManager, index) {
  17883.       getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17884.     };
  17885.     var reset = function (editor, undoManager) {
  17886.       getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17887.     };
  17888.     var hasUndo = function (editor, undoManager, index) {
  17889.       return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17890.     };
  17891.     var hasRedo = function (editor, undoManager, index) {
  17892.       return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17893.     };
  17894.     var transact = function (editor, undoManager, locks, callback) {
  17895.       return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17896.     };
  17897.     var ignore = function (editor, locks, callback) {
  17898.       getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17899.     };
  17900.     var extra = function (editor, undoManager, index, callback1, callback2) {
  17901.       getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17902.     };
  17903.     var matchFormat = function (editor, name, vars, node, similar) {
  17904.       return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17905.     };
  17906.     var matchAllFormats = function (editor, names, vars) {
  17907.       return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17908.     };
  17909.     var matchNodeFormat = function (editor, node, name, vars, similar) {
  17910.       return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17911.     };
  17912.     var canApplyFormat = function (editor, name) {
  17913.       return getRtcInstanceWithError(editor).formatter.canApply(name);
  17914.     };
  17915.     var closestFormat = function (editor, names) {
  17916.       return getRtcInstanceWithError(editor).formatter.closest(names);
  17917.     };
  17918.     var applyFormat = function (editor, name, vars, node) {
  17919.       getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17920.     };
  17921.     var removeFormat = function (editor, name, vars, node, similar) {
  17922.       getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17923.     };
  17924.     var toggleFormat = function (editor, name, vars, node) {
  17925.       getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17926.     };
  17927.     var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17928.       return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17929.     };
  17930.     var getContent$2 = function (editor, args, format) {
  17931.       return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17932.     };
  17933.     var setContent$2 = function (editor, content, args) {
  17934.       return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17935.     };
  17936.     var insertContent = function (editor, value, details) {
  17937.       return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17938.     };
  17939.     var getSelectedContent = function (editor, format, args) {
  17940.       return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17941.     };
  17942.     var addVisual$1 = function (editor, elm) {
  17943.       return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17944.     };
  17945.  
  17946.     var getContent$1 = function (editor, args) {
  17947.       if (args === void 0) {
  17948.         args = {};
  17949.       }
  17950.       var format = args.format ? args.format : 'html';
  17951.       return getSelectedContent(editor, format, args);
  17952.     };
  17953.  
  17954.     var removeEmpty = function (text) {
  17955.       if (text.dom.length === 0) {
  17956.         remove$7(text);
  17957.         return Optional.none();
  17958.       } else {
  17959.         return Optional.some(text);
  17960.       }
  17961.     };
  17962.     var walkPastBookmark = function (node, start) {
  17963.       return node.filter(function (elm) {
  17964.         return BookmarkManager.isBookmarkNode(elm.dom);
  17965.       }).bind(start ? nextSibling : prevSibling);
  17966.     };
  17967.     var merge = function (outer, inner, rng, start) {
  17968.       var outerElm = outer.dom;
  17969.       var innerElm = inner.dom;
  17970.       var oldLength = start ? outerElm.length : innerElm.length;
  17971.       if (start) {
  17972.         mergeTextNodes(outerElm, innerElm, false, !start);
  17973.         rng.setStart(innerElm, oldLength);
  17974.       } else {
  17975.         mergeTextNodes(innerElm, outerElm, false, !start);
  17976.         rng.setEnd(innerElm, oldLength);
  17977.       }
  17978.     };
  17979.     var normalizeTextIfRequired = function (inner, start) {
  17980.       parent(inner).each(function (root) {
  17981.         var text = inner.dom;
  17982.         if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17983.           normalizeWhitespaceAfter(text, 0);
  17984.         } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17985.           normalizeWhitespaceBefore(text, text.length);
  17986.         }
  17987.       });
  17988.     };
  17989.     var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17990.       outerNode.bind(function (outer) {
  17991.         var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17992.         normalizer(outer.dom, start ? outer.dom.length : 0);
  17993.         return innerNode.filter(isText$8).map(function (inner) {
  17994.           return merge(outer, inner, rng, start);
  17995.         });
  17996.       }).orThunk(function () {
  17997.         var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17998.         return innerTextNode.map(function (inner) {
  17999.           return normalizeTextIfRequired(inner, start);
  18000.         });
  18001.       });
  18002.     };
  18003.     var rngSetContent = function (rng, fragment) {
  18004.       var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  18005.       var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  18006.       rng.deleteContents();
  18007.       rng.insertNode(fragment);
  18008.       var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  18009.       var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  18010.       mergeAndNormalizeText(prevText, firstChild, rng, true);
  18011.       mergeAndNormalizeText(nextText, lastChild, rng, false);
  18012.       rng.collapse(false);
  18013.     };
  18014.     var setupArgs = function (args, content) {
  18015.       return __assign(__assign({ format: 'html' }, args), {
  18016.         set: true,
  18017.         selection: true,
  18018.         content: content
  18019.       });
  18020.     };
  18021.     var cleanContent = function (editor, args) {
  18022.       if (args.format !== 'raw') {
  18023.         var rng = editor.selection.getRng();
  18024.         var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  18025.         var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  18026.         var node = editor.parser.parse(args.content, __assign(__assign({
  18027.           isRootContent: true,
  18028.           forced_root_block: false
  18029.         }, contextArgs), args));
  18030.         return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  18031.       } else {
  18032.         return args.content;
  18033.       }
  18034.     };
  18035.     var setContent$1 = function (editor, content, args) {
  18036.       if (args === void 0) {
  18037.         args = {};
  18038.       }
  18039.       var defaultedArgs = setupArgs(args, content);
  18040.       var updatedArgs = defaultedArgs;
  18041.       if (!defaultedArgs.no_events) {
  18042.         var eventArgs = editor.fire('BeforeSetContent', defaultedArgs);
  18043.         if (eventArgs.isDefaultPrevented()) {
  18044.           editor.fire('SetContent', eventArgs);
  18045.           return;
  18046.         } else {
  18047.           updatedArgs = eventArgs;
  18048.         }
  18049.       }
  18050.       updatedArgs.content = cleanContent(editor, updatedArgs);
  18051.       var rng = editor.selection.getRng();
  18052.       rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  18053.       editor.selection.setRng(rng);
  18054.       scrollRangeIntoView(editor, rng);
  18055.       if (!updatedArgs.no_events) {
  18056.         editor.fire('SetContent', updatedArgs);
  18057.       }
  18058.     };
  18059.  
  18060.     var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  18061.       if (callbackMap && has$2(callbackMap, selector)) {
  18062.         var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  18063.           return cb !== callback;
  18064.         });
  18065.         if (newCallbacks.length === 0) {
  18066.           delete callbackMap[selector];
  18067.         } else {
  18068.           callbackMap[selector] = newCallbacks;
  18069.         }
  18070.       }
  18071.     };
  18072.     function SelectorChanged (dom, editor) {
  18073.       var selectorChangedData;
  18074.       var currentSelectors;
  18075.       var findMatchingNode = function (selector, nodes) {
  18076.         return find$3(nodes, function (node) {
  18077.           return dom.is(node, selector);
  18078.         });
  18079.       };
  18080.       var getParents = function (elem) {
  18081.         return dom.getParents(elem, null, dom.getRoot());
  18082.       };
  18083.       return {
  18084.         selectorChangedWithUnbind: function (selector, callback) {
  18085.           if (!selectorChangedData) {
  18086.             selectorChangedData = {};
  18087.             currentSelectors = {};
  18088.             editor.on('NodeChange', function (e) {
  18089.               var node = e.element;
  18090.               var parents = getParents(node);
  18091.               var matchedSelectors = {};
  18092.               Tools.each(selectorChangedData, function (callbacks, selector) {
  18093.                 findMatchingNode(selector, parents).each(function (node) {
  18094.                   if (!currentSelectors[selector]) {
  18095.                     each$k(callbacks, function (callback) {
  18096.                       callback(true, {
  18097.                         node: node,
  18098.                         selector: selector,
  18099.                         parents: parents
  18100.                       });
  18101.                     });
  18102.                     currentSelectors[selector] = callbacks;
  18103.                   }
  18104.                   matchedSelectors[selector] = callbacks;
  18105.                 });
  18106.               });
  18107.               Tools.each(currentSelectors, function (callbacks, selector) {
  18108.                 if (!matchedSelectors[selector]) {
  18109.                   delete currentSelectors[selector];
  18110.                   Tools.each(callbacks, function (callback) {
  18111.                     callback(false, {
  18112.                       node: node,
  18113.                       selector: selector,
  18114.                       parents: parents
  18115.                     });
  18116.                   });
  18117.                 }
  18118.               });
  18119.             });
  18120.           }
  18121.           if (!selectorChangedData[selector]) {
  18122.             selectorChangedData[selector] = [];
  18123.           }
  18124.           selectorChangedData[selector].push(callback);
  18125.           findMatchingNode(selector, getParents(editor.selection.getStart())).each(function () {
  18126.             currentSelectors[selector] = selectorChangedData[selector];
  18127.           });
  18128.           return {
  18129.             unbind: function () {
  18130.               deleteFromCallbackMap(selectorChangedData, selector, callback);
  18131.               deleteFromCallbackMap(currentSelectors, selector, callback);
  18132.             }
  18133.           };
  18134.         }
  18135.       };
  18136.     }
  18137.  
  18138.     var isNativeIeSelection = function (rng) {
  18139.       return !!rng.select;
  18140.     };
  18141.     var isAttachedToDom = function (node) {
  18142.       return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  18143.     };
  18144.     var isValidRange = function (rng) {
  18145.       if (!rng) {
  18146.         return false;
  18147.       } else if (isNativeIeSelection(rng)) {
  18148.         return true;
  18149.       } else {
  18150.         return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  18151.       }
  18152.     };
  18153.     var EditorSelection = function (dom, win, serializer, editor) {
  18154.       var selectedRange;
  18155.       var explicitRange;
  18156.       var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  18157.       var setCursorLocation = function (node, offset) {
  18158.         var rng = dom.createRng();
  18159.         if (isNonNullable(node) && isNonNullable(offset)) {
  18160.           rng.setStart(node, offset);
  18161.           rng.setEnd(node, offset);
  18162.           setRng(rng);
  18163.           collapse(false);
  18164.         } else {
  18165.           moveEndPoint(dom, rng, editor.getBody(), true);
  18166.           setRng(rng);
  18167.         }
  18168.       };
  18169.       var getContent = function (args) {
  18170.         return getContent$1(editor, args);
  18171.       };
  18172.       var setContent = function (content, args) {
  18173.         return setContent$1(editor, content, args);
  18174.       };
  18175.       var getStart$1 = function (real) {
  18176.         return getStart(editor.getBody(), getRng$1(), real);
  18177.       };
  18178.       var getEnd$1 = function (real) {
  18179.         return getEnd(editor.getBody(), getRng$1(), real);
  18180.       };
  18181.       var getBookmark = function (type, normalized) {
  18182.         return bookmarkManager.getBookmark(type, normalized);
  18183.       };
  18184.       var moveToBookmark = function (bookmark) {
  18185.         return bookmarkManager.moveToBookmark(bookmark);
  18186.       };
  18187.       var select$1 = function (node, content) {
  18188.         select(dom, node, content).each(setRng);
  18189.         return node;
  18190.       };
  18191.       var isCollapsed = function () {
  18192.         var rng = getRng$1(), sel = getSel();
  18193.         if (!rng || rng.item) {
  18194.           return false;
  18195.         }
  18196.         if (rng.compareEndPoints) {
  18197.           return rng.compareEndPoints('StartToEnd', rng) === 0;
  18198.         }
  18199.         return !sel || rng.collapsed;
  18200.       };
  18201.       var collapse = function (toStart) {
  18202.         var rng = getRng$1();
  18203.         rng.collapse(!!toStart);
  18204.         setRng(rng);
  18205.       };
  18206.       var getSel = function () {
  18207.         return win.getSelection ? win.getSelection() : win.document.selection;
  18208.       };
  18209.       var getRng$1 = function () {
  18210.         var selection, rng, elm;
  18211.         var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  18212.           try {
  18213.             return sourceRange.compareBoundaryPoints(how, destinationRange);
  18214.           } catch (ex) {
  18215.             return -1;
  18216.           }
  18217.         };
  18218.         var doc = win.document;
  18219.         if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  18220.           var bookmark = getRng(editor);
  18221.           if (bookmark.isSome()) {
  18222.             return bookmark.map(function (r) {
  18223.               return processRanges(editor, [r])[0];
  18224.             }).getOr(doc.createRange());
  18225.           }
  18226.         }
  18227.         try {
  18228.           if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  18229.             if (selection.rangeCount > 0) {
  18230.               rng = selection.getRangeAt(0);
  18231.             } else {
  18232.               rng = selection.createRange ? selection.createRange() : doc.createRange();
  18233.             }
  18234.             rng = processRanges(editor, [rng])[0];
  18235.           }
  18236.         } catch (ex) {
  18237.         }
  18238.         if (!rng) {
  18239.           rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  18240.         }
  18241.         if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  18242.           elm = dom.getRoot();
  18243.           rng.setStart(elm, 0);
  18244.           rng.setEnd(elm, 0);
  18245.         }
  18246.         if (selectedRange && explicitRange) {
  18247.           if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  18248.             rng = explicitRange;
  18249.           } else {
  18250.             selectedRange = null;
  18251.             explicitRange = null;
  18252.           }
  18253.         }
  18254.         return rng;
  18255.       };
  18256.       var setRng = function (rng, forward) {
  18257.         var node;
  18258.         if (!isValidRange(rng)) {
  18259.           return;
  18260.         }
  18261.         var ieRange = isNativeIeSelection(rng) ? rng : null;
  18262.         if (ieRange) {
  18263.           explicitRange = null;
  18264.           try {
  18265.             ieRange.select();
  18266.           } catch (ex) {
  18267.           }
  18268.           return;
  18269.         }
  18270.         var sel = getSel();
  18271.         var evt = editor.fire('SetSelectionRange', {
  18272.           range: rng,
  18273.           forward: forward
  18274.         });
  18275.         rng = evt.range;
  18276.         if (sel) {
  18277.           explicitRange = rng;
  18278.           try {
  18279.             sel.removeAllRanges();
  18280.             sel.addRange(rng);
  18281.           } catch (ex) {
  18282.           }
  18283.           if (forward === false && sel.extend) {
  18284.             sel.collapse(rng.endContainer, rng.endOffset);
  18285.             sel.extend(rng.startContainer, rng.startOffset);
  18286.           }
  18287.           selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  18288.         }
  18289.         if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  18290.           if (rng.endOffset - rng.startOffset < 2) {
  18291.             if (rng.startContainer.hasChildNodes()) {
  18292.               node = rng.startContainer.childNodes[rng.startOffset];
  18293.               if (node && node.tagName === 'IMG') {
  18294.                 sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  18295.                 if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  18296.                   sel.setBaseAndExtent(node, 0, node, 1);
  18297.                 }
  18298.               }
  18299.             }
  18300.           }
  18301.         }
  18302.         editor.fire('AfterSetSelectionRange', {
  18303.           range: rng,
  18304.           forward: forward
  18305.         });
  18306.       };
  18307.       var setNode = function (elm) {
  18308.         setContent(dom.getOuterHTML(elm));
  18309.         return elm;
  18310.       };
  18311.       var getNode$1 = function () {
  18312.         return getNode(editor.getBody(), getRng$1());
  18313.       };
  18314.       var getSelectedBlocks$1 = function (startElm, endElm) {
  18315.         return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  18316.       };
  18317.       var isForward = function () {
  18318.         var sel = getSel();
  18319.         var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  18320.         var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  18321.         if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  18322.           return true;
  18323.         }
  18324.         var anchorRange = dom.createRng();
  18325.         anchorRange.setStart(anchorNode, sel.anchorOffset);
  18326.         anchorRange.collapse(true);
  18327.         var focusRange = dom.createRng();
  18328.         focusRange.setStart(focusNode, sel.focusOffset);
  18329.         focusRange.collapse(true);
  18330.         return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  18331.       };
  18332.       var normalize = function () {
  18333.         var rng = getRng$1();
  18334.         var sel = getSel();
  18335.         if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  18336.           var normRng = normalize$2(dom, rng);
  18337.           normRng.each(function (normRng) {
  18338.             setRng(normRng, isForward());
  18339.           });
  18340.           return normRng.getOr(rng);
  18341.         }
  18342.         return rng;
  18343.       };
  18344.       var selectorChanged = function (selector, callback) {
  18345.         selectorChangedWithUnbind(selector, callback);
  18346.         return exports;
  18347.       };
  18348.       var getScrollContainer = function () {
  18349.         var scrollContainer;
  18350.         var node = dom.getRoot();
  18351.         while (node && node.nodeName !== 'BODY') {
  18352.           if (node.scrollHeight > node.clientHeight) {
  18353.             scrollContainer = node;
  18354.             break;
  18355.           }
  18356.           node = node.parentNode;
  18357.         }
  18358.         return scrollContainer;
  18359.       };
  18360.       var scrollIntoView = function (elm, alignToTop) {
  18361.         if (isNonNullable(elm)) {
  18362.           scrollElementIntoView(editor, elm, alignToTop);
  18363.         } else {
  18364.           scrollRangeIntoView(editor, getRng$1(), alignToTop);
  18365.         }
  18366.       };
  18367.       var placeCaretAt = function (clientX, clientY) {
  18368.         return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  18369.       };
  18370.       var getBoundingClientRect = function () {
  18371.         var rng = getRng$1();
  18372.         return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  18373.       };
  18374.       var destroy = function () {
  18375.         win = selectedRange = explicitRange = null;
  18376.         controlSelection.destroy();
  18377.       };
  18378.       var exports = {
  18379.         bookmarkManager: null,
  18380.         controlSelection: null,
  18381.         dom: dom,
  18382.         win: win,
  18383.         serializer: serializer,
  18384.         editor: editor,
  18385.         collapse: collapse,
  18386.         setCursorLocation: setCursorLocation,
  18387.         getContent: getContent,
  18388.         setContent: setContent,
  18389.         getBookmark: getBookmark,
  18390.         moveToBookmark: moveToBookmark,
  18391.         select: select$1,
  18392.         isCollapsed: isCollapsed,
  18393.         isForward: isForward,
  18394.         setNode: setNode,
  18395.         getNode: getNode$1,
  18396.         getSel: getSel,
  18397.         setRng: setRng,
  18398.         getRng: getRng$1,
  18399.         getStart: getStart$1,
  18400.         getEnd: getEnd$1,
  18401.         getSelectedBlocks: getSelectedBlocks$1,
  18402.         normalize: normalize,
  18403.         selectorChanged: selectorChanged,
  18404.         selectorChangedWithUnbind: selectorChangedWithUnbind,
  18405.         getScrollContainer: getScrollContainer,
  18406.         scrollIntoView: scrollIntoView,
  18407.         placeCaretAt: placeCaretAt,
  18408.         getBoundingClientRect: getBoundingClientRect,
  18409.         destroy: destroy
  18410.       };
  18411.       var bookmarkManager = BookmarkManager(exports);
  18412.       var controlSelection = ControlSelection(exports, editor);
  18413.       exports.bookmarkManager = bookmarkManager;
  18414.       exports.controlSelection = controlSelection;
  18415.       return exports;
  18416.     };
  18417.  
  18418.     var removeAttrs = function (node, names) {
  18419.       each$k(names, function (name) {
  18420.         node.attr(name, null);
  18421.       });
  18422.     };
  18423.     var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  18424.       domParser.addNodeFilter('font', function (nodes) {
  18425.         each$k(nodes, function (node) {
  18426.           var props = styles.parse(node.attr('style'));
  18427.           var color = node.attr('color');
  18428.           var face = node.attr('face');
  18429.           var size = node.attr('size');
  18430.           if (color) {
  18431.             props.color = color;
  18432.           }
  18433.           if (face) {
  18434.             props['font-family'] = face;
  18435.           }
  18436.           if (size) {
  18437.             props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  18438.           }
  18439.           node.name = 'span';
  18440.           node.attr('style', styles.serialize(props));
  18441.           removeAttrs(node, [
  18442.             'color',
  18443.             'face',
  18444.             'size'
  18445.           ]);
  18446.         });
  18447.       });
  18448.     };
  18449.     var addStrikeToSpanFilter = function (domParser, styles) {
  18450.       domParser.addNodeFilter('strike', function (nodes) {
  18451.         each$k(nodes, function (node) {
  18452.           var props = styles.parse(node.attr('style'));
  18453.           props['text-decoration'] = 'line-through';
  18454.           node.name = 'span';
  18455.           node.attr('style', styles.serialize(props));
  18456.         });
  18457.       });
  18458.     };
  18459.     var addFilters = function (domParser, settings) {
  18460.       var styles = Styles();
  18461.       if (settings.convert_fonts_to_spans) {
  18462.         addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  18463.       }
  18464.       addStrikeToSpanFilter(domParser, styles);
  18465.     };
  18466.     var register$2 = function (domParser, settings) {
  18467.       if (settings.inline_styles) {
  18468.         addFilters(domParser, settings);
  18469.       }
  18470.     };
  18471.  
  18472.     var blobUriToBlob = function (url) {
  18473.       return new promiseObj(function (resolve, reject) {
  18474.         var rejectWithError = function () {
  18475.           reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  18476.         };
  18477.         try {
  18478.           var xhr_1 = new XMLHttpRequest();
  18479.           xhr_1.open('GET', url, true);
  18480.           xhr_1.responseType = 'blob';
  18481.           xhr_1.onload = function () {
  18482.             if (xhr_1.status === 200) {
  18483.               resolve(xhr_1.response);
  18484.             } else {
  18485.               rejectWithError();
  18486.             }
  18487.           };
  18488.           xhr_1.onerror = rejectWithError;
  18489.           xhr_1.send();
  18490.         } catch (ex) {
  18491.           rejectWithError();
  18492.         }
  18493.       });
  18494.     };
  18495.     var parseDataUri = function (uri) {
  18496.       var type;
  18497.       var uriParts = decodeURIComponent(uri).split(',');
  18498.       var matches = /data:([^;]+)/.exec(uriParts[0]);
  18499.       if (matches) {
  18500.         type = matches[1];
  18501.       }
  18502.       return {
  18503.         type: type,
  18504.         data: uriParts[1]
  18505.       };
  18506.     };
  18507.     var buildBlob = function (type, data) {
  18508.       var str;
  18509.       try {
  18510.         str = atob(data);
  18511.       } catch (e) {
  18512.         return Optional.none();
  18513.       }
  18514.       var arr = new Uint8Array(str.length);
  18515.       for (var i = 0; i < arr.length; i++) {
  18516.         arr[i] = str.charCodeAt(i);
  18517.       }
  18518.       return Optional.some(new Blob([arr], { type: type }));
  18519.     };
  18520.     var dataUriToBlob = function (uri) {
  18521.       return new promiseObj(function (resolve) {
  18522.         var _a = parseDataUri(uri), type = _a.type, data = _a.data;
  18523.         buildBlob(type, data).fold(function () {
  18524.           return resolve(new Blob([]));
  18525.         }, resolve);
  18526.       });
  18527.     };
  18528.     var uriToBlob = function (url) {
  18529.       if (url.indexOf('blob:') === 0) {
  18530.         return blobUriToBlob(url);
  18531.       }
  18532.       if (url.indexOf('data:') === 0) {
  18533.         return dataUriToBlob(url);
  18534.       }
  18535.       return null;
  18536.     };
  18537.     var blobToDataUri = function (blob) {
  18538.       return new promiseObj(function (resolve) {
  18539.         var reader = new FileReader();
  18540.         reader.onloadend = function () {
  18541.           resolve(reader.result);
  18542.         };
  18543.         reader.readAsDataURL(blob);
  18544.       });
  18545.     };
  18546.  
  18547.     var count$1 = 0;
  18548.     var uniqueId = function (prefix) {
  18549.       return (prefix || 'blobid') + count$1++;
  18550.     };
  18551.     var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  18552.       var base64, blobInfo;
  18553.       if (img.src.indexOf('blob:') === 0) {
  18554.         blobInfo = blobCache.getByUri(img.src);
  18555.         if (blobInfo) {
  18556.           resolve({
  18557.             image: img,
  18558.             blobInfo: blobInfo
  18559.           });
  18560.         } else {
  18561.           uriToBlob(img.src).then(function (blob) {
  18562.             blobToDataUri(blob).then(function (dataUri) {
  18563.               base64 = parseDataUri(dataUri).data;
  18564.               blobInfo = blobCache.create(uniqueId(), blob, base64);
  18565.               blobCache.add(blobInfo);
  18566.               resolve({
  18567.                 image: img,
  18568.                 blobInfo: blobInfo
  18569.               });
  18570.             });
  18571.           }, function (err) {
  18572.             reject(err);
  18573.           });
  18574.         }
  18575.         return;
  18576.       }
  18577.       var _a = parseDataUri(img.src), data = _a.data, type = _a.type;
  18578.       base64 = data;
  18579.       blobInfo = blobCache.getByData(base64, type);
  18580.       if (blobInfo) {
  18581.         resolve({
  18582.           image: img,
  18583.           blobInfo: blobInfo
  18584.         });
  18585.       } else {
  18586.         uriToBlob(img.src).then(function (blob) {
  18587.           blobInfo = blobCache.create(uniqueId(), blob, base64);
  18588.           blobCache.add(blobInfo);
  18589.           resolve({
  18590.             image: img,
  18591.             blobInfo: blobInfo
  18592.           });
  18593.         }, function (err) {
  18594.           reject(err);
  18595.         });
  18596.       }
  18597.     };
  18598.     var getAllImages = function (elm) {
  18599.       return elm ? from(elm.getElementsByTagName('img')) : [];
  18600.     };
  18601.     var ImageScanner = function (uploadStatus, blobCache) {
  18602.       var cachedPromises = {};
  18603.       var findAll = function (elm, predicate) {
  18604.         if (!predicate) {
  18605.           predicate = always;
  18606.         }
  18607.         var images = filter$4(getAllImages(elm), function (img) {
  18608.           var src = img.src;
  18609.           if (!Env.fileApi) {
  18610.             return false;
  18611.           }
  18612.           if (img.hasAttribute('data-mce-bogus')) {
  18613.             return false;
  18614.           }
  18615.           if (img.hasAttribute('data-mce-placeholder')) {
  18616.             return false;
  18617.           }
  18618.           if (!src || src === Env.transparentSrc) {
  18619.             return false;
  18620.           }
  18621.           if (src.indexOf('blob:') === 0) {
  18622.             return !uploadStatus.isUploaded(src) && predicate(img);
  18623.           }
  18624.           if (src.indexOf('data:') === 0) {
  18625.             return predicate(img);
  18626.           }
  18627.           return false;
  18628.         });
  18629.         var promises = map$3(images, function (img) {
  18630.           if (cachedPromises[img.src] !== undefined) {
  18631.             return new promiseObj(function (resolve) {
  18632.               cachedPromises[img.src].then(function (imageInfo) {
  18633.                 if (typeof imageInfo === 'string') {
  18634.                   return imageInfo;
  18635.                 }
  18636.                 resolve({
  18637.                   image: img,
  18638.                   blobInfo: imageInfo.blobInfo
  18639.                 });
  18640.               });
  18641.             });
  18642.           }
  18643.           var newPromise = new promiseObj(function (resolve, reject) {
  18644.             imageToBlobInfo(blobCache, img, resolve, reject);
  18645.           }).then(function (result) {
  18646.             delete cachedPromises[result.image.src];
  18647.             return result;
  18648.           }).catch(function (error) {
  18649.             delete cachedPromises[img.src];
  18650.             return error;
  18651.           });
  18652.           cachedPromises[img.src] = newPromise;
  18653.           return newPromise;
  18654.         });
  18655.         return promiseObj.all(promises);
  18656.       };
  18657.       return { findAll: findAll };
  18658.     };
  18659.  
  18660.     var paddEmptyNode = function (settings, args, blockElements, node) {
  18661.       var brPreferred = settings.padd_empty_with_br || args.insert;
  18662.       if (brPreferred && blockElements[node.name]) {
  18663.         node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18664.       } else {
  18665.         node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18666.       }
  18667.     };
  18668.     var isPaddedWithNbsp = function (node) {
  18669.       return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18670.     };
  18671.     var hasOnlyChild = function (node, name) {
  18672.       return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18673.     };
  18674.     var isPadded = function (schema, node) {
  18675.       var rule = schema.getElementRule(node.name);
  18676.       return rule && rule.paddEmpty;
  18677.     };
  18678.     var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18679.       return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18680.         return isPadded(schema, node);
  18681.       });
  18682.     };
  18683.     var isLineBreakNode = function (node, blockElements) {
  18684.       return node && (has$2(blockElements, node.name) || node.name === 'br');
  18685.     };
  18686.  
  18687.     var isBogusImage = function (img) {
  18688.       return isNonNullable(img.attr('data-mce-bogus'));
  18689.     };
  18690.     var isInternalImageSource = function (img) {
  18691.       return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18692.     };
  18693.     var isValidDataImg = function (img, settings) {
  18694.       if (settings.images_dataimg_filter) {
  18695.         var imgElem_1 = new Image();
  18696.         imgElem_1.src = img.attr('src');
  18697.         each$j(img.attributes.map, function (value, key) {
  18698.           imgElem_1.setAttribute(key, value);
  18699.         });
  18700.         return settings.images_dataimg_filter(imgElem_1);
  18701.       } else {
  18702.         return true;
  18703.       }
  18704.     };
  18705.     var registerBase64ImageFilter = function (parser, settings) {
  18706.       var blobCache = settings.blob_cache;
  18707.       var processImage = function (img) {
  18708.         var inputSrc = img.attr('src');
  18709.         if (isInternalImageSource(img) || isBogusImage(img)) {
  18710.           return;
  18711.         }
  18712.         parseDataUri$1(inputSrc).filter(function () {
  18713.           return isValidDataImg(img, settings);
  18714.         }).bind(function (_a) {
  18715.           var type = _a.type, data = _a.data;
  18716.           return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18717.             return buildBlob(type, data).map(function (blob) {
  18718.               var blobInfo = blobCache.create(uniqueId(), blob, data);
  18719.               blobCache.add(blobInfo);
  18720.               return blobInfo;
  18721.             });
  18722.           });
  18723.         }).each(function (blobInfo) {
  18724.           img.attr('src', blobInfo.blobUri());
  18725.         });
  18726.       };
  18727.       if (blobCache) {
  18728.         parser.addAttributeFilter('src', function (nodes) {
  18729.           return each$k(nodes, processImage);
  18730.         });
  18731.       }
  18732.     };
  18733.     var register$1 = function (parser, settings) {
  18734.       var schema = parser.schema;
  18735.       if (settings.remove_trailing_brs) {
  18736.         parser.addNodeFilter('br', function (nodes, _, args) {
  18737.           var i;
  18738.           var l = nodes.length;
  18739.           var node;
  18740.           var blockElements = Tools.extend({}, schema.getBlockElements());
  18741.           var nonEmptyElements = schema.getNonEmptyElements();
  18742.           var parent, lastParent, prev, prevName;
  18743.           var whiteSpaceElements = schema.getWhiteSpaceElements();
  18744.           var elementRule, textNode;
  18745.           blockElements.body = 1;
  18746.           for (i = 0; i < l; i++) {
  18747.             node = nodes[i];
  18748.             parent = node.parent;
  18749.             if (blockElements[node.parent.name] && node === parent.lastChild) {
  18750.               prev = node.prev;
  18751.               while (prev) {
  18752.                 prevName = prev.name;
  18753.                 if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18754.                   if (prevName === 'br') {
  18755.                     node = null;
  18756.                   }
  18757.                   break;
  18758.                 }
  18759.                 prev = prev.prev;
  18760.               }
  18761.               if (node) {
  18762.                 node.remove();
  18763.                 if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18764.                   elementRule = schema.getElementRule(parent.name);
  18765.                   if (elementRule) {
  18766.                     if (elementRule.removeEmpty) {
  18767.                       parent.remove();
  18768.                     } else if (elementRule.paddEmpty) {
  18769.                       paddEmptyNode(settings, args, blockElements, parent);
  18770.                     }
  18771.                   }
  18772.                 }
  18773.               }
  18774.             } else {
  18775.               lastParent = node;
  18776.               while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18777.                 lastParent = parent;
  18778.                 if (blockElements[parent.name]) {
  18779.                   break;
  18780.                 }
  18781.                 parent = parent.parent;
  18782.               }
  18783.               if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18784.                 textNode = new AstNode('#text', 3);
  18785.                 textNode.value = nbsp;
  18786.                 node.replace(textNode);
  18787.               }
  18788.             }
  18789.           }
  18790.         });
  18791.       }
  18792.       parser.addAttributeFilter('href', function (nodes) {
  18793.         var i = nodes.length;
  18794.         var appendRel = function (rel) {
  18795.           var parts = rel.split(' ').filter(function (p) {
  18796.             return p.length > 0;
  18797.           });
  18798.           return parts.concat(['noopener']).sort().join(' ');
  18799.         };
  18800.         var addNoOpener = function (rel) {
  18801.           var newRel = rel ? Tools.trim(rel) : '';
  18802.           if (!/\b(noopener)\b/g.test(newRel)) {
  18803.             return appendRel(newRel);
  18804.           } else {
  18805.             return newRel;
  18806.           }
  18807.         };
  18808.         if (!settings.allow_unsafe_link_target) {
  18809.           while (i--) {
  18810.             var node = nodes[i];
  18811.             if (node.name === 'a' && node.attr('target') === '_blank') {
  18812.               node.attr('rel', addNoOpener(node.attr('rel')));
  18813.             }
  18814.           }
  18815.         }
  18816.       });
  18817.       if (!settings.allow_html_in_named_anchor) {
  18818.         parser.addAttributeFilter('id,name', function (nodes) {
  18819.           var i = nodes.length, sibling, prevSibling, parent, node;
  18820.           while (i--) {
  18821.             node = nodes[i];
  18822.             if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18823.               parent = node.parent;
  18824.               sibling = node.lastChild;
  18825.               do {
  18826.                 prevSibling = sibling.prev;
  18827.                 parent.insert(sibling, node);
  18828.                 sibling = prevSibling;
  18829.               } while (sibling);
  18830.             }
  18831.           }
  18832.         });
  18833.       }
  18834.       if (settings.fix_list_elements) {
  18835.         parser.addNodeFilter('ul,ol', function (nodes) {
  18836.           var i = nodes.length, node, parentNode;
  18837.           while (i--) {
  18838.             node = nodes[i];
  18839.             parentNode = node.parent;
  18840.             if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18841.               if (node.prev && node.prev.name === 'li') {
  18842.                 node.prev.append(node);
  18843.               } else {
  18844.                 var li = new AstNode('li', 1);
  18845.                 li.attr('style', 'list-style-type: none');
  18846.                 node.wrap(li);
  18847.               }
  18848.             }
  18849.           }
  18850.         });
  18851.       }
  18852.       if (settings.validate && schema.getValidClasses()) {
  18853.         parser.addAttributeFilter('class', function (nodes) {
  18854.           var validClasses = schema.getValidClasses();
  18855.           var i = nodes.length;
  18856.           while (i--) {
  18857.             var node = nodes[i];
  18858.             var classList = node.attr('class').split(' ');
  18859.             var classValue = '';
  18860.             for (var ci = 0; ci < classList.length; ci++) {
  18861.               var className = classList[ci];
  18862.               var valid = false;
  18863.               var validClassesMap = validClasses['*'];
  18864.               if (validClassesMap && validClassesMap[className]) {
  18865.                 valid = true;
  18866.               }
  18867.               validClassesMap = validClasses[node.name];
  18868.               if (!valid && validClassesMap && validClassesMap[className]) {
  18869.                 valid = true;
  18870.               }
  18871.               if (valid) {
  18872.                 if (classValue) {
  18873.                   classValue += ' ';
  18874.                 }
  18875.                 classValue += className;
  18876.               }
  18877.             }
  18878.             if (!classValue.length) {
  18879.               classValue = null;
  18880.             }
  18881.             node.attr('class', classValue);
  18882.           }
  18883.         });
  18884.       }
  18885.       registerBase64ImageFilter(parser, settings);
  18886.     };
  18887.  
  18888.     var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18889.     var DomParser = function (settings, schema) {
  18890.       if (schema === void 0) {
  18891.         schema = Schema();
  18892.       }
  18893.       var nodeFilters = {};
  18894.       var attributeFilters = [];
  18895.       var matchedNodes = {};
  18896.       var matchedAttributes = {};
  18897.       settings = settings || {};
  18898.       settings.validate = 'validate' in settings ? settings.validate : true;
  18899.       settings.root_name = settings.root_name || 'body';
  18900.       var fixInvalidChildren = function (nodes) {
  18901.         var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18902.         var nonEmptyElements = schema.getNonEmptyElements();
  18903.         var whitespaceElements = schema.getWhiteSpaceElements();
  18904.         var textBlockElements = schema.getTextBlockElements();
  18905.         var specialElements = schema.getSpecialElements();
  18906.         var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18907.           if (originalNodeParent === void 0) {
  18908.             originalNodeParent = node.parent;
  18909.           }
  18910.           if (specialElements[node.name]) {
  18911.             node.empty().remove();
  18912.           } else {
  18913.             var children = node.children();
  18914.             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18915.               var childNode = children_1[_i];
  18916.               if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18917.                 removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18918.               }
  18919.             }
  18920.             node.unwrap();
  18921.           }
  18922.         };
  18923.         for (var ni = 0; ni < nodes.length; ni++) {
  18924.           var node = nodes[ni];
  18925.           var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18926.           if (!node.parent || node.fixed) {
  18927.             continue;
  18928.           }
  18929.           if (textBlockElements[node.name] && node.parent.name === 'li') {
  18930.             var sibling = node.next;
  18931.             while (sibling) {
  18932.               if (textBlockElements[sibling.name]) {
  18933.                 sibling.name = 'li';
  18934.                 sibling.fixed = true;
  18935.                 node.parent.insert(sibling, node.parent);
  18936.               } else {
  18937.                 break;
  18938.               }
  18939.               sibling = sibling.next;
  18940.             }
  18941.             node.unwrap();
  18942.             continue;
  18943.           }
  18944.           var parents = [node];
  18945.           for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18946.             parents.push(parent_1);
  18947.           }
  18948.           if (parent_1 && parents.length > 1) {
  18949.             if (schema.isValidChild(parent_1.name, node.name)) {
  18950.               parents.reverse();
  18951.               newParent = filterNode(parents[0].clone());
  18952.               var currentNode = newParent;
  18953.               for (var i = 0; i < parents.length - 1; i++) {
  18954.                 if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18955.                   tempNode = filterNode(parents[i].clone());
  18956.                   currentNode.append(tempNode);
  18957.                 } else {
  18958.                   tempNode = currentNode;
  18959.                 }
  18960.                 for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  18961.                   var nextNode = childNode.next;
  18962.                   tempNode.append(childNode);
  18963.                   childNode = nextNode;
  18964.                 }
  18965.                 currentNode = tempNode;
  18966.               }
  18967.               if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  18968.                 parent_1.insert(newParent, parents[0], true);
  18969.                 parent_1.insert(node, newParent);
  18970.               } else {
  18971.                 parent_1.insert(node, parents[0], true);
  18972.               }
  18973.               parent_1 = parents[0];
  18974.               if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  18975.                 parent_1.empty().remove();
  18976.               }
  18977.             } else {
  18978.               removeOrUnwrapInvalidNode(node);
  18979.             }
  18980.           } else if (node.parent) {
  18981.             if (node.name === 'li') {
  18982.               var sibling = node.prev;
  18983.               if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18984.                 sibling.append(node);
  18985.                 continue;
  18986.               }
  18987.               sibling = node.next;
  18988.               if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  18989.                 sibling.insert(node, sibling.firstChild, true);
  18990.                 continue;
  18991.               }
  18992.               node.wrap(filterNode(new AstNode('ul', 1)));
  18993.               continue;
  18994.             }
  18995.             if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  18996.               node.wrap(filterNode(new AstNode('div', 1)));
  18997.             } else {
  18998.               removeOrUnwrapInvalidNode(node);
  18999.             }
  19000.           }
  19001.         }
  19002.       };
  19003.       var filterNode = function (node) {
  19004.         var name = node.name;
  19005.         if (name in nodeFilters) {
  19006.           var list = matchedNodes[name];
  19007.           if (list) {
  19008.             list.push(node);
  19009.           } else {
  19010.             matchedNodes[name] = [node];
  19011.           }
  19012.         }
  19013.         var i = attributeFilters.length;
  19014.         while (i--) {
  19015.           var attrName = attributeFilters[i].name;
  19016.           if (attrName in node.attributes.map) {
  19017.             var list = matchedAttributes[attrName];
  19018.             if (list) {
  19019.               list.push(node);
  19020.             } else {
  19021.               matchedAttributes[attrName] = [node];
  19022.             }
  19023.           }
  19024.         }
  19025.         return node;
  19026.       };
  19027.       var addNodeFilter = function (name, callback) {
  19028.         each$6(explode$2(name), function (name) {
  19029.           var list = nodeFilters[name];
  19030.           if (!list) {
  19031.             nodeFilters[name] = list = [];
  19032.           }
  19033.           list.push(callback);
  19034.         });
  19035.       };
  19036.       var getNodeFilters = function () {
  19037.         var out = [];
  19038.         for (var name_1 in nodeFilters) {
  19039.           if (has$2(nodeFilters, name_1)) {
  19040.             out.push({
  19041.               name: name_1,
  19042.               callbacks: nodeFilters[name_1]
  19043.             });
  19044.           }
  19045.         }
  19046.         return out;
  19047.       };
  19048.       var addAttributeFilter = function (name, callback) {
  19049.         each$6(explode$2(name), function (name) {
  19050.           var i;
  19051.           for (i = 0; i < attributeFilters.length; i++) {
  19052.             if (attributeFilters[i].name === name) {
  19053.               attributeFilters[i].callbacks.push(callback);
  19054.               return;
  19055.             }
  19056.           }
  19057.           attributeFilters.push({
  19058.             name: name,
  19059.             callbacks: [callback]
  19060.           });
  19061.         });
  19062.       };
  19063.       var getAttributeFilters = function () {
  19064.         return [].concat(attributeFilters);
  19065.       };
  19066.       var parse = function (html, args) {
  19067.         var nodes, i, l, fi, fl, list, name;
  19068.         var invalidChildren = [];
  19069.         var node;
  19070.         var getRootBlockName = function (name) {
  19071.           if (name === false) {
  19072.             return '';
  19073.           } else if (name === true) {
  19074.             return 'p';
  19075.           } else {
  19076.             return name;
  19077.           }
  19078.         };
  19079.         args = args || {};
  19080.         matchedNodes = {};
  19081.         matchedAttributes = {};
  19082.         var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  19083.         var nonEmptyElements = schema.getNonEmptyElements();
  19084.         var children = schema.children;
  19085.         var validate = settings.validate;
  19086.         var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  19087.         var rootBlockName = getRootBlockName(forcedRootBlockName);
  19088.         var whiteSpaceElements = schema.getWhiteSpaceElements();
  19089.         var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  19090.         var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  19091.         var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  19092.         var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  19093.         var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  19094.         var addRootBlocks = function () {
  19095.           var node = rootNode.firstChild, rootBlockNode = null;
  19096.           var trim = function (rootBlock) {
  19097.             if (rootBlock) {
  19098.               node = rootBlock.firstChild;
  19099.               if (node && node.type === 3) {
  19100.                 node.value = node.value.replace(startWhiteSpaceRegExp, '');
  19101.               }
  19102.               node = rootBlock.lastChild;
  19103.               if (node && node.type === 3) {
  19104.                 node.value = node.value.replace(endWhiteSpaceRegExp, '');
  19105.               }
  19106.             }
  19107.           };
  19108.           if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  19109.             return;
  19110.           }
  19111.           while (node) {
  19112.             var next = node.next;
  19113.             if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  19114.               if (!rootBlockNode) {
  19115.                 rootBlockNode = createNode(rootBlockName, 1);
  19116.                 rootBlockNode.attr(settings.forced_root_block_attrs);
  19117.                 rootNode.insert(rootBlockNode, node);
  19118.                 rootBlockNode.append(node);
  19119.               } else {
  19120.                 rootBlockNode.append(node);
  19121.               }
  19122.             } else {
  19123.               trim(rootBlockNode);
  19124.               rootBlockNode = null;
  19125.             }
  19126.             node = next;
  19127.           }
  19128.           trim(rootBlockNode);
  19129.         };
  19130.         var createNode = function (name, type) {
  19131.           var node = new AstNode(name, type);
  19132.           var list;
  19133.           if (name in nodeFilters) {
  19134.             list = matchedNodes[name];
  19135.             if (list) {
  19136.               list.push(node);
  19137.             } else {
  19138.               matchedNodes[name] = [node];
  19139.             }
  19140.           }
  19141.           return node;
  19142.         };
  19143.         var removeWhitespaceBefore = function (node) {
  19144.           var blockElements = schema.getBlockElements();
  19145.           for (var textNode = node.prev; textNode && textNode.type === 3;) {
  19146.             var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  19147.             if (textVal.length > 0) {
  19148.               textNode.value = textVal;
  19149.               return;
  19150.             }
  19151.             var textNodeNext = textNode.next;
  19152.             if (textNodeNext) {
  19153.               if (textNodeNext.type === 3 && textNodeNext.value.length) {
  19154.                 textNode = textNode.prev;
  19155.                 continue;
  19156.               }
  19157.               if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  19158.                 textNode = textNode.prev;
  19159.                 continue;
  19160.               }
  19161.             }
  19162.             var sibling = textNode.prev;
  19163.             textNode.remove();
  19164.             textNode = sibling;
  19165.           }
  19166.         };
  19167.         var cloneAndExcludeBlocks = function (input) {
  19168.           var output = {};
  19169.           for (var name_2 in input) {
  19170.             if (name_2 !== 'li' && name_2 !== 'p') {
  19171.               output[name_2] = input[name_2];
  19172.             }
  19173.           }
  19174.           return output;
  19175.         };
  19176.         var parser = SaxParser({
  19177.           validate: validate,
  19178.           document: settings.document,
  19179.           allow_html_data_urls: settings.allow_html_data_urls,
  19180.           allow_svg_data_urls: settings.allow_svg_data_urls,
  19181.           allow_script_urls: settings.allow_script_urls,
  19182.           allow_conditional_comments: settings.allow_conditional_comments,
  19183.           preserve_cdata: settings.preserve_cdata,
  19184.           self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  19185.           cdata: function (text) {
  19186.             node.append(createNode('#cdata', 4)).value = text;
  19187.           },
  19188.           text: function (text, raw) {
  19189.             var textNode;
  19190.             if (!isInWhiteSpacePreservedElement) {
  19191.               text = text.replace(allWhiteSpaceRegExp, ' ');
  19192.               if (isLineBreakNode(node.lastChild, blockElements)) {
  19193.                 text = text.replace(startWhiteSpaceRegExp, '');
  19194.               }
  19195.             }
  19196.             if (text.length !== 0) {
  19197.               textNode = createNode('#text', 3);
  19198.               textNode.raw = !!raw;
  19199.               node.append(textNode).value = text;
  19200.             }
  19201.           },
  19202.           comment: function (text) {
  19203.             node.append(createNode('#comment', 8)).value = text;
  19204.           },
  19205.           pi: function (name, text) {
  19206.             node.append(createNode(name, 7)).value = text;
  19207.             removeWhitespaceBefore(node);
  19208.           },
  19209.           doctype: function (text) {
  19210.             var newNode = node.append(createNode('#doctype', 10));
  19211.             newNode.value = text;
  19212.             removeWhitespaceBefore(node);
  19213.           },
  19214.           start: function (name, attrs, empty) {
  19215.             var elementRule = validate ? schema.getElementRule(name) : {};
  19216.             if (elementRule) {
  19217.               var newNode = createNode(elementRule.outputName || name, 1);
  19218.               newNode.attributes = attrs;
  19219.               newNode.shortEnded = empty;
  19220.               node.append(newNode);
  19221.               var parent_2 = children[node.name];
  19222.               if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  19223.                 invalidChildren.push(newNode);
  19224.               }
  19225.               var attrFiltersLen = attributeFilters.length;
  19226.               while (attrFiltersLen--) {
  19227.                 var attrName = attributeFilters[attrFiltersLen].name;
  19228.                 if (attrName in attrs.map) {
  19229.                   list = matchedAttributes[attrName];
  19230.                   if (list) {
  19231.                     list.push(newNode);
  19232.                   } else {
  19233.                     matchedAttributes[attrName] = [newNode];
  19234.                   }
  19235.                 }
  19236.               }
  19237.               if (blockElements[name]) {
  19238.                 removeWhitespaceBefore(newNode);
  19239.               }
  19240.               if (!empty) {
  19241.                 node = newNode;
  19242.               }
  19243.               if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19244.                 isInWhiteSpacePreservedElement = true;
  19245.               }
  19246.             }
  19247.           },
  19248.           end: function (name) {
  19249.             var textNode, text, sibling, tempNode;
  19250.             var elementRule = validate ? schema.getElementRule(name) : {};
  19251.             if (elementRule) {
  19252.               if (blockElements[name]) {
  19253.                 if (!isInWhiteSpacePreservedElement) {
  19254.                   textNode = node.firstChild;
  19255.                   if (textNode && textNode.type === 3) {
  19256.                     text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19257.                     if (text.length > 0) {
  19258.                       textNode.value = text;
  19259.                       textNode = textNode.next;
  19260.                     } else {
  19261.                       sibling = textNode.next;
  19262.                       textNode.remove();
  19263.                       textNode = sibling;
  19264.                       while (textNode && textNode.type === 3) {
  19265.                         text = textNode.value;
  19266.                         sibling = textNode.next;
  19267.                         if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19268.                           textNode.remove();
  19269.                           textNode = sibling;
  19270.                         }
  19271.                         textNode = sibling;
  19272.                       }
  19273.                     }
  19274.                   }
  19275.                   textNode = node.lastChild;
  19276.                   if (textNode && textNode.type === 3) {
  19277.                     text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19278.                     if (text.length > 0) {
  19279.                       textNode.value = text;
  19280.                       textNode = textNode.prev;
  19281.                     } else {
  19282.                       sibling = textNode.prev;
  19283.                       textNode.remove();
  19284.                       textNode = sibling;
  19285.                       while (textNode && textNode.type === 3) {
  19286.                         text = textNode.value;
  19287.                         sibling = textNode.prev;
  19288.                         if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19289.                           textNode.remove();
  19290.                           textNode = sibling;
  19291.                         }
  19292.                         textNode = sibling;
  19293.                       }
  19294.                     }
  19295.                   }
  19296.                 }
  19297.               }
  19298.               if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19299.                 isInWhiteSpacePreservedElement = false;
  19300.               }
  19301.               if (elementRule.removeEmpty && isEmpty(schema, nonEmptyElements, whiteSpaceElements, node)) {
  19302.                 tempNode = node.parent;
  19303.                 if (blockElements[node.name]) {
  19304.                   node.empty().remove();
  19305.                 } else {
  19306.                   node.unwrap();
  19307.                 }
  19308.                 node = tempNode;
  19309.                 return;
  19310.               }
  19311.               if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isEmpty(schema, nonEmptyElements, whiteSpaceElements, node))) {
  19312.                 paddEmptyNode(settings, args, blockElements, node);
  19313.               }
  19314.               node = node.parent;
  19315.             }
  19316.           }
  19317.         }, schema);
  19318.         var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19319.         parser.parse(html, args.format);
  19320.         if (validate && invalidChildren.length) {
  19321.           if (!args.context) {
  19322.             fixInvalidChildren(invalidChildren);
  19323.           } else {
  19324.             args.invalid = true;
  19325.           }
  19326.         }
  19327.         if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19328.           addRootBlocks();
  19329.         }
  19330.         if (!args.invalid) {
  19331.           for (name in matchedNodes) {
  19332.             if (!has$2(matchedNodes, name)) {
  19333.               continue;
  19334.             }
  19335.             list = nodeFilters[name];
  19336.             nodes = matchedNodes[name];
  19337.             fi = nodes.length;
  19338.             while (fi--) {
  19339.               if (!nodes[fi].parent) {
  19340.                 nodes.splice(fi, 1);
  19341.               }
  19342.             }
  19343.             for (i = 0, l = list.length; i < l; i++) {
  19344.               list[i](nodes, name, args);
  19345.             }
  19346.           }
  19347.           for (i = 0, l = attributeFilters.length; i < l; i++) {
  19348.             list = attributeFilters[i];
  19349.             if (list.name in matchedAttributes) {
  19350.               nodes = matchedAttributes[list.name];
  19351.               fi = nodes.length;
  19352.               while (fi--) {
  19353.                 if (!nodes[fi].parent) {
  19354.                   nodes.splice(fi, 1);
  19355.                 }
  19356.               }
  19357.               for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19358.                 list.callbacks[fi](nodes, list.name, args);
  19359.               }
  19360.             }
  19361.           }
  19362.         }
  19363.         return rootNode;
  19364.       };
  19365.       var exports = {
  19366.         schema: schema,
  19367.         addAttributeFilter: addAttributeFilter,
  19368.         getAttributeFilters: getAttributeFilters,
  19369.         addNodeFilter: addNodeFilter,
  19370.         getNodeFilters: getNodeFilters,
  19371.         filterNode: filterNode,
  19372.         parse: parse
  19373.       };
  19374.       register$1(exports, settings);
  19375.       register$2(exports, settings);
  19376.       return exports;
  19377.     };
  19378.  
  19379.     var register = function (htmlParser, settings, dom) {
  19380.       htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19381.         var i = nodes.length;
  19382.         while (i--) {
  19383.           var node = nodes[i];
  19384.           node.attr('tabindex', node.attr('data-mce-tabindex'));
  19385.           node.attr(name, null);
  19386.         }
  19387.       });
  19388.       htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19389.         var internalName = 'data-mce-' + name;
  19390.         var urlConverter = settings.url_converter;
  19391.         var urlConverterScope = settings.url_converter_scope;
  19392.         var i = nodes.length;
  19393.         while (i--) {
  19394.           var node = nodes[i];
  19395.           var value = node.attr(internalName);
  19396.           if (value !== undefined) {
  19397.             node.attr(name, value.length > 0 ? value : null);
  19398.             node.attr(internalName, null);
  19399.           } else {
  19400.             value = node.attr(name);
  19401.             if (name === 'style') {
  19402.               value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19403.             } else if (urlConverter) {
  19404.               value = urlConverter.call(urlConverterScope, value, name, node.name);
  19405.             }
  19406.             node.attr(name, value.length > 0 ? value : null);
  19407.           }
  19408.         }
  19409.       });
  19410.       htmlParser.addAttributeFilter('class', function (nodes) {
  19411.         var i = nodes.length;
  19412.         while (i--) {
  19413.           var node = nodes[i];
  19414.           var value = node.attr('class');
  19415.           if (value) {
  19416.             value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19417.             node.attr('class', value.length > 0 ? value : null);
  19418.           }
  19419.         }
  19420.       });
  19421.       htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19422.         var i = nodes.length;
  19423.         while (i--) {
  19424.           var node = nodes[i];
  19425.           if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19426.             var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19427.               return !isZwsp(firstChild.value);
  19428.             });
  19429.             if (hasChildren) {
  19430.               node.unwrap();
  19431.             } else {
  19432.               node.remove();
  19433.             }
  19434.           }
  19435.         }
  19436.       });
  19437.       htmlParser.addNodeFilter('noscript', function (nodes) {
  19438.         var i = nodes.length;
  19439.         while (i--) {
  19440.           var node = nodes[i].firstChild;
  19441.           if (node) {
  19442.             node.value = Entities.decode(node.value);
  19443.           }
  19444.         }
  19445.       });
  19446.       htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19447.         var trim = function (value) {
  19448.           return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n').replace(/^[\r\n]*|[\r\n]*$/g, '').replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '').replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
  19449.         };
  19450.         var i = nodes.length;
  19451.         while (i--) {
  19452.           var node = nodes[i];
  19453.           var value = node.firstChild ? node.firstChild.value : '';
  19454.           if (name === 'script') {
  19455.             var type = node.attr('type');
  19456.             if (type) {
  19457.               node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19458.             }
  19459.             if (settings.element_format === 'xhtml' && value.length > 0) {
  19460.               node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19461.             }
  19462.           } else {
  19463.             if (settings.element_format === 'xhtml' && value.length > 0) {
  19464.               node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19465.             }
  19466.           }
  19467.         }
  19468.       });
  19469.       htmlParser.addNodeFilter('#comment', function (nodes) {
  19470.         var i = nodes.length;
  19471.         while (i--) {
  19472.           var node = nodes[i];
  19473.           if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19474.             node.name = '#cdata';
  19475.             node.type = 4;
  19476.             node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19477.           } else if (node.value.indexOf('mce:protected ') === 0) {
  19478.             node.name = '#text';
  19479.             node.type = 3;
  19480.             node.raw = true;
  19481.             node.value = unescape(node.value).substr(14);
  19482.           }
  19483.         }
  19484.       });
  19485.       htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19486.         var i = nodes.length;
  19487.         while (i--) {
  19488.           var node = nodes[i];
  19489.           if (node.type === 7) {
  19490.             node.remove();
  19491.           } else if (node.type === 1) {
  19492.             if (name === 'input' && !node.attr('type')) {
  19493.               node.attr('type', 'text');
  19494.             }
  19495.           }
  19496.         }
  19497.       });
  19498.       htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19499.         each$k(nodes, function (node) {
  19500.           if (node.attr('data-mce-type') === 'format-caret') {
  19501.             if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19502.               node.remove();
  19503.             } else {
  19504.               node.unwrap();
  19505.             }
  19506.           }
  19507.         });
  19508.       });
  19509.       htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,' + 'data-mce-selected,data-mce-expando,' + 'data-mce-type,data-mce-resize,data-mce-placeholder', function (nodes, name) {
  19510.         var i = nodes.length;
  19511.         while (i--) {
  19512.           nodes[i].attr(name, null);
  19513.         }
  19514.       });
  19515.     };
  19516.     var trimTrailingBr = function (rootNode) {
  19517.       var isBr = function (node) {
  19518.         return node && node.name === 'br';
  19519.       };
  19520.       var brNode1 = rootNode.lastChild;
  19521.       if (isBr(brNode1)) {
  19522.         var brNode2 = brNode1.prev;
  19523.         if (isBr(brNode2)) {
  19524.           brNode1.remove();
  19525.           brNode2.remove();
  19526.         }
  19527.       }
  19528.     };
  19529.  
  19530.     var preProcess = function (editor, node, args) {
  19531.       var oldDoc;
  19532.       var dom = editor.dom;
  19533.       var clonedNode = node.cloneNode(true);
  19534.       var impl = document.implementation;
  19535.       if (impl.createHTMLDocument) {
  19536.         var doc_1 = impl.createHTMLDocument('');
  19537.         Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19538.           doc_1.body.appendChild(doc_1.importNode(node, true));
  19539.         });
  19540.         if (clonedNode.nodeName !== 'BODY') {
  19541.           clonedNode = doc_1.body.firstChild;
  19542.         } else {
  19543.           clonedNode = doc_1.body;
  19544.         }
  19545.         oldDoc = dom.doc;
  19546.         dom.doc = doc_1;
  19547.       }
  19548.       firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19549.       if (oldDoc) {
  19550.         dom.doc = oldDoc;
  19551.       }
  19552.       return clonedNode;
  19553.     };
  19554.     var shouldFireEvent = function (editor, args) {
  19555.       return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19556.     };
  19557.     var process = function (editor, node, args) {
  19558.       return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19559.     };
  19560.  
  19561.     var addTempAttr = function (htmlParser, tempAttrs, name) {
  19562.       if (Tools.inArray(tempAttrs, name) === -1) {
  19563.         htmlParser.addAttributeFilter(name, function (nodes, name) {
  19564.           var i = nodes.length;
  19565.           while (i--) {
  19566.             nodes[i].attr(name, null);
  19567.           }
  19568.         });
  19569.         tempAttrs.push(name);
  19570.       }
  19571.     };
  19572.     var postProcess = function (editor, args, content) {
  19573.       if (!args.no_events && editor) {
  19574.         var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19575.         return outArgs.content;
  19576.       } else {
  19577.         return content;
  19578.       }
  19579.     };
  19580.     var getHtmlFromNode = function (dom, node, args) {
  19581.       var html = trim$2(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19582.       return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19583.     };
  19584.     var parseHtml = function (htmlParser, html, args) {
  19585.       var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19586.       var rootNode = htmlParser.parse(html, parserArgs);
  19587.       trimTrailingBr(rootNode);
  19588.       return rootNode;
  19589.     };
  19590.     var serializeNode = function (settings, schema, node) {
  19591.       var htmlSerializer = HtmlSerializer(settings, schema);
  19592.       return htmlSerializer.serialize(node);
  19593.     };
  19594.     var toHtml = function (editor, settings, schema, rootNode, args) {
  19595.       var content = serializeNode(settings, schema, rootNode);
  19596.       return postProcess(editor, args, content);
  19597.     };
  19598.     var DomSerializerImpl = function (settings, editor) {
  19599.       var tempAttrs = ['data-mce-selected'];
  19600.       var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19601.       var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19602.       settings.entity_encoding = settings.entity_encoding || 'named';
  19603.       settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19604.       var htmlParser = DomParser(settings, schema);
  19605.       register(htmlParser, settings, dom);
  19606.       var serialize = function (node, parserArgs) {
  19607.         if (parserArgs === void 0) {
  19608.           parserArgs = {};
  19609.         }
  19610.         var args = __assign({ format: 'html' }, parserArgs);
  19611.         var targetNode = process(editor, node, args);
  19612.         var html = getHtmlFromNode(dom, targetNode, args);
  19613.         var rootNode = parseHtml(htmlParser, html, args);
  19614.         return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19615.       };
  19616.       return {
  19617.         schema: schema,
  19618.         addNodeFilter: htmlParser.addNodeFilter,
  19619.         addAttributeFilter: htmlParser.addAttributeFilter,
  19620.         serialize: serialize,
  19621.         addRules: schema.addValidElements,
  19622.         setRules: schema.setValidElements,
  19623.         addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19624.         getTempAttrs: constant(tempAttrs),
  19625.         getNodeFilters: htmlParser.getNodeFilters,
  19626.         getAttributeFilters: htmlParser.getAttributeFilters
  19627.       };
  19628.     };
  19629.  
  19630.     var DomSerializer = function (settings, editor) {
  19631.       var domSerializer = DomSerializerImpl(settings, editor);
  19632.       return {
  19633.         schema: domSerializer.schema,
  19634.         addNodeFilter: domSerializer.addNodeFilter,
  19635.         addAttributeFilter: domSerializer.addAttributeFilter,
  19636.         serialize: domSerializer.serialize,
  19637.         addRules: domSerializer.addRules,
  19638.         setRules: domSerializer.setRules,
  19639.         addTempAttr: domSerializer.addTempAttr,
  19640.         getTempAttrs: domSerializer.getTempAttrs,
  19641.         getNodeFilters: domSerializer.getNodeFilters,
  19642.         getAttributeFilters: domSerializer.getAttributeFilters
  19643.       };
  19644.     };
  19645.  
  19646.     var defaultFormat = 'html';
  19647.     var getContent = function (editor, args) {
  19648.       if (args === void 0) {
  19649.         args = {};
  19650.       }
  19651.       var format = args.format ? args.format : defaultFormat;
  19652.       return getContent$2(editor, args, format);
  19653.     };
  19654.  
  19655.     var setContent = function (editor, content, args) {
  19656.       if (args === void 0) {
  19657.         args = {};
  19658.       }
  19659.       return setContent$2(editor, content, args);
  19660.     };
  19661.  
  19662.     var DOM$7 = DOMUtils.DOM;
  19663.     var restoreOriginalStyles = function (editor) {
  19664.       DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19665.     };
  19666.     var safeDestroy = function (x) {
  19667.       return Optional.from(x).each(function (x) {
  19668.         return x.destroy();
  19669.       });
  19670.     };
  19671.     var clearDomReferences = function (editor) {
  19672.       editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19673.       editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19674.       editor.iframeElement = editor.targetElm = null;
  19675.       if (editor.selection) {
  19676.         editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19677.       }
  19678.     };
  19679.     var restoreForm = function (editor) {
  19680.       var form = editor.formElement;
  19681.       if (form) {
  19682.         if (form._mceOldSubmit) {
  19683.           form.submit = form._mceOldSubmit;
  19684.           form._mceOldSubmit = null;
  19685.         }
  19686.         DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19687.       }
  19688.     };
  19689.     var remove = function (editor) {
  19690.       if (!editor.removed) {
  19691.         var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19692.         var body = editor.getBody();
  19693.         var element = editor.getElement();
  19694.         if (body) {
  19695.           editor.save({ is_removing: true });
  19696.         }
  19697.         editor.removed = true;
  19698.         editor.unbindAllNativeEvents();
  19699.         if (editor.hasHiddenInput && element) {
  19700.           DOM$7.remove(element.nextSibling);
  19701.         }
  19702.         fireRemove(editor);
  19703.         editor.editorManager.remove(editor);
  19704.         if (!editor.inline && body) {
  19705.           restoreOriginalStyles(editor);
  19706.         }
  19707.         fireDetach(editor);
  19708.         DOM$7.remove(editor.getContainer());
  19709.         safeDestroy(_selectionOverrides);
  19710.         safeDestroy(editorUpload);
  19711.         editor.destroy();
  19712.       }
  19713.     };
  19714.     var destroy = function (editor, automatic) {
  19715.       var selection = editor.selection, dom = editor.dom;
  19716.       if (editor.destroyed) {
  19717.         return;
  19718.       }
  19719.       if (!automatic && !editor.removed) {
  19720.         editor.remove();
  19721.         return;
  19722.       }
  19723.       if (!automatic) {
  19724.         editor.editorManager.off('beforeunload', editor._beforeUnload);
  19725.         if (editor.theme && editor.theme.destroy) {
  19726.           editor.theme.destroy();
  19727.         }
  19728.         safeDestroy(selection);
  19729.         safeDestroy(dom);
  19730.       }
  19731.       restoreForm(editor);
  19732.       clearDomReferences(editor);
  19733.       editor.destroyed = true;
  19734.     };
  19735.  
  19736.     var deep = function (old, nu) {
  19737.       var bothObjects = isObject(old) && isObject(nu);
  19738.       return bothObjects ? deepMerge(old, nu) : nu;
  19739.     };
  19740.     var baseMerge = function (merger) {
  19741.       return function () {
  19742.         var objects = [];
  19743.         for (var _i = 0; _i < arguments.length; _i++) {
  19744.           objects[_i] = arguments[_i];
  19745.         }
  19746.         if (objects.length === 0) {
  19747.           throw new Error('Can\'t merge zero objects');
  19748.         }
  19749.         var ret = {};
  19750.         for (var j = 0; j < objects.length; j++) {
  19751.           var curObject = objects[j];
  19752.           for (var key in curObject) {
  19753.             if (has$2(curObject, key)) {
  19754.               ret[key] = merger(ret[key], curObject[key]);
  19755.             }
  19756.           }
  19757.         }
  19758.         return ret;
  19759.       };
  19760.     };
  19761.     var deepMerge = baseMerge(deep);
  19762.  
  19763.     var deprecatedSettings = ('autoresize_on_init,content_editable_state,convert_fonts_to_spans,inline_styles,padd_empty_with_br,block_elements,' + 'boolean_attributes,editor_deselector,editor_selector,elements,file_browser_callback_types,filepicker_validator_handler,' + 'force_hex_style_colors,force_p_newlines,gecko_spellcheck,images_dataimg_filter,media_scripts,mode,move_caret_before_on_enter_elements,' + 'non_empty_elements,self_closing_elements,short_ended_elements,special,spellchecker_select_languages,spellchecker_whitelist,' + 'tab_focus,table_responsive_width,text_block_elements,text_inline_elements,toolbar_drawer,types,validate,whitespace_elements,' + 'paste_word_valid_elements,paste_retain_style_properties,paste_convert_word_fake_lists').split(',');
  19764.     var deprecatedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  19765.     var movedToPremiumPlugins = 'imagetools,toc'.split(',');
  19766.     var getDeprecatedSettings = function (settings) {
  19767.       var settingNames = filter$4(deprecatedSettings, function (setting) {
  19768.         return has$2(settings, setting);
  19769.       });
  19770.       var forcedRootBlock = settings.forced_root_block;
  19771.       if (forcedRootBlock === false || forcedRootBlock === '') {
  19772.         settingNames.push('forced_root_block (false only)');
  19773.       }
  19774.       return sort(settingNames);
  19775.     };
  19776.     var getDeprecatedPlugins = function (settings) {
  19777.       var plugins = Tools.makeMap(settings.plugins, ' ');
  19778.       var hasPlugin = function (plugin) {
  19779.         return has$2(plugins, plugin);
  19780.       };
  19781.       var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function (plugin) {
  19782.         return hasPlugin(plugin) ? [plugin + ' (moving to premium)'] : [];
  19783.       }), true);
  19784.       return sort(pluginNames);
  19785.     };
  19786.     var logDeprecationsWarning = function (rawSettings, finalSettings) {
  19787.       var deprecatedSettings = getDeprecatedSettings(rawSettings);
  19788.       var deprecatedPlugins = getDeprecatedPlugins(finalSettings);
  19789.       var hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  19790.       var hasDeprecatedSettings = deprecatedSettings.length > 0;
  19791.       var isLegacyMobileTheme = finalSettings.theme === 'mobile';
  19792.       if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
  19793.         var listJoiner = '\n- ';
  19794.         var themesMessage = isLegacyMobileTheme ? '\n\nThemes:' + listJoiner + 'mobile' : '';
  19795.         var pluginsMessage = hasDeprecatedPlugins ? '\n\nPlugins:' + listJoiner + deprecatedPlugins.join(listJoiner) : '';
  19796.         var settingsMessage = hasDeprecatedSettings ? '\n\nSettings:' + listJoiner + deprecatedSettings.join(listJoiner) : '';
  19797.         console.warn('The following deprecated features are currently enabled, these will be removed in TinyMCE 6.0. ' + 'See https://www.tiny.cloud/docs/release-notes/6.0-upcoming-changes/ for more information.' + themesMessage + pluginsMessage + settingsMessage);
  19798.       }
  19799.     };
  19800.  
  19801.     var sectionResult = function (sections, settings) {
  19802.       return {
  19803.         sections: constant(sections),
  19804.         settings: constant(settings)
  19805.       };
  19806.     };
  19807.     var deviceDetection = detect().deviceType;
  19808.     var isTouch = deviceDetection.isTouch();
  19809.     var isPhone = deviceDetection.isPhone();
  19810.     var isTablet = deviceDetection.isTablet();
  19811.     var legacyMobilePlugins = [
  19812.       'lists',
  19813.       'autolink',
  19814.       'autosave'
  19815.     ];
  19816.     var defaultTouchSettings = {
  19817.       table_grid: false,
  19818.       object_resizing: false,
  19819.       resize: false
  19820.     };
  19821.     var normalizePlugins = function (plugins) {
  19822.       var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19823.       var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$4);
  19824.       return filter$4(trimmedPlugins, function (item) {
  19825.         return item.length > 0;
  19826.       });
  19827.     };
  19828.     var filterLegacyMobilePlugins = function (plugins) {
  19829.       return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19830.     };
  19831.     var extractSections = function (keys, settings) {
  19832.       var result = bifilter(settings, function (value, key) {
  19833.         return contains$3(keys, key);
  19834.       });
  19835.       return sectionResult(result.t, result.f);
  19836.     };
  19837.     var getSection = function (sectionResult, name, defaults) {
  19838.       if (defaults === void 0) {
  19839.         defaults = {};
  19840.       }
  19841.       var sections = sectionResult.sections();
  19842.       var sectionSettings = get$9(sections, name).getOr({});
  19843.       return Tools.extend({}, defaults, sectionSettings);
  19844.     };
  19845.     var hasSection = function (sectionResult, name) {
  19846.       return has$2(sectionResult.sections(), name);
  19847.     };
  19848.     var isSectionTheme = function (sectionResult, name, theme) {
  19849.       var section = sectionResult.sections();
  19850.       return hasSection(sectionResult, name) && section[name].theme === theme;
  19851.     };
  19852.     var getSectionConfig = function (sectionResult, name) {
  19853.       return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19854.     };
  19855.     var getToolbarMode = function (settings, defaultVal) {
  19856.       return get$9(settings, 'toolbar_mode').orThunk(function () {
  19857.         return get$9(settings, 'toolbar_drawer').map(function (val) {
  19858.           return val === false ? 'wrap' : val;
  19859.         });
  19860.       }).getOr(defaultVal);
  19861.     };
  19862.     var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19863.       var baseDefaults = {
  19864.         id: id,
  19865.         theme: 'silver',
  19866.         toolbar_mode: getToolbarMode(settings, 'floating'),
  19867.         plugins: '',
  19868.         document_base_url: documentBaseUrl,
  19869.         add_form_submit_trigger: true,
  19870.         submit_patch: true,
  19871.         add_unload_trigger: true,
  19872.         convert_urls: true,
  19873.         relative_urls: true,
  19874.         remove_script_host: true,
  19875.         object_resizing: true,
  19876.         doctype: '<!DOCTYPE html>',
  19877.         visual: true,
  19878.         font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19879.         forced_root_block: 'p',
  19880.         hidden_input: true,
  19881.         inline_styles: true,
  19882.         convert_fonts_to_spans: true,
  19883.         indent: true,
  19884.         indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  19885.         indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' + 'tfoot,tbody,tr,section,summary,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
  19886.         entity_encoding: 'named',
  19887.         url_converter: editor.convertURL,
  19888.         url_converter_scope: editor
  19889.       };
  19890.       return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19891.     };
  19892.     var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19893.       var defaultMobileSettings = {
  19894.         resize: false,
  19895.         toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19896.         toolbar_sticky: false
  19897.       };
  19898.       var defaultPhoneSettings = { menubar: false };
  19899.       return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19900.     };
  19901.     var getExternalPlugins = function (overrideSettings, settings) {
  19902.       var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19903.       if (overrideSettings && overrideSettings.external_plugins) {
  19904.         return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19905.       } else {
  19906.         return userDefinedExternalPlugins;
  19907.       }
  19908.     };
  19909.     var combinePlugins = function (forcedPlugins, plugins) {
  19910.       return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19911.     };
  19912.     var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19913.       if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19914.         return filterLegacyMobilePlugins(mobilePlugins);
  19915.       } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19916.         return mobilePlugins;
  19917.       } else {
  19918.         return desktopPlugins;
  19919.       }
  19920.     };
  19921.     var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19922.       var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19923.       var desktopPlugins = normalizePlugins(settings.plugins);
  19924.       var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19925.       var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19926.       var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19927.       var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19928.       if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19929.         throw new Error('RTC plugin is not supported on IE 11.');
  19930.       }
  19931.       return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19932.     };
  19933.     var isOnMobile = function (isMobileDevice, sectionResult) {
  19934.       return isMobileDevice && hasSection(sectionResult, 'mobile');
  19935.     };
  19936.     var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19937.       var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19938.       var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19939.       var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19940.         validate: true,
  19941.         external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19942.       });
  19943.       return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19944.     };
  19945.     var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19946.       var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19947.       var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19948.       if (finalSettings.deprecation_warnings !== false) {
  19949.         logDeprecationsWarning(settings, finalSettings);
  19950.       }
  19951.       return finalSettings;
  19952.     };
  19953.     var getFiltered = function (predicate, editor, name) {
  19954.       return Optional.from(editor.settings[name]).filter(predicate);
  19955.     };
  19956.     var getParamObject = function (value) {
  19957.       var output = {};
  19958.       if (typeof value === 'string') {
  19959.         each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  19960.           var arr = val.split('=');
  19961.           if (arr.length > 1) {
  19962.             output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  19963.           } else {
  19964.             output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  19965.           }
  19966.         });
  19967.       } else {
  19968.         output = value;
  19969.       }
  19970.       return output;
  19971.     };
  19972.     var isArrayOf = function (p) {
  19973.       return function (a) {
  19974.         return isArray$1(a) && forall(a, p);
  19975.       };
  19976.     };
  19977.     var getParam = function (editor, name, defaultVal, type) {
  19978.       var value = name in editor.settings ? editor.settings[name] : defaultVal;
  19979.       if (type === 'hash') {
  19980.         return getParamObject(value);
  19981.       } else if (type === 'string') {
  19982.         return getFiltered(isString$1, editor, name).getOr(defaultVal);
  19983.       } else if (type === 'number') {
  19984.         return getFiltered(isNumber, editor, name).getOr(defaultVal);
  19985.       } else if (type === 'boolean') {
  19986.         return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  19987.       } else if (type === 'object') {
  19988.         return getFiltered(isObject, editor, name).getOr(defaultVal);
  19989.       } else if (type === 'array') {
  19990.         return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  19991.       } else if (type === 'string[]') {
  19992.         return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  19993.       } else if (type === 'function') {
  19994.         return getFiltered(isFunction, editor, name).getOr(defaultVal);
  19995.       } else {
  19996.         return value;
  19997.       }
  19998.     };
  19999.  
  20000.     var CreateIconManager = function () {
  20001.       var lookup = {};
  20002.       var add = function (id, iconPack) {
  20003.         lookup[id] = iconPack;
  20004.       };
  20005.       var get = function (id) {
  20006.         if (lookup[id]) {
  20007.           return lookup[id];
  20008.         }
  20009.         return { icons: {} };
  20010.       };
  20011.       var has = function (id) {
  20012.         return has$2(lookup, id);
  20013.       };
  20014.       return {
  20015.         add: add,
  20016.         get: get,
  20017.         has: has
  20018.       };
  20019.     };
  20020.     var IconManager = CreateIconManager();
  20021.  
  20022.     var getProp = function (propName, elm) {
  20023.       var rawElm = elm.dom;
  20024.       return rawElm[propName];
  20025.     };
  20026.     var getComputedSizeProp = function (propName, elm) {
  20027.       return parseInt(get$5(elm, propName), 10);
  20028.     };
  20029.     var getClientWidth = curry(getProp, 'clientWidth');
  20030.     var getClientHeight = curry(getProp, 'clientHeight');
  20031.     var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  20032.     var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  20033.     var getBoundingClientRect = function (elm) {
  20034.       return elm.dom.getBoundingClientRect();
  20035.     };
  20036.     var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  20037.       var clientWidth = getClientWidth(bodyElm);
  20038.       var clientHeight = getClientHeight(bodyElm);
  20039.       return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  20040.     };
  20041.     var transpose = function (inline, elm, clientX, clientY) {
  20042.       var clientRect = getBoundingClientRect(elm);
  20043.       var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  20044.       var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  20045.       var x = clientX - deltaX;
  20046.       var y = clientY - deltaY;
  20047.       return {
  20048.         x: x,
  20049.         y: y
  20050.       };
  20051.     };
  20052.     var isXYInContentArea = function (editor, clientX, clientY) {
  20053.       var bodyElm = SugarElement.fromDom(editor.getBody());
  20054.       var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  20055.       var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  20056.       return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  20057.     };
  20058.     var fromDomSafe = function (node) {
  20059.       return Optional.from(node).map(SugarElement.fromDom);
  20060.     };
  20061.     var isEditorAttachedToDom = function (editor) {
  20062.       var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  20063.       return fromDomSafe(rawContainer).map(inBody).getOr(false);
  20064.     };
  20065.  
  20066.     var NotificationManagerImpl = function () {
  20067.       var unimplemented = function () {
  20068.         throw new Error('Theme did not provide a NotificationManager implementation.');
  20069.       };
  20070.       return {
  20071.         open: unimplemented,
  20072.         close: unimplemented,
  20073.         reposition: unimplemented,
  20074.         getArgs: unimplemented
  20075.       };
  20076.     };
  20077.  
  20078.     var NotificationManager = function (editor) {
  20079.       var notifications = [];
  20080.       var getImplementation = function () {
  20081.         var theme = editor.theme;
  20082.         return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  20083.       };
  20084.       var getTopNotification = function () {
  20085.         return Optional.from(notifications[0]);
  20086.       };
  20087.       var isEqual = function (a, b) {
  20088.         return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  20089.       };
  20090.       var reposition = function () {
  20091.         if (notifications.length > 0) {
  20092.           getImplementation().reposition(notifications);
  20093.         }
  20094.       };
  20095.       var addNotification = function (notification) {
  20096.         notifications.push(notification);
  20097.       };
  20098.       var closeNotification = function (notification) {
  20099.         findIndex$2(notifications, function (otherNotification) {
  20100.           return otherNotification === notification;
  20101.         }).each(function (index) {
  20102.           notifications.splice(index, 1);
  20103.         });
  20104.       };
  20105.       var open = function (spec, fireEvent) {
  20106.         if (fireEvent === void 0) {
  20107.           fireEvent = true;
  20108.         }
  20109.         if (editor.removed || !isEditorAttachedToDom(editor)) {
  20110.           return;
  20111.         }
  20112.         if (fireEvent) {
  20113.           editor.fire('BeforeOpenNotification', { notification: spec });
  20114.         }
  20115.         return find$3(notifications, function (notification) {
  20116.           return isEqual(getImplementation().getArgs(notification), spec);
  20117.         }).getOrThunk(function () {
  20118.           editor.editorManager.setActive(editor);
  20119.           var notification = getImplementation().open(spec, function () {
  20120.             closeNotification(notification);
  20121.             reposition();
  20122.             getTopNotification().fold(function () {
  20123.               return editor.focus();
  20124.             }, function (top) {
  20125.               return focus$1(SugarElement.fromDom(top.getEl()));
  20126.             });
  20127.           });
  20128.           addNotification(notification);
  20129.           reposition();
  20130.           editor.fire('OpenNotification', { notification: __assign({}, notification) });
  20131.           return notification;
  20132.         });
  20133.       };
  20134.       var close = function () {
  20135.         getTopNotification().each(function (notification) {
  20136.           getImplementation().close(notification);
  20137.           closeNotification(notification);
  20138.           reposition();
  20139.         });
  20140.       };
  20141.       var getNotifications = constant(notifications);
  20142.       var registerEvents = function (editor) {
  20143.         editor.on('SkinLoaded', function () {
  20144.           var serviceMessage = getServiceMessage(editor);
  20145.           if (serviceMessage) {
  20146.             open({
  20147.               text: serviceMessage,
  20148.               type: 'warning',
  20149.               timeout: 0
  20150.             }, false);
  20151.           }
  20152.           reposition();
  20153.         });
  20154.         editor.on('show ResizeEditor ResizeWindow NodeChange', function () {
  20155.           Delay.requestAnimationFrame(reposition);
  20156.         });
  20157.         editor.on('remove', function () {
  20158.           each$k(notifications.slice(), function (notification) {
  20159.             getImplementation().close(notification);
  20160.           });
  20161.         });
  20162.       };
  20163.       registerEvents(editor);
  20164.       return {
  20165.         open: open,
  20166.         close: close,
  20167.         getNotifications: getNotifications
  20168.       };
  20169.     };
  20170.  
  20171.     var PluginManager = AddOnManager.PluginManager;
  20172.  
  20173.     var ThemeManager = AddOnManager.ThemeManager;
  20174.  
  20175.     function WindowManagerImpl () {
  20176.       var unimplemented = function () {
  20177.         throw new Error('Theme did not provide a WindowManager implementation.');
  20178.       };
  20179.       return {
  20180.         open: unimplemented,
  20181.         openUrl: unimplemented,
  20182.         alert: unimplemented,
  20183.         confirm: unimplemented,
  20184.         close: unimplemented,
  20185.         getParams: unimplemented,
  20186.         setParams: unimplemented
  20187.       };
  20188.     }
  20189.  
  20190.     var WindowManager = function (editor) {
  20191.       var dialogs = [];
  20192.       var getImplementation = function () {
  20193.         var theme = editor.theme;
  20194.         return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  20195.       };
  20196.       var funcBind = function (scope, f) {
  20197.         return function () {
  20198.           var args = [];
  20199.           for (var _i = 0; _i < arguments.length; _i++) {
  20200.             args[_i] = arguments[_i];
  20201.           }
  20202.           return f ? f.apply(scope, args) : undefined;
  20203.         };
  20204.       };
  20205.       var fireOpenEvent = function (dialog) {
  20206.         editor.fire('OpenWindow', { dialog: dialog });
  20207.       };
  20208.       var fireCloseEvent = function (dialog) {
  20209.         editor.fire('CloseWindow', { dialog: dialog });
  20210.       };
  20211.       var addDialog = function (dialog) {
  20212.         dialogs.push(dialog);
  20213.         fireOpenEvent(dialog);
  20214.       };
  20215.       var closeDialog = function (dialog) {
  20216.         fireCloseEvent(dialog);
  20217.         dialogs = filter$4(dialogs, function (otherDialog) {
  20218.           return otherDialog !== dialog;
  20219.         });
  20220.         if (dialogs.length === 0) {
  20221.           editor.focus();
  20222.         }
  20223.       };
  20224.       var getTopDialog = function () {
  20225.         return Optional.from(dialogs[dialogs.length - 1]);
  20226.       };
  20227.       var storeSelectionAndOpenDialog = function (openDialog) {
  20228.         editor.editorManager.setActive(editor);
  20229.         store(editor);
  20230.         var dialog = openDialog();
  20231.         addDialog(dialog);
  20232.         return dialog;
  20233.       };
  20234.       var open = function (args, params) {
  20235.         return storeSelectionAndOpenDialog(function () {
  20236.           return getImplementation().open(args, params, closeDialog);
  20237.         });
  20238.       };
  20239.       var openUrl = function (args) {
  20240.         return storeSelectionAndOpenDialog(function () {
  20241.           return getImplementation().openUrl(args, closeDialog);
  20242.         });
  20243.       };
  20244.       var alert = function (message, callback, scope) {
  20245.         var windowManagerImpl = getImplementation();
  20246.         windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20247.       };
  20248.       var confirm = function (message, callback, scope) {
  20249.         var windowManagerImpl = getImplementation();
  20250.         windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20251.       };
  20252.       var close = function () {
  20253.         getTopDialog().each(function (dialog) {
  20254.           getImplementation().close(dialog);
  20255.           closeDialog(dialog);
  20256.         });
  20257.       };
  20258.       editor.on('remove', function () {
  20259.         each$k(dialogs, function (dialog) {
  20260.           getImplementation().close(dialog);
  20261.         });
  20262.       });
  20263.       return {
  20264.         open: open,
  20265.         openUrl: openUrl,
  20266.         alert: alert,
  20267.         confirm: confirm,
  20268.         close: close
  20269.       };
  20270.     };
  20271.  
  20272.     var displayNotification = function (editor, message) {
  20273.       editor.notificationManager.open({
  20274.         type: 'error',
  20275.         text: message
  20276.       });
  20277.     };
  20278.     var displayError = function (editor, message) {
  20279.       if (editor._skinLoaded) {
  20280.         displayNotification(editor, message);
  20281.       } else {
  20282.         editor.on('SkinLoaded', function () {
  20283.           displayNotification(editor, message);
  20284.         });
  20285.       }
  20286.     };
  20287.     var uploadError = function (editor, message) {
  20288.       displayError(editor, I18n.translate([
  20289.         'Failed to upload image: {0}',
  20290.         message
  20291.       ]));
  20292.     };
  20293.     var logError = function (editor, errorType, msg) {
  20294.       fireError(editor, errorType, { message: msg });
  20295.       console.error(msg);
  20296.     };
  20297.     var createLoadError = function (type, url, name) {
  20298.       return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20299.     };
  20300.     var pluginLoadError = function (editor, url, name) {
  20301.       logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20302.     };
  20303.     var iconsLoadError = function (editor, url, name) {
  20304.       logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20305.     };
  20306.     var languageLoadError = function (editor, url, name) {
  20307.       logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20308.     };
  20309.     var pluginInitError = function (editor, name, err) {
  20310.       var message = I18n.translate([
  20311.         'Failed to initialize plugin: {0}',
  20312.         name
  20313.       ]);
  20314.       fireError(editor, 'PluginLoadError', { message: message });
  20315.       initError(message, err);
  20316.       displayError(editor, message);
  20317.     };
  20318.     var initError = function (message) {
  20319.       var x = [];
  20320.       for (var _i = 1; _i < arguments.length; _i++) {
  20321.         x[_i - 1] = arguments[_i];
  20322.       }
  20323.       var console = window.console;
  20324.       if (console) {
  20325.         if (console.error) {
  20326.           console.error.apply(console, __spreadArray([message], x, false));
  20327.         } else {
  20328.           console.log.apply(console, __spreadArray([message], x, false));
  20329.         }
  20330.       }
  20331.     };
  20332.  
  20333.     var isContentCssSkinName = function (url) {
  20334.       return /^[a-z0-9\-]+$/i.test(url);
  20335.     };
  20336.     var getContentCssUrls = function (editor) {
  20337.       return transformToUrls(editor, getContentCss(editor));
  20338.     };
  20339.     var getFontCssUrls = function (editor) {
  20340.       return transformToUrls(editor, getFontCss(editor));
  20341.     };
  20342.     var transformToUrls = function (editor, cssLinks) {
  20343.       var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20344.       var suffix = editor.editorManager.suffix;
  20345.       var contentCssFile = 'content' + suffix + '.css';
  20346.       var inline = editor.inline === true;
  20347.       return map$3(cssLinks, function (url) {
  20348.         if (isContentCssSkinName(url) && !inline) {
  20349.           return skinUrl + '/' + url + '/' + contentCssFile;
  20350.         } else {
  20351.           return editor.documentBaseURI.toAbsolute(url);
  20352.         }
  20353.       });
  20354.     };
  20355.     var appendContentCssFromSettings = function (editor) {
  20356.       editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20357.     };
  20358.  
  20359.     var UploadStatus = function () {
  20360.       var PENDING = 1, UPLOADED = 2;
  20361.       var blobUriStatuses = {};
  20362.       var createStatus = function (status, resultUri) {
  20363.         return {
  20364.           status: status,
  20365.           resultUri: resultUri
  20366.         };
  20367.       };
  20368.       var hasBlobUri = function (blobUri) {
  20369.         return blobUri in blobUriStatuses;
  20370.       };
  20371.       var getResultUri = function (blobUri) {
  20372.         var result = blobUriStatuses[blobUri];
  20373.         return result ? result.resultUri : null;
  20374.       };
  20375.       var isPending = function (blobUri) {
  20376.         return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20377.       };
  20378.       var isUploaded = function (blobUri) {
  20379.         return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20380.       };
  20381.       var markPending = function (blobUri) {
  20382.         blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20383.       };
  20384.       var markUploaded = function (blobUri, resultUri) {
  20385.         blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20386.       };
  20387.       var removeFailed = function (blobUri) {
  20388.         delete blobUriStatuses[blobUri];
  20389.       };
  20390.       var destroy = function () {
  20391.         blobUriStatuses = {};
  20392.       };
  20393.       return {
  20394.         hasBlobUri: hasBlobUri,
  20395.         getResultUri: getResultUri,
  20396.         isPending: isPending,
  20397.         isUploaded: isUploaded,
  20398.         markPending: markPending,
  20399.         markUploaded: markUploaded,
  20400.         removeFailed: removeFailed,
  20401.         destroy: destroy
  20402.       };
  20403.     };
  20404.  
  20405.     var count = 0;
  20406.     var seed = function () {
  20407.       var rnd = function () {
  20408.         return Math.round(Math.random() * 4294967295).toString(36);
  20409.       };
  20410.       var now = new Date().getTime();
  20411.       return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20412.     };
  20413.     var uuid = function (prefix) {
  20414.       return prefix + count++ + seed();
  20415.     };
  20416.  
  20417.     var BlobCache = function () {
  20418.       var cache = [];
  20419.       var mimeToExt = function (mime) {
  20420.         var mimes = {
  20421.           'image/jpeg': 'jpg',
  20422.           'image/jpg': 'jpg',
  20423.           'image/gif': 'gif',
  20424.           'image/png': 'png',
  20425.           'image/apng': 'apng',
  20426.           'image/avif': 'avif',
  20427.           'image/svg+xml': 'svg',
  20428.           'image/webp': 'webp',
  20429.           'image/bmp': 'bmp',
  20430.           'image/tiff': 'tiff'
  20431.         };
  20432.         return mimes[mime.toLowerCase()] || 'dat';
  20433.       };
  20434.       var create = function (o, blob, base64, name, filename) {
  20435.         if (isString$1(o)) {
  20436.           var id = o;
  20437.           return toBlobInfo({
  20438.             id: id,
  20439.             name: name,
  20440.             filename: filename,
  20441.             blob: blob,
  20442.             base64: base64
  20443.           });
  20444.         } else if (isObject(o)) {
  20445.           return toBlobInfo(o);
  20446.         } else {
  20447.           throw new Error('Unknown input type');
  20448.         }
  20449.       };
  20450.       var toBlobInfo = function (o) {
  20451.         if (!o.blob || !o.base64) {
  20452.           throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20453.         }
  20454.         var id = o.id || uuid('blobid');
  20455.         var name = o.name || id;
  20456.         var blob = o.blob;
  20457.         return {
  20458.           id: constant(id),
  20459.           name: constant(name),
  20460.           filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20461.           blob: constant(blob),
  20462.           base64: constant(o.base64),
  20463.           blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20464.           uri: constant(o.uri)
  20465.         };
  20466.       };
  20467.       var add = function (blobInfo) {
  20468.         if (!get(blobInfo.id())) {
  20469.           cache.push(blobInfo);
  20470.         }
  20471.       };
  20472.       var findFirst = function (predicate) {
  20473.         return find$3(cache, predicate).getOrUndefined();
  20474.       };
  20475.       var get = function (id) {
  20476.         return findFirst(function (cachedBlobInfo) {
  20477.           return cachedBlobInfo.id() === id;
  20478.         });
  20479.       };
  20480.       var getByUri = function (blobUri) {
  20481.         return findFirst(function (blobInfo) {
  20482.           return blobInfo.blobUri() === blobUri;
  20483.         });
  20484.       };
  20485.       var getByData = function (base64, type) {
  20486.         return findFirst(function (blobInfo) {
  20487.           return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20488.         });
  20489.       };
  20490.       var removeByUri = function (blobUri) {
  20491.         cache = filter$4(cache, function (blobInfo) {
  20492.           if (blobInfo.blobUri() === blobUri) {
  20493.             URL.revokeObjectURL(blobInfo.blobUri());
  20494.             return false;
  20495.           }
  20496.           return true;
  20497.         });
  20498.       };
  20499.       var destroy = function () {
  20500.         each$k(cache, function (cachedBlobInfo) {
  20501.           URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20502.         });
  20503.         cache = [];
  20504.       };
  20505.       return {
  20506.         create: create,
  20507.         add: add,
  20508.         get: get,
  20509.         getByUri: getByUri,
  20510.         getByData: getByData,
  20511.         findFirst: findFirst,
  20512.         removeByUri: removeByUri,
  20513.         destroy: destroy
  20514.       };
  20515.     };
  20516.  
  20517.     var Uploader = function (uploadStatus, settings) {
  20518.       var pendingPromises = {};
  20519.       var pathJoin = function (path1, path2) {
  20520.         if (path1) {
  20521.           return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20522.         }
  20523.         return path2;
  20524.       };
  20525.       var defaultHandler = function (blobInfo, success, failure, progress) {
  20526.         var xhr = new XMLHttpRequest();
  20527.         xhr.open('POST', settings.url);
  20528.         xhr.withCredentials = settings.credentials;
  20529.         xhr.upload.onprogress = function (e) {
  20530.           progress(e.loaded / e.total * 100);
  20531.         };
  20532.         xhr.onerror = function () {
  20533.           failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20534.         };
  20535.         xhr.onload = function () {
  20536.           if (xhr.status < 200 || xhr.status >= 300) {
  20537.             failure('HTTP Error: ' + xhr.status);
  20538.             return;
  20539.           }
  20540.           var json = JSON.parse(xhr.responseText);
  20541.           if (!json || typeof json.location !== 'string') {
  20542.             failure('Invalid JSON: ' + xhr.responseText);
  20543.             return;
  20544.           }
  20545.           success(pathJoin(settings.basePath, json.location));
  20546.         };
  20547.         var formData = new FormData();
  20548.         formData.append('file', blobInfo.blob(), blobInfo.filename());
  20549.         xhr.send(formData);
  20550.       };
  20551.       var noUpload = function () {
  20552.         return new promiseObj(function (resolve) {
  20553.           resolve([]);
  20554.         });
  20555.       };
  20556.       var handlerSuccess = function (blobInfo, url) {
  20557.         return {
  20558.           url: url,
  20559.           blobInfo: blobInfo,
  20560.           status: true
  20561.         };
  20562.       };
  20563.       var handlerFailure = function (blobInfo, message, options) {
  20564.         return {
  20565.           url: '',
  20566.           blobInfo: blobInfo,
  20567.           status: false,
  20568.           error: {
  20569.             message: message,
  20570.             options: options
  20571.           }
  20572.         };
  20573.       };
  20574.       var resolvePending = function (blobUri, result) {
  20575.         Tools.each(pendingPromises[blobUri], function (resolve) {
  20576.           resolve(result);
  20577.         });
  20578.         delete pendingPromises[blobUri];
  20579.       };
  20580.       var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20581.         uploadStatus.markPending(blobInfo.blobUri());
  20582.         return new promiseObj(function (resolve) {
  20583.           var notification, progress;
  20584.           try {
  20585.             var closeNotification_1 = function () {
  20586.               if (notification) {
  20587.                 notification.close();
  20588.                 progress = noop;
  20589.               }
  20590.             };
  20591.             var success = function (url) {
  20592.               closeNotification_1();
  20593.               uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20594.               resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20595.               resolve(handlerSuccess(blobInfo, url));
  20596.             };
  20597.             var failure = function (error, options) {
  20598.               var failureOptions = options ? options : {};
  20599.               closeNotification_1();
  20600.               uploadStatus.removeFailed(blobInfo.blobUri());
  20601.               resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20602.               resolve(handlerFailure(blobInfo, error, failureOptions));
  20603.             };
  20604.             progress = function (percent) {
  20605.               if (percent < 0 || percent > 100) {
  20606.                 return;
  20607.               }
  20608.               Optional.from(notification).orThunk(function () {
  20609.                 return Optional.from(openNotification).map(apply);
  20610.               }).each(function (n) {
  20611.                 notification = n;
  20612.                 n.progressBar.value(percent);
  20613.               });
  20614.             };
  20615.             handler(blobInfo, success, failure, progress);
  20616.           } catch (ex) {
  20617.             resolve(handlerFailure(blobInfo, ex.message, {}));
  20618.           }
  20619.         });
  20620.       };
  20621.       var isDefaultHandler = function (handler) {
  20622.         return handler === defaultHandler;
  20623.       };
  20624.       var pendingUploadBlobInfo = function (blobInfo) {
  20625.         var blobUri = blobInfo.blobUri();
  20626.         return new promiseObj(function (resolve) {
  20627.           pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20628.           pendingPromises[blobUri].push(resolve);
  20629.         });
  20630.       };
  20631.       var uploadBlobs = function (blobInfos, openNotification) {
  20632.         blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20633.           return !uploadStatus.isUploaded(blobInfo.blobUri());
  20634.         });
  20635.         return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20636.           return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20637.         }));
  20638.       };
  20639.       var upload = function (blobInfos, openNotification) {
  20640.         return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20641.       };
  20642.       if (isFunction(settings.handler) === false) {
  20643.         settings.handler = defaultHandler;
  20644.       }
  20645.       return { upload: upload };
  20646.     };
  20647.  
  20648.     var openNotification = function (editor) {
  20649.       return function () {
  20650.         return editor.notificationManager.open({
  20651.           text: editor.translate('Image uploading...'),
  20652.           type: 'info',
  20653.           timeout: -1,
  20654.           progressBar: true
  20655.         });
  20656.       };
  20657.     };
  20658.     var createUploader = function (editor, uploadStatus) {
  20659.       return Uploader(uploadStatus, {
  20660.         url: getImageUploadUrl(editor),
  20661.         basePath: getImageUploadBasePath(editor),
  20662.         credentials: getImagesUploadCredentials(editor),
  20663.         handler: getImagesUploadHandler(editor)
  20664.       });
  20665.     };
  20666.     var ImageUploader = function (editor) {
  20667.       var uploadStatus = UploadStatus();
  20668.       var uploader = createUploader(editor, uploadStatus);
  20669.       return {
  20670.         upload: function (blobInfos, showNotification) {
  20671.           if (showNotification === void 0) {
  20672.             showNotification = true;
  20673.           }
  20674.           return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20675.         }
  20676.       };
  20677.     };
  20678.  
  20679.     var UploadChangeHandler = function (editor) {
  20680.       var lastChangedLevel = Cell(null);
  20681.       editor.on('change AddUndo', function (e) {
  20682.         lastChangedLevel.set(__assign({}, e.level));
  20683.       });
  20684.       var fireIfChanged = function () {
  20685.         var data = editor.undoManager.data;
  20686.         last$2(data).filter(function (level) {
  20687.           return !isEq$1(lastChangedLevel.get(), level);
  20688.         }).each(function (level) {
  20689.           editor.setDirty(true);
  20690.           editor.fire('change', {
  20691.             level: level,
  20692.             lastLevel: get$a(data, data.length - 2).getOrNull()
  20693.           });
  20694.         });
  20695.       };
  20696.       return { fireIfChanged: fireIfChanged };
  20697.     };
  20698.     var EditorUpload = function (editor) {
  20699.       var blobCache = BlobCache();
  20700.       var uploader, imageScanner;
  20701.       var uploadStatus = UploadStatus();
  20702.       var urlFilters = [];
  20703.       var changeHandler = UploadChangeHandler(editor);
  20704.       var aliveGuard = function (callback) {
  20705.         return function (result) {
  20706.           if (editor.selection) {
  20707.             return callback(result);
  20708.           }
  20709.           return [];
  20710.         };
  20711.       };
  20712.       var cacheInvalidator = function (url) {
  20713.         return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20714.       };
  20715.       var replaceString = function (content, search, replace) {
  20716.         var index = 0;
  20717.         do {
  20718.           index = content.indexOf(search, index);
  20719.           if (index !== -1) {
  20720.             content = content.substring(0, index) + replace + content.substr(index + search.length);
  20721.             index += replace.length - search.length + 1;
  20722.           }
  20723.         } while (index !== -1);
  20724.         return content;
  20725.       };
  20726.       var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20727.         var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20728.         content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20729.         content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20730.         return content;
  20731.       };
  20732.       var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20733.         each$k(editor.undoManager.data, function (level) {
  20734.           if (level.type === 'fragmented') {
  20735.             level.fragments = map$3(level.fragments, function (fragment) {
  20736.               return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20737.             });
  20738.           } else {
  20739.             level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20740.           }
  20741.         });
  20742.       };
  20743.       var replaceImageUriInView = function (image, resultUri) {
  20744.         var src = editor.convertURL(resultUri, 'src');
  20745.         replaceUrlInUndoStack(image.src, resultUri);
  20746.         editor.$(image).attr({
  20747.           'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20748.           'data-mce-src': src
  20749.         });
  20750.       };
  20751.       var uploadImages = function (callback) {
  20752.         if (!uploader) {
  20753.           uploader = createUploader(editor, uploadStatus);
  20754.         }
  20755.         return scanForImages().then(aliveGuard(function (imageInfos) {
  20756.           var blobInfos = map$3(imageInfos, function (imageInfo) {
  20757.             return imageInfo.blobInfo;
  20758.           });
  20759.           return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20760.             var imagesToRemove = [];
  20761.             var filteredResult = map$3(result, function (uploadInfo, index) {
  20762.               var blobInfo = imageInfos[index].blobInfo;
  20763.               var image = imageInfos[index].image;
  20764.               if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20765.                 blobCache.removeByUri(image.src);
  20766.                 if (isRtc(editor)) ; else {
  20767.                   replaceImageUriInView(image, uploadInfo.url);
  20768.                 }
  20769.               } else if (uploadInfo.error) {
  20770.                 if (uploadInfo.error.options.remove) {
  20771.                   replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20772.                   imagesToRemove.push(image);
  20773.                 }
  20774.                 uploadError(editor, uploadInfo.error.message);
  20775.               }
  20776.               return {
  20777.                 element: image,
  20778.                 status: uploadInfo.status,
  20779.                 uploadUri: uploadInfo.url,
  20780.                 blobInfo: blobInfo
  20781.               };
  20782.             });
  20783.             if (filteredResult.length > 0) {
  20784.               changeHandler.fireIfChanged();
  20785.             }
  20786.             if (imagesToRemove.length > 0) {
  20787.               if (isRtc(editor)) {
  20788.                 console.error('Removing images on failed uploads is currently unsupported for RTC');
  20789.               } else {
  20790.                 editor.undoManager.transact(function () {
  20791.                   each$k(imagesToRemove, function (element) {
  20792.                     editor.dom.remove(element);
  20793.                     blobCache.removeByUri(element.src);
  20794.                   });
  20795.                 });
  20796.               }
  20797.             }
  20798.             if (callback) {
  20799.               callback(filteredResult);
  20800.             }
  20801.             return filteredResult;
  20802.           }));
  20803.         }));
  20804.       };
  20805.       var uploadImagesAuto = function (callback) {
  20806.         if (isAutomaticUploadsEnabled(editor)) {
  20807.           return uploadImages(callback);
  20808.         }
  20809.       };
  20810.       var isValidDataUriImage = function (imgElm) {
  20811.         if (forall(urlFilters, function (filter) {
  20812.             return filter(imgElm);
  20813.           }) === false) {
  20814.           return false;
  20815.         }
  20816.         if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20817.           var dataImgFilter = getImagesDataImgFilter(editor);
  20818.           return dataImgFilter(imgElm);
  20819.         }
  20820.         return true;
  20821.       };
  20822.       var addFilter = function (filter) {
  20823.         urlFilters.push(filter);
  20824.       };
  20825.       var scanForImages = function () {
  20826.         if (!imageScanner) {
  20827.           imageScanner = ImageScanner(uploadStatus, blobCache);
  20828.         }
  20829.         return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20830.           result = filter$4(result, function (resultItem) {
  20831.             if (typeof resultItem === 'string') {
  20832.               displayError(editor, resultItem);
  20833.               return false;
  20834.             }
  20835.             return true;
  20836.           });
  20837.           if (isRtc(editor)) ; else {
  20838.             each$k(result, function (resultItem) {
  20839.               replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20840.               resultItem.image.src = resultItem.blobInfo.blobUri();
  20841.               resultItem.image.removeAttribute('data-mce-src');
  20842.             });
  20843.           }
  20844.           return result;
  20845.         }));
  20846.       };
  20847.       var destroy = function () {
  20848.         blobCache.destroy();
  20849.         uploadStatus.destroy();
  20850.         imageScanner = uploader = null;
  20851.       };
  20852.       var replaceBlobUris = function (content) {
  20853.         return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20854.           var resultUri = uploadStatus.getResultUri(blobUri);
  20855.           if (resultUri) {
  20856.             return 'src="' + resultUri + '"';
  20857.           }
  20858.           var blobInfo = blobCache.getByUri(blobUri);
  20859.           if (!blobInfo) {
  20860.             blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20861.               return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20862.             }, null);
  20863.           }
  20864.           if (blobInfo) {
  20865.             var blob = blobInfo.blob();
  20866.             return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20867.           }
  20868.           return match;
  20869.         });
  20870.       };
  20871.       editor.on('SetContent', function () {
  20872.         if (isAutomaticUploadsEnabled(editor)) {
  20873.           uploadImagesAuto();
  20874.         } else {
  20875.           scanForImages();
  20876.         }
  20877.       });
  20878.       editor.on('RawSaveContent', function (e) {
  20879.         e.content = replaceBlobUris(e.content);
  20880.       });
  20881.       editor.on('GetContent', function (e) {
  20882.         if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20883.           return;
  20884.         }
  20885.         e.content = replaceBlobUris(e.content);
  20886.       });
  20887.       editor.on('PostRender', function () {
  20888.         editor.parser.addNodeFilter('img', function (images) {
  20889.           each$k(images, function (img) {
  20890.             var src = img.attr('src');
  20891.             if (blobCache.getByUri(src)) {
  20892.               return;
  20893.             }
  20894.             var resultUri = uploadStatus.getResultUri(src);
  20895.             if (resultUri) {
  20896.               img.attr('src', resultUri);
  20897.             }
  20898.           });
  20899.         });
  20900.       });
  20901.       return {
  20902.         blobCache: blobCache,
  20903.         addFilter: addFilter,
  20904.         uploadImages: uploadImages,
  20905.         uploadImagesAuto: uploadImagesAuto,
  20906.         scanForImages: scanForImages,
  20907.         destroy: destroy
  20908.       };
  20909.     };
  20910.  
  20911.     var get = function (dom) {
  20912.       var formats = {
  20913.         valigntop: [{
  20914.             selector: 'td,th',
  20915.             styles: { verticalAlign: 'top' }
  20916.           }],
  20917.         valignmiddle: [{
  20918.             selector: 'td,th',
  20919.             styles: { verticalAlign: 'middle' }
  20920.           }],
  20921.         valignbottom: [{
  20922.             selector: 'td,th',
  20923.             styles: { verticalAlign: 'bottom' }
  20924.           }],
  20925.         alignleft: [
  20926.           {
  20927.             selector: 'figure.image',
  20928.             collapsed: false,
  20929.             classes: 'align-left',
  20930.             ceFalseOverride: true,
  20931.             preview: 'font-family font-size'
  20932.           },
  20933.           {
  20934.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20935.             styles: { textAlign: 'left' },
  20936.             inherit: false,
  20937.             preview: false,
  20938.             defaultBlock: 'div'
  20939.           },
  20940.           {
  20941.             selector: 'img,table,audio,video',
  20942.             collapsed: false,
  20943.             styles: { float: 'left' },
  20944.             preview: 'font-family font-size'
  20945.           }
  20946.         ],
  20947.         aligncenter: [
  20948.           {
  20949.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20950.             styles: { textAlign: 'center' },
  20951.             inherit: false,
  20952.             preview: 'font-family font-size',
  20953.             defaultBlock: 'div'
  20954.           },
  20955.           {
  20956.             selector: 'figure.image',
  20957.             collapsed: false,
  20958.             classes: 'align-center',
  20959.             ceFalseOverride: true,
  20960.             preview: 'font-family font-size'
  20961.           },
  20962.           {
  20963.             selector: 'img,audio,video',
  20964.             collapsed: false,
  20965.             styles: {
  20966.               display: 'block',
  20967.               marginLeft: 'auto',
  20968.               marginRight: 'auto'
  20969.             },
  20970.             preview: false
  20971.           },
  20972.           {
  20973.             selector: 'table',
  20974.             collapsed: false,
  20975.             styles: {
  20976.               marginLeft: 'auto',
  20977.               marginRight: 'auto'
  20978.             },
  20979.             preview: 'font-family font-size'
  20980.           }
  20981.         ],
  20982.         alignright: [
  20983.           {
  20984.             selector: 'figure.image',
  20985.             collapsed: false,
  20986.             classes: 'align-right',
  20987.             ceFalseOverride: true,
  20988.             preview: 'font-family font-size'
  20989.           },
  20990.           {
  20991.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20992.             styles: { textAlign: 'right' },
  20993.             inherit: false,
  20994.             preview: 'font-family font-size',
  20995.             defaultBlock: 'div'
  20996.           },
  20997.           {
  20998.             selector: 'img,table,audio,video',
  20999.             collapsed: false,
  21000.             styles: { float: 'right' },
  21001.             preview: 'font-family font-size'
  21002.           }
  21003.         ],
  21004.         alignjustify: [{
  21005.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  21006.             styles: { textAlign: 'justify' },
  21007.             inherit: false,
  21008.             defaultBlock: 'div',
  21009.             preview: 'font-family font-size'
  21010.           }],
  21011.         bold: [
  21012.           {
  21013.             inline: 'strong',
  21014.             remove: 'all',
  21015.             preserve_attributes: [
  21016.               'class',
  21017.               'style'
  21018.             ]
  21019.           },
  21020.           {
  21021.             inline: 'span',
  21022.             styles: { fontWeight: 'bold' }
  21023.           },
  21024.           {
  21025.             inline: 'b',
  21026.             remove: 'all',
  21027.             preserve_attributes: [
  21028.               'class',
  21029.               'style'
  21030.             ]
  21031.           }
  21032.         ],
  21033.         italic: [
  21034.           {
  21035.             inline: 'em',
  21036.             remove: 'all',
  21037.             preserve_attributes: [
  21038.               'class',
  21039.               'style'
  21040.             ]
  21041.           },
  21042.           {
  21043.             inline: 'span',
  21044.             styles: { fontStyle: 'italic' }
  21045.           },
  21046.           {
  21047.             inline: 'i',
  21048.             remove: 'all',
  21049.             preserve_attributes: [
  21050.               'class',
  21051.               'style'
  21052.             ]
  21053.           }
  21054.         ],
  21055.         underline: [
  21056.           {
  21057.             inline: 'span',
  21058.             styles: { textDecoration: 'underline' },
  21059.             exact: true
  21060.           },
  21061.           {
  21062.             inline: 'u',
  21063.             remove: 'all',
  21064.             preserve_attributes: [
  21065.               'class',
  21066.               'style'
  21067.             ]
  21068.           }
  21069.         ],
  21070.         strikethrough: [
  21071.           {
  21072.             inline: 'span',
  21073.             styles: { textDecoration: 'line-through' },
  21074.             exact: true
  21075.           },
  21076.           {
  21077.             inline: 'strike',
  21078.             remove: 'all',
  21079.             preserve_attributes: [
  21080.               'class',
  21081.               'style'
  21082.             ]
  21083.           },
  21084.           {
  21085.             inline: 's',
  21086.             remove: 'all',
  21087.             preserve_attributes: [
  21088.               'class',
  21089.               'style'
  21090.             ]
  21091.           }
  21092.         ],
  21093.         forecolor: {
  21094.           inline: 'span',
  21095.           styles: { color: '%value' },
  21096.           links: true,
  21097.           remove_similar: true,
  21098.           clear_child_styles: true
  21099.         },
  21100.         hilitecolor: {
  21101.           inline: 'span',
  21102.           styles: { backgroundColor: '%value' },
  21103.           links: true,
  21104.           remove_similar: true,
  21105.           clear_child_styles: true
  21106.         },
  21107.         fontname: {
  21108.           inline: 'span',
  21109.           toggle: false,
  21110.           styles: { fontFamily: '%value' },
  21111.           clear_child_styles: true
  21112.         },
  21113.         fontsize: {
  21114.           inline: 'span',
  21115.           toggle: false,
  21116.           styles: { fontSize: '%value' },
  21117.           clear_child_styles: true
  21118.         },
  21119.         lineheight: {
  21120.           selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  21121.           defaultBlock: 'p',
  21122.           styles: { lineHeight: '%value' }
  21123.         },
  21124.         fontsize_class: {
  21125.           inline: 'span',
  21126.           attributes: { class: '%value' }
  21127.         },
  21128.         blockquote: {
  21129.           block: 'blockquote',
  21130.           wrapper: true,
  21131.           remove: 'all'
  21132.         },
  21133.         subscript: { inline: 'sub' },
  21134.         superscript: { inline: 'sup' },
  21135.         code: { inline: 'code' },
  21136.         link: {
  21137.           inline: 'a',
  21138.           selector: 'a',
  21139.           remove: 'all',
  21140.           split: true,
  21141.           deep: true,
  21142.           onmatch: function (node, _fmt, _itemName) {
  21143.             return isElement$5(node) && node.hasAttribute('href');
  21144.           },
  21145.           onformat: function (elm, _fmt, vars) {
  21146.             Tools.each(vars, function (value, key) {
  21147.               dom.setAttrib(elm, key, value);
  21148.             });
  21149.           }
  21150.         },
  21151.         lang: {
  21152.           inline: 'span',
  21153.           clear_child_styles: true,
  21154.           remove_similar: true,
  21155.           attributes: {
  21156.             'lang': '%value',
  21157.             'data-mce-lang': function (vars) {
  21158.               var _a;
  21159.               return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  21160.             }
  21161.           }
  21162.         },
  21163.         removeformat: [
  21164.           {
  21165.             selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  21166.             remove: 'all',
  21167.             split: true,
  21168.             expand: false,
  21169.             block_expand: true,
  21170.             deep: true
  21171.           },
  21172.           {
  21173.             selector: 'span',
  21174.             attributes: [
  21175.               'style',
  21176.               'class'
  21177.             ],
  21178.             remove: 'empty',
  21179.             split: true,
  21180.             expand: false,
  21181.             deep: true
  21182.           },
  21183.           {
  21184.             selector: '*',
  21185.             attributes: [
  21186.               'style',
  21187.               'class'
  21188.             ],
  21189.             split: false,
  21190.             expand: false,
  21191.             deep: true
  21192.           }
  21193.         ]
  21194.       };
  21195.       Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  21196.         formats[name] = {
  21197.           block: name,
  21198.           remove: 'all'
  21199.         };
  21200.       });
  21201.       return formats;
  21202.     };
  21203.  
  21204.     var FormatRegistry = function (editor) {
  21205.       var formats = {};
  21206.       var get$1 = function (name) {
  21207.         return isNonNullable(name) ? formats[name] : formats;
  21208.       };
  21209.       var has = function (name) {
  21210.         return has$2(formats, name);
  21211.       };
  21212.       var register = function (name, format) {
  21213.         if (name) {
  21214.           if (!isString$1(name)) {
  21215.             each$j(name, function (format, name) {
  21216.               register(name, format);
  21217.             });
  21218.           } else {
  21219.             if (!isArray$1(format)) {
  21220.               format = [format];
  21221.             }
  21222.             each$k(format, function (format) {
  21223.               if (isUndefined(format.deep)) {
  21224.                 format.deep = !isSelectorFormat(format);
  21225.               }
  21226.               if (isUndefined(format.split)) {
  21227.                 format.split = !isSelectorFormat(format) || isInlineFormat(format);
  21228.               }
  21229.               if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  21230.                 format.remove = 'none';
  21231.               }
  21232.               if (isSelectorFormat(format) && isInlineFormat(format)) {
  21233.                 format.mixed = true;
  21234.                 format.block_expand = true;
  21235.               }
  21236.               if (isString$1(format.classes)) {
  21237.                 format.classes = format.classes.split(/\s+/);
  21238.               }
  21239.             });
  21240.             formats[name] = format;
  21241.           }
  21242.         }
  21243.       };
  21244.       var unregister = function (name) {
  21245.         if (name && formats[name]) {
  21246.           delete formats[name];
  21247.         }
  21248.         return formats;
  21249.       };
  21250.       register(get(editor.dom));
  21251.       register(getFormats(editor));
  21252.       return {
  21253.         get: get$1,
  21254.         has: has,
  21255.         register: register,
  21256.         unregister: unregister
  21257.       };
  21258.     };
  21259.  
  21260.     var each$5 = Tools.each;
  21261.     var dom = DOMUtils.DOM;
  21262.     var parsedSelectorToHtml = function (ancestry, editor) {
  21263.       var elm, item, fragment;
  21264.       var schema = editor && editor.schema || Schema({});
  21265.       var decorate = function (elm, item) {
  21266.         if (item.classes.length) {
  21267.           dom.addClass(elm, item.classes.join(' '));
  21268.         }
  21269.         dom.setAttribs(elm, item.attrs);
  21270.       };
  21271.       var createElement = function (sItem) {
  21272.         item = typeof sItem === 'string' ? {
  21273.           name: sItem,
  21274.           classes: [],
  21275.           attrs: {}
  21276.         } : sItem;
  21277.         var elm = dom.create(item.name);
  21278.         decorate(elm, item);
  21279.         return elm;
  21280.       };
  21281.       var getRequiredParent = function (elm, candidate) {
  21282.         var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21283.         var elmRule = schema.getElementRule(name);
  21284.         var parentsRequired = elmRule && elmRule.parentsRequired;
  21285.         if (parentsRequired && parentsRequired.length) {
  21286.           return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21287.         } else {
  21288.           return false;
  21289.         }
  21290.       };
  21291.       var wrapInHtml = function (elm, ancestry, siblings) {
  21292.         var parent, parentCandidate;
  21293.         var ancestor = ancestry.length > 0 && ancestry[0];
  21294.         var ancestorName = ancestor && ancestor.name;
  21295.         var parentRequired = getRequiredParent(elm, ancestorName);
  21296.         if (parentRequired) {
  21297.           if (ancestorName === parentRequired) {
  21298.             parentCandidate = ancestry[0];
  21299.             ancestry = ancestry.slice(1);
  21300.           } else {
  21301.             parentCandidate = parentRequired;
  21302.           }
  21303.         } else if (ancestor) {
  21304.           parentCandidate = ancestry[0];
  21305.           ancestry = ancestry.slice(1);
  21306.         } else if (!siblings) {
  21307.           return elm;
  21308.         }
  21309.         if (parentCandidate) {
  21310.           parent = createElement(parentCandidate);
  21311.           parent.appendChild(elm);
  21312.         }
  21313.         if (siblings) {
  21314.           if (!parent) {
  21315.             parent = dom.create('div');
  21316.             parent.appendChild(elm);
  21317.           }
  21318.           Tools.each(siblings, function (sibling) {
  21319.             var siblingElm = createElement(sibling);
  21320.             parent.insertBefore(siblingElm, elm);
  21321.           });
  21322.         }
  21323.         return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21324.       };
  21325.       if (ancestry && ancestry.length) {
  21326.         item = ancestry[0];
  21327.         elm = createElement(item);
  21328.         fragment = dom.create('div');
  21329.         fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21330.         return fragment;
  21331.       } else {
  21332.         return '';
  21333.       }
  21334.     };
  21335.     var parseSelectorItem = function (item) {
  21336.       var tagName;
  21337.       var obj = {
  21338.         classes: [],
  21339.         attrs: {}
  21340.       };
  21341.       item = obj.selector = Tools.trim(item);
  21342.       if (item !== '*') {
  21343.         tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21344.           switch ($1) {
  21345.           case '#':
  21346.             obj.attrs.id = $2;
  21347.             break;
  21348.           case '.':
  21349.             obj.classes.push($2);
  21350.             break;
  21351.           case ':':
  21352.             if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21353.               obj.attrs[$2] = $2;
  21354.             }
  21355.             break;
  21356.           }
  21357.           if ($3 === '[') {
  21358.             var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21359.             if (m) {
  21360.               obj.attrs[m[1]] = m[2];
  21361.             }
  21362.           }
  21363.           return '';
  21364.         });
  21365.       }
  21366.       obj.name = tagName || 'div';
  21367.       return obj;
  21368.     };
  21369.     var parseSelector = function (selector) {
  21370.       if (!selector || typeof selector !== 'string') {
  21371.         return [];
  21372.       }
  21373.       selector = selector.split(/\s*,\s*/)[0];
  21374.       selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21375.       return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21376.         var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21377.         var obj = siblings.pop();
  21378.         if (siblings.length) {
  21379.           obj.siblings = siblings;
  21380.         }
  21381.         return obj;
  21382.       }).reverse();
  21383.     };
  21384.     var getCssText = function (editor, format) {
  21385.       var name, previewFrag;
  21386.       var previewCss = '', parentFontSize;
  21387.       var previewStyles = getPreviewStyles(editor);
  21388.       if (previewStyles === '') {
  21389.         return '';
  21390.       }
  21391.       var removeVars = function (val) {
  21392.         return val.replace(/%(\w+)/g, '');
  21393.       };
  21394.       if (typeof format === 'string') {
  21395.         format = editor.formatter.get(format);
  21396.         if (!format) {
  21397.           return;
  21398.         }
  21399.         format = format[0];
  21400.       }
  21401.       if ('preview' in format) {
  21402.         var previewOpt = get$9(format, 'preview');
  21403.         if (is$1(previewOpt, false)) {
  21404.           return '';
  21405.         } else {
  21406.           previewStyles = previewOpt.getOr(previewStyles);
  21407.         }
  21408.       }
  21409.       name = format.block || format.inline || 'span';
  21410.       var items = parseSelector(format.selector);
  21411.       if (items.length) {
  21412.         if (!items[0].name) {
  21413.           items[0].name = name;
  21414.         }
  21415.         name = format.selector;
  21416.         previewFrag = parsedSelectorToHtml(items, editor);
  21417.       } else {
  21418.         previewFrag = parsedSelectorToHtml([name], editor);
  21419.       }
  21420.       var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21421.       each$5(format.styles, function (value, name) {
  21422.         var newValue = removeVars(value);
  21423.         if (newValue) {
  21424.           dom.setStyle(previewElm, name, newValue);
  21425.         }
  21426.       });
  21427.       each$5(format.attributes, function (value, name) {
  21428.         var newValue = removeVars(value);
  21429.         if (newValue) {
  21430.           dom.setAttrib(previewElm, name, newValue);
  21431.         }
  21432.       });
  21433.       each$5(format.classes, function (value) {
  21434.         var newValue = removeVars(value);
  21435.         if (!dom.hasClass(previewElm, newValue)) {
  21436.           dom.addClass(previewElm, newValue);
  21437.         }
  21438.       });
  21439.       editor.fire('PreviewFormats');
  21440.       dom.setStyles(previewFrag, {
  21441.         position: 'absolute',
  21442.         left: -65535
  21443.       });
  21444.       editor.getBody().appendChild(previewFrag);
  21445.       parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21446.       parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21447.       each$5(previewStyles.split(' '), function (name) {
  21448.         var value = dom.getStyle(previewElm, name, true);
  21449.         if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21450.           value = dom.getStyle(editor.getBody(), name, true);
  21451.           if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21452.             return;
  21453.           }
  21454.         }
  21455.         if (name === 'color') {
  21456.           if (dom.toHex(value).toLowerCase() === '#000000') {
  21457.             return;
  21458.           }
  21459.         }
  21460.         if (name === 'font-size') {
  21461.           if (/em|%$/.test(value)) {
  21462.             if (parentFontSize === 0) {
  21463.               return;
  21464.             }
  21465.             var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21466.             value = numValue * parentFontSize + 'px';
  21467.           }
  21468.         }
  21469.         if (name === 'border' && value) {
  21470.           previewCss += 'padding:0 2px;';
  21471.         }
  21472.         previewCss += name + ':' + value + ';';
  21473.       });
  21474.       editor.fire('AfterPreviewFormats');
  21475.       dom.remove(previewFrag);
  21476.       return previewCss;
  21477.     };
  21478.  
  21479.     var setup$h = function (editor) {
  21480.       editor.addShortcut('meta+b', '', 'Bold');
  21481.       editor.addShortcut('meta+i', '', 'Italic');
  21482.       editor.addShortcut('meta+u', '', 'Underline');
  21483.       for (var i = 1; i <= 6; i++) {
  21484.         editor.addShortcut('access+' + i, '', [
  21485.           'FormatBlock',
  21486.           false,
  21487.           'h' + i
  21488.         ]);
  21489.       }
  21490.       editor.addShortcut('access+7', '', [
  21491.         'FormatBlock',
  21492.         false,
  21493.         'p'
  21494.       ]);
  21495.       editor.addShortcut('access+8', '', [
  21496.         'FormatBlock',
  21497.         false,
  21498.         'div'
  21499.       ]);
  21500.       editor.addShortcut('access+9', '', [
  21501.         'FormatBlock',
  21502.         false,
  21503.         'address'
  21504.       ]);
  21505.     };
  21506.  
  21507.     var Formatter = function (editor) {
  21508.       var formats = FormatRegistry(editor);
  21509.       var formatChangeState = Cell(null);
  21510.       setup$h(editor);
  21511.       setup$k(editor);
  21512.       return {
  21513.         get: formats.get,
  21514.         has: formats.has,
  21515.         register: formats.register,
  21516.         unregister: formats.unregister,
  21517.         apply: function (name, vars, node) {
  21518.           applyFormat(editor, name, vars, node);
  21519.         },
  21520.         remove: function (name, vars, node, similar) {
  21521.           removeFormat(editor, name, vars, node, similar);
  21522.         },
  21523.         toggle: function (name, vars, node) {
  21524.           toggleFormat(editor, name, vars, node);
  21525.         },
  21526.         match: function (name, vars, node, similar) {
  21527.           return matchFormat(editor, name, vars, node, similar);
  21528.         },
  21529.         closest: function (names) {
  21530.           return closestFormat(editor, names);
  21531.         },
  21532.         matchAll: function (names, vars) {
  21533.           return matchAllFormats(editor, names, vars);
  21534.         },
  21535.         matchNode: function (node, name, vars, similar) {
  21536.           return matchNodeFormat(editor, node, name, vars, similar);
  21537.         },
  21538.         canApply: function (name) {
  21539.           return canApplyFormat(editor, name);
  21540.         },
  21541.         formatChanged: function (formats, callback, similar, vars) {
  21542.           return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21543.         },
  21544.         getCssText: curry(getCssText, editor)
  21545.       };
  21546.     };
  21547.  
  21548.     var shouldIgnoreCommand = function (cmd) {
  21549.       switch (cmd.toLowerCase()) {
  21550.       case 'undo':
  21551.       case 'redo':
  21552.       case 'mcerepaint':
  21553.       case 'mcefocus':
  21554.         return true;
  21555.       default:
  21556.         return false;
  21557.       }
  21558.     };
  21559.     var registerEvents = function (editor, undoManager, locks) {
  21560.       var isFirstTypedCharacter = Cell(false);
  21561.       var addNonTypingUndoLevel = function (e) {
  21562.         setTyping(undoManager, false, locks);
  21563.         undoManager.add({}, e);
  21564.       };
  21565.       editor.on('init', function () {
  21566.         undoManager.add();
  21567.       });
  21568.       editor.on('BeforeExecCommand', function (e) {
  21569.         var cmd = e.command;
  21570.         if (!shouldIgnoreCommand(cmd)) {
  21571.           endTyping(undoManager, locks);
  21572.           undoManager.beforeChange();
  21573.         }
  21574.       });
  21575.       editor.on('ExecCommand', function (e) {
  21576.         var cmd = e.command;
  21577.         if (!shouldIgnoreCommand(cmd)) {
  21578.           addNonTypingUndoLevel(e);
  21579.         }
  21580.       });
  21581.       editor.on('ObjectResizeStart cut', function () {
  21582.         undoManager.beforeChange();
  21583.       });
  21584.       editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21585.       editor.on('dragend', addNonTypingUndoLevel);
  21586.       editor.on('keyup', function (e) {
  21587.         var keyCode = e.keyCode;
  21588.         if (e.isDefaultPrevented()) {
  21589.           return;
  21590.         }
  21591.         if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21592.           addNonTypingUndoLevel();
  21593.           editor.nodeChanged();
  21594.         }
  21595.         if (keyCode === 46 || keyCode === 8) {
  21596.           editor.nodeChanged();
  21597.         }
  21598.         if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21599.           if (editor.isDirty() === false) {
  21600.             editor.setDirty(true);
  21601.             editor.fire('change', {
  21602.               level: undoManager.data[0],
  21603.               lastLevel: null
  21604.             });
  21605.           }
  21606.           editor.fire('TypingUndo');
  21607.           isFirstTypedCharacter.set(false);
  21608.           editor.nodeChanged();
  21609.         }
  21610.       });
  21611.       editor.on('keydown', function (e) {
  21612.         var keyCode = e.keyCode;
  21613.         if (e.isDefaultPrevented()) {
  21614.           return;
  21615.         }
  21616.         if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21617.           if (undoManager.typing) {
  21618.             addNonTypingUndoLevel(e);
  21619.           }
  21620.           return;
  21621.         }
  21622.         var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21623.         if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21624.           undoManager.beforeChange();
  21625.           setTyping(undoManager, true, locks);
  21626.           undoManager.add({}, e);
  21627.           isFirstTypedCharacter.set(true);
  21628.         }
  21629.       });
  21630.       editor.on('mousedown', function (e) {
  21631.         if (undoManager.typing) {
  21632.           addNonTypingUndoLevel(e);
  21633.         }
  21634.       });
  21635.       var isInsertReplacementText = function (event) {
  21636.         return event.inputType === 'insertReplacementText';
  21637.       };
  21638.       var isInsertTextDataNull = function (event) {
  21639.         return event.inputType === 'insertText' && event.data === null;
  21640.       };
  21641.       var isInsertFromPasteOrDrop = function (event) {
  21642.         return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21643.       };
  21644.       editor.on('input', function (e) {
  21645.         if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21646.           addNonTypingUndoLevel(e);
  21647.         }
  21648.       });
  21649.       editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21650.         if (!e.isDefaultPrevented()) {
  21651.           editor.nodeChanged();
  21652.         }
  21653.       });
  21654.     };
  21655.     var addKeyboardShortcuts = function (editor) {
  21656.       editor.addShortcut('meta+z', '', 'Undo');
  21657.       editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21658.     };
  21659.  
  21660.     var UndoManager = function (editor) {
  21661.       var beforeBookmark = value();
  21662.       var locks = Cell(0);
  21663.       var index = Cell(0);
  21664.       var undoManager = {
  21665.         data: [],
  21666.         typing: false,
  21667.         beforeChange: function () {
  21668.           beforeChange(editor, locks, beforeBookmark);
  21669.         },
  21670.         add: function (level, event) {
  21671.           return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21672.         },
  21673.         undo: function () {
  21674.           return undo(editor, undoManager, locks, index);
  21675.         },
  21676.         redo: function () {
  21677.           return redo(editor, index, undoManager.data);
  21678.         },
  21679.         clear: function () {
  21680.           clear(editor, undoManager, index);
  21681.         },
  21682.         reset: function () {
  21683.           reset(editor, undoManager);
  21684.         },
  21685.         hasUndo: function () {
  21686.           return hasUndo(editor, undoManager, index);
  21687.         },
  21688.         hasRedo: function () {
  21689.           return hasRedo(editor, undoManager, index);
  21690.         },
  21691.         transact: function (callback) {
  21692.           return transact(editor, undoManager, locks, callback);
  21693.         },
  21694.         ignore: function (callback) {
  21695.           ignore(editor, locks, callback);
  21696.         },
  21697.         extra: function (callback1, callback2) {
  21698.           extra(editor, undoManager, index, callback1, callback2);
  21699.         }
  21700.       };
  21701.       if (!isRtc(editor)) {
  21702.         registerEvents(editor, undoManager, locks);
  21703.       }
  21704.       addKeyboardShortcuts(editor);
  21705.       return undoManager;
  21706.     };
  21707.  
  21708.     var nonTypingKeycodes = [
  21709.       9,
  21710.       27,
  21711.       VK.HOME,
  21712.       VK.END,
  21713.       19,
  21714.       20,
  21715.       44,
  21716.       144,
  21717.       145,
  21718.       33,
  21719.       34,
  21720.       45,
  21721.       16,
  21722.       17,
  21723.       18,
  21724.       91,
  21725.       92,
  21726.       93,
  21727.       VK.DOWN,
  21728.       VK.UP,
  21729.       VK.LEFT,
  21730.       VK.RIGHT
  21731.     ].concat(Env.browser.isFirefox() ? [224] : []);
  21732.     var placeholderAttr = 'data-mce-placeholder';
  21733.     var isKeyboardEvent = function (e) {
  21734.       return e.type === 'keydown' || e.type === 'keyup';
  21735.     };
  21736.     var isDeleteEvent = function (e) {
  21737.       var keyCode = e.keyCode;
  21738.       return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21739.     };
  21740.     var isNonTypingKeyboardEvent = function (e) {
  21741.       if (isKeyboardEvent(e)) {
  21742.         var keyCode = e.keyCode;
  21743.         return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21744.       } else {
  21745.         return false;
  21746.       }
  21747.     };
  21748.     var isTypingKeyboardEvent = function (e) {
  21749.       return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21750.     };
  21751.     var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21752.       if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21753.         var isForcedRootBlockFalse = forcedRootBlock === '';
  21754.         var firstElement = rootElm.firstElementChild;
  21755.         if (!firstElement) {
  21756.           return true;
  21757.         } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21758.           return false;
  21759.         } else {
  21760.           return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21761.         }
  21762.       } else {
  21763.         return false;
  21764.       }
  21765.     };
  21766.     var setup$g = function (editor) {
  21767.       var dom = editor.dom;
  21768.       var rootBlock = getForcedRootBlock(editor);
  21769.       var placeholder = getPlaceholder(editor);
  21770.       var updatePlaceholder = function (e, initial) {
  21771.         if (isNonTypingKeyboardEvent(e)) {
  21772.           return;
  21773.         }
  21774.         var body = editor.getBody();
  21775.         var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21776.         var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21777.         if (isPlaceholderShown !== showPlaceholder || initial) {
  21778.           dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21779.           dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21780.           firePlaceholderToggle(editor, showPlaceholder);
  21781.           editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21782.           editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21783.         }
  21784.       };
  21785.       if (placeholder) {
  21786.         editor.on('init', function (e) {
  21787.           updatePlaceholder(e, true);
  21788.           editor.on('change SetContent ExecCommand', updatePlaceholder);
  21789.           editor.on('paste', function (e) {
  21790.             return Delay.setEditorTimeout(editor, function () {
  21791.               return updatePlaceholder(e);
  21792.             });
  21793.           });
  21794.         });
  21795.       }
  21796.     };
  21797.  
  21798.     var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21799.     var hasStrongRtl = function (text) {
  21800.       return strongRtl.test(text);
  21801.     };
  21802.  
  21803.     var isInlineTarget = function (editor, elm) {
  21804.       return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21805.     };
  21806.     var isRtl = function (element) {
  21807.       return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21808.     };
  21809.     var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21810.       return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21811.     };
  21812.     var findRootInline = function (isInlineTarget, rootNode, pos) {
  21813.       var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21814.       return Optional.from(parents[parents.length - 1]);
  21815.     };
  21816.     var hasSameParentBlock = function (rootNode, node1, node2) {
  21817.       var block1 = getParentBlock$2(node1, rootNode);
  21818.       var block2 = getParentBlock$2(node2, rootNode);
  21819.       return block1 && block1 === block2;
  21820.     };
  21821.     var isAtZwsp = function (pos) {
  21822.       return isBeforeInline(pos) || isAfterInline(pos);
  21823.     };
  21824.     var normalizePosition = function (forward, pos) {
  21825.       if (!pos) {
  21826.         return pos;
  21827.       }
  21828.       var container = pos.container(), offset = pos.offset();
  21829.       if (forward) {
  21830.         if (isCaretContainerInline(container)) {
  21831.           if (isText$7(container.nextSibling)) {
  21832.             return CaretPosition(container.nextSibling, 0);
  21833.           } else {
  21834.             return CaretPosition.after(container);
  21835.           }
  21836.         } else {
  21837.           return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21838.         }
  21839.       } else {
  21840.         if (isCaretContainerInline(container)) {
  21841.           if (isText$7(container.previousSibling)) {
  21842.             return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21843.           } else {
  21844.             return CaretPosition.before(container);
  21845.           }
  21846.         } else {
  21847.           return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21848.         }
  21849.       }
  21850.     };
  21851.     var normalizeForwards = curry(normalizePosition, true);
  21852.     var normalizeBackwards = curry(normalizePosition, false);
  21853.  
  21854.     var isBeforeRoot = function (rootNode) {
  21855.       return function (elm) {
  21856.         return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21857.       };
  21858.     };
  21859.     var isTextBlockOrListItem = function (element) {
  21860.       return isTextBlock$2(element) || isListItem(element);
  21861.     };
  21862.     var getParentBlock$1 = function (rootNode, elm) {
  21863.       if (contains$1(rootNode, elm)) {
  21864.         return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21865.       } else {
  21866.         return Optional.none();
  21867.       }
  21868.     };
  21869.     var placeCaretInEmptyBody = function (editor) {
  21870.       var body = editor.getBody();
  21871.       var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21872.       editor.selection.setCursorLocation(node, 0);
  21873.     };
  21874.     var paddEmptyBody = function (editor) {
  21875.       if (editor.dom.isEmpty(editor.getBody())) {
  21876.         editor.setContent('');
  21877.         placeCaretInEmptyBody(editor);
  21878.       }
  21879.     };
  21880.     var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21881.       return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21882.         var normalizedFirstPos = normalizePosition(true, firstPos);
  21883.         var normalizedLastPos = normalizePosition(false, lastPos);
  21884.         var normalizedFromPos = normalizePosition(false, fromPos);
  21885.         if (forward) {
  21886.           return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21887.             return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21888.           });
  21889.         } else {
  21890.           return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21891.             return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21892.           });
  21893.         }
  21894.       }).getOr(true);
  21895.     };
  21896.  
  21897.     var blockPosition = function (block, position) {
  21898.       return {
  21899.         block: block,
  21900.         position: position
  21901.       };
  21902.     };
  21903.     var blockBoundary = function (from, to) {
  21904.       return {
  21905.         from: from,
  21906.         to: to
  21907.       };
  21908.     };
  21909.     var getBlockPosition = function (rootNode, pos) {
  21910.       var rootElm = SugarElement.fromDom(rootNode);
  21911.       var containerElm = SugarElement.fromDom(pos.container());
  21912.       return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21913.         return blockPosition(block, pos);
  21914.       });
  21915.     };
  21916.     var isDifferentBlocks = function (blockBoundary) {
  21917.       return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21918.     };
  21919.     var hasSameParent = function (blockBoundary) {
  21920.       return parent(blockBoundary.from.block).bind(function (parent1) {
  21921.         return parent(blockBoundary.to.block).filter(function (parent2) {
  21922.           return eq(parent1, parent2);
  21923.         });
  21924.       }).isSome();
  21925.     };
  21926.     var isEditable$1 = function (blockBoundary) {
  21927.       return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21928.     };
  21929.     var skipLastBr = function (rootNode, forward, blockPosition) {
  21930.       if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21931.         return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21932.           if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21933.             return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21934.               return getBlockPosition(rootNode, to);
  21935.             });
  21936.           } else {
  21937.             return Optional.some(blockPosition);
  21938.           }
  21939.         }).getOr(blockPosition);
  21940.       } else {
  21941.         return blockPosition;
  21942.       }
  21943.     };
  21944.     var readFromRange = function (rootNode, forward, rng) {
  21945.       var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21946.       var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21947.         return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21948.           return getBlockPosition(rootNode, to).map(function (blockPos) {
  21949.             return skipLastBr(rootNode, forward, blockPos);
  21950.           });
  21951.         });
  21952.       });
  21953.       return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  21954.         return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  21955.       });
  21956.     };
  21957.     var read$1 = function (rootNode, forward, rng) {
  21958.       return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  21959.     };
  21960.  
  21961.     var getChildrenUntilBlockBoundary = function (block) {
  21962.       var children$1 = children(block);
  21963.       return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  21964.         return children$1.slice(0, index);
  21965.       });
  21966.     };
  21967.     var extractChildren = function (block) {
  21968.       var children = getChildrenUntilBlockBoundary(block);
  21969.       each$k(children, remove$7);
  21970.       return children;
  21971.     };
  21972.     var removeEmptyRoot = function (rootNode, block) {
  21973.       var parents = parentsAndSelf(block, rootNode);
  21974.       return find$3(parents.reverse(), function (element) {
  21975.         return isEmpty$2(element);
  21976.       }).each(remove$7);
  21977.     };
  21978.     var isEmptyBefore = function (el) {
  21979.       return filter$4(prevSiblings(el), function (el) {
  21980.         return !isEmpty$2(el);
  21981.       }).length === 0;
  21982.     };
  21983.     var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  21984.       if (isEmpty$2(toBlock)) {
  21985.         fillWithPaddingBr(toBlock);
  21986.         return firstPositionIn(toBlock.dom);
  21987.       }
  21988.       if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  21989.         before$4(insertionPoint, SugarElement.fromTag('br'));
  21990.       }
  21991.       var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  21992.       each$k(extractChildren(fromBlock), function (child) {
  21993.         before$4(insertionPoint, child);
  21994.       });
  21995.       removeEmptyRoot(rootNode, fromBlock);
  21996.       return position;
  21997.     };
  21998.     var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  21999.       if (isEmpty$2(toBlock)) {
  22000.         remove$7(toBlock);
  22001.         if (isEmpty$2(fromBlock)) {
  22002.           fillWithPaddingBr(fromBlock);
  22003.         }
  22004.         return firstPositionIn(fromBlock.dom);
  22005.       }
  22006.       var position = lastPositionIn(toBlock.dom);
  22007.       each$k(extractChildren(fromBlock), function (child) {
  22008.         append$1(toBlock, child);
  22009.       });
  22010.       removeEmptyRoot(rootNode, fromBlock);
  22011.       return position;
  22012.     };
  22013.     var findInsertionPoint = function (toBlock, block) {
  22014.       var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  22015.       return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  22016.     };
  22017.     var getInsertionPoint = function (fromBlock, toBlock) {
  22018.       return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  22019.     };
  22020.     var trimBr = function (first, block) {
  22021.       positionIn(first, block.dom).map(function (position) {
  22022.         return position.getNode();
  22023.       }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  22024.     };
  22025.     var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  22026.       trimBr(true, fromBlock);
  22027.       trimBr(false, toBlock);
  22028.       return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  22029.     };
  22030.     var mergeBlocks = function (rootNode, forward, block1, block2) {
  22031.       return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  22032.     };
  22033.  
  22034.     var backspaceDelete$8 = function (editor, forward) {
  22035.       var rootNode = SugarElement.fromDom(editor.getBody());
  22036.       var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  22037.         return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  22038.       });
  22039.       position.each(function (pos) {
  22040.         editor.selection.setRng(pos.toRange());
  22041.       });
  22042.       return position.isSome();
  22043.     };
  22044.  
  22045.     var deleteRangeMergeBlocks = function (rootNode, selection) {
  22046.       var rng = selection.getRng();
  22047.       return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  22048.         if (eq(block1, block2) === false) {
  22049.           rng.deleteContents();
  22050.           mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  22051.             selection.setRng(pos.toRange());
  22052.           });
  22053.           return true;
  22054.         } else {
  22055.           return false;
  22056.         }
  22057.       }).getOr(false);
  22058.     };
  22059.     var isRawNodeInTable = function (root, rawNode) {
  22060.       var node = SugarElement.fromDom(rawNode);
  22061.       var isRoot = curry(eq, root);
  22062.       return ancestor$3(node, isTableCell$4, isRoot).isSome();
  22063.     };
  22064.     var isSelectionInTable = function (root, rng) {
  22065.       return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  22066.     };
  22067.     var isEverythingSelected = function (root, rng) {
  22068.       var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  22069.       var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  22070.       return !isSelectionInTable(root, rng) && noPrevious && noNext;
  22071.     };
  22072.     var emptyEditor = function (editor) {
  22073.       editor.setContent('');
  22074.       editor.selection.setCursorLocation();
  22075.       return true;
  22076.     };
  22077.     var deleteRange$1 = function (editor) {
  22078.       var rootNode = SugarElement.fromDom(editor.getBody());
  22079.       var rng = editor.selection.getRng();
  22080.       return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  22081.     };
  22082.     var backspaceDelete$7 = function (editor, _forward) {
  22083.       return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  22084.     };
  22085.  
  22086.     var isContentEditableTrue$2 = isContentEditableTrue$4;
  22087.     var isContentEditableFalse$4 = isContentEditableFalse$b;
  22088.     var showCaret = function (direction, editor, node, before, scrollIntoView) {
  22089.       return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  22090.     };
  22091.     var getNodeRange = function (node) {
  22092.       var rng = node.ownerDocument.createRange();
  22093.       rng.selectNode(node);
  22094.       return rng;
  22095.     };
  22096.     var selectNode = function (editor, node) {
  22097.       var e = editor.fire('BeforeObjectSelected', { target: node });
  22098.       if (e.isDefaultPrevented()) {
  22099.         return Optional.none();
  22100.       }
  22101.       return Optional.some(getNodeRange(node));
  22102.     };
  22103.     var renderCaretAtRange = function (editor, range, scrollIntoView) {
  22104.       var normalizedRange = normalizeRange(1, editor.getBody(), range);
  22105.       var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  22106.       var caretPositionNode = caretPosition.getNode();
  22107.       if (isInlineFakeCaretTarget(caretPositionNode)) {
  22108.         return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  22109.       }
  22110.       var caretPositionBeforeNode = caretPosition.getNode(true);
  22111.       if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  22112.         return showCaret(1, editor, caretPositionBeforeNode, false, false);
  22113.       }
  22114.       var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  22115.         return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  22116.       });
  22117.       if (isInlineFakeCaretTarget(ceRoot)) {
  22118.         return showCaret(1, editor, ceRoot, false, scrollIntoView);
  22119.       }
  22120.       return Optional.none();
  22121.     };
  22122.     var renderRangeCaret = function (editor, range, scrollIntoView) {
  22123.       return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  22124.     };
  22125.  
  22126.     var isBeforeBoundary = function (pos) {
  22127.       return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  22128.     };
  22129.     var isAfterBoundary = function (pos) {
  22130.       return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  22131.     };
  22132.     var trimEmptyTextNode = function (dom, node) {
  22133.       if (isText$7(node) && node.data.length === 0) {
  22134.         dom.remove(node);
  22135.       }
  22136.     };
  22137.     var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  22138.       showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  22139.         if (range.collapsed) {
  22140.           var deleteRange = range.cloneRange();
  22141.           if (forward) {
  22142.             deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  22143.           } else {
  22144.             deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  22145.           }
  22146.           deleteRange.deleteContents();
  22147.         } else {
  22148.           range.deleteContents();
  22149.         }
  22150.         editor.selection.setRng(caretRange);
  22151.       });
  22152.       trimEmptyTextNode(editor.dom, node);
  22153.       return true;
  22154.     };
  22155.     var deleteBoundaryText = function (editor, forward) {
  22156.       var range = editor.selection.getRng();
  22157.       if (!isText$7(range.commonAncestorContainer)) {
  22158.         return false;
  22159.       }
  22160.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22161.       var caretWalker = CaretWalker(editor.getBody());
  22162.       var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  22163.       var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  22164.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22165.       var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  22166.       if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  22167.         return false;
  22168.       } else if (isBeforeFn(nextCaretPosition)) {
  22169.         return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  22170.       }
  22171.       var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22172.       if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22173.         if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22174.           return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  22175.         }
  22176.       }
  22177.       return false;
  22178.     };
  22179.     var backspaceDelete$6 = function (editor, forward) {
  22180.       return deleteBoundaryText(editor, forward);
  22181.     };
  22182.  
  22183.     var isCompoundElement = function (node) {
  22184.       return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  22185.     };
  22186.     var DeleteAction = Adt.generate([
  22187.       { remove: ['element'] },
  22188.       { moveToElement: ['element'] },
  22189.       { moveToPosition: ['position'] }
  22190.     ]);
  22191.     var isAtContentEditableBlockCaret = function (forward, from) {
  22192.       var elm = from.getNode(forward === false);
  22193.       var caretLocation = forward ? 'after' : 'before';
  22194.       return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  22195.     };
  22196.     var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  22197.       var inSameBlock = function (elm) {
  22198.         return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  22199.       };
  22200.       return getRelativeCefElm(!forward, from).fold(function () {
  22201.         return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  22202.       }, inSameBlock);
  22203.     };
  22204.     var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  22205.       var toCefElm = to.getNode(forward === false);
  22206.       return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  22207.         return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  22208.       }).orThunk(function () {
  22209.         return Optional.some(DeleteAction.moveToElement(toCefElm));
  22210.       });
  22211.     };
  22212.     var findCefPosition = function (root, forward, from) {
  22213.       return fromPosition(forward, root, from).bind(function (to) {
  22214.         if (isCompoundElement(to.getNode())) {
  22215.           return Optional.none();
  22216.         } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  22217.           return Optional.none();
  22218.         } else if (forward && isContentEditableFalse$b(to.getNode())) {
  22219.           return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22220.         } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  22221.           return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22222.         } else if (forward && isAfterContentEditableFalse(from)) {
  22223.           return Optional.some(DeleteAction.moveToPosition(to));
  22224.         } else if (forward === false && isBeforeContentEditableFalse(from)) {
  22225.           return Optional.some(DeleteAction.moveToPosition(to));
  22226.         } else {
  22227.           return Optional.none();
  22228.         }
  22229.       });
  22230.     };
  22231.     var getContentEditableBlockAction = function (forward, elm) {
  22232.       if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  22233.         return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  22234.       } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  22235.         return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  22236.       } else {
  22237.         return Optional.none();
  22238.       }
  22239.     };
  22240.     var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  22241.       return deleteAction.fold(function (elm) {
  22242.         return Optional.some(DeleteAction.remove(elm));
  22243.       }, function (elm) {
  22244.         return Optional.some(DeleteAction.moveToElement(elm));
  22245.       }, function (to) {
  22246.         if (isInSameBlock(from, to, root)) {
  22247.           return Optional.none();
  22248.         } else {
  22249.           return Optional.some(DeleteAction.moveToPosition(to));
  22250.         }
  22251.       });
  22252.     };
  22253.     var getContentEditableAction = function (root, forward, from) {
  22254.       if (isAtContentEditableBlockCaret(forward, from)) {
  22255.         return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  22256.           return findCefPosition(root, forward, from);
  22257.         }, Optional.some);
  22258.       } else {
  22259.         return findCefPosition(root, forward, from).bind(function (deleteAction) {
  22260.           return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  22261.         });
  22262.       }
  22263.     };
  22264.     var read = function (root, forward, rng) {
  22265.       var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  22266.       var from = CaretPosition.fromRangeStart(normalizedRange);
  22267.       var rootElement = SugarElement.fromDom(root);
  22268.       if (forward === false && isAfterContentEditableFalse(from)) {
  22269.         return Optional.some(DeleteAction.remove(from.getNode(true)));
  22270.       } else if (forward && isBeforeContentEditableFalse(from)) {
  22271.         return Optional.some(DeleteAction.remove(from.getNode()));
  22272.       } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22273.         return findPreviousBr(rootElement, from).map(function (br) {
  22274.           return DeleteAction.remove(br.getNode());
  22275.         });
  22276.       } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22277.         return findNextBr(rootElement, from).map(function (br) {
  22278.           return DeleteAction.remove(br.getNode());
  22279.         });
  22280.       } else {
  22281.         return getContentEditableAction(root, forward, from);
  22282.       }
  22283.     };
  22284.  
  22285.     var deleteElement$1 = function (editor, forward) {
  22286.       return function (element) {
  22287.         editor._selectionOverrides.hideFakeCaret();
  22288.         deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22289.         return true;
  22290.       };
  22291.     };
  22292.     var moveToElement = function (editor, forward) {
  22293.       return function (element) {
  22294.         var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22295.         editor.selection.setRng(pos.toRange());
  22296.         return true;
  22297.       };
  22298.     };
  22299.     var moveToPosition = function (editor) {
  22300.       return function (pos) {
  22301.         editor.selection.setRng(pos.toRange());
  22302.         return true;
  22303.       };
  22304.     };
  22305.     var getAncestorCe = function (editor, node) {
  22306.       return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22307.     };
  22308.     var backspaceDeleteCaret = function (editor, forward) {
  22309.       var selectedNode = editor.selection.getNode();
  22310.       return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22311.         return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22312.           return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22313.         });
  22314.       }, always);
  22315.     };
  22316.     var deleteOffscreenSelection = function (rootElement) {
  22317.       each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22318.     };
  22319.     var backspaceDeleteRange = function (editor, forward) {
  22320.       var selectedNode = editor.selection.getNode();
  22321.       if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22322.         var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22323.         return hasCefAncestor.fold(function () {
  22324.           deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22325.           deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22326.           paddEmptyBody(editor);
  22327.           return true;
  22328.         }, always);
  22329.       }
  22330.       return false;
  22331.     };
  22332.     var paddEmptyElement = function (editor) {
  22333.       var dom = editor.dom, selection = editor.selection;
  22334.       var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22335.       if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22336.         var br = dom.create('br', { 'data-mce-bogus': '1' });
  22337.         dom.setHTML(ceRoot, '');
  22338.         ceRoot.appendChild(br);
  22339.         selection.setRng(CaretPosition.before(br).toRange());
  22340.       }
  22341.       return true;
  22342.     };
  22343.     var backspaceDelete$5 = function (editor, forward) {
  22344.       if (editor.selection.isCollapsed()) {
  22345.         return backspaceDeleteCaret(editor, forward);
  22346.       } else {
  22347.         return backspaceDeleteRange(editor, forward);
  22348.       }
  22349.     };
  22350.  
  22351.     var deleteCaret$2 = function (editor, forward) {
  22352.       var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22353.       return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22354.         return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22355.       }).bind(function (pos) {
  22356.         return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22357.       }).exists(function (elm) {
  22358.         editor.selection.select(elm);
  22359.         return true;
  22360.       });
  22361.     };
  22362.     var backspaceDelete$4 = function (editor, forward) {
  22363.       return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22364.     };
  22365.  
  22366.     var isText = isText$7;
  22367.     var startsWithCaretContainer = function (node) {
  22368.       return isText(node) && node.data[0] === ZWSP$1;
  22369.     };
  22370.     var endsWithCaretContainer = function (node) {
  22371.       return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22372.     };
  22373.     var createZwsp = function (node) {
  22374.       return node.ownerDocument.createTextNode(ZWSP$1);
  22375.     };
  22376.     var insertBefore = function (node) {
  22377.       if (isText(node.previousSibling)) {
  22378.         if (endsWithCaretContainer(node.previousSibling)) {
  22379.           return node.previousSibling;
  22380.         } else {
  22381.           node.previousSibling.appendData(ZWSP$1);
  22382.           return node.previousSibling;
  22383.         }
  22384.       } else if (isText(node)) {
  22385.         if (startsWithCaretContainer(node)) {
  22386.           return node;
  22387.         } else {
  22388.           node.insertData(0, ZWSP$1);
  22389.           return node;
  22390.         }
  22391.       } else {
  22392.         var newNode = createZwsp(node);
  22393.         node.parentNode.insertBefore(newNode, node);
  22394.         return newNode;
  22395.       }
  22396.     };
  22397.     var insertAfter = function (node) {
  22398.       if (isText(node.nextSibling)) {
  22399.         if (startsWithCaretContainer(node.nextSibling)) {
  22400.           return node.nextSibling;
  22401.         } else {
  22402.           node.nextSibling.insertData(0, ZWSP$1);
  22403.           return node.nextSibling;
  22404.         }
  22405.       } else if (isText(node)) {
  22406.         if (endsWithCaretContainer(node)) {
  22407.           return node;
  22408.         } else {
  22409.           node.appendData(ZWSP$1);
  22410.           return node;
  22411.         }
  22412.       } else {
  22413.         var newNode = createZwsp(node);
  22414.         if (node.nextSibling) {
  22415.           node.parentNode.insertBefore(newNode, node.nextSibling);
  22416.         } else {
  22417.           node.parentNode.appendChild(newNode);
  22418.         }
  22419.         return newNode;
  22420.       }
  22421.     };
  22422.     var insertInline = function (before, node) {
  22423.       return before ? insertBefore(node) : insertAfter(node);
  22424.     };
  22425.     var insertInlineBefore = curry(insertInline, true);
  22426.     var insertInlineAfter = curry(insertInline, false);
  22427.  
  22428.     var insertInlinePos = function (pos, before) {
  22429.       if (isText$7(pos.container())) {
  22430.         return insertInline(before, pos.container());
  22431.       } else {
  22432.         return insertInline(before, pos.getNode());
  22433.       }
  22434.     };
  22435.     var isPosCaretContainer = function (pos, caret) {
  22436.       var caretNode = caret.get();
  22437.       return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22438.     };
  22439.     var renderCaret = function (caret, location) {
  22440.       return location.fold(function (element) {
  22441.         remove$2(caret.get());
  22442.         var text = insertInlineBefore(element);
  22443.         caret.set(text);
  22444.         return Optional.some(CaretPosition(text, text.length - 1));
  22445.       }, function (element) {
  22446.         return firstPositionIn(element).map(function (pos) {
  22447.           if (!isPosCaretContainer(pos, caret)) {
  22448.             remove$2(caret.get());
  22449.             var text = insertInlinePos(pos, true);
  22450.             caret.set(text);
  22451.             return CaretPosition(text, 1);
  22452.           } else {
  22453.             return CaretPosition(caret.get(), 1);
  22454.           }
  22455.         });
  22456.       }, function (element) {
  22457.         return lastPositionIn(element).map(function (pos) {
  22458.           if (!isPosCaretContainer(pos, caret)) {
  22459.             remove$2(caret.get());
  22460.             var text = insertInlinePos(pos, false);
  22461.             caret.set(text);
  22462.             return CaretPosition(text, text.length - 1);
  22463.           } else {
  22464.             return CaretPosition(caret.get(), caret.get().length - 1);
  22465.           }
  22466.         });
  22467.       }, function (element) {
  22468.         remove$2(caret.get());
  22469.         var text = insertInlineAfter(element);
  22470.         caret.set(text);
  22471.         return Optional.some(CaretPosition(text, 1));
  22472.       });
  22473.     };
  22474.  
  22475.     var evaluateUntil = function (fns, args) {
  22476.       for (var i = 0; i < fns.length; i++) {
  22477.         var result = fns[i].apply(null, args);
  22478.         if (result.isSome()) {
  22479.           return result;
  22480.         }
  22481.       }
  22482.       return Optional.none();
  22483.     };
  22484.  
  22485.     var Location = Adt.generate([
  22486.       { before: ['element'] },
  22487.       { start: ['element'] },
  22488.       { end: ['element'] },
  22489.       { after: ['element'] }
  22490.     ]);
  22491.     var rescope$1 = function (rootNode, node) {
  22492.       var parentBlock = getParentBlock$2(node, rootNode);
  22493.       return parentBlock ? parentBlock : rootNode;
  22494.     };
  22495.     var before = function (isInlineTarget, rootNode, pos) {
  22496.       var nPos = normalizeForwards(pos);
  22497.       var scope = rescope$1(rootNode, nPos.container());
  22498.       return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22499.         return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22500.           return Location.before(inline);
  22501.         });
  22502.       }, Optional.none);
  22503.     };
  22504.     var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22505.       return getParentCaretContainer(rootNode, elm) === null;
  22506.     };
  22507.     var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22508.       return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22509.     };
  22510.     var start$1 = function (isInlineTarget, rootNode, pos) {
  22511.       var nPos = normalizeBackwards(pos);
  22512.       return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22513.         var prevPos = prevPosition(inline, nPos);
  22514.         return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22515.       });
  22516.     };
  22517.     var end = function (isInlineTarget, rootNode, pos) {
  22518.       var nPos = normalizeForwards(pos);
  22519.       return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22520.         var nextPos = nextPosition(inline, nPos);
  22521.         return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22522.       });
  22523.     };
  22524.     var after = function (isInlineTarget, rootNode, pos) {
  22525.       var nPos = normalizeBackwards(pos);
  22526.       var scope = rescope$1(rootNode, nPos.container());
  22527.       return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22528.         return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22529.           return Location.after(inline);
  22530.         });
  22531.       }, Optional.none);
  22532.     };
  22533.     var isValidLocation = function (location) {
  22534.       return isRtl(getElement(location)) === false;
  22535.     };
  22536.     var readLocation = function (isInlineTarget, rootNode, pos) {
  22537.       var location = evaluateUntil([
  22538.         before,
  22539.         start$1,
  22540.         end,
  22541.         after
  22542.       ], [
  22543.         isInlineTarget,
  22544.         rootNode,
  22545.         pos
  22546.       ]);
  22547.       return location.filter(isValidLocation);
  22548.     };
  22549.     var getElement = function (location) {
  22550.       return location.fold(identity, identity, identity, identity);
  22551.     };
  22552.     var getName = function (location) {
  22553.       return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22554.     };
  22555.     var outside = function (location) {
  22556.       return location.fold(Location.before, Location.before, Location.after, Location.after);
  22557.     };
  22558.     var inside = function (location) {
  22559.       return location.fold(Location.start, Location.start, Location.end, Location.end);
  22560.     };
  22561.     var isEq = function (location1, location2) {
  22562.       return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22563.     };
  22564.     var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22565.       return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22566.         if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22567.           return Location.after(forward ? fromInline : toInline);
  22568.         } else {
  22569.           return location;
  22570.         }
  22571.       }).getOr(location);
  22572.     };
  22573.     var skipNoMovement = function (fromLocation, toLocation) {
  22574.       return fromLocation.fold(always, function (fromLocation) {
  22575.         return !isEq(fromLocation, toLocation);
  22576.       });
  22577.     };
  22578.     var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22579.       var from = normalizePosition(forward, pos);
  22580.       var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22581.       var location = to.fold(function () {
  22582.         return fromLocation.map(outside);
  22583.       }, function (to) {
  22584.         return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22585.       });
  22586.       return location.filter(isValidLocation);
  22587.     };
  22588.     var findLocationSimple = function (forward, location) {
  22589.       if (forward) {
  22590.         return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22591.       } else {
  22592.         return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22593.       }
  22594.     };
  22595.     var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22596.       var from = normalizePosition(forward, pos);
  22597.       var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22598.       return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22599.         return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22600.       });
  22601.     };
  22602.     curry(findLocation$1, false);
  22603.     curry(findLocation$1, true);
  22604.  
  22605.     var hasSelectionModifyApi = function (editor) {
  22606.       return isFunction(editor.selection.getSel().modify);
  22607.     };
  22608.     var moveRel = function (forward, selection, pos) {
  22609.       var delta = forward ? 1 : -1;
  22610.       selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22611.       selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22612.       return true;
  22613.     };
  22614.     var moveByWord = function (forward, editor) {
  22615.       var rng = editor.selection.getRng();
  22616.       var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22617.       if (!hasSelectionModifyApi(editor)) {
  22618.         return false;
  22619.       } else if (forward && isBeforeInline(pos)) {
  22620.         return moveRel(true, editor.selection, pos);
  22621.       } else if (!forward && isAfterInline(pos)) {
  22622.         return moveRel(false, editor.selection, pos);
  22623.       } else {
  22624.         return false;
  22625.       }
  22626.     };
  22627.  
  22628.     var BreakType;
  22629.     (function (BreakType) {
  22630.       BreakType[BreakType['Br'] = 0] = 'Br';
  22631.       BreakType[BreakType['Block'] = 1] = 'Block';
  22632.       BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22633.       BreakType[BreakType['Eol'] = 3] = 'Eol';
  22634.     }(BreakType || (BreakType = {})));
  22635.     var flip = function (direction, positions) {
  22636.       return direction === HDirection.Backwards ? reverse(positions) : positions;
  22637.     };
  22638.     var walk = function (direction, caretWalker, pos) {
  22639.       return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22640.     };
  22641.     var getBreakType = function (scope, direction, currentPos, nextPos) {
  22642.       if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22643.         return BreakType.Br;
  22644.       } else if (isInSameBlock(currentPos, nextPos) === false) {
  22645.         return BreakType.Block;
  22646.       } else {
  22647.         return BreakType.Wrap;
  22648.       }
  22649.     };
  22650.     var getPositionsUntil = function (predicate, direction, scope, start) {
  22651.       var caretWalker = CaretWalker(scope);
  22652.       var currentPos = start;
  22653.       var positions = [];
  22654.       while (currentPos) {
  22655.         var nextPos = walk(direction, caretWalker, currentPos);
  22656.         if (!nextPos) {
  22657.           break;
  22658.         }
  22659.         if (isBr$5(nextPos.getNode(false))) {
  22660.           if (direction === HDirection.Forwards) {
  22661.             return {
  22662.               positions: flip(direction, positions).concat([nextPos]),
  22663.               breakType: BreakType.Br,
  22664.               breakAt: Optional.some(nextPos)
  22665.             };
  22666.           } else {
  22667.             return {
  22668.               positions: flip(direction, positions),
  22669.               breakType: BreakType.Br,
  22670.               breakAt: Optional.some(nextPos)
  22671.             };
  22672.           }
  22673.         }
  22674.         if (!nextPos.isVisible()) {
  22675.           currentPos = nextPos;
  22676.           continue;
  22677.         }
  22678.         if (predicate(currentPos, nextPos)) {
  22679.           var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22680.           return {
  22681.             positions: flip(direction, positions),
  22682.             breakType: breakType,
  22683.             breakAt: Optional.some(nextPos)
  22684.           };
  22685.         }
  22686.         positions.push(nextPos);
  22687.         currentPos = nextPos;
  22688.       }
  22689.       return {
  22690.         positions: flip(direction, positions),
  22691.         breakType: BreakType.Eol,
  22692.         breakAt: Optional.none()
  22693.       };
  22694.     };
  22695.     var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22696.       return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22697.         var positions = getPositionsUntilBreak(scope, pos).positions;
  22698.         return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22699.       }).getOr([]);
  22700.     };
  22701.     var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22702.       return foldl(positions, function (acc, newPos) {
  22703.         return acc.fold(function () {
  22704.           return Optional.some(newPos);
  22705.         }, function (lastPos) {
  22706.           return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22707.             var lastDist = Math.abs(x - lastRect.left);
  22708.             var newDist = Math.abs(x - newRect.left);
  22709.             return newDist <= lastDist ? newPos : lastPos;
  22710.           }).or(acc);
  22711.         });
  22712.       }, Optional.none());
  22713.     };
  22714.     var findClosestHorizontalPosition = function (positions, pos) {
  22715.       return head(pos.getClientRects()).bind(function (targetRect) {
  22716.         return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22717.       });
  22718.     };
  22719.     var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22720.     var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22721.     var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22722.     var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22723.     var isAtFirstLine = function (scope, pos) {
  22724.       return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22725.     };
  22726.     var isAtLastLine = function (scope, pos) {
  22727.       return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22728.     };
  22729.     var getFirstLinePositions = function (scope) {
  22730.       return firstPositionIn(scope).map(function (pos) {
  22731.         return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22732.       }).getOr([]);
  22733.     };
  22734.     var getLastLinePositions = function (scope) {
  22735.       return lastPositionIn(scope).map(function (pos) {
  22736.         return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22737.       }).getOr([]);
  22738.     };
  22739.  
  22740.     var getNodeClientRects = function (node) {
  22741.       var toArrayWithNode = function (clientRects) {
  22742.         return map$3(clientRects, function (rect) {
  22743.           var clientRect = clone(rect);
  22744.           clientRect.node = node;
  22745.           return clientRect;
  22746.         });
  22747.       };
  22748.       if (isElement$5(node)) {
  22749.         return toArrayWithNode(node.getClientRects());
  22750.       }
  22751.       if (isText$7(node)) {
  22752.         var rng = node.ownerDocument.createRange();
  22753.         rng.setStart(node, 0);
  22754.         rng.setEnd(node, node.data.length);
  22755.         return toArrayWithNode(rng.getClientRects());
  22756.       }
  22757.     };
  22758.     var getClientRects = function (nodes) {
  22759.       return bind(nodes, getNodeClientRects);
  22760.     };
  22761.  
  22762.     var VDirection;
  22763.     (function (VDirection) {
  22764.       VDirection[VDirection['Up'] = -1] = 'Up';
  22765.       VDirection[VDirection['Down'] = 1] = 'Down';
  22766.     }(VDirection || (VDirection = {})));
  22767.     var findUntil = function (direction, root, predicateFn, node) {
  22768.       while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22769.         if (predicateFn(node)) {
  22770.           return;
  22771.         }
  22772.       }
  22773.     };
  22774.     var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22775.       var line = 0;
  22776.       var result = [];
  22777.       var add = function (node) {
  22778.         var clientRects = getClientRects([node]);
  22779.         if (direction === -1) {
  22780.           clientRects = clientRects.reverse();
  22781.         }
  22782.         for (var i = 0; i < clientRects.length; i++) {
  22783.           var clientRect = clientRects[i];
  22784.           if (isBeflowFn(clientRect, targetClientRect)) {
  22785.             continue;
  22786.           }
  22787.           if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22788.             line++;
  22789.           }
  22790.           clientRect.line = line;
  22791.           if (predicateFn(clientRect)) {
  22792.             return true;
  22793.           }
  22794.           result.push(clientRect);
  22795.         }
  22796.       };
  22797.       var targetClientRect = last$1(caretPosition.getClientRects());
  22798.       if (!targetClientRect) {
  22799.         return result;
  22800.       }
  22801.       var node = caretPosition.getNode();
  22802.       add(node);
  22803.       findUntil(direction, root, add, node);
  22804.       return result;
  22805.     };
  22806.     var aboveLineNumber = function (lineNumber, clientRect) {
  22807.       return clientRect.line > lineNumber;
  22808.     };
  22809.     var isLineNumber = function (lineNumber, clientRect) {
  22810.       return clientRect.line === lineNumber;
  22811.     };
  22812.     var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22813.     var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22814.     var positionsUntil = function (direction, root, predicateFn, node) {
  22815.       var caretWalker = CaretWalker(root);
  22816.       var walkFn;
  22817.       var isBelowFn;
  22818.       var isAboveFn;
  22819.       var caretPosition;
  22820.       var result = [];
  22821.       var line = 0;
  22822.       var getClientRect = function (caretPosition) {
  22823.         if (direction === 1) {
  22824.           return last$1(caretPosition.getClientRects());
  22825.         }
  22826.         return last$1(caretPosition.getClientRects());
  22827.       };
  22828.       if (direction === 1) {
  22829.         walkFn = caretWalker.next;
  22830.         isBelowFn = isBelow$1;
  22831.         isAboveFn = isAbove$1;
  22832.         caretPosition = CaretPosition.after(node);
  22833.       } else {
  22834.         walkFn = caretWalker.prev;
  22835.         isBelowFn = isAbove$1;
  22836.         isAboveFn = isBelow$1;
  22837.         caretPosition = CaretPosition.before(node);
  22838.       }
  22839.       var targetClientRect = getClientRect(caretPosition);
  22840.       do {
  22841.         if (!caretPosition.isVisible()) {
  22842.           continue;
  22843.         }
  22844.         var rect = getClientRect(caretPosition);
  22845.         if (isAboveFn(rect, targetClientRect)) {
  22846.           continue;
  22847.         }
  22848.         if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22849.           line++;
  22850.         }
  22851.         var clientRect = clone(rect);
  22852.         clientRect.position = caretPosition;
  22853.         clientRect.line = line;
  22854.         if (predicateFn(clientRect)) {
  22855.           return result;
  22856.         }
  22857.         result.push(clientRect);
  22858.       } while (caretPosition = walkFn(caretPosition));
  22859.       return result;
  22860.     };
  22861.     var isAboveLine = function (lineNumber) {
  22862.       return function (clientRect) {
  22863.         return aboveLineNumber(lineNumber, clientRect);
  22864.       };
  22865.     };
  22866.     var isLine = function (lineNumber) {
  22867.       return function (clientRect) {
  22868.         return isLineNumber(lineNumber, clientRect);
  22869.       };
  22870.     };
  22871.  
  22872.     var isContentEditableFalse$3 = isContentEditableFalse$b;
  22873.     var findNode = findNode$1;
  22874.     var distanceToRectLeft = function (clientRect, clientX) {
  22875.       return Math.abs(clientRect.left - clientX);
  22876.     };
  22877.     var distanceToRectRight = function (clientRect, clientX) {
  22878.       return Math.abs(clientRect.right - clientX);
  22879.     };
  22880.     var isInsideX = function (clientX, clientRect) {
  22881.       return clientX >= clientRect.left && clientX <= clientRect.right;
  22882.     };
  22883.     var isInsideY = function (clientY, clientRect) {
  22884.       return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22885.     };
  22886.     var isNodeClientRect = function (rect) {
  22887.       return hasNonNullableKey(rect, 'node');
  22888.     };
  22889.     var findClosestClientRect = function (clientRects, clientX, allowInside) {
  22890.       if (allowInside === void 0) {
  22891.         allowInside = always;
  22892.       }
  22893.       return reduce(clientRects, function (oldClientRect, clientRect) {
  22894.         if (isInsideX(clientX, clientRect)) {
  22895.           return allowInside(clientRect) ? clientRect : oldClientRect;
  22896.         }
  22897.         if (isInsideX(clientX, oldClientRect)) {
  22898.           return allowInside(oldClientRect) ? oldClientRect : clientRect;
  22899.         }
  22900.         var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22901.         var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22902.         if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  22903.           return clientRect;
  22904.         }
  22905.         if (newDistance < oldDistance) {
  22906.           return clientRect;
  22907.         }
  22908.         return oldClientRect;
  22909.       });
  22910.     };
  22911.     var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22912.       var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22913.       do {
  22914.         if (!node || predicateFn(node)) {
  22915.           return;
  22916.         }
  22917.       } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22918.     };
  22919.     var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22920.       if (includeChildren === void 0) {
  22921.         includeChildren = true;
  22922.       }
  22923.       var clientRects = [];
  22924.       var collect = function (checkPosFn, node) {
  22925.         var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22926.           return !checkPosFn(clientRect, targetNodeRect);
  22927.         });
  22928.         clientRects = clientRects.concat(lineRects);
  22929.         return lineRects.length === 0;
  22930.       };
  22931.       clientRects.push(targetNodeRect);
  22932.       walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22933.       walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22934.       return clientRects;
  22935.     };
  22936.     var getFakeCaretTargets = function (root) {
  22937.       return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22938.     };
  22939.     var caretInfo = function (clientRect, clientX) {
  22940.       return {
  22941.         node: clientRect.node,
  22942.         before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22943.       };
  22944.     };
  22945.     var closestFakeCaret = function (root, clientX, clientY) {
  22946.       var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22947.       var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22948.       var checkInside = function (clientRect) {
  22949.         return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
  22950.       };
  22951.       var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
  22952.       if (closestNodeRect) {
  22953.         var includeChildren = checkInside(closestNodeRect);
  22954.         closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
  22955.         if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  22956.           return caretInfo(closestNodeRect, clientX);
  22957.         }
  22958.       }
  22959.       return null;
  22960.     };
  22961.  
  22962.     var moveToRange = function (editor, rng) {
  22963.       editor.selection.setRng(rng);
  22964.       scrollRangeIntoView(editor, editor.selection.getRng());
  22965.     };
  22966.     var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  22967.       return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  22968.     };
  22969.     var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  22970.       var forwards = direction === HDirection.Forwards;
  22971.       var caretWalker = CaretWalker(editor.getBody());
  22972.       var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  22973.       var isBeforeFn = forwards ? isBefore : isAfter;
  22974.       if (!range.collapsed) {
  22975.         var node = getSelectedNode(range);
  22976.         if (isElement(node)) {
  22977.           return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  22978.         }
  22979.       }
  22980.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22981.       if (isBeforeFn(caretPosition)) {
  22982.         return selectNode(editor, caretPosition.getNode(!forwards));
  22983.       }
  22984.       var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  22985.       var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  22986.       if (!nextCaretPosition) {
  22987.         return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  22988.       }
  22989.       if (isBeforeFn(nextCaretPosition)) {
  22990.         return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  22991.       }
  22992.       var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22993.       if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22994.         if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22995.           return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  22996.         }
  22997.       }
  22998.       if (rangeIsInContainerBlock) {
  22999.         return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  23000.       }
  23001.       return Optional.none();
  23002.     };
  23003.     var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  23004.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  23005.       var caretClientRect = last$1(caretPosition.getClientRects());
  23006.       var forwards = direction === VDirection.Down;
  23007.       if (!caretClientRect) {
  23008.         return Optional.none();
  23009.       }
  23010.       var walkerFn = forwards ? downUntil : upUntil;
  23011.       var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  23012.       var nextLinePositions = filter$4(linePositions, isLine(1));
  23013.       var clientX = caretClientRect.left;
  23014.       var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  23015.       if (nextLineRect && isElement(nextLineRect.node)) {
  23016.         var dist1 = Math.abs(clientX - nextLineRect.left);
  23017.         var dist2 = Math.abs(clientX - nextLineRect.right);
  23018.         return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  23019.       }
  23020.       var currentNode;
  23021.       if (isBefore(caretPosition)) {
  23022.         currentNode = caretPosition.getNode();
  23023.       } else if (isAfter(caretPosition)) {
  23024.         currentNode = caretPosition.getNode(true);
  23025.       } else {
  23026.         currentNode = getSelectedNode(range);
  23027.       }
  23028.       if (currentNode) {
  23029.         var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  23030.         var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  23031.         if (closestNextLineRect) {
  23032.           return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  23033.         }
  23034.         closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  23035.         if (closestNextLineRect) {
  23036.           return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  23037.         }
  23038.       }
  23039.       if (nextLinePositions.length === 0) {
  23040.         return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  23041.           return renderRangeCaret(editor, pos.toRange(), false);
  23042.         });
  23043.       }
  23044.       return Optional.none();
  23045.     };
  23046.     var getLineEndPoint = function (editor, forward) {
  23047.       var rng = editor.selection.getRng();
  23048.       var body = editor.getBody();
  23049.       if (forward) {
  23050.         var from = CaretPosition.fromRangeEnd(rng);
  23051.         var result = getPositionsUntilNextLine(body, from);
  23052.         return last$2(result.positions);
  23053.       } else {
  23054.         var from = CaretPosition.fromRangeStart(rng);
  23055.         var result = getPositionsUntilPreviousLine(body, from);
  23056.         return head(result.positions);
  23057.       }
  23058.     };
  23059.     var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  23060.       return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  23061.         editor.selection.setRng(pos.toRange());
  23062.         return true;
  23063.       });
  23064.     };
  23065.  
  23066.     var setCaretPosition = function (editor, pos) {
  23067.       var rng = editor.dom.createRng();
  23068.       rng.setStart(pos.container(), pos.offset());
  23069.       rng.setEnd(pos.container(), pos.offset());
  23070.       editor.selection.setRng(rng);
  23071.     };
  23072.     var setSelected = function (state, elm) {
  23073.       if (state) {
  23074.         elm.setAttribute('data-mce-selected', 'inline-boundary');
  23075.       } else {
  23076.         elm.removeAttribute('data-mce-selected');
  23077.       }
  23078.     };
  23079.     var renderCaretLocation = function (editor, caret, location) {
  23080.       return renderCaret(caret, location).map(function (pos) {
  23081.         setCaretPosition(editor, pos);
  23082.         return location;
  23083.       });
  23084.     };
  23085.     var findLocation = function (editor, caret, forward) {
  23086.       var rootNode = editor.getBody();
  23087.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  23088.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23089.       var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  23090.       return location.bind(function (location) {
  23091.         return renderCaretLocation(editor, caret, location);
  23092.       });
  23093.     };
  23094.     var toggleInlines = function (isInlineTarget, dom, elms) {
  23095.       var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  23096.         return e.dom;
  23097.       });
  23098.       var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  23099.       var targetInlines = filter$4(elms, isInlineTarget);
  23100.       each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  23101.       each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  23102.     };
  23103.     var safeRemoveCaretContainer = function (editor, caret) {
  23104.       if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  23105.         var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23106.         if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  23107.           setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  23108.           caret.set(null);
  23109.         }
  23110.       }
  23111.     };
  23112.     var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  23113.       if (editor.selection.isCollapsed()) {
  23114.         var inlines = filter$4(elms, isInlineTarget);
  23115.         each$k(inlines, function (_inline) {
  23116.           var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23117.           readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  23118.             return renderCaretLocation(editor, caret, location);
  23119.           });
  23120.         });
  23121.       }
  23122.     };
  23123.     var move$2 = function (editor, caret, forward) {
  23124.       return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  23125.     };
  23126.     var moveWord = function (forward, editor, _caret) {
  23127.       return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  23128.     };
  23129.     var setupSelectedState = function (editor) {
  23130.       var caret = Cell(null);
  23131.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23132.       editor.on('NodeChange', function (e) {
  23133.         if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  23134.           toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  23135.           safeRemoveCaretContainer(editor, caret);
  23136.           renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  23137.         }
  23138.       });
  23139.       return caret;
  23140.     };
  23141.     var moveNextWord = curry(moveWord, true);
  23142.     var movePrevWord = curry(moveWord, false);
  23143.     var moveToLineEndPoint$2 = function (editor, forward, caret) {
  23144.       if (isInlineBoundariesEnabled(editor)) {
  23145.         var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  23146.           var rng = editor.selection.getRng();
  23147.           return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  23148.         });
  23149.         return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  23150.           var outsideLoc = outside(loc);
  23151.           return renderCaret(caret, outsideLoc).exists(function (pos) {
  23152.             setCaretPosition(editor, pos);
  23153.             return true;
  23154.           });
  23155.         });
  23156.       } else {
  23157.         return false;
  23158.       }
  23159.     };
  23160.  
  23161.     var rangeFromPositions = function (from, to) {
  23162.       var range = document.createRange();
  23163.       range.setStart(from.container(), from.offset());
  23164.       range.setEnd(to.container(), to.offset());
  23165.       return range;
  23166.     };
  23167.     var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  23168.       return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  23169.         var normalizedFirstPos = normalizePosition(true, firstPos);
  23170.         var normalizedLastPos = normalizePosition(false, lastPos);
  23171.         return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  23172.           return pos.isEqual(normalizedLastPos);
  23173.         });
  23174.       }).getOr(true);
  23175.     };
  23176.     var setCaretLocation = function (editor, caret) {
  23177.       return function (location) {
  23178.         return renderCaret(caret, location).exists(function (pos) {
  23179.           setCaretPosition(editor, pos);
  23180.           return true;
  23181.         });
  23182.       };
  23183.     };
  23184.     var deleteFromTo = function (editor, caret, from, to) {
  23185.       var rootNode = editor.getBody();
  23186.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23187.       editor.undoManager.ignore(function () {
  23188.         editor.selection.setRng(rangeFromPositions(from, to));
  23189.         editor.execCommand('Delete');
  23190.         readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  23191.       });
  23192.       editor.nodeChanged();
  23193.     };
  23194.     var rescope = function (rootNode, node) {
  23195.       var parentBlock = getParentBlock$2(node, rootNode);
  23196.       return parentBlock ? parentBlock : rootNode;
  23197.     };
  23198.     var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  23199.       var rootNode = rescope(editor.getBody(), from.container());
  23200.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23201.       var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  23202.       return fromLocation.bind(function (location) {
  23203.         if (forward) {
  23204.           return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  23205.         } else {
  23206.           return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  23207.         }
  23208.       }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  23209.         var toPosition = navigate(forward, rootNode, from);
  23210.         var toLocation = toPosition.bind(function (pos) {
  23211.           return readLocation(isInlineTarget$1, rootNode, pos);
  23212.         });
  23213.         return lift2(fromLocation, toLocation, function () {
  23214.           return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  23215.             if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  23216.               deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  23217.               return true;
  23218.             } else {
  23219.               return false;
  23220.             }
  23221.           });
  23222.         }).orThunk(function () {
  23223.           return toLocation.bind(function (_) {
  23224.             return toPosition.map(function (to) {
  23225.               if (forward) {
  23226.                 deleteFromTo(editor, caret, from, to);
  23227.               } else {
  23228.                 deleteFromTo(editor, caret, to, from);
  23229.               }
  23230.               return true;
  23231.             });
  23232.           });
  23233.         }).getOr(false);
  23234.       });
  23235.     };
  23236.     var backspaceDelete$3 = function (editor, caret, forward) {
  23237.       if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  23238.         var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  23239.         return backspaceDeleteCollapsed(editor, caret, forward, from);
  23240.       }
  23241.       return false;
  23242.     };
  23243.  
  23244.     var getParentInlines = function (rootElm, startElm) {
  23245.       var parents = parentsAndSelf(startElm, rootElm);
  23246.       return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  23247.         return parents.slice(0, index);
  23248.       });
  23249.     };
  23250.     var hasOnlyOneChild = function (elm) {
  23251.       return childNodesCount(elm) === 1;
  23252.     };
  23253.     var deleteLastPosition = function (forward, editor, target, parentInlines) {
  23254.       var isFormatElement$1 = curry(isFormatElement, editor);
  23255.       var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  23256.         return elm.dom;
  23257.       });
  23258.       if (formatNodes.length === 0) {
  23259.         deleteElement$2(editor, forward, target);
  23260.       } else {
  23261.         var pos = replaceWithCaretFormat(target.dom, formatNodes);
  23262.         editor.selection.setRng(pos.toRange());
  23263.       }
  23264.     };
  23265.     var deleteCaret$1 = function (editor, forward) {
  23266.       var rootElm = SugarElement.fromDom(editor.getBody());
  23267.       var startElm = SugarElement.fromDom(editor.selection.getStart());
  23268.       var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  23269.       return last$2(parentInlines).exists(function (target) {
  23270.         var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23271.         if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  23272.           deleteLastPosition(forward, editor, target, parentInlines);
  23273.           return true;
  23274.         } else {
  23275.           return false;
  23276.         }
  23277.       });
  23278.     };
  23279.     var backspaceDelete$2 = function (editor, forward) {
  23280.       return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  23281.     };
  23282.  
  23283.     var deleteElement = function (editor, forward, element) {
  23284.       editor._selectionOverrides.hideFakeCaret();
  23285.       deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23286.       return true;
  23287.     };
  23288.     var deleteCaret = function (editor, forward) {
  23289.       var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23290.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23291.       var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23292.       if (isNearMedia(fromPos)) {
  23293.         return deleteElement(editor, forward, fromPos.getNode(!forward));
  23294.       } else {
  23295.         return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23296.           return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23297.         }).exists(function (pos) {
  23298.           return deleteElement(editor, forward, pos.getNode(!forward));
  23299.         });
  23300.       }
  23301.     };
  23302.     var deleteRange = function (editor, forward) {
  23303.       var selectedNode = editor.selection.getNode();
  23304.       return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23305.     };
  23306.     var backspaceDelete$1 = function (editor, forward) {
  23307.       return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23308.     };
  23309.  
  23310.     var isEditable = function (target) {
  23311.       return closest$3(target, function (elm) {
  23312.         return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23313.       }).exists(function (elm) {
  23314.         return isContentEditableTrue$4(elm.dom);
  23315.       });
  23316.     };
  23317.     var parseIndentValue = function (value) {
  23318.       var number = parseInt(value, 10);
  23319.       return isNaN(number) ? 0 : number;
  23320.     };
  23321.     var getIndentStyleName = function (useMargin, element) {
  23322.       var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23323.       var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23324.       return indentStyleName + suffix;
  23325.     };
  23326.     var indentElement = function (dom, command, useMargin, value, unit, element) {
  23327.       var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23328.       if (command === 'outdent') {
  23329.         var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23330.         dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23331.       } else {
  23332.         var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23333.         dom.setStyle(element, indentStyleName, styleValue);
  23334.       }
  23335.     };
  23336.     var validateBlocks = function (editor, blocks) {
  23337.       return forall(blocks, function (block) {
  23338.         var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23339.         var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23340.         var contentEditable = editor.dom.getContentEditable(block.dom);
  23341.         return contentEditable !== 'false' && intentValue > 0;
  23342.       });
  23343.     };
  23344.     var canOutdent = function (editor) {
  23345.       var blocks = getBlocksToIndent(editor);
  23346.       return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23347.     };
  23348.     var isListComponent = function (el) {
  23349.       return isList(el) || isListItem(el);
  23350.     };
  23351.     var parentIsListComponent = function (el) {
  23352.       return parent(el).exists(isListComponent);
  23353.     };
  23354.     var getBlocksToIndent = function (editor) {
  23355.       return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23356.         return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23357.       });
  23358.     };
  23359.     var handle = function (editor, command) {
  23360.       var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23361.       var indentation = getIndentation(editor);
  23362.       var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23363.       var indentValue = parseInt(indentation, 10);
  23364.       var useMargin = shouldIndentUseMargin(editor);
  23365.       var forcedRootBlock = getForcedRootBlock(editor);
  23366.       if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23367.         if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23368.           formatter.apply('div');
  23369.         }
  23370.       }
  23371.       each$k(getBlocksToIndent(editor), function (block) {
  23372.         indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23373.       });
  23374.     };
  23375.  
  23376.     var backspaceDelete = function (editor, _forward) {
  23377.       if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23378.         var dom = editor.dom;
  23379.         var rng = editor.selection.getRng();
  23380.         var pos = CaretPosition.fromRangeStart(rng);
  23381.         var block = dom.getParent(rng.startContainer, dom.isBlock);
  23382.         if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23383.           handle(editor, 'outdent');
  23384.           return true;
  23385.         }
  23386.       }
  23387.       return false;
  23388.     };
  23389.  
  23390.     var nativeCommand = function (editor, command) {
  23391.       editor.getDoc().execCommand(command, false, null);
  23392.     };
  23393.     var deleteCommand = function (editor, caret) {
  23394.       if (backspaceDelete(editor)) {
  23395.         return;
  23396.       } else if (backspaceDelete$5(editor, false)) {
  23397.         return;
  23398.       } else if (backspaceDelete$6(editor, false)) {
  23399.         return;
  23400.       } else if (backspaceDelete$3(editor, caret, false)) {
  23401.         return;
  23402.       } else if (backspaceDelete$8(editor, false)) {
  23403.         return;
  23404.       } else if (backspaceDelete$9(editor)) {
  23405.         return;
  23406.       } else if (backspaceDelete$4(editor, false)) {
  23407.         return;
  23408.       } else if (backspaceDelete$1(editor, false)) {
  23409.         return;
  23410.       } else if (backspaceDelete$7(editor)) {
  23411.         return;
  23412.       } else if (backspaceDelete$2(editor, false)) {
  23413.         return;
  23414.       } else {
  23415.         nativeCommand(editor, 'Delete');
  23416.         paddEmptyBody(editor);
  23417.       }
  23418.     };
  23419.     var forwardDeleteCommand = function (editor, caret) {
  23420.       if (backspaceDelete$5(editor, true)) {
  23421.         return;
  23422.       } else if (backspaceDelete$6(editor, true)) {
  23423.         return;
  23424.       } else if (backspaceDelete$3(editor, caret, true)) {
  23425.         return;
  23426.       } else if (backspaceDelete$8(editor, true)) {
  23427.         return;
  23428.       } else if (backspaceDelete$9(editor)) {
  23429.         return;
  23430.       } else if (backspaceDelete$4(editor, true)) {
  23431.         return;
  23432.       } else if (backspaceDelete$1(editor, true)) {
  23433.         return;
  23434.       } else if (backspaceDelete$7(editor)) {
  23435.         return;
  23436.       } else if (backspaceDelete$2(editor, true)) {
  23437.         return;
  23438.       } else {
  23439.         nativeCommand(editor, 'ForwardDelete');
  23440.       }
  23441.     };
  23442.     var setup$f = function (editor, caret) {
  23443.       editor.addCommand('delete', function () {
  23444.         deleteCommand(editor, caret);
  23445.       });
  23446.       editor.addCommand('forwardDelete', function () {
  23447.         forwardDeleteCommand(editor, caret);
  23448.       });
  23449.     };
  23450.  
  23451.     var SIGNIFICANT_MOVE = 5;
  23452.     var LONGPRESS_DELAY = 400;
  23453.     var getTouch = function (event) {
  23454.       if (event.touches === undefined || event.touches.length !== 1) {
  23455.         return Optional.none();
  23456.       }
  23457.       return Optional.some(event.touches[0]);
  23458.     };
  23459.     var isFarEnough = function (touch, data) {
  23460.       var distX = Math.abs(touch.clientX - data.x);
  23461.       var distY = Math.abs(touch.clientY - data.y);
  23462.       return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23463.     };
  23464.     var setup$e = function (editor) {
  23465.       var startData = value();
  23466.       var longpressFired = Cell(false);
  23467.       var debounceLongpress = last(function (e) {
  23468.         editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23469.         longpressFired.set(true);
  23470.       }, LONGPRESS_DELAY);
  23471.       editor.on('touchstart', function (e) {
  23472.         getTouch(e).each(function (touch) {
  23473.           debounceLongpress.cancel();
  23474.           var data = {
  23475.             x: touch.clientX,
  23476.             y: touch.clientY,
  23477.             target: e.target
  23478.           };
  23479.           debounceLongpress.throttle(e);
  23480.           longpressFired.set(false);
  23481.           startData.set(data);
  23482.         });
  23483.       }, true);
  23484.       editor.on('touchmove', function (e) {
  23485.         debounceLongpress.cancel();
  23486.         getTouch(e).each(function (touch) {
  23487.           startData.on(function (data) {
  23488.             if (isFarEnough(touch, data)) {
  23489.               startData.clear();
  23490.               longpressFired.set(false);
  23491.               editor.fire('longpresscancel');
  23492.             }
  23493.           });
  23494.         });
  23495.       }, true);
  23496.       editor.on('touchend touchcancel', function (e) {
  23497.         debounceLongpress.cancel();
  23498.         if (e.type === 'touchcancel') {
  23499.           return;
  23500.         }
  23501.         startData.get().filter(function (data) {
  23502.           return data.target.isEqualNode(e.target);
  23503.         }).each(function () {
  23504.           if (longpressFired.get()) {
  23505.             e.preventDefault();
  23506.           } else {
  23507.             editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23508.           }
  23509.         });
  23510.       }, true);
  23511.     };
  23512.  
  23513.     var isBlockElement = function (blockElements, node) {
  23514.       return has$2(blockElements, node.nodeName);
  23515.     };
  23516.     var isValidTarget = function (blockElements, node) {
  23517.       if (isText$7(node)) {
  23518.         return true;
  23519.       } else if (isElement$5(node)) {
  23520.         return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23521.       } else {
  23522.         return false;
  23523.       }
  23524.     };
  23525.     var hasBlockParent = function (blockElements, root, node) {
  23526.       return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23527.         return isBlockElement(blockElements, elm.dom);
  23528.       });
  23529.     };
  23530.     var shouldRemoveTextNode = function (blockElements, node) {
  23531.       if (isText$7(node)) {
  23532.         if (node.nodeValue.length === 0) {
  23533.           return true;
  23534.         } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23535.           return true;
  23536.         }
  23537.       }
  23538.       return false;
  23539.     };
  23540.     var addRootBlocks = function (editor) {
  23541.       var dom = editor.dom, selection = editor.selection;
  23542.       var schema = editor.schema, blockElements = schema.getBlockElements();
  23543.       var node = selection.getStart();
  23544.       var rootNode = editor.getBody();
  23545.       var rootBlockNode, tempNode, wrapped;
  23546.       var forcedRootBlock = getForcedRootBlock(editor);
  23547.       if (!node || !isElement$5(node) || !forcedRootBlock) {
  23548.         return;
  23549.       }
  23550.       var rootNodeName = rootNode.nodeName.toLowerCase();
  23551.       if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23552.         return;
  23553.       }
  23554.       var rng = selection.getRng();
  23555.       var startContainer = rng.startContainer;
  23556.       var startOffset = rng.startOffset;
  23557.       var endContainer = rng.endContainer;
  23558.       var endOffset = rng.endOffset;
  23559.       var restoreSelection = hasFocus(editor);
  23560.       node = rootNode.firstChild;
  23561.       while (node) {
  23562.         if (isValidTarget(blockElements, node)) {
  23563.           if (shouldRemoveTextNode(blockElements, node)) {
  23564.             tempNode = node;
  23565.             node = node.nextSibling;
  23566.             dom.remove(tempNode);
  23567.             continue;
  23568.           }
  23569.           if (!rootBlockNode) {
  23570.             rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23571.             node.parentNode.insertBefore(rootBlockNode, node);
  23572.             wrapped = true;
  23573.           }
  23574.           tempNode = node;
  23575.           node = node.nextSibling;
  23576.           rootBlockNode.appendChild(tempNode);
  23577.         } else {
  23578.           rootBlockNode = null;
  23579.           node = node.nextSibling;
  23580.         }
  23581.       }
  23582.       if (wrapped && restoreSelection) {
  23583.         rng.setStart(startContainer, startOffset);
  23584.         rng.setEnd(endContainer, endOffset);
  23585.         selection.setRng(rng);
  23586.         editor.nodeChanged();
  23587.       }
  23588.     };
  23589.     var setup$d = function (editor) {
  23590.       if (getForcedRootBlock(editor)) {
  23591.         editor.on('NodeChange', curry(addRootBlocks, editor));
  23592.       }
  23593.     };
  23594.  
  23595.     var findBlockCaretContainer = function (editor) {
  23596.       return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23597.         return elm.dom;
  23598.       }).getOrNull();
  23599.     };
  23600.     var removeIeControlRect = function (editor) {
  23601.       editor.selection.setRng(editor.selection.getRng());
  23602.     };
  23603.     var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23604.       if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23605.         showCaretContainerBlock(blockCaretContainer);
  23606.         removeIeControlRect(editor);
  23607.         editor.selection.scrollIntoView(blockCaretContainer);
  23608.       }
  23609.     };
  23610.     var handleBlockContainer = function (editor, e) {
  23611.       var blockCaretContainer = findBlockCaretContainer(editor);
  23612.       if (!blockCaretContainer) {
  23613.         return;
  23614.       }
  23615.       if (e.type === 'compositionstart') {
  23616.         e.preventDefault();
  23617.         e.stopPropagation();
  23618.         showBlockCaretContainer(editor, blockCaretContainer);
  23619.         return;
  23620.       }
  23621.       if (hasContent(blockCaretContainer)) {
  23622.         showBlockCaretContainer(editor, blockCaretContainer);
  23623.         editor.undoManager.add();
  23624.       }
  23625.     };
  23626.     var setup$c = function (editor) {
  23627.       editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23628.     };
  23629.  
  23630.     var isContentEditableFalse$2 = isContentEditableFalse$b;
  23631.     var moveToCeFalseHorizontally = function (direction, editor, range) {
  23632.       return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23633.     };
  23634.     var moveToCeFalseVertically = function (direction, editor, range) {
  23635.       var isBefore = function (caretPosition) {
  23636.         return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23637.       };
  23638.       var isAfter = function (caretPosition) {
  23639.         return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23640.       };
  23641.       return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23642.     };
  23643.     var createTextBlock = function (editor) {
  23644.       var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23645.       if (!Env.ie || Env.ie >= 11) {
  23646.         textBlock.innerHTML = '<br data-mce-bogus="1">';
  23647.       }
  23648.       return textBlock;
  23649.     };
  23650.     var exitPreBlock = function (editor, direction, range) {
  23651.       var caretWalker = CaretWalker(editor.getBody());
  23652.       var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23653.       if (range.collapsed && hasForcedRootBlock(editor)) {
  23654.         var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23655.         if (!pre) {
  23656.           return;
  23657.         }
  23658.         var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23659.         if (!caretPos) {
  23660.           var newBlock = createTextBlock(editor);
  23661.           if (direction === 1) {
  23662.             editor.$(pre).after(newBlock);
  23663.           } else {
  23664.             editor.$(pre).before(newBlock);
  23665.           }
  23666.           editor.selection.select(newBlock, true);
  23667.           editor.selection.collapse();
  23668.         }
  23669.       }
  23670.     };
  23671.     var getHorizontalRange = function (editor, forward) {
  23672.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23673.       var range = editor.selection.getRng();
  23674.       return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23675.         exitPreBlock(editor, direction, range);
  23676.         return Optional.none();
  23677.       });
  23678.     };
  23679.     var getVerticalRange = function (editor, down) {
  23680.       var direction = down ? 1 : -1;
  23681.       var range = editor.selection.getRng();
  23682.       return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23683.         exitPreBlock(editor, direction, range);
  23684.         return Optional.none();
  23685.       });
  23686.     };
  23687.     var moveH$2 = function (editor, forward) {
  23688.       return getHorizontalRange(editor, forward).exists(function (newRange) {
  23689.         moveToRange(editor, newRange);
  23690.         return true;
  23691.       });
  23692.     };
  23693.     var moveV$3 = function (editor, down) {
  23694.       return getVerticalRange(editor, down).exists(function (newRange) {
  23695.         moveToRange(editor, newRange);
  23696.         return true;
  23697.       });
  23698.     };
  23699.     var moveToLineEndPoint$1 = function (editor, forward) {
  23700.       var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23701.       return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23702.     };
  23703.  
  23704.     var isTarget = function (node) {
  23705.       return contains$3(['figcaption'], name(node));
  23706.     };
  23707.     var rangeBefore = function (target) {
  23708.       var rng = document.createRange();
  23709.       rng.setStartBefore(target.dom);
  23710.       rng.setEndBefore(target.dom);
  23711.       return rng;
  23712.     };
  23713.     var insertElement = function (root, elm, forward) {
  23714.       if (forward) {
  23715.         append$1(root, elm);
  23716.       } else {
  23717.         prepend(root, elm);
  23718.       }
  23719.     };
  23720.     var insertBr = function (root, forward) {
  23721.       var br = SugarElement.fromTag('br');
  23722.       insertElement(root, br, forward);
  23723.       return rangeBefore(br);
  23724.     };
  23725.     var insertBlock = function (root, forward, blockName, attrs) {
  23726.       var block = SugarElement.fromTag(blockName);
  23727.       var br = SugarElement.fromTag('br');
  23728.       setAll$1(block, attrs);
  23729.       append$1(block, br);
  23730.       insertElement(root, block, forward);
  23731.       return rangeBefore(br);
  23732.     };
  23733.     var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23734.       if (rootBlockName === '') {
  23735.         return insertBr(root, forward);
  23736.       } else {
  23737.         return insertBlock(root, forward, rootBlockName, attrs);
  23738.       }
  23739.     };
  23740.     var getClosestTargetBlock = function (pos, root) {
  23741.       var isRoot = curry(eq, root);
  23742.       return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23743.     };
  23744.     var isAtFirstOrLastLine = function (root, forward, pos) {
  23745.       return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23746.     };
  23747.     var moveCaretToNewEmptyLine = function (editor, forward) {
  23748.       var root = SugarElement.fromDom(editor.getBody());
  23749.       var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23750.       var rootBlock = getForcedRootBlock(editor);
  23751.       var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23752.       return getClosestTargetBlock(pos, root).exists(function () {
  23753.         if (isAtFirstOrLastLine(root, forward, pos)) {
  23754.           var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23755.           editor.selection.setRng(rng);
  23756.           return true;
  23757.         } else {
  23758.           return false;
  23759.         }
  23760.       });
  23761.     };
  23762.     var moveV$2 = function (editor, forward) {
  23763.       if (editor.selection.isCollapsed()) {
  23764.         return moveCaretToNewEmptyLine(editor, forward);
  23765.       } else {
  23766.         return false;
  23767.       }
  23768.     };
  23769.  
  23770.     var defaultPatterns = function (patterns) {
  23771.       return map$3(patterns, function (pattern) {
  23772.         return __assign({
  23773.           shiftKey: false,
  23774.           altKey: false,
  23775.           ctrlKey: false,
  23776.           metaKey: false,
  23777.           keyCode: 0,
  23778.           action: noop
  23779.         }, pattern);
  23780.       });
  23781.     };
  23782.     var matchesEvent = function (pattern, evt) {
  23783.       return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23784.     };
  23785.     var match$1 = function (patterns, evt) {
  23786.       return bind(defaultPatterns(patterns), function (pattern) {
  23787.         return matchesEvent(pattern, evt) ? [pattern] : [];
  23788.       });
  23789.     };
  23790.     var action = function (f) {
  23791.       var x = [];
  23792.       for (var _i = 1; _i < arguments.length; _i++) {
  23793.         x[_i - 1] = arguments[_i];
  23794.       }
  23795.       return function () {
  23796.         return f.apply(null, x);
  23797.       };
  23798.     };
  23799.     var execute = function (patterns, evt) {
  23800.       return find$3(match$1(patterns, evt), function (pattern) {
  23801.         return pattern.action();
  23802.       });
  23803.     };
  23804.  
  23805.     var moveH$1 = function (editor, forward) {
  23806.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23807.       var range = editor.selection.getRng();
  23808.       return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23809.         moveToRange(editor, newRange);
  23810.         return true;
  23811.       });
  23812.     };
  23813.     var moveV$1 = function (editor, down) {
  23814.       var direction = down ? 1 : -1;
  23815.       var range = editor.selection.getRng();
  23816.       return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23817.         moveToRange(editor, newRange);
  23818.         return true;
  23819.       });
  23820.     };
  23821.     var moveToLineEndPoint = function (editor, forward) {
  23822.       var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23823.       return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23824.     };
  23825.  
  23826.     var deflate = function (rect, delta) {
  23827.       return {
  23828.         left: rect.left - delta,
  23829.         top: rect.top - delta,
  23830.         right: rect.right + delta * 2,
  23831.         bottom: rect.bottom + delta * 2,
  23832.         width: rect.width + delta,
  23833.         height: rect.height + delta
  23834.       };
  23835.     };
  23836.     var getCorners = function (getYAxisValue, tds) {
  23837.       return bind(tds, function (td) {
  23838.         var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23839.         return [
  23840.           {
  23841.             x: rect.left,
  23842.             y: getYAxisValue(rect),
  23843.             cell: td
  23844.           },
  23845.           {
  23846.             x: rect.right,
  23847.             y: getYAxisValue(rect),
  23848.             cell: td
  23849.           }
  23850.         ];
  23851.       });
  23852.     };
  23853.     var findClosestCorner = function (corners, x, y) {
  23854.       return foldl(corners, function (acc, newCorner) {
  23855.         return acc.fold(function () {
  23856.           return Optional.some(newCorner);
  23857.         }, function (oldCorner) {
  23858.           var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23859.           var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23860.           return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23861.         });
  23862.       }, Optional.none());
  23863.     };
  23864.     var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23865.       var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23866.         return e.dom;
  23867.       });
  23868.       var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23869.         return isTargetCorner(corner, y);
  23870.       });
  23871.       return findClosestCorner(corners, x, y).map(function (corner) {
  23872.         return corner.cell;
  23873.       });
  23874.     };
  23875.     var getBottomValue = function (rect) {
  23876.       return rect.bottom;
  23877.     };
  23878.     var getTopValue = function (rect) {
  23879.       return rect.top;
  23880.     };
  23881.     var isAbove = function (corner, y) {
  23882.       return corner.y < y;
  23883.     };
  23884.     var isBelow = function (corner, y) {
  23885.       return corner.y > y;
  23886.     };
  23887.     var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23888.     var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23889.     var findClosestPositionInAboveCell = function (table, pos) {
  23890.       return head(pos.getClientRects()).bind(function (rect) {
  23891.         return getClosestCellAbove(table, rect.left, rect.top);
  23892.       }).bind(function (cell) {
  23893.         return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23894.       });
  23895.     };
  23896.     var findClosestPositionInBelowCell = function (table, pos) {
  23897.       return last$2(pos.getClientRects()).bind(function (rect) {
  23898.         return getClosestCellBelow(table, rect.left, rect.top);
  23899.       }).bind(function (cell) {
  23900.         return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23901.       });
  23902.     };
  23903.  
  23904.     var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23905.       return lineInfo.breakAt.exists(function (breakPos) {
  23906.         return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23907.       });
  23908.     };
  23909.     var startsWithWrapBreak = function (lineInfo) {
  23910.       return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23911.     };
  23912.     var startsWithBrBreak = function (lineInfo) {
  23913.       return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23914.     };
  23915.     var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23916.       var lineInfo = getPositionsUntil(scope, pos);
  23917.       if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23918.         return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23919.       } else {
  23920.         return lineInfo.breakAt.isNone();
  23921.       }
  23922.     };
  23923.     var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23924.     var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23925.     var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23926.       var caretPos = CaretPosition.fromRangeStart(rng);
  23927.       return positionIn(!forward, table).exists(function (pos) {
  23928.         return pos.isEqual(caretPos);
  23929.       });
  23930.     };
  23931.     var navigateHorizontally = function (editor, forward, table, _td) {
  23932.       var rng = editor.selection.getRng();
  23933.       var direction = forward ? 1 : -1;
  23934.       if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23935.         showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23936.           moveToRange(editor, newRng);
  23937.         });
  23938.         return true;
  23939.       }
  23940.       return false;
  23941.     };
  23942.     var getClosestAbovePosition = function (root, table, start) {
  23943.       return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23944.         return head(start.getClientRects()).bind(function (rect) {
  23945.           return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23946.         });
  23947.       }).getOr(CaretPosition.before(table));
  23948.     };
  23949.     var getClosestBelowPosition = function (root, table, start) {
  23950.       return findClosestPositionInBelowCell(table, start).orThunk(function () {
  23951.         return head(start.getClientRects()).bind(function (rect) {
  23952.           return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  23953.         });
  23954.       }).getOr(CaretPosition.after(table));
  23955.     };
  23956.     var getTable = function (previous, pos) {
  23957.       var node = pos.getNode(previous);
  23958.       return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  23959.     };
  23960.     var renderBlock = function (down, editor, table, pos) {
  23961.       var forcedRootBlock = getForcedRootBlock(editor);
  23962.       if (forcedRootBlock) {
  23963.         editor.undoManager.transact(function () {
  23964.           var element = SugarElement.fromTag(forcedRootBlock);
  23965.           setAll$1(element, getForcedRootBlockAttrs(editor));
  23966.           append$1(element, SugarElement.fromTag('br'));
  23967.           if (down) {
  23968.             after$3(SugarElement.fromDom(table), element);
  23969.           } else {
  23970.             before$4(SugarElement.fromDom(table), element);
  23971.           }
  23972.           var rng = editor.dom.createRng();
  23973.           rng.setStart(element.dom, 0);
  23974.           rng.setEnd(element.dom, 0);
  23975.           moveToRange(editor, rng);
  23976.         });
  23977.       } else {
  23978.         moveToRange(editor, pos.toRange());
  23979.       }
  23980.     };
  23981.     var moveCaret = function (editor, down, pos) {
  23982.       var table = down ? getTable(true, pos) : getTable(false, pos);
  23983.       var last = down === false;
  23984.       table.fold(function () {
  23985.         return moveToRange(editor, pos.toRange());
  23986.       }, function (table) {
  23987.         return positionIn(last, editor.getBody()).filter(function (lastPos) {
  23988.           return lastPos.isEqual(pos);
  23989.         }).fold(function () {
  23990.           return moveToRange(editor, pos.toRange());
  23991.         }, function (_) {
  23992.           return renderBlock(down, editor, table, pos);
  23993.         });
  23994.       });
  23995.     };
  23996.     var navigateVertically = function (editor, down, table, td) {
  23997.       var rng = editor.selection.getRng();
  23998.       var pos = CaretPosition.fromRangeStart(rng);
  23999.       var root = editor.getBody();
  24000.       if (!down && isAtFirstTableCellLine(td, pos)) {
  24001.         var newPos = getClosestAbovePosition(root, table, pos);
  24002.         moveCaret(editor, down, newPos);
  24003.         return true;
  24004.       } else if (down && isAtLastTableCellLine(td, pos)) {
  24005.         var newPos = getClosestBelowPosition(root, table, pos);
  24006.         moveCaret(editor, down, newPos);
  24007.         return true;
  24008.       } else {
  24009.         return false;
  24010.       }
  24011.     };
  24012.     var move$1 = function (editor, forward, mover) {
  24013.       return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  24014.         return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  24015.           return mover(editor, forward, table, td);
  24016.         });
  24017.       }).getOr(false);
  24018.     };
  24019.     var moveH = function (editor, forward) {
  24020.       return move$1(editor, forward, navigateHorizontally);
  24021.     };
  24022.     var moveV = function (editor, forward) {
  24023.       return move$1(editor, forward, navigateVertically);
  24024.     };
  24025.  
  24026.     var executeKeydownOverride$3 = function (editor, caret, evt) {
  24027.       var os = detect().os;
  24028.       execute([
  24029.         {
  24030.           keyCode: VK.RIGHT,
  24031.           action: action(moveH$2, editor, true)
  24032.         },
  24033.         {
  24034.           keyCode: VK.LEFT,
  24035.           action: action(moveH$2, editor, false)
  24036.         },
  24037.         {
  24038.           keyCode: VK.UP,
  24039.           action: action(moveV$3, editor, false)
  24040.         },
  24041.         {
  24042.           keyCode: VK.DOWN,
  24043.           action: action(moveV$3, editor, true)
  24044.         },
  24045.         {
  24046.           keyCode: VK.RIGHT,
  24047.           action: action(moveH, editor, true)
  24048.         },
  24049.         {
  24050.           keyCode: VK.LEFT,
  24051.           action: action(moveH, editor, false)
  24052.         },
  24053.         {
  24054.           keyCode: VK.UP,
  24055.           action: action(moveV, editor, false)
  24056.         },
  24057.         {
  24058.           keyCode: VK.DOWN,
  24059.           action: action(moveV, editor, true)
  24060.         },
  24061.         {
  24062.           keyCode: VK.RIGHT,
  24063.           action: action(moveH$1, editor, true)
  24064.         },
  24065.         {
  24066.           keyCode: VK.LEFT,
  24067.           action: action(moveH$1, editor, false)
  24068.         },
  24069.         {
  24070.           keyCode: VK.UP,
  24071.           action: action(moveV$1, editor, false)
  24072.         },
  24073.         {
  24074.           keyCode: VK.DOWN,
  24075.           action: action(moveV$1, editor, true)
  24076.         },
  24077.         {
  24078.           keyCode: VK.RIGHT,
  24079.           action: action(move$2, editor, caret, true)
  24080.         },
  24081.         {
  24082.           keyCode: VK.LEFT,
  24083.           action: action(move$2, editor, caret, false)
  24084.         },
  24085.         {
  24086.           keyCode: VK.RIGHT,
  24087.           ctrlKey: !os.isOSX(),
  24088.           altKey: os.isOSX(),
  24089.           action: action(moveNextWord, editor, caret)
  24090.         },
  24091.         {
  24092.           keyCode: VK.LEFT,
  24093.           ctrlKey: !os.isOSX(),
  24094.           altKey: os.isOSX(),
  24095.           action: action(movePrevWord, editor, caret)
  24096.         },
  24097.         {
  24098.           keyCode: VK.UP,
  24099.           action: action(moveV$2, editor, false)
  24100.         },
  24101.         {
  24102.           keyCode: VK.DOWN,
  24103.           action: action(moveV$2, editor, true)
  24104.         }
  24105.       ], evt).each(function (_) {
  24106.         evt.preventDefault();
  24107.       });
  24108.     };
  24109.     var setup$b = function (editor, caret) {
  24110.       editor.on('keydown', function (evt) {
  24111.         if (evt.isDefaultPrevented() === false) {
  24112.           executeKeydownOverride$3(editor, caret, evt);
  24113.         }
  24114.       });
  24115.     };
  24116.  
  24117.     var executeKeydownOverride$2 = function (editor, caret, evt) {
  24118.       execute([
  24119.         {
  24120.           keyCode: VK.BACKSPACE,
  24121.           action: action(backspaceDelete, editor, false)
  24122.         },
  24123.         {
  24124.           keyCode: VK.BACKSPACE,
  24125.           action: action(backspaceDelete$5, editor, false)
  24126.         },
  24127.         {
  24128.           keyCode: VK.DELETE,
  24129.           action: action(backspaceDelete$5, editor, true)
  24130.         },
  24131.         {
  24132.           keyCode: VK.BACKSPACE,
  24133.           action: action(backspaceDelete$6, editor, false)
  24134.         },
  24135.         {
  24136.           keyCode: VK.DELETE,
  24137.           action: action(backspaceDelete$6, editor, true)
  24138.         },
  24139.         {
  24140.           keyCode: VK.BACKSPACE,
  24141.           action: action(backspaceDelete$3, editor, caret, false)
  24142.         },
  24143.         {
  24144.           keyCode: VK.DELETE,
  24145.           action: action(backspaceDelete$3, editor, caret, true)
  24146.         },
  24147.         {
  24148.           keyCode: VK.BACKSPACE,
  24149.           action: action(backspaceDelete$9, editor, false)
  24150.         },
  24151.         {
  24152.           keyCode: VK.DELETE,
  24153.           action: action(backspaceDelete$9, editor, true)
  24154.         },
  24155.         {
  24156.           keyCode: VK.BACKSPACE,
  24157.           action: action(backspaceDelete$4, editor, false)
  24158.         },
  24159.         {
  24160.           keyCode: VK.DELETE,
  24161.           action: action(backspaceDelete$4, editor, true)
  24162.         },
  24163.         {
  24164.           keyCode: VK.BACKSPACE,
  24165.           action: action(backspaceDelete$1, editor, false)
  24166.         },
  24167.         {
  24168.           keyCode: VK.DELETE,
  24169.           action: action(backspaceDelete$1, editor, true)
  24170.         },
  24171.         {
  24172.           keyCode: VK.BACKSPACE,
  24173.           action: action(backspaceDelete$7, editor, false)
  24174.         },
  24175.         {
  24176.           keyCode: VK.DELETE,
  24177.           action: action(backspaceDelete$7, editor, true)
  24178.         },
  24179.         {
  24180.           keyCode: VK.BACKSPACE,
  24181.           action: action(backspaceDelete$8, editor, false)
  24182.         },
  24183.         {
  24184.           keyCode: VK.DELETE,
  24185.           action: action(backspaceDelete$8, editor, true)
  24186.         },
  24187.         {
  24188.           keyCode: VK.BACKSPACE,
  24189.           action: action(backspaceDelete$2, editor, false)
  24190.         },
  24191.         {
  24192.           keyCode: VK.DELETE,
  24193.           action: action(backspaceDelete$2, editor, true)
  24194.         }
  24195.       ], evt).each(function (_) {
  24196.         evt.preventDefault();
  24197.       });
  24198.     };
  24199.     var executeKeyupOverride = function (editor, evt) {
  24200.       execute([
  24201.         {
  24202.           keyCode: VK.BACKSPACE,
  24203.           action: action(paddEmptyElement, editor)
  24204.         },
  24205.         {
  24206.           keyCode: VK.DELETE,
  24207.           action: action(paddEmptyElement, editor)
  24208.         }
  24209.       ], evt);
  24210.     };
  24211.     var setup$a = function (editor, caret) {
  24212.       editor.on('keydown', function (evt) {
  24213.         if (evt.isDefaultPrevented() === false) {
  24214.           executeKeydownOverride$2(editor, caret, evt);
  24215.         }
  24216.       });
  24217.       editor.on('keyup', function (evt) {
  24218.         if (evt.isDefaultPrevented() === false) {
  24219.           executeKeyupOverride(editor, evt);
  24220.         }
  24221.       });
  24222.     };
  24223.  
  24224.     var firstNonWhiteSpaceNodeSibling = function (node) {
  24225.       while (node) {
  24226.         if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  24227.           return node;
  24228.         }
  24229.         node = node.nextSibling;
  24230.       }
  24231.     };
  24232.     var moveToCaretPosition = function (editor, root) {
  24233.       var node, lastNode = root;
  24234.       var dom = editor.dom;
  24235.       var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  24236.       if (!root) {
  24237.         return;
  24238.       }
  24239.       if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  24240.         var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  24241.         if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  24242.           root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  24243.         }
  24244.       }
  24245.       var rng = dom.createRng();
  24246.       root.normalize();
  24247.       if (root.hasChildNodes()) {
  24248.         var walker = new DomTreeWalker(root, root);
  24249.         while (node = walker.current()) {
  24250.           if (isText$7(node)) {
  24251.             rng.setStart(node, 0);
  24252.             rng.setEnd(node, 0);
  24253.             break;
  24254.           }
  24255.           if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  24256.             rng.setStartBefore(node);
  24257.             rng.setEndBefore(node);
  24258.             break;
  24259.           }
  24260.           lastNode = node;
  24261.           node = walker.next();
  24262.         }
  24263.         if (!node) {
  24264.           rng.setStart(lastNode, 0);
  24265.           rng.setEnd(lastNode, 0);
  24266.         }
  24267.       } else {
  24268.         if (isBr$5(root)) {
  24269.           if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  24270.             rng.setStartBefore(root);
  24271.             rng.setEndBefore(root);
  24272.           } else {
  24273.             rng.setStartAfter(root);
  24274.             rng.setEndAfter(root);
  24275.           }
  24276.         } else {
  24277.           rng.setStart(root, 0);
  24278.           rng.setEnd(root, 0);
  24279.         }
  24280.       }
  24281.       editor.selection.setRng(rng);
  24282.       scrollRangeIntoView(editor, rng);
  24283.     };
  24284.     var getEditableRoot$1 = function (dom, node) {
  24285.       var root = dom.getRoot();
  24286.       var parent, editableRoot;
  24287.       parent = node;
  24288.       while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24289.         if (dom.getContentEditable(parent) === 'true') {
  24290.           editableRoot = parent;
  24291.         }
  24292.         parent = parent.parentNode;
  24293.       }
  24294.       return parent !== root ? editableRoot : root;
  24295.     };
  24296.     var getParentBlock = function (editor) {
  24297.       return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  24298.     };
  24299.     var getParentBlockName = function (editor) {
  24300.       return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24301.         return parentBlock.nodeName.toUpperCase();
  24302.       });
  24303.     };
  24304.     var isListItemParentBlock = function (editor) {
  24305.       return getParentBlock(editor).filter(function (elm) {
  24306.         return isListItem(SugarElement.fromDom(elm));
  24307.       }).isSome();
  24308.     };
  24309.  
  24310.     var hasFirstChild = function (elm, name) {
  24311.       return elm.firstChild && elm.firstChild.nodeName === name;
  24312.     };
  24313.     var isFirstChild = function (elm) {
  24314.       var _a;
  24315.       return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24316.     };
  24317.     var hasParent = function (elm, parentName) {
  24318.       return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24319.     };
  24320.     var isListBlock = function (elm) {
  24321.       return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24322.     };
  24323.     var isNestedList = function (elm) {
  24324.       return isListBlock(elm) && isListBlock(elm.parentNode);
  24325.     };
  24326.     var getContainerBlock = function (containerBlock) {
  24327.       var containerBlockParent = containerBlock.parentNode;
  24328.       if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24329.         return containerBlockParent;
  24330.       }
  24331.       return containerBlock;
  24332.     };
  24333.     var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24334.       var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24335.       while (node) {
  24336.         if (isElement$5(node)) {
  24337.           break;
  24338.         }
  24339.         node = node[first ? 'nextSibling' : 'previousSibling'];
  24340.       }
  24341.       return node === parentBlock;
  24342.     };
  24343.     var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24344.       var dom = editor.dom;
  24345.       var rng = editor.selection.getRng();
  24346.       if (containerBlock === editor.getBody()) {
  24347.         return;
  24348.       }
  24349.       if (isNestedList(containerBlock)) {
  24350.         newBlockName = 'LI';
  24351.       }
  24352.       var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24353.       if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24354.         if (hasParent(containerBlock, 'LI')) {
  24355.           var containerBlockParent = getContainerBlock(containerBlock);
  24356.           dom.insertAfter(newBlock, containerBlockParent);
  24357.           if (isFirstChild(containerBlock)) {
  24358.             dom.remove(containerBlockParent);
  24359.           } else {
  24360.             dom.remove(containerBlock);
  24361.           }
  24362.         } else {
  24363.           dom.replace(newBlock, containerBlock);
  24364.         }
  24365.       } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24366.         if (hasParent(containerBlock, 'LI')) {
  24367.           dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24368.           newBlock.appendChild(dom.doc.createTextNode(' '));
  24369.           newBlock.appendChild(containerBlock);
  24370.         } else {
  24371.           containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24372.         }
  24373.         dom.remove(parentBlock);
  24374.       } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24375.         dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24376.         dom.remove(parentBlock);
  24377.       } else {
  24378.         containerBlock = getContainerBlock(containerBlock);
  24379.         var tmpRng = rng.cloneRange();
  24380.         tmpRng.setStartAfter(parentBlock);
  24381.         tmpRng.setEndAfter(containerBlock);
  24382.         var fragment = tmpRng.extractContents();
  24383.         if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24384.           newBlock = fragment.firstChild;
  24385.           dom.insertAfter(fragment, containerBlock);
  24386.         } else {
  24387.           dom.insertAfter(fragment, containerBlock);
  24388.           dom.insertAfter(newBlock, containerBlock);
  24389.         }
  24390.         dom.remove(parentBlock);
  24391.       }
  24392.       moveToCaretPosition(editor, newBlock);
  24393.     };
  24394.  
  24395.     var trimZwsp = function (fragment) {
  24396.       each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24397.         var rawNode = text.dom;
  24398.         rawNode.nodeValue = trim$2(rawNode.nodeValue);
  24399.       });
  24400.     };
  24401.     var isEmptyAnchor = function (dom, elm) {
  24402.       return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24403.     };
  24404.     var isTableCell = function (node) {
  24405.       return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24406.     };
  24407.     var emptyBlock = function (elm) {
  24408.       elm.innerHTML = '<br data-mce-bogus="1">';
  24409.     };
  24410.     var containerAndSiblingName = function (container, nodeName) {
  24411.       return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24412.     };
  24413.     var canSplitBlock = function (dom, node) {
  24414.       return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24415.     };
  24416.     var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24417.       var node = block;
  24418.       var firstChilds = [];
  24419.       var i;
  24420.       if (!node) {
  24421.         return;
  24422.       }
  24423.       while (node = node.firstChild) {
  24424.         if (dom.isBlock(node)) {
  24425.           return;
  24426.         }
  24427.         if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24428.           firstChilds.push(node);
  24429.         }
  24430.       }
  24431.       i = firstChilds.length;
  24432.       while (i--) {
  24433.         node = firstChilds[i];
  24434.         if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24435.           dom.remove(node);
  24436.         } else {
  24437.           if (isEmptyAnchor(dom, node)) {
  24438.             dom.remove(node);
  24439.           }
  24440.         }
  24441.       }
  24442.     };
  24443.     var normalizeZwspOffset = function (start, container, offset) {
  24444.       if (isText$7(container) === false) {
  24445.         return offset;
  24446.       } else if (start) {
  24447.         return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24448.       } else {
  24449.         return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24450.       }
  24451.     };
  24452.     var includeZwspInRange = function (rng) {
  24453.       var newRng = rng.cloneRange();
  24454.       newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24455.       newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24456.       return newRng;
  24457.     };
  24458.     var trimLeadingLineBreaks = function (node) {
  24459.       do {
  24460.         if (isText$7(node)) {
  24461.           node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24462.         }
  24463.         node = node.firstChild;
  24464.       } while (node);
  24465.     };
  24466.     var getEditableRoot = function (dom, node) {
  24467.       var root = dom.getRoot();
  24468.       var parent, editableRoot;
  24469.       parent = node;
  24470.       while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24471.         if (dom.getContentEditable(parent) === 'true') {
  24472.           editableRoot = parent;
  24473.         }
  24474.         parent = parent.parentNode;
  24475.       }
  24476.       return parent !== root ? editableRoot : root;
  24477.     };
  24478.     var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24479.       var dom = editor.dom;
  24480.       Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24481.         var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24482.         var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24483.         dom.setStyles(node, newStyles);
  24484.       });
  24485.       var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24486.         return attrClasses.split(/\s+/);
  24487.       });
  24488.       var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24489.         return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24490.           return clazz !== '';
  24491.         });
  24492.       });
  24493.       lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24494.         var filteredClasses = filter$4(currentClasses, function (clazz) {
  24495.           return !contains$3(attrClasses, clazz);
  24496.         });
  24497.         var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
  24498.         dom.setAttrib(node, 'class', newClasses.join(' '));
  24499.       });
  24500.       var appliedAttrs = [
  24501.         'style',
  24502.         'class'
  24503.       ];
  24504.       var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24505.         return !contains$3(appliedAttrs, attrs);
  24506.       });
  24507.       dom.setAttribs(node, remainingAttrs);
  24508.     };
  24509.     var setForcedBlockAttrs = function (editor, node) {
  24510.       var forcedRootBlockName = getForcedRootBlock(editor);
  24511.       if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24512.         var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24513.         applyAttributes(editor, node, forcedRootBlockAttrs);
  24514.       }
  24515.     };
  24516.     var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24517.       var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24518.       var blockName = newBlockName || 'P';
  24519.       var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24520.       parentBlock = dom.getParent(container, dom.isBlock);
  24521.       if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24522.         parentBlock = parentBlock || editableRoot;
  24523.         if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24524.           rootBlockName = parentBlock.nodeName.toLowerCase();
  24525.         } else {
  24526.           rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24527.         }
  24528.         if (!parentBlock.hasChildNodes()) {
  24529.           newBlock = dom.create(blockName);
  24530.           setForcedBlockAttrs(editor, newBlock);
  24531.           parentBlock.appendChild(newBlock);
  24532.           rng.setStart(newBlock, 0);
  24533.           rng.setEnd(newBlock, 0);
  24534.           return newBlock;
  24535.         }
  24536.         node = container;
  24537.         while (node.parentNode !== parentBlock) {
  24538.           node = node.parentNode;
  24539.         }
  24540.         while (node && !dom.isBlock(node)) {
  24541.           startNode = node;
  24542.           node = node.previousSibling;
  24543.         }
  24544.         if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24545.           newBlock = dom.create(blockName);
  24546.           setForcedBlockAttrs(editor, newBlock);
  24547.           startNode.parentNode.insertBefore(newBlock, startNode);
  24548.           node = startNode;
  24549.           while (node && !dom.isBlock(node)) {
  24550.             next = node.nextSibling;
  24551.             newBlock.appendChild(node);
  24552.             node = next;
  24553.           }
  24554.           rng.setStart(container, offset);
  24555.           rng.setEnd(container, offset);
  24556.         }
  24557.       }
  24558.       return container;
  24559.     };
  24560.     var addBrToBlockIfNeeded = function (dom, block) {
  24561.       block.normalize();
  24562.       var lastChild = block.lastChild;
  24563.       if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24564.         dom.add(block, 'br');
  24565.       }
  24566.     };
  24567.     var insert$2 = function (editor, evt) {
  24568.       var tmpRng, container, offset, parentBlock;
  24569.       var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24570.       var dom = editor.dom;
  24571.       var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24572.       var rng = editor.selection.getRng();
  24573.       var createNewBlock = function (name) {
  24574.         var node = container, block, clonedNode, caretNode;
  24575.         var textInlineElements = schema.getTextInlineElements();
  24576.         if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24577.           block = dom.create(name || newBlockName);
  24578.         } else {
  24579.           block = parentBlock.cloneNode(false);
  24580.         }
  24581.         caretNode = block;
  24582.         if (shouldKeepStyles(editor) === false) {
  24583.           dom.setAttrib(block, 'style', null);
  24584.           dom.setAttrib(block, 'class', null);
  24585.         } else {
  24586.           do {
  24587.             if (textInlineElements[node.nodeName]) {
  24588.               if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24589.                 continue;
  24590.               }
  24591.               clonedNode = node.cloneNode(false);
  24592.               dom.setAttrib(clonedNode, 'id', '');
  24593.               if (block.hasChildNodes()) {
  24594.                 clonedNode.appendChild(block.firstChild);
  24595.                 block.appendChild(clonedNode);
  24596.               } else {
  24597.                 caretNode = clonedNode;
  24598.                 block.appendChild(clonedNode);
  24599.               }
  24600.             }
  24601.           } while ((node = node.parentNode) && node !== editableRoot);
  24602.         }
  24603.         setForcedBlockAttrs(editor, block);
  24604.         emptyBlock(caretNode);
  24605.         return block;
  24606.       };
  24607.       var isCaretAtStartOrEndOfBlock = function (start) {
  24608.         var node, name;
  24609.         var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24610.         if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24611.           return false;
  24612.         }
  24613.         if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24614.           return true;
  24615.         }
  24616.         if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24617.           return true;
  24618.         }
  24619.         if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24620.           return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24621.         }
  24622.         var walker = new DomTreeWalker(container, parentBlock);
  24623.         if (isText$7(container)) {
  24624.           if (start && normalizedOffset === 0) {
  24625.             walker.prev();
  24626.           } else if (!start && normalizedOffset === container.nodeValue.length) {
  24627.             walker.next();
  24628.           }
  24629.         }
  24630.         while (node = walker.current()) {
  24631.           if (isElement$5(node)) {
  24632.             if (!node.getAttribute('data-mce-bogus')) {
  24633.               name = node.nodeName.toLowerCase();
  24634.               if (nonEmptyElementsMap[name] && name !== 'br') {
  24635.                 return false;
  24636.               }
  24637.             }
  24638.           } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24639.             return false;
  24640.           }
  24641.           if (start) {
  24642.             walker.prev();
  24643.           } else {
  24644.             walker.next();
  24645.           }
  24646.         }
  24647.         return true;
  24648.       };
  24649.       var insertNewBlockAfter = function () {
  24650.         if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24651.           newBlock = createNewBlock(newBlockName);
  24652.         } else {
  24653.           newBlock = createNewBlock();
  24654.         }
  24655.         if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24656.           newBlock = dom.split(containerBlock, parentBlock);
  24657.         } else {
  24658.           dom.insertAfter(newBlock, parentBlock);
  24659.         }
  24660.         moveToCaretPosition(editor, newBlock);
  24661.       };
  24662.       normalize$2(dom, rng).each(function (normRng) {
  24663.         rng.setStart(normRng.startContainer, normRng.startOffset);
  24664.         rng.setEnd(normRng.endContainer, normRng.endOffset);
  24665.       });
  24666.       container = rng.startContainer;
  24667.       offset = rng.startOffset;
  24668.       newBlockName = getForcedRootBlock(editor);
  24669.       var shiftKey = !!(evt && evt.shiftKey);
  24670.       var ctrlKey = !!(evt && evt.ctrlKey);
  24671.       if (isElement$5(container) && container.hasChildNodes()) {
  24672.         isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24673.         container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24674.         if (isAfterLastNodeInContainer && isText$7(container)) {
  24675.           offset = container.nodeValue.length;
  24676.         } else {
  24677.           offset = 0;
  24678.         }
  24679.       }
  24680.       var editableRoot = getEditableRoot(dom, container);
  24681.       if (!editableRoot) {
  24682.         return;
  24683.       }
  24684.       if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24685.         container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24686.       }
  24687.       parentBlock = dom.getParent(container, dom.isBlock);
  24688.       containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24689.       parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24690.       var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24691.       if (containerBlockName === 'LI' && !ctrlKey) {
  24692.         parentBlock = containerBlock;
  24693.         containerBlock = containerBlock.parentNode;
  24694.         parentBlockName = containerBlockName;
  24695.       }
  24696.       if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24697.         if (dom.isEmpty(parentBlock)) {
  24698.           insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24699.           return;
  24700.         }
  24701.       }
  24702.       if (newBlockName && parentBlock === editor.getBody()) {
  24703.         return;
  24704.       }
  24705.       newBlockName = newBlockName || 'P';
  24706.       if (isCaretContainerBlock$1(parentBlock)) {
  24707.         newBlock = showCaretContainerBlock(parentBlock);
  24708.         if (dom.isEmpty(parentBlock)) {
  24709.           emptyBlock(parentBlock);
  24710.         }
  24711.         setForcedBlockAttrs(editor, newBlock);
  24712.         moveToCaretPosition(editor, newBlock);
  24713.       } else if (isCaretAtStartOrEndOfBlock()) {
  24714.         insertNewBlockAfter();
  24715.       } else if (isCaretAtStartOrEndOfBlock(true)) {
  24716.         newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24717.         moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24718.       } else {
  24719.         tmpRng = includeZwspInRange(rng).cloneRange();
  24720.         tmpRng.setEndAfter(parentBlock);
  24721.         fragment = tmpRng.extractContents();
  24722.         trimZwsp(fragment);
  24723.         trimLeadingLineBreaks(fragment);
  24724.         newBlock = fragment.firstChild;
  24725.         dom.insertAfter(fragment, parentBlock);
  24726.         trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24727.         addBrToBlockIfNeeded(dom, parentBlock);
  24728.         if (dom.isEmpty(parentBlock)) {
  24729.           emptyBlock(parentBlock);
  24730.         }
  24731.         newBlock.normalize();
  24732.         if (dom.isEmpty(newBlock)) {
  24733.           dom.remove(newBlock);
  24734.           insertNewBlockAfter();
  24735.         } else {
  24736.           setForcedBlockAttrs(editor, newBlock);
  24737.           moveToCaretPosition(editor, newBlock);
  24738.         }
  24739.       }
  24740.       dom.setAttrib(newBlock, 'id', '');
  24741.       editor.fire('NewBlock', { newBlock: newBlock });
  24742.     };
  24743.  
  24744.     var hasRightSideContent = function (schema, container, parentBlock) {
  24745.       var walker = new DomTreeWalker(container, parentBlock);
  24746.       var node;
  24747.       var nonEmptyElementsMap = schema.getNonEmptyElements();
  24748.       while (node = walker.next()) {
  24749.         if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24750.           return true;
  24751.         }
  24752.       }
  24753.     };
  24754.     var moveSelectionToBr = function (editor, brElm, extraBr) {
  24755.       var rng = editor.dom.createRng();
  24756.       if (!extraBr) {
  24757.         rng.setStartAfter(brElm);
  24758.         rng.setEndAfter(brElm);
  24759.       } else {
  24760.         rng.setStartBefore(brElm);
  24761.         rng.setEndBefore(brElm);
  24762.       }
  24763.       editor.selection.setRng(rng);
  24764.       scrollRangeIntoView(editor, rng);
  24765.     };
  24766.     var insertBrAtCaret = function (editor, evt) {
  24767.       var selection = editor.selection;
  24768.       var dom = editor.dom;
  24769.       var rng = selection.getRng();
  24770.       var brElm;
  24771.       var extraBr;
  24772.       normalize$2(dom, rng).each(function (normRng) {
  24773.         rng.setStart(normRng.startContainer, normRng.startOffset);
  24774.         rng.setEnd(normRng.endContainer, normRng.endOffset);
  24775.       });
  24776.       var offset = rng.startOffset;
  24777.       var container = rng.startContainer;
  24778.       if (container.nodeType === 1 && container.hasChildNodes()) {
  24779.         var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24780.         container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24781.         if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24782.           offset = container.nodeValue.length;
  24783.         } else {
  24784.           offset = 0;
  24785.         }
  24786.       }
  24787.       var parentBlock = dom.getParent(container, dom.isBlock);
  24788.       var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24789.       var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24790.       var isControlKey = !!(evt && evt.ctrlKey);
  24791.       if (containerBlockName === 'LI' && !isControlKey) {
  24792.         parentBlock = containerBlock;
  24793.       }
  24794.       if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24795.         if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24796.           brElm = dom.create('br');
  24797.           rng.insertNode(brElm);
  24798.           rng.setStartAfter(brElm);
  24799.           rng.setEndAfter(brElm);
  24800.           extraBr = true;
  24801.         }
  24802.       }
  24803.       brElm = dom.create('br');
  24804.       rangeInsertNode(dom, rng, brElm);
  24805.       moveSelectionToBr(editor, brElm, extraBr);
  24806.       editor.undoManager.add();
  24807.     };
  24808.     var insertBrBefore = function (editor, inline) {
  24809.       var br = SugarElement.fromTag('br');
  24810.       before$4(SugarElement.fromDom(inline), br);
  24811.       editor.undoManager.add();
  24812.     };
  24813.     var insertBrAfter = function (editor, inline) {
  24814.       if (!hasBrAfter(editor.getBody(), inline)) {
  24815.         after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24816.       }
  24817.       var br = SugarElement.fromTag('br');
  24818.       after$3(SugarElement.fromDom(inline), br);
  24819.       moveSelectionToBr(editor, br.dom, false);
  24820.       editor.undoManager.add();
  24821.     };
  24822.     var isBeforeBr = function (pos) {
  24823.       return isBr$5(pos.getNode());
  24824.     };
  24825.     var hasBrAfter = function (rootNode, startNode) {
  24826.       if (isBeforeBr(CaretPosition.after(startNode))) {
  24827.         return true;
  24828.       } else {
  24829.         return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24830.           return isBr$5(pos.getNode());
  24831.         }).getOr(false);
  24832.       }
  24833.     };
  24834.     var isAnchorLink = function (elm) {
  24835.       return elm && elm.nodeName === 'A' && 'href' in elm;
  24836.     };
  24837.     var isInsideAnchor = function (location) {
  24838.       return location.fold(never, isAnchorLink, isAnchorLink, never);
  24839.     };
  24840.     var readInlineAnchorLocation = function (editor) {
  24841.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  24842.       var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24843.       return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24844.     };
  24845.     var insertBrOutsideAnchor = function (editor, location) {
  24846.       location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24847.     };
  24848.     var insert$1 = function (editor, evt) {
  24849.       var anchorLocation = readInlineAnchorLocation(editor);
  24850.       if (anchorLocation.isSome()) {
  24851.         anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24852.       } else {
  24853.         insertBrAtCaret(editor, evt);
  24854.       }
  24855.     };
  24856.  
  24857.     var matchesSelector = function (editor, selector) {
  24858.       return getParentBlock(editor).filter(function (parentBlock) {
  24859.         return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24860.       }).isSome();
  24861.     };
  24862.     var shouldInsertBr = function (editor) {
  24863.       return matchesSelector(editor, getBrNewLineSelector(editor));
  24864.     };
  24865.     var shouldBlockNewLine$1 = function (editor) {
  24866.       return matchesSelector(editor, getNoNewLineSelector(editor));
  24867.     };
  24868.  
  24869.     var newLineAction = Adt.generate([
  24870.       { br: [] },
  24871.       { block: [] },
  24872.       { none: [] }
  24873.     ]);
  24874.     var shouldBlockNewLine = function (editor, _shiftKey) {
  24875.       return shouldBlockNewLine$1(editor);
  24876.     };
  24877.     var isBrMode = function (requiredState) {
  24878.       return function (editor, _shiftKey) {
  24879.         var brMode = getForcedRootBlock(editor) === '';
  24880.         return brMode === requiredState;
  24881.       };
  24882.     };
  24883.     var inListBlock = function (requiredState) {
  24884.       return function (editor, _shiftKey) {
  24885.         return isListItemParentBlock(editor) === requiredState;
  24886.       };
  24887.     };
  24888.     var inBlock = function (blockName, requiredState) {
  24889.       return function (editor, _shiftKey) {
  24890.         var state = getParentBlockName(editor) === blockName.toUpperCase();
  24891.         return state === requiredState;
  24892.       };
  24893.     };
  24894.     var inPreBlock = function (requiredState) {
  24895.       return inBlock('pre', requiredState);
  24896.     };
  24897.     var inSummaryBlock = function () {
  24898.       return inBlock('summary', true);
  24899.     };
  24900.     var shouldPutBrInPre = function (requiredState) {
  24901.       return function (editor, _shiftKey) {
  24902.         return shouldPutBrInPre$1(editor) === requiredState;
  24903.       };
  24904.     };
  24905.     var inBrContext = function (editor, _shiftKey) {
  24906.       return shouldInsertBr(editor);
  24907.     };
  24908.     var hasShiftKey = function (_editor, shiftKey) {
  24909.       return shiftKey;
  24910.     };
  24911.     var canInsertIntoEditableRoot = function (editor) {
  24912.       var forcedRootBlock = getForcedRootBlock(editor);
  24913.       var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24914.       return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24915.     };
  24916.     var match = function (predicates, action) {
  24917.       return function (editor, shiftKey) {
  24918.         var isMatch = foldl(predicates, function (res, p) {
  24919.           return res && p(editor, shiftKey);
  24920.         }, true);
  24921.         return isMatch ? Optional.some(action) : Optional.none();
  24922.       };
  24923.     };
  24924.     var getAction = function (editor, evt) {
  24925.       return evaluateUntil([
  24926.         match([shouldBlockNewLine], newLineAction.none()),
  24927.         match([inSummaryBlock()], newLineAction.br()),
  24928.         match([
  24929.           inPreBlock(true),
  24930.           shouldPutBrInPre(false),
  24931.           hasShiftKey
  24932.         ], newLineAction.br()),
  24933.         match([
  24934.           inPreBlock(true),
  24935.           shouldPutBrInPre(false)
  24936.         ], newLineAction.block()),
  24937.         match([
  24938.           inPreBlock(true),
  24939.           shouldPutBrInPre(true),
  24940.           hasShiftKey
  24941.         ], newLineAction.block()),
  24942.         match([
  24943.           inPreBlock(true),
  24944.           shouldPutBrInPre(true)
  24945.         ], newLineAction.br()),
  24946.         match([
  24947.           inListBlock(true),
  24948.           hasShiftKey
  24949.         ], newLineAction.br()),
  24950.         match([inListBlock(true)], newLineAction.block()),
  24951.         match([
  24952.           isBrMode(true),
  24953.           hasShiftKey,
  24954.           canInsertIntoEditableRoot
  24955.         ], newLineAction.block()),
  24956.         match([isBrMode(true)], newLineAction.br()),
  24957.         match([inBrContext], newLineAction.br()),
  24958.         match([
  24959.           isBrMode(false),
  24960.           hasShiftKey
  24961.         ], newLineAction.br()),
  24962.         match([canInsertIntoEditableRoot], newLineAction.block())
  24963.       ], [
  24964.         editor,
  24965.         !!(evt && evt.shiftKey)
  24966.       ]).getOr(newLineAction.none());
  24967.     };
  24968.  
  24969.     var insert = function (editor, evt) {
  24970.       getAction(editor, evt).fold(function () {
  24971.         insert$1(editor, evt);
  24972.       }, function () {
  24973.         insert$2(editor, evt);
  24974.       }, noop);
  24975.     };
  24976.  
  24977.     var handleEnterKeyEvent = function (editor, event) {
  24978.       if (event.isDefaultPrevented()) {
  24979.         return;
  24980.       }
  24981.       event.preventDefault();
  24982.       endTypingLevelIgnoreLocks(editor.undoManager);
  24983.       editor.undoManager.transact(function () {
  24984.         if (editor.selection.isCollapsed() === false) {
  24985.           editor.execCommand('Delete');
  24986.         }
  24987.         insert(editor, event);
  24988.       });
  24989.     };
  24990.     var setup$9 = function (editor) {
  24991.       editor.on('keydown', function (event) {
  24992.         if (event.keyCode === VK.ENTER) {
  24993.           handleEnterKeyEvent(editor, event);
  24994.         }
  24995.       });
  24996.     };
  24997.  
  24998.     var executeKeydownOverride$1 = function (editor, caret, evt) {
  24999.       execute([
  25000.         {
  25001.           keyCode: VK.END,
  25002.           action: action(moveToLineEndPoint$1, editor, true)
  25003.         },
  25004.         {
  25005.           keyCode: VK.HOME,
  25006.           action: action(moveToLineEndPoint$1, editor, false)
  25007.         },
  25008.         {
  25009.           keyCode: VK.END,
  25010.           action: action(moveToLineEndPoint, editor, true)
  25011.         },
  25012.         {
  25013.           keyCode: VK.HOME,
  25014.           action: action(moveToLineEndPoint, editor, false)
  25015.         },
  25016.         {
  25017.           keyCode: VK.END,
  25018.           action: action(moveToLineEndPoint$2, editor, true, caret)
  25019.         },
  25020.         {
  25021.           keyCode: VK.HOME,
  25022.           action: action(moveToLineEndPoint$2, editor, false, caret)
  25023.         }
  25024.       ], evt).each(function (_) {
  25025.         evt.preventDefault();
  25026.       });
  25027.     };
  25028.     var setup$8 = function (editor, caret) {
  25029.       editor.on('keydown', function (evt) {
  25030.         if (evt.isDefaultPrevented() === false) {
  25031.           executeKeydownOverride$1(editor, caret, evt);
  25032.         }
  25033.       });
  25034.     };
  25035.  
  25036.     var browser = detect().browser;
  25037.     var setupIeInput = function (editor) {
  25038.       var keypressThrotter = first(function () {
  25039.         if (!editor.composing) {
  25040.           normalizeNbspsInEditor(editor);
  25041.         }
  25042.       }, 0);
  25043.       if (browser.isIE()) {
  25044.         editor.on('keypress', function (_e) {
  25045.           keypressThrotter.throttle();
  25046.         });
  25047.         editor.on('remove', function (_e) {
  25048.           keypressThrotter.cancel();
  25049.         });
  25050.       }
  25051.     };
  25052.     var setup$7 = function (editor) {
  25053.       setupIeInput(editor);
  25054.       editor.on('input', function (e) {
  25055.         if (e.isComposing === false) {
  25056.           normalizeNbspsInEditor(editor);
  25057.         }
  25058.       });
  25059.     };
  25060.  
  25061.     var platform = detect();
  25062.     var executeKeyupAction = function (editor, caret, evt) {
  25063.       execute([
  25064.         {
  25065.           keyCode: VK.PAGE_UP,
  25066.           action: action(moveToLineEndPoint$2, editor, false, caret)
  25067.         },
  25068.         {
  25069.           keyCode: VK.PAGE_DOWN,
  25070.           action: action(moveToLineEndPoint$2, editor, true, caret)
  25071.         }
  25072.       ], evt);
  25073.     };
  25074.     var stopImmediatePropagation = function (e) {
  25075.       return e.stopImmediatePropagation();
  25076.     };
  25077.     var isPageUpDown = function (evt) {
  25078.       return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  25079.     };
  25080.     var setNodeChangeBlocker = function (blocked, editor, block) {
  25081.       if (block && !blocked.get()) {
  25082.         editor.on('NodeChange', stopImmediatePropagation, true);
  25083.       } else if (!block && blocked.get()) {
  25084.         editor.off('NodeChange', stopImmediatePropagation);
  25085.       }
  25086.       blocked.set(block);
  25087.     };
  25088.     var setup$6 = function (editor, caret) {
  25089.       if (platform.os.isOSX()) {
  25090.         return;
  25091.       }
  25092.       var blocked = Cell(false);
  25093.       editor.on('keydown', function (evt) {
  25094.         if (isPageUpDown(evt)) {
  25095.           setNodeChangeBlocker(blocked, editor, true);
  25096.         }
  25097.       });
  25098.       editor.on('keyup', function (evt) {
  25099.         if (evt.isDefaultPrevented() === false) {
  25100.           executeKeyupAction(editor, caret, evt);
  25101.         }
  25102.         if (isPageUpDown(evt) && blocked.get()) {
  25103.           setNodeChangeBlocker(blocked, editor, false);
  25104.           editor.nodeChanged();
  25105.         }
  25106.       });
  25107.     };
  25108.  
  25109.     var insertTextAtPosition = function (text, pos) {
  25110.       var container = pos.container();
  25111.       var offset = pos.offset();
  25112.       if (isText$7(container)) {
  25113.         container.insertData(offset, text);
  25114.         return Optional.some(CaretPosition(container, offset + text.length));
  25115.       } else {
  25116.         return getElementFromPosition(pos).map(function (elm) {
  25117.           var textNode = SugarElement.fromText(text);
  25118.           if (pos.isAtEnd()) {
  25119.             after$3(elm, textNode);
  25120.           } else {
  25121.             before$4(elm, textNode);
  25122.           }
  25123.           return CaretPosition(textNode.dom, text.length);
  25124.         });
  25125.       }
  25126.     };
  25127.     var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  25128.     var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  25129.  
  25130.     var locationToCaretPosition = function (root) {
  25131.       return function (location) {
  25132.         return location.fold(function (element) {
  25133.           return prevPosition(root.dom, CaretPosition.before(element));
  25134.         }, function (element) {
  25135.           return firstPositionIn(element);
  25136.         }, function (element) {
  25137.           return lastPositionIn(element);
  25138.         }, function (element) {
  25139.           return nextPosition(root.dom, CaretPosition.after(element));
  25140.         });
  25141.       };
  25142.     };
  25143.     var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  25144.       return function (checkPos) {
  25145.         return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  25146.       };
  25147.     };
  25148.     var setSelection = function (editor) {
  25149.       return function (pos) {
  25150.         editor.selection.setRng(pos.toRange());
  25151.         editor.nodeChanged();
  25152.         return true;
  25153.       };
  25154.     };
  25155.     var insertSpaceOrNbspAtSelection = function (editor) {
  25156.       var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  25157.       var root = SugarElement.fromDom(editor.getBody());
  25158.       if (editor.selection.isCollapsed()) {
  25159.         var isInlineTarget$1 = curry(isInlineTarget, editor);
  25160.         var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  25161.         return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  25162.       } else {
  25163.         return false;
  25164.       }
  25165.     };
  25166.  
  25167.     var executeKeydownOverride = function (editor, evt) {
  25168.       execute([{
  25169.           keyCode: VK.SPACEBAR,
  25170.           action: action(insertSpaceOrNbspAtSelection, editor)
  25171.         }], evt).each(function (_) {
  25172.         evt.preventDefault();
  25173.       });
  25174.     };
  25175.     var setup$5 = function (editor) {
  25176.       editor.on('keydown', function (evt) {
  25177.         if (evt.isDefaultPrevented() === false) {
  25178.           executeKeydownOverride(editor, evt);
  25179.         }
  25180.       });
  25181.     };
  25182.  
  25183.     var registerKeyboardOverrides = function (editor) {
  25184.       var caret = setupSelectedState(editor);
  25185.       setup$c(editor);
  25186.       setup$b(editor, caret);
  25187.       setup$a(editor, caret);
  25188.       setup$9(editor);
  25189.       setup$5(editor);
  25190.       setup$7(editor);
  25191.       setup$8(editor, caret);
  25192.       setup$6(editor, caret);
  25193.       return caret;
  25194.     };
  25195.     var setup$4 = function (editor) {
  25196.       if (!isRtc(editor)) {
  25197.         return registerKeyboardOverrides(editor);
  25198.       } else {
  25199.         return Cell(null);
  25200.       }
  25201.     };
  25202.  
  25203.     var NodeChange = function () {
  25204.       function NodeChange(editor) {
  25205.         this.lastPath = [];
  25206.         this.editor = editor;
  25207.         var lastRng;
  25208.         var self = this;
  25209.         if (!('onselectionchange' in editor.getDoc())) {
  25210.           editor.on('NodeChange click mouseup keyup focus', function (e) {
  25211.             var nativeRng = editor.selection.getRng();
  25212.             var fakeRng = {
  25213.               startContainer: nativeRng.startContainer,
  25214.               startOffset: nativeRng.startOffset,
  25215.               endContainer: nativeRng.endContainer,
  25216.               endOffset: nativeRng.endOffset
  25217.             };
  25218.             if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  25219.               editor.fire('SelectionChange');
  25220.             }
  25221.             lastRng = fakeRng;
  25222.           });
  25223.         }
  25224.         editor.on('contextmenu', function () {
  25225.           editor.fire('SelectionChange');
  25226.         });
  25227.         editor.on('SelectionChange', function () {
  25228.           var startElm = editor.selection.getStart(true);
  25229.           if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  25230.             return;
  25231.           }
  25232.           if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  25233.             editor.nodeChanged({ selectionChange: true });
  25234.           }
  25235.         });
  25236.         editor.on('mouseup', function (e) {
  25237.           if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  25238.             if (editor.selection.getNode().nodeName === 'IMG') {
  25239.               Delay.setEditorTimeout(editor, function () {
  25240.                 editor.nodeChanged();
  25241.               });
  25242.             } else {
  25243.               editor.nodeChanged();
  25244.             }
  25245.           }
  25246.         });
  25247.       }
  25248.       NodeChange.prototype.nodeChanged = function (args) {
  25249.         var selection = this.editor.selection;
  25250.         var node, parents, root;
  25251.         if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  25252.           root = this.editor.getBody();
  25253.           node = selection.getStart(true) || root;
  25254.           if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  25255.             node = root;
  25256.           }
  25257.           parents = [];
  25258.           this.editor.dom.getParent(node, function (node) {
  25259.             if (node === root) {
  25260.               return true;
  25261.             }
  25262.             parents.push(node);
  25263.           });
  25264.           args = args || {};
  25265.           args.element = node;
  25266.           args.parents = parents;
  25267.           this.editor.fire('NodeChange', args);
  25268.         }
  25269.       };
  25270.       NodeChange.prototype.isSameElementPath = function (startElm) {
  25271.         var i;
  25272.         var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  25273.         if (currentPath.length === this.lastPath.length) {
  25274.           for (i = currentPath.length; i >= 0; i--) {
  25275.             if (currentPath[i] !== this.lastPath[i]) {
  25276.               break;
  25277.             }
  25278.           }
  25279.           if (i === -1) {
  25280.             this.lastPath = currentPath;
  25281.             return true;
  25282.           }
  25283.         }
  25284.         this.lastPath = currentPath;
  25285.         return false;
  25286.       };
  25287.       return NodeChange;
  25288.     }();
  25289.  
  25290.     var preventSummaryToggle = function (editor) {
  25291.       editor.on('click', function (e) {
  25292.         if (editor.dom.getParent(e.target, 'details')) {
  25293.           e.preventDefault();
  25294.         }
  25295.       });
  25296.     };
  25297.     var filterDetails = function (editor) {
  25298.       editor.parser.addNodeFilter('details', function (elms) {
  25299.         each$k(elms, function (details) {
  25300.           details.attr('data-mce-open', details.attr('open'));
  25301.           details.attr('open', 'open');
  25302.         });
  25303.       });
  25304.       editor.serializer.addNodeFilter('details', function (elms) {
  25305.         each$k(elms, function (details) {
  25306.           var open = details.attr('data-mce-open');
  25307.           details.attr('open', isString$1(open) ? open : null);
  25308.           details.attr('data-mce-open', null);
  25309.         });
  25310.       });
  25311.     };
  25312.     var setup$3 = function (editor) {
  25313.       preventSummaryToggle(editor);
  25314.       filterDetails(editor);
  25315.     };
  25316.  
  25317.     var isTextBlockNode = function (node) {
  25318.       return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25319.     };
  25320.     var normalizeSelection = function (editor) {
  25321.       var rng = editor.selection.getRng();
  25322.       var startPos = CaretPosition.fromRangeStart(rng);
  25323.       var endPos = CaretPosition.fromRangeEnd(rng);
  25324.       if (CaretPosition.isElementPosition(startPos)) {
  25325.         var container = startPos.container();
  25326.         if (isTextBlockNode(container)) {
  25327.           firstPositionIn(container).each(function (pos) {
  25328.             return rng.setStart(pos.container(), pos.offset());
  25329.           });
  25330.         }
  25331.       }
  25332.       if (CaretPosition.isElementPosition(endPos)) {
  25333.         var container = startPos.container();
  25334.         if (isTextBlockNode(container)) {
  25335.           lastPositionIn(container).each(function (pos) {
  25336.             return rng.setEnd(pos.container(), pos.offset());
  25337.           });
  25338.         }
  25339.       }
  25340.       editor.selection.setRng(normalize(rng));
  25341.     };
  25342.     var setup$2 = function (editor) {
  25343.       editor.on('click', function (e) {
  25344.         if (e.detail >= 3) {
  25345.           normalizeSelection(editor);
  25346.         }
  25347.       });
  25348.     };
  25349.  
  25350.     var getAbsolutePosition = function (elm) {
  25351.       var clientRect = elm.getBoundingClientRect();
  25352.       var doc = elm.ownerDocument;
  25353.       var docElem = doc.documentElement;
  25354.       var win = doc.defaultView;
  25355.       return {
  25356.         top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25357.         left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25358.       };
  25359.     };
  25360.     var getBodyPosition = function (editor) {
  25361.       return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25362.         left: 0,
  25363.         top: 0
  25364.       };
  25365.     };
  25366.     var getScrollPosition = function (editor) {
  25367.       var body = editor.getBody();
  25368.       return editor.inline ? {
  25369.         left: body.scrollLeft,
  25370.         top: body.scrollTop
  25371.       } : {
  25372.         left: 0,
  25373.         top: 0
  25374.       };
  25375.     };
  25376.     var getBodyScroll = function (editor) {
  25377.       var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25378.       var inlineScroll = {
  25379.         left: body.scrollLeft,
  25380.         top: body.scrollTop
  25381.       };
  25382.       var iframeScroll = {
  25383.         left: body.scrollLeft || docElm.scrollLeft,
  25384.         top: body.scrollTop || docElm.scrollTop
  25385.       };
  25386.       return editor.inline ? inlineScroll : iframeScroll;
  25387.     };
  25388.     var getMousePosition = function (editor, event) {
  25389.       if (event.target.ownerDocument !== editor.getDoc()) {
  25390.         var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25391.         var scrollPosition = getBodyScroll(editor);
  25392.         return {
  25393.           left: event.pageX - iframePosition.left + scrollPosition.left,
  25394.           top: event.pageY - iframePosition.top + scrollPosition.top
  25395.         };
  25396.       }
  25397.       return {
  25398.         left: event.pageX,
  25399.         top: event.pageY
  25400.       };
  25401.     };
  25402.     var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25403.       return {
  25404.         pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25405.         pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25406.       };
  25407.     };
  25408.     var calc = function (editor, event) {
  25409.       return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25410.     };
  25411.  
  25412.     var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25413.     var isDraggable = function (rootElm, elm) {
  25414.       return isContentEditableFalse$1(elm) && elm !== rootElm;
  25415.     };
  25416.     var isValidDropTarget = function (editor, targetElement, dragElement) {
  25417.       if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25418.         return false;
  25419.       }
  25420.       return !isContentEditableFalse$1(targetElement);
  25421.     };
  25422.     var cloneElement = function (elm) {
  25423.       var cloneElm = elm.cloneNode(true);
  25424.       cloneElm.removeAttribute('data-mce-selected');
  25425.       return cloneElm;
  25426.     };
  25427.     var createGhost = function (editor, elm, width, height) {
  25428.       var dom = editor.dom;
  25429.       var clonedElm = elm.cloneNode(true);
  25430.       dom.setStyles(clonedElm, {
  25431.         width: width,
  25432.         height: height
  25433.       });
  25434.       dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25435.       var ghostElm = dom.create('div', {
  25436.         'class': 'mce-drag-container',
  25437.         'data-mce-bogus': 'all',
  25438.         'unselectable': 'on',
  25439.         'contenteditable': 'false'
  25440.       });
  25441.       dom.setStyles(ghostElm, {
  25442.         position: 'absolute',
  25443.         opacity: 0.5,
  25444.         overflow: 'hidden',
  25445.         border: 0,
  25446.         padding: 0,
  25447.         margin: 0,
  25448.         width: width,
  25449.         height: height
  25450.       });
  25451.       dom.setStyles(clonedElm, {
  25452.         margin: 0,
  25453.         boxSizing: 'border-box'
  25454.       });
  25455.       ghostElm.appendChild(clonedElm);
  25456.       return ghostElm;
  25457.     };
  25458.     var appendGhostToBody = function (ghostElm, bodyElm) {
  25459.       if (ghostElm.parentNode !== bodyElm) {
  25460.         bodyElm.appendChild(ghostElm);
  25461.       }
  25462.     };
  25463.     var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25464.       var overflowX = 0, overflowY = 0;
  25465.       ghostElm.style.left = position.pageX + 'px';
  25466.       ghostElm.style.top = position.pageY + 'px';
  25467.       if (position.pageX + width > maxX) {
  25468.         overflowX = position.pageX + width - maxX;
  25469.       }
  25470.       if (position.pageY + height > maxY) {
  25471.         overflowY = position.pageY + height - maxY;
  25472.       }
  25473.       ghostElm.style.width = width - overflowX + 'px';
  25474.       ghostElm.style.height = height - overflowY + 'px';
  25475.     };
  25476.     var removeElement = function (elm) {
  25477.       if (elm && elm.parentNode) {
  25478.         elm.parentNode.removeChild(elm);
  25479.       }
  25480.     };
  25481.     var isLeftMouseButtonPressed = function (e) {
  25482.       return e.button === 0;
  25483.     };
  25484.     var applyRelPos = function (state, position) {
  25485.       return {
  25486.         pageX: position.pageX - state.relX,
  25487.         pageY: position.pageY + 5
  25488.       };
  25489.     };
  25490.     var start = function (state, editor) {
  25491.       return function (e) {
  25492.         if (isLeftMouseButtonPressed(e)) {
  25493.           var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25494.           if (isDraggable(editor.getBody(), ceElm)) {
  25495.             var elmPos = editor.dom.getPos(ceElm);
  25496.             var bodyElm = editor.getBody();
  25497.             var docElm = editor.getDoc().documentElement;
  25498.             state.set({
  25499.               element: ceElm,
  25500.               dragging: false,
  25501.               screenX: e.screenX,
  25502.               screenY: e.screenY,
  25503.               maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25504.               maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25505.               relX: e.pageX - elmPos.x,
  25506.               relY: e.pageY - elmPos.y,
  25507.               width: ceElm.offsetWidth,
  25508.               height: ceElm.offsetHeight,
  25509.               ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25510.             });
  25511.           }
  25512.         }
  25513.       };
  25514.     };
  25515.     var move = function (state, editor) {
  25516.       var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25517.         editor._selectionOverrides.hideFakeCaret();
  25518.         editor.selection.placeCaretAt(clientX, clientY);
  25519.       }, 0);
  25520.       editor.on('remove', throttledPlaceCaretAt.stop);
  25521.       return function (e) {
  25522.         return state.on(function (state) {
  25523.           var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25524.           if (!state.dragging && movement > 10) {
  25525.             var args = editor.fire('dragstart', { target: state.element });
  25526.             if (args.isDefaultPrevented()) {
  25527.               return;
  25528.             }
  25529.             state.dragging = true;
  25530.             editor.focus();
  25531.           }
  25532.           if (state.dragging) {
  25533.             var targetPos = applyRelPos(state, calc(editor, e));
  25534.             appendGhostToBody(state.ghost, editor.getBody());
  25535.             moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25536.             throttledPlaceCaretAt(e.clientX, e.clientY);
  25537.           }
  25538.         });
  25539.       };
  25540.     };
  25541.     var getRawTarget = function (selection) {
  25542.       var rng = selection.getSel().getRangeAt(0);
  25543.       var startContainer = rng.startContainer;
  25544.       return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25545.     };
  25546.     var drop = function (state, editor) {
  25547.       return function (e) {
  25548.         state.on(function (state) {
  25549.           if (state.dragging) {
  25550.             if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25551.               var targetClone_1 = cloneElement(state.element);
  25552.               var args = editor.fire('drop', {
  25553.                 clientX: e.clientX,
  25554.                 clientY: e.clientY
  25555.               });
  25556.               if (!args.isDefaultPrevented()) {
  25557.                 editor.undoManager.transact(function () {
  25558.                   removeElement(state.element);
  25559.                   editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25560.                   editor._selectionOverrides.hideFakeCaret();
  25561.                 });
  25562.               }
  25563.             }
  25564.             editor.fire('dragend');
  25565.           }
  25566.         });
  25567.         removeDragState(state);
  25568.       };
  25569.     };
  25570.     var stop = function (state, editor) {
  25571.       return function () {
  25572.         state.on(function (state) {
  25573.           if (state.dragging) {
  25574.             editor.fire('dragend');
  25575.           }
  25576.         });
  25577.         removeDragState(state);
  25578.       };
  25579.     };
  25580.     var removeDragState = function (state) {
  25581.       state.on(function (state) {
  25582.         removeElement(state.ghost);
  25583.       });
  25584.       state.clear();
  25585.     };
  25586.     var bindFakeDragEvents = function (editor) {
  25587.       var state = value();
  25588.       var pageDom = DOMUtils.DOM;
  25589.       var rootDocument = document;
  25590.       var dragStartHandler = start(state, editor);
  25591.       var dragHandler = move(state, editor);
  25592.       var dropHandler = drop(state, editor);
  25593.       var dragEndHandler = stop(state, editor);
  25594.       editor.on('mousedown', dragStartHandler);
  25595.       editor.on('mousemove', dragHandler);
  25596.       editor.on('mouseup', dropHandler);
  25597.       pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25598.       pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25599.       editor.on('remove', function () {
  25600.         pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25601.         pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25602.       });
  25603.       editor.on('keydown', function (e) {
  25604.         if (e.keyCode === VK.ESC) {
  25605.           dragEndHandler();
  25606.         }
  25607.       });
  25608.     };
  25609.     var blockIeDrop = function (editor) {
  25610.       editor.on('drop', function (e) {
  25611.         var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25612.         if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25613.           e.preventDefault();
  25614.         }
  25615.       });
  25616.     };
  25617.     var blockUnsupportedFileDrop = function (editor) {
  25618.       var preventFileDrop = function (e) {
  25619.         if (!e.isDefaultPrevented()) {
  25620.           var dataTransfer = e.dataTransfer;
  25621.           if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25622.             e.preventDefault();
  25623.             if (e.type === 'drop') {
  25624.               displayError(editor, 'Dropped file type is not supported');
  25625.             }
  25626.           }
  25627.         }
  25628.       };
  25629.       var preventFileDropIfUIElement = function (e) {
  25630.         if (isUIElement(editor, e.target)) {
  25631.           preventFileDrop(e);
  25632.         }
  25633.       };
  25634.       var setup = function () {
  25635.         var pageDom = DOMUtils.DOM;
  25636.         var dom = editor.dom;
  25637.         var doc = document;
  25638.         var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25639.         var eventNames = [
  25640.           'drop',
  25641.           'dragover'
  25642.         ];
  25643.         each$k(eventNames, function (name) {
  25644.           pageDom.bind(doc, name, preventFileDropIfUIElement);
  25645.           dom.bind(editorRoot, name, preventFileDrop);
  25646.         });
  25647.         editor.on('remove', function () {
  25648.           each$k(eventNames, function (name) {
  25649.             pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25650.             dom.unbind(editorRoot, name, preventFileDrop);
  25651.           });
  25652.         });
  25653.       };
  25654.       editor.on('init', function () {
  25655.         Delay.setEditorTimeout(editor, setup, 0);
  25656.       });
  25657.     };
  25658.     var init$2 = function (editor) {
  25659.       bindFakeDragEvents(editor);
  25660.       blockIeDrop(editor);
  25661.       if (shouldBlockUnsupportedDrop(editor)) {
  25662.         blockUnsupportedFileDrop(editor);
  25663.       }
  25664.     };
  25665.  
  25666.     var setup$1 = function (editor) {
  25667.       var renderFocusCaret = first(function () {
  25668.         if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25669.           var rng = editor.selection.getRng();
  25670.           if (rng.collapsed) {
  25671.             var caretRange = renderRangeCaret(editor, rng, false);
  25672.             editor.selection.setRng(caretRange);
  25673.           }
  25674.         }
  25675.       }, 0);
  25676.       editor.on('focus', function () {
  25677.         renderFocusCaret.throttle();
  25678.       });
  25679.       editor.on('blur', function () {
  25680.         renderFocusCaret.cancel();
  25681.       });
  25682.     };
  25683.  
  25684.     var setup = function (editor) {
  25685.       editor.on('init', function () {
  25686.         editor.on('focusin', function (e) {
  25687.           var target = e.target;
  25688.           if (isMedia$2(target)) {
  25689.             var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25690.             var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25691.             if (editor.selection.getNode() !== node) {
  25692.               selectNode(editor, node).each(function (rng) {
  25693.                 return editor.selection.setRng(rng);
  25694.               });
  25695.             }
  25696.           }
  25697.         });
  25698.       });
  25699.     };
  25700.  
  25701.     var isContentEditableTrue = isContentEditableTrue$4;
  25702.     var isContentEditableFalse = isContentEditableFalse$b;
  25703.     var getContentEditableRoot = function (editor, node) {
  25704.       return getContentEditableRoot$1(editor.getBody(), node);
  25705.     };
  25706.     var SelectionOverrides = function (editor) {
  25707.       var selection = editor.selection, dom = editor.dom;
  25708.       var isBlock = dom.isBlock;
  25709.       var rootNode = editor.getBody();
  25710.       var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25711.         return hasFocus(editor);
  25712.       });
  25713.       var realSelectionId = 'sel-' + dom.uniqueId();
  25714.       var elementSelectionAttr = 'data-mce-selected';
  25715.       var selectedElement;
  25716.       var isFakeSelectionElement = function (node) {
  25717.         return dom.hasClass(node, 'mce-offscreen-selection');
  25718.       };
  25719.       var isFakeSelectionTargetElement = function (node) {
  25720.         return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25721.       };
  25722.       var isNearFakeSelectionElement = function (pos) {
  25723.         return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25724.       };
  25725.       var getRealSelectionElement = function () {
  25726.         var container = dom.get(realSelectionId);
  25727.         return container ? container.getElementsByTagName('*')[0] : container;
  25728.       };
  25729.       var setRange = function (range) {
  25730.         if (range) {
  25731.           selection.setRng(range);
  25732.         }
  25733.       };
  25734.       var getRange = selection.getRng;
  25735.       var showCaret = function (direction, node, before, scrollIntoView) {
  25736.         if (scrollIntoView === void 0) {
  25737.           scrollIntoView = true;
  25738.         }
  25739.         var e = editor.fire('ShowCaret', {
  25740.           target: node,
  25741.           direction: direction,
  25742.           before: before
  25743.         });
  25744.         if (e.isDefaultPrevented()) {
  25745.           return null;
  25746.         }
  25747.         if (scrollIntoView) {
  25748.           selection.scrollIntoView(node, direction === -1);
  25749.         }
  25750.         return fakeCaret.show(before, node);
  25751.       };
  25752.       var showBlockCaretContainer = function (blockCaretContainer) {
  25753.         if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25754.           showCaretContainerBlock(blockCaretContainer);
  25755.           setRange(getRange());
  25756.           selection.scrollIntoView(blockCaretContainer);
  25757.         }
  25758.       };
  25759.       var registerEvents = function () {
  25760.         editor.on('mouseup', function (e) {
  25761.           var range = getRange();
  25762.           if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25763.             renderCaretAtRange(editor, range, false).each(setRange);
  25764.           }
  25765.         });
  25766.         editor.on('click', function (e) {
  25767.           var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25768.           if (contentEditableRoot) {
  25769.             if (isContentEditableFalse(contentEditableRoot)) {
  25770.               e.preventDefault();
  25771.               editor.focus();
  25772.             }
  25773.             if (isContentEditableTrue(contentEditableRoot)) {
  25774.               if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25775.                 removeElementSelection();
  25776.               }
  25777.             }
  25778.           }
  25779.         });
  25780.         editor.on('blur NewBlock', removeElementSelection);
  25781.         editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25782.         var hasNormalCaretPosition = function (elm) {
  25783.           var start = elm.firstChild;
  25784.           if (isNullable(start)) {
  25785.             return false;
  25786.           }
  25787.           var startPos = CaretPosition.before(start);
  25788.           if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
  25789.             return !isNearFakeSelectionElement(startPos);
  25790.           } else {
  25791.             var caretWalker = CaretWalker(elm);
  25792.             var newPos = caretWalker.next(startPos);
  25793.             return newPos && !isNearFakeSelectionElement(newPos);
  25794.           }
  25795.         };
  25796.         var isInSameBlock = function (node1, node2) {
  25797.           var block1 = dom.getParent(node1, isBlock);
  25798.           var block2 = dom.getParent(node2, isBlock);
  25799.           return block1 === block2;
  25800.         };
  25801.         var hasBetterMouseTarget = function (targetNode, caretNode) {
  25802.           var targetBlock = dom.getParent(targetNode, isBlock);
  25803.           var caretBlock = dom.getParent(caretNode, isBlock);
  25804.           if (isNullable(targetBlock)) {
  25805.             return false;
  25806.           }
  25807.           if (targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25808.             return true;
  25809.           }
  25810.           return !dom.isChildOf(caretBlock, targetBlock) && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25811.         };
  25812.         editor.on('tap', function (e) {
  25813.           var targetElm = e.target;
  25814.           var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25815.           if (isContentEditableFalse(contentEditableRoot)) {
  25816.             e.preventDefault();
  25817.             selectNode(editor, contentEditableRoot).each(setElementSelection);
  25818.           } else if (isFakeSelectionTargetElement(targetElm)) {
  25819.             selectNode(editor, targetElm).each(setElementSelection);
  25820.           }
  25821.         }, true);
  25822.         editor.on('mousedown', function (e) {
  25823.           var targetElm = e.target;
  25824.           if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25825.             return;
  25826.           }
  25827.           if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25828.             return;
  25829.           }
  25830.           var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25831.           if (contentEditableRoot) {
  25832.             if (isContentEditableFalse(contentEditableRoot)) {
  25833.               e.preventDefault();
  25834.               selectNode(editor, contentEditableRoot).each(setElementSelection);
  25835.             } else {
  25836.               removeElementSelection();
  25837.               if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25838.                 hideFakeCaret();
  25839.                 selection.placeCaretAt(e.clientX, e.clientY);
  25840.               }
  25841.             }
  25842.           } else if (isFakeSelectionTargetElement(targetElm)) {
  25843.             selectNode(editor, targetElm).each(setElementSelection);
  25844.           } else if (isFakeCaretTarget(targetElm) === false) {
  25845.             removeElementSelection();
  25846.             hideFakeCaret();
  25847.             var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25848.             if (fakeCaretInfo) {
  25849.               if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25850.                 e.preventDefault();
  25851.                 var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25852.                 setRange(range);
  25853.                 editor.getBody().focus();
  25854.               }
  25855.             }
  25856.           }
  25857.         });
  25858.         editor.on('keypress', function (e) {
  25859.           if (VK.modifierPressed(e)) {
  25860.             return;
  25861.           }
  25862.           if (isContentEditableFalse(selection.getNode())) {
  25863.             e.preventDefault();
  25864.           }
  25865.         });
  25866.         editor.on('GetSelectionRange', function (e) {
  25867.           var rng = e.range;
  25868.           if (selectedElement) {
  25869.             if (!selectedElement.parentNode) {
  25870.               selectedElement = null;
  25871.               return;
  25872.             }
  25873.             rng = rng.cloneRange();
  25874.             rng.selectNode(selectedElement);
  25875.             e.range = rng;
  25876.           }
  25877.         });
  25878.         editor.on('SetSelectionRange', function (e) {
  25879.           e.range = normalizeShortEndedElementSelection(e.range);
  25880.           var rng = setElementSelection(e.range, e.forward);
  25881.           if (rng) {
  25882.             e.range = rng;
  25883.           }
  25884.         });
  25885.         var isPasteBin = function (node) {
  25886.           return node.id === 'mcepastebin';
  25887.         };
  25888.         editor.on('AfterSetSelectionRange', function (e) {
  25889.           var rng = e.range;
  25890.           var parentNode = rng.startContainer.parentNode;
  25891.           if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25892.             hideFakeCaret();
  25893.           }
  25894.           if (!isFakeSelectionElement(parentNode)) {
  25895.             removeElementSelection();
  25896.           }
  25897.         });
  25898.         editor.on('copy', function (e) {
  25899.           var clipboardData = e.clipboardData;
  25900.           if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25901.             var realSelectionElement = getRealSelectionElement();
  25902.             if (realSelectionElement) {
  25903.               e.preventDefault();
  25904.               clipboardData.clearData();
  25905.               clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25906.               clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25907.             }
  25908.           }
  25909.         });
  25910.         init$2(editor);
  25911.         setup$1(editor);
  25912.         setup(editor);
  25913.       };
  25914.       var isWithinCaretContainer = function (node) {
  25915.         return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25916.       };
  25917.       var isRangeInCaretContainer = function (rng) {
  25918.         return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25919.       };
  25920.       var normalizeShortEndedElementSelection = function (rng) {
  25921.         var shortEndedElements = editor.schema.getShortEndedElements();
  25922.         var newRng = dom.createRng();
  25923.         var startContainer = rng.startContainer;
  25924.         var startOffset = rng.startOffset;
  25925.         var endContainer = rng.endContainer;
  25926.         var endOffset = rng.endOffset;
  25927.         if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25928.           if (startOffset === 0) {
  25929.             newRng.setStartBefore(startContainer);
  25930.           } else {
  25931.             newRng.setStartAfter(startContainer);
  25932.           }
  25933.         } else {
  25934.           newRng.setStart(startContainer, startOffset);
  25935.         }
  25936.         if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25937.           if (endOffset === 0) {
  25938.             newRng.setEndBefore(endContainer);
  25939.           } else {
  25940.             newRng.setEndAfter(endContainer);
  25941.           }
  25942.         } else {
  25943.           newRng.setEnd(endContainer, endOffset);
  25944.         }
  25945.         return newRng;
  25946.       };
  25947.       var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25948.         var $ = editor.$;
  25949.         var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  25950.           return $([]);
  25951.         }, function (elm) {
  25952.           return $([elm.dom]);
  25953.         });
  25954.         if ($realSelectionContainer.length === 0) {
  25955.           $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  25956.           $realSelectionContainer.appendTo(editor.getBody());
  25957.         }
  25958.         var newRange = dom.createRng();
  25959.         if (targetClone === origTargetClone && Env.ie) {
  25960.           $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  25961.           newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  25962.           newRange.setEndAfter(targetClone);
  25963.         } else {
  25964.           $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  25965.           newRange.setStart($realSelectionContainer[0].firstChild, 1);
  25966.           newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  25967.         }
  25968.         $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  25969.         $realSelectionContainer[0].focus();
  25970.         var sel = selection.getSel();
  25971.         sel.removeAllRanges();
  25972.         sel.addRange(newRange);
  25973.         return newRange;
  25974.       };
  25975.       var selectElement = function (elm) {
  25976.         var targetClone = elm.cloneNode(true);
  25977.         var e = editor.fire('ObjectSelected', {
  25978.           target: elm,
  25979.           targetClone: targetClone
  25980.         });
  25981.         if (e.isDefaultPrevented()) {
  25982.           return null;
  25983.         }
  25984.         var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  25985.         var nodeElm = SugarElement.fromDom(elm);
  25986.         each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  25987.           if (!eq(nodeElm, elm)) {
  25988.             remove$6(elm, elementSelectionAttr);
  25989.           }
  25990.         });
  25991.         if (!dom.getAttrib(elm, elementSelectionAttr)) {
  25992.           elm.setAttribute(elementSelectionAttr, '1');
  25993.         }
  25994.         selectedElement = elm;
  25995.         hideFakeCaret();
  25996.         return range;
  25997.       };
  25998.       var setElementSelection = function (range, forward) {
  25999.         if (!range) {
  26000.           return null;
  26001.         }
  26002.         if (range.collapsed) {
  26003.           if (!isRangeInCaretContainer(range)) {
  26004.             var dir = forward ? 1 : -1;
  26005.             var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  26006.             var beforeNode = caretPosition.getNode(!forward);
  26007.             if (isFakeCaretTarget(beforeNode)) {
  26008.               return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  26009.             }
  26010.             var afterNode = caretPosition.getNode(forward);
  26011.             if (isFakeCaretTarget(afterNode)) {
  26012.               return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  26013.             }
  26014.           }
  26015.           return null;
  26016.         }
  26017.         var startContainer = range.startContainer;
  26018.         var startOffset = range.startOffset;
  26019.         var endOffset = range.endOffset;
  26020.         if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  26021.           startContainer = startContainer.parentNode;
  26022.           startOffset = dom.nodeIndex(startContainer);
  26023.           startContainer = startContainer.parentNode;
  26024.         }
  26025.         if (startContainer.nodeType !== 1) {
  26026.           return null;
  26027.         }
  26028.         if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  26029.           var node = startContainer.childNodes[startOffset];
  26030.           if (isFakeSelectionTargetElement(node)) {
  26031.             return selectElement(node);
  26032.           }
  26033.         }
  26034.         return null;
  26035.       };
  26036.       var removeElementSelection = function () {
  26037.         if (selectedElement) {
  26038.           selectedElement.removeAttribute(elementSelectionAttr);
  26039.         }
  26040.         descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  26041.         selectedElement = null;
  26042.       };
  26043.       var destroy = function () {
  26044.         fakeCaret.destroy();
  26045.         selectedElement = null;
  26046.       };
  26047.       var hideFakeCaret = function () {
  26048.         fakeCaret.hide();
  26049.       };
  26050.       if (Env.ceFalse && !isRtc(editor)) {
  26051.         registerEvents();
  26052.       }
  26053.       return {
  26054.         showCaret: showCaret,
  26055.         showBlockCaretContainer: showBlockCaretContainer,
  26056.         hideFakeCaret: hideFakeCaret,
  26057.         destroy: destroy
  26058.       };
  26059.     };
  26060.  
  26061.     var Quirks = function (editor) {
  26062.       var each = Tools.each;
  26063.       var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  26064.       var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  26065.       var mceInternalUrlPrefix = 'data:text/mce-internal,';
  26066.       var mceInternalDataType = isIE ? 'Text' : 'URL';
  26067.       var setEditorCommandState = function (cmd, state) {
  26068.         try {
  26069.           editor.getDoc().execCommand(cmd, false, state);
  26070.         } catch (ex) {
  26071.         }
  26072.       };
  26073.       var isDefaultPrevented = function (e) {
  26074.         return e.isDefaultPrevented();
  26075.       };
  26076.       var setMceInternalContent = function (e) {
  26077.         var selectionHtml, internalContent;
  26078.         if (e.dataTransfer) {
  26079.           if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  26080.             selection.select(e.target);
  26081.           }
  26082.           selectionHtml = editor.selection.getContent();
  26083.           if (selectionHtml.length > 0) {
  26084.             internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  26085.             e.dataTransfer.setData(mceInternalDataType, internalContent);
  26086.           }
  26087.         }
  26088.       };
  26089.       var getMceInternalContent = function (e) {
  26090.         var internalContent;
  26091.         if (e.dataTransfer) {
  26092.           internalContent = e.dataTransfer.getData(mceInternalDataType);
  26093.           if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  26094.             internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  26095.             return {
  26096.               id: unescape(internalContent[0]),
  26097.               html: unescape(internalContent[1])
  26098.             };
  26099.           }
  26100.         }
  26101.         return null;
  26102.       };
  26103.       var insertClipboardContents = function (content, internal) {
  26104.         if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  26105.           editor.execCommand('mceInsertClipboardContent', false, {
  26106.             content: content,
  26107.             internal: internal
  26108.           });
  26109.         } else {
  26110.           editor.execCommand('mceInsertContent', false, content);
  26111.         }
  26112.       };
  26113.       var emptyEditorWhenDeleting = function () {
  26114.         var serializeRng = function (rng) {
  26115.           var body = dom.create('body');
  26116.           var contents = rng.cloneContents();
  26117.           body.appendChild(contents);
  26118.           return selection.serializer.serialize(body, { format: 'html' });
  26119.         };
  26120.         var allContentsSelected = function (rng) {
  26121.           var selection = serializeRng(rng);
  26122.           var allRng = dom.createRng();
  26123.           allRng.selectNode(editor.getBody());
  26124.           var allSelection = serializeRng(allRng);
  26125.           return selection === allSelection;
  26126.         };
  26127.         editor.on('keydown', function (e) {
  26128.           var keyCode = e.keyCode;
  26129.           var isCollapsed, body;
  26130.           if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  26131.             isCollapsed = editor.selection.isCollapsed();
  26132.             body = editor.getBody();
  26133.             if (isCollapsed && !dom.isEmpty(body)) {
  26134.               return;
  26135.             }
  26136.             if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  26137.               return;
  26138.             }
  26139.             e.preventDefault();
  26140.             editor.setContent('');
  26141.             if (body.firstChild && dom.isBlock(body.firstChild)) {
  26142.               editor.selection.setCursorLocation(body.firstChild, 0);
  26143.             } else {
  26144.               editor.selection.setCursorLocation(body, 0);
  26145.             }
  26146.             editor.nodeChanged();
  26147.           }
  26148.         });
  26149.       };
  26150.       var selectAll = function () {
  26151.         editor.shortcuts.add('meta+a', null, 'SelectAll');
  26152.       };
  26153.       var documentElementEditingFocus = function () {
  26154.         if (!editor.inline) {
  26155.           dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  26156.             var rng;
  26157.             if (e.target === editor.getDoc().documentElement) {
  26158.               rng = selection.getRng();
  26159.               editor.getBody().focus();
  26160.               if (e.type === 'mousedown') {
  26161.                 if (isCaretContainer$2(rng.startContainer)) {
  26162.                   return;
  26163.                 }
  26164.                 selection.placeCaretAt(e.clientX, e.clientY);
  26165.               } else {
  26166.                 selection.setRng(rng);
  26167.               }
  26168.             }
  26169.           });
  26170.         }
  26171.       };
  26172.       var removeHrOnBackspace = function () {
  26173.         editor.on('keydown', function (e) {
  26174.           if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26175.             if (!editor.getBody().getElementsByTagName('hr').length) {
  26176.               return;
  26177.             }
  26178.             if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26179.               var node = selection.getNode();
  26180.               var previousSibling = node.previousSibling;
  26181.               if (node.nodeName === 'HR') {
  26182.                 dom.remove(node);
  26183.                 e.preventDefault();
  26184.                 return;
  26185.               }
  26186.               if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  26187.                 dom.remove(previousSibling);
  26188.                 e.preventDefault();
  26189.               }
  26190.             }
  26191.           }
  26192.         });
  26193.       };
  26194.       var focusBody = function () {
  26195.         if (!Range.prototype.getClientRects) {
  26196.           editor.on('mousedown', function (e) {
  26197.             if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  26198.               var body_1 = editor.getBody();
  26199.               body_1.blur();
  26200.               Delay.setEditorTimeout(editor, function () {
  26201.                 body_1.focus();
  26202.               });
  26203.             }
  26204.           });
  26205.         }
  26206.       };
  26207.       var selectControlElements = function () {
  26208.         editor.on('click', function (e) {
  26209.           var target = e.target;
  26210.           if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  26211.             e.preventDefault();
  26212.             editor.selection.select(target);
  26213.             editor.nodeChanged();
  26214.           }
  26215.           if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  26216.             e.preventDefault();
  26217.             selection.select(target);
  26218.           }
  26219.         });
  26220.       };
  26221.       var removeStylesWhenDeletingAcrossBlockElements = function () {
  26222.         var getAttributeApplyFunction = function () {
  26223.           var template = dom.getAttribs(selection.getStart().cloneNode(false));
  26224.           return function () {
  26225.             var target = selection.getStart();
  26226.             if (target !== editor.getBody()) {
  26227.               dom.setAttrib(target, 'style', null);
  26228.               each(template, function (attr) {
  26229.                 target.setAttributeNode(attr.cloneNode(true));
  26230.               });
  26231.             }
  26232.           };
  26233.         };
  26234.         var isSelectionAcrossElements = function () {
  26235.           return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  26236.         };
  26237.         editor.on('keypress', function (e) {
  26238.           var applyAttributes;
  26239.           if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  26240.             applyAttributes = getAttributeApplyFunction();
  26241.             editor.getDoc().execCommand('delete', false, null);
  26242.             applyAttributes();
  26243.             e.preventDefault();
  26244.             return false;
  26245.           }
  26246.         });
  26247.         dom.bind(editor.getDoc(), 'cut', function (e) {
  26248.           var applyAttributes;
  26249.           if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  26250.             applyAttributes = getAttributeApplyFunction();
  26251.             Delay.setEditorTimeout(editor, function () {
  26252.               applyAttributes();
  26253.             });
  26254.           }
  26255.         });
  26256.       };
  26257.       var disableBackspaceIntoATable = function () {
  26258.         editor.on('keydown', function (e) {
  26259.           if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26260.             if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26261.               var previousSibling = selection.getNode().previousSibling;
  26262.               if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  26263.                 e.preventDefault();
  26264.                 return false;
  26265.               }
  26266.             }
  26267.           }
  26268.         });
  26269.       };
  26270.       var removeBlockQuoteOnBackSpace = function () {
  26271.         editor.on('keydown', function (e) {
  26272.           var rng, parent;
  26273.           if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  26274.             return;
  26275.           }
  26276.           rng = selection.getRng();
  26277.           var container = rng.startContainer;
  26278.           var offset = rng.startOffset;
  26279.           var root = dom.getRoot();
  26280.           parent = container;
  26281.           if (!rng.collapsed || offset !== 0) {
  26282.             return;
  26283.           }
  26284.           while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  26285.             parent = parent.parentNode;
  26286.           }
  26287.           if (parent.tagName === 'BLOCKQUOTE') {
  26288.             editor.formatter.toggle('blockquote', null, parent);
  26289.             rng = dom.createRng();
  26290.             rng.setStart(container, 0);
  26291.             rng.setEnd(container, 0);
  26292.             selection.setRng(rng);
  26293.           }
  26294.         });
  26295.       };
  26296.       var setGeckoEditingOptions = function () {
  26297.         var setOpts = function () {
  26298.           setEditorCommandState('StyleWithCSS', false);
  26299.           setEditorCommandState('enableInlineTableEditing', false);
  26300.           if (!getObjectResizing(editor)) {
  26301.             setEditorCommandState('enableObjectResizing', false);
  26302.           }
  26303.         };
  26304.         if (!isReadOnly$1(editor)) {
  26305.           editor.on('BeforeExecCommand mousedown', setOpts);
  26306.         }
  26307.       };
  26308.       var addBrAfterLastLinks = function () {
  26309.         var fixLinks = function () {
  26310.           each(dom.select('a'), function (node) {
  26311.             var parentNode = node.parentNode;
  26312.             var root = dom.getRoot();
  26313.             if (parentNode.lastChild === node) {
  26314.               while (parentNode && !dom.isBlock(parentNode)) {
  26315.                 if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  26316.                   return;
  26317.                 }
  26318.                 parentNode = parentNode.parentNode;
  26319.               }
  26320.               dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  26321.             }
  26322.           });
  26323.         };
  26324.         editor.on('SetContent ExecCommand', function (e) {
  26325.           if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26326.             fixLinks();
  26327.           }
  26328.         });
  26329.       };
  26330.       var setDefaultBlockType = function () {
  26331.         if (getForcedRootBlock(editor)) {
  26332.           editor.on('init', function () {
  26333.             setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26334.           });
  26335.         }
  26336.       };
  26337.       var normalizeSelection = function () {
  26338.         editor.on('keyup focusin mouseup', function (e) {
  26339.           if (!VK.modifierPressed(e)) {
  26340.             selection.normalize();
  26341.           }
  26342.         }, true);
  26343.       };
  26344.       var showBrokenImageIcon = function () {
  26345.         editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26346.       };
  26347.       var restoreFocusOnKeyDown = function () {
  26348.         if (!editor.inline) {
  26349.           editor.on('keydown', function () {
  26350.             if (document.activeElement === document.body) {
  26351.               editor.getWin().focus();
  26352.             }
  26353.           });
  26354.         }
  26355.       };
  26356.       var bodyHeight = function () {
  26357.         if (!editor.inline) {
  26358.           editor.contentStyles.push('body {min-height: 150px}');
  26359.           editor.on('click', function (e) {
  26360.             var rng;
  26361.             if (e.target.nodeName === 'HTML') {
  26362.               if (Env.ie > 11) {
  26363.                 editor.getBody().focus();
  26364.                 return;
  26365.               }
  26366.               rng = editor.selection.getRng();
  26367.               editor.getBody().focus();
  26368.               editor.selection.setRng(rng);
  26369.               editor.selection.normalize();
  26370.               editor.nodeChanged();
  26371.             }
  26372.           });
  26373.         }
  26374.       };
  26375.       var blockCmdArrowNavigation = function () {
  26376.         if (Env.mac) {
  26377.           editor.on('keydown', function (e) {
  26378.             if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26379.               e.preventDefault();
  26380.               var selection_1 = editor.selection.getSel();
  26381.               selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26382.             }
  26383.           });
  26384.         }
  26385.       };
  26386.       var disableAutoUrlDetect = function () {
  26387.         setEditorCommandState('AutoUrlDetect', false);
  26388.       };
  26389.       var tapLinksAndImages = function () {
  26390.         editor.on('click', function (e) {
  26391.           var elm = e.target;
  26392.           do {
  26393.             if (elm.tagName === 'A') {
  26394.               e.preventDefault();
  26395.               return;
  26396.             }
  26397.           } while (elm = elm.parentNode);
  26398.         });
  26399.         editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26400.       };
  26401.       var blockFormSubmitInsideEditor = function () {
  26402.         editor.on('init', function () {
  26403.           editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26404.             e.preventDefault();
  26405.           });
  26406.         });
  26407.       };
  26408.       var removeAppleInterchangeBrs = function () {
  26409.         parser.addNodeFilter('br', function (nodes) {
  26410.           var i = nodes.length;
  26411.           while (i--) {
  26412.             if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26413.               nodes[i].remove();
  26414.             }
  26415.           }
  26416.         });
  26417.       };
  26418.       var ieInternalDragAndDrop = function () {
  26419.         editor.on('dragstart', function (e) {
  26420.           setMceInternalContent(e);
  26421.         });
  26422.         editor.on('drop', function (e) {
  26423.           if (!isDefaultPrevented(e)) {
  26424.             var internalContent = getMceInternalContent(e);
  26425.             if (internalContent && internalContent.id !== editor.id) {
  26426.               e.preventDefault();
  26427.               var rng = fromPoint(e.x, e.y, editor.getDoc());
  26428.               selection.setRng(rng);
  26429.               insertClipboardContents(internalContent.html, true);
  26430.             }
  26431.           }
  26432.         });
  26433.       };
  26434.       var refreshContentEditable = noop;
  26435.       var isHidden = function () {
  26436.         if (!isGecko || editor.removed) {
  26437.           return false;
  26438.         }
  26439.         var sel = editor.selection.getSel();
  26440.         return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26441.       };
  26442.       var setupRtc = function () {
  26443.         if (isWebKit) {
  26444.           documentElementEditingFocus();
  26445.           selectControlElements();
  26446.           blockFormSubmitInsideEditor();
  26447.           selectAll();
  26448.           if (Env.iOS) {
  26449.             restoreFocusOnKeyDown();
  26450.             bodyHeight();
  26451.             tapLinksAndImages();
  26452.           }
  26453.         }
  26454.         if (isGecko) {
  26455.           focusBody();
  26456.           setGeckoEditingOptions();
  26457.           showBrokenImageIcon();
  26458.           blockCmdArrowNavigation();
  26459.         }
  26460.       };
  26461.       var setup = function () {
  26462.         removeBlockQuoteOnBackSpace();
  26463.         emptyEditorWhenDeleting();
  26464.         if (!Env.windowsPhone) {
  26465.           normalizeSelection();
  26466.         }
  26467.         if (isWebKit) {
  26468.           documentElementEditingFocus();
  26469.           selectControlElements();
  26470.           setDefaultBlockType();
  26471.           blockFormSubmitInsideEditor();
  26472.           disableBackspaceIntoATable();
  26473.           removeAppleInterchangeBrs();
  26474.           if (Env.iOS) {
  26475.             restoreFocusOnKeyDown();
  26476.             bodyHeight();
  26477.             tapLinksAndImages();
  26478.           } else {
  26479.             selectAll();
  26480.           }
  26481.         }
  26482.         if (Env.ie >= 11) {
  26483.           bodyHeight();
  26484.           disableBackspaceIntoATable();
  26485.         }
  26486.         if (Env.ie) {
  26487.           selectAll();
  26488.           disableAutoUrlDetect();
  26489.           ieInternalDragAndDrop();
  26490.         }
  26491.         if (isGecko) {
  26492.           removeHrOnBackspace();
  26493.           focusBody();
  26494.           removeStylesWhenDeletingAcrossBlockElements();
  26495.           setGeckoEditingOptions();
  26496.           addBrAfterLastLinks();
  26497.           showBrokenImageIcon();
  26498.           blockCmdArrowNavigation();
  26499.           disableBackspaceIntoATable();
  26500.         }
  26501.       };
  26502.       if (isRtc(editor)) {
  26503.         setupRtc();
  26504.       } else {
  26505.         setup();
  26506.       }
  26507.       return {
  26508.         refreshContentEditable: refreshContentEditable,
  26509.         isHidden: isHidden
  26510.       };
  26511.     };
  26512.  
  26513.     var DOM$6 = DOMUtils.DOM;
  26514.     var appendStyle = function (editor, text) {
  26515.       var body = SugarElement.fromDom(editor.getBody());
  26516.       var container = getStyleContainer(getRootNode(body));
  26517.       var style = SugarElement.fromTag('style');
  26518.       set$1(style, 'type', 'text/css');
  26519.       append$1(style, SugarElement.fromText(text));
  26520.       append$1(container, style);
  26521.       editor.on('remove', function () {
  26522.         remove$7(style);
  26523.       });
  26524.     };
  26525.     var getRootName = function (editor) {
  26526.       return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26527.     };
  26528.     var removeUndefined = function (obj) {
  26529.       return filter$3(obj, function (v) {
  26530.         return isUndefined(v) === false;
  26531.       });
  26532.     };
  26533.     var mkParserSettings = function (editor) {
  26534.       var settings = editor.settings;
  26535.       var blobCache = editor.editorUpload.blobCache;
  26536.       return removeUndefined({
  26537.         allow_conditional_comments: settings.allow_conditional_comments,
  26538.         allow_html_data_urls: settings.allow_html_data_urls,
  26539.         allow_svg_data_urls: settings.allow_svg_data_urls,
  26540.         allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26541.         allow_script_urls: settings.allow_script_urls,
  26542.         allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26543.         convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26544.         fix_list_elements: settings.fix_list_elements,
  26545.         font_size_legacy_values: settings.font_size_legacy_values,
  26546.         forced_root_block: settings.forced_root_block,
  26547.         forced_root_block_attrs: settings.forced_root_block_attrs,
  26548.         padd_empty_with_br: settings.padd_empty_with_br,
  26549.         preserve_cdata: settings.preserve_cdata,
  26550.         remove_trailing_brs: settings.remove_trailing_brs,
  26551.         inline_styles: settings.inline_styles,
  26552.         root_name: getRootName(editor),
  26553.         validate: true,
  26554.         blob_cache: blobCache,
  26555.         document: editor.getDoc(),
  26556.         images_dataimg_filter: settings.images_dataimg_filter
  26557.       });
  26558.     };
  26559.     var mkSerializerSettings = function (editor) {
  26560.       var settings = editor.settings;
  26561.       return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({
  26562.         url_converter: settings.url_converter,
  26563.         url_converter_scope: settings.url_converter_scope,
  26564.         element_format: settings.element_format,
  26565.         entities: settings.entities,
  26566.         entity_encoding: settings.entity_encoding,
  26567.         indent: settings.indent,
  26568.         indent_after: settings.indent_after,
  26569.         indent_before: settings.indent_before,
  26570.         block_elements: settings.block_elements,
  26571.         boolean_attributes: settings.boolean_attributes,
  26572.         custom_elements: settings.custom_elements,
  26573.         extended_valid_elements: settings.extended_valid_elements,
  26574.         invalid_elements: settings.invalid_elements,
  26575.         invalid_styles: settings.invalid_styles,
  26576.         move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26577.         non_empty_elements: settings.non_empty_elements,
  26578.         schema: settings.schema,
  26579.         self_closing_elements: settings.self_closing_elements,
  26580.         short_ended_elements: settings.short_ended_elements,
  26581.         special: settings.special,
  26582.         text_block_elements: settings.text_block_elements,
  26583.         text_inline_elements: settings.text_inline_elements,
  26584.         valid_children: settings.valid_children,
  26585.         valid_classes: settings.valid_classes,
  26586.         valid_elements: settings.valid_elements,
  26587.         valid_styles: settings.valid_styles,
  26588.         verify_html: settings.verify_html,
  26589.         whitespace_elements: settings.whitespace_elements
  26590.       }));
  26591.     };
  26592.     var createParser = function (editor) {
  26593.       var parser = DomParser(mkParserSettings(editor), editor.schema);
  26594.       parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26595.         var i = nodes.length, node, value;
  26596.         var dom = editor.dom;
  26597.         var internalName = 'data-mce-' + name;
  26598.         while (i--) {
  26599.           node = nodes[i];
  26600.           value = node.attr(name);
  26601.           if (value && !node.attr(internalName)) {
  26602.             if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26603.               continue;
  26604.             }
  26605.             if (name === 'style') {
  26606.               value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26607.               if (!value.length) {
  26608.                 value = null;
  26609.               }
  26610.               node.attr(internalName, value);
  26611.               node.attr(name, value);
  26612.             } else if (name === 'tabindex') {
  26613.               node.attr(internalName, value);
  26614.               node.attr(name, null);
  26615.             } else {
  26616.               node.attr(internalName, editor.convertURL(value, name, node.name));
  26617.             }
  26618.           }
  26619.         }
  26620.       });
  26621.       parser.addNodeFilter('script', function (nodes) {
  26622.         var i = nodes.length;
  26623.         while (i--) {
  26624.           var node = nodes[i];
  26625.           var type = node.attr('type') || 'no/type';
  26626.           if (type.indexOf('mce-') !== 0) {
  26627.             node.attr('type', 'mce-' + type);
  26628.           }
  26629.         }
  26630.       });
  26631.       if (editor.settings.preserve_cdata) {
  26632.         parser.addNodeFilter('#cdata', function (nodes) {
  26633.           var i = nodes.length;
  26634.           while (i--) {
  26635.             var node = nodes[i];
  26636.             node.type = 8;
  26637.             node.name = '#comment';
  26638.             node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26639.           }
  26640.         });
  26641.       }
  26642.       parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26643.         var i = nodes.length;
  26644.         var nonEmptyElements = editor.schema.getNonEmptyElements();
  26645.         while (i--) {
  26646.           var node = nodes[i];
  26647.           if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26648.             node.append(new AstNode('br', 1)).shortEnded = true;
  26649.           }
  26650.         }
  26651.       });
  26652.       return parser;
  26653.     };
  26654.     var autoFocus = function (editor) {
  26655.       if (editor.settings.auto_focus) {
  26656.         Delay.setEditorTimeout(editor, function () {
  26657.           var focusEditor;
  26658.           if (editor.settings.auto_focus === true) {
  26659.             focusEditor = editor;
  26660.           } else {
  26661.             focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26662.           }
  26663.           if (!focusEditor.destroyed) {
  26664.             focusEditor.focus();
  26665.           }
  26666.         }, 100);
  26667.       }
  26668.     };
  26669.     var moveSelectionToFirstCaretPosition = function (editor) {
  26670.       var root = editor.dom.getRoot();
  26671.       if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26672.         firstPositionIn(root).each(function (pos) {
  26673.           var node = pos.getNode();
  26674.           var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26675.           if (Env.browser.isIE()) {
  26676.             storeNative(editor, caretPos.toRange());
  26677.           } else {
  26678.             editor.selection.setRng(caretPos.toRange());
  26679.           }
  26680.         });
  26681.       }
  26682.     };
  26683.     var initEditor = function (editor) {
  26684.       editor.bindPendingEventDelegates();
  26685.       editor.initialized = true;
  26686.       fireInit(editor);
  26687.       editor.focus(true);
  26688.       moveSelectionToFirstCaretPosition(editor);
  26689.       editor.nodeChanged({ initial: true });
  26690.       editor.execCallback('init_instance_callback', editor);
  26691.       autoFocus(editor);
  26692.     };
  26693.     var getStyleSheetLoader$1 = function (editor) {
  26694.       return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26695.     };
  26696.     var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26697.       var promises = [new promiseObj(function (resolve, reject) {
  26698.           return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26699.         })];
  26700.       if (editor.inline) {
  26701.         return promises;
  26702.       } else {
  26703.         return promises.concat([new promiseObj(function (resolve, reject) {
  26704.             return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26705.           })]);
  26706.       }
  26707.     };
  26708.     var loadContentCss = function (editor) {
  26709.       var styleSheetLoader = getStyleSheetLoader$1(editor);
  26710.       var fontCss = getFontCss(editor);
  26711.       var css = editor.contentCSS;
  26712.       var removeCss = function () {
  26713.         styleSheetLoader.unloadAll(css);
  26714.         if (!editor.inline) {
  26715.           editor.ui.styleSheetLoader.unloadAll(fontCss);
  26716.         }
  26717.       };
  26718.       var loaded = function () {
  26719.         if (editor.removed) {
  26720.           removeCss();
  26721.         } else {
  26722.           editor.on('remove', removeCss);
  26723.         }
  26724.       };
  26725.       if (editor.contentStyles.length > 0) {
  26726.         var contentCssText_1 = '';
  26727.         Tools.each(editor.contentStyles, function (style) {
  26728.           contentCssText_1 += style + '\r\n';
  26729.         });
  26730.         editor.dom.addStyle(contentCssText_1);
  26731.       }
  26732.       var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26733.       if (editor.settings.content_style) {
  26734.         appendStyle(editor, editor.settings.content_style);
  26735.       }
  26736.       return allStylesheets;
  26737.     };
  26738.     var preInit = function (editor) {
  26739.       var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26740.       firePreInit(editor);
  26741.       if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26742.         doc.body.spellcheck = false;
  26743.         DOM$6.setAttrib(body, 'spellcheck', 'false');
  26744.       }
  26745.       editor.quirks = Quirks(editor);
  26746.       firePostRender(editor);
  26747.       var directionality = getDirectionality(editor);
  26748.       if (directionality !== undefined) {
  26749.         body.dir = directionality;
  26750.       }
  26751.       if (settings.protect) {
  26752.         editor.on('BeforeSetContent', function (e) {
  26753.           Tools.each(settings.protect, function (pattern) {
  26754.             e.content = e.content.replace(pattern, function (str) {
  26755.               return '<!--mce:protected ' + escape(str) + '-->';
  26756.             });
  26757.           });
  26758.         });
  26759.       }
  26760.       editor.on('SetContent', function () {
  26761.         editor.addVisual(editor.getBody());
  26762.       });
  26763.       editor.on('compositionstart compositionend', function (e) {
  26764.         editor.composing = e.type === 'compositionstart';
  26765.       });
  26766.     };
  26767.     var loadInitialContent = function (editor) {
  26768.       if (!isRtc(editor)) {
  26769.         editor.load({
  26770.           initial: true,
  26771.           format: 'html'
  26772.         });
  26773.       }
  26774.       editor.startContent = editor.getContent({ format: 'raw' });
  26775.     };
  26776.     var initEditorWithInitialContent = function (editor) {
  26777.       if (editor.removed !== true) {
  26778.         loadInitialContent(editor);
  26779.         initEditor(editor);
  26780.       }
  26781.     };
  26782.     var initContentBody = function (editor, skipWrite) {
  26783.       var settings = editor.settings;
  26784.       var targetElm = editor.getElement();
  26785.       var doc = editor.getDoc();
  26786.       if (!settings.inline) {
  26787.         editor.getElement().style.visibility = editor.orgVisibility;
  26788.       }
  26789.       if (!skipWrite && !editor.inline) {
  26790.         doc.open();
  26791.         doc.write(editor.iframeHTML);
  26792.         doc.close();
  26793.       }
  26794.       if (editor.inline) {
  26795.         DOM$6.addClass(targetElm, 'mce-content-body');
  26796.         editor.contentDocument = doc = document;
  26797.         editor.contentWindow = window;
  26798.         editor.bodyElement = targetElm;
  26799.         editor.contentAreaContainer = targetElm;
  26800.       }
  26801.       var body = editor.getBody();
  26802.       body.disabled = true;
  26803.       editor.readonly = !!settings.readonly;
  26804.       if (!editor.readonly) {
  26805.         if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26806.           body.style.position = 'relative';
  26807.         }
  26808.         body.contentEditable = editor.getParam('content_editable_state', true);
  26809.       }
  26810.       body.disabled = false;
  26811.       editor.editorUpload = EditorUpload(editor);
  26812.       editor.schema = Schema(settings);
  26813.       editor.dom = DOMUtils(doc, {
  26814.         keep_values: true,
  26815.         url_converter: editor.convertURL,
  26816.         url_converter_scope: editor,
  26817.         hex_colors: settings.force_hex_style_colors,
  26818.         update_styles: true,
  26819.         root_element: editor.inline ? editor.getBody() : null,
  26820.         collect: function () {
  26821.           return editor.inline;
  26822.         },
  26823.         schema: editor.schema,
  26824.         contentCssCors: shouldUseContentCssCors(editor),
  26825.         referrerPolicy: getReferrerPolicy(editor),
  26826.         onSetAttrib: function (e) {
  26827.           editor.fire('SetAttrib', e);
  26828.         }
  26829.       });
  26830.       editor.parser = createParser(editor);
  26831.       editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26832.       editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26833.       editor.annotator = Annotator(editor);
  26834.       editor.formatter = Formatter(editor);
  26835.       editor.undoManager = UndoManager(editor);
  26836.       editor._nodeChangeDispatcher = new NodeChange(editor);
  26837.       editor._selectionOverrides = SelectionOverrides(editor);
  26838.       setup$e(editor);
  26839.       setup$3(editor);
  26840.       if (!isRtc(editor)) {
  26841.         setup$2(editor);
  26842.       }
  26843.       var caret = setup$4(editor);
  26844.       setup$f(editor, caret);
  26845.       setup$d(editor);
  26846.       setup$g(editor);
  26847.       var setupRtcThunk = setup$i(editor);
  26848.       preInit(editor);
  26849.       setupRtcThunk.fold(function () {
  26850.         loadContentCss(editor).then(function () {
  26851.           return initEditorWithInitialContent(editor);
  26852.         });
  26853.       }, function (setupRtc) {
  26854.         editor.setProgressState(true);
  26855.         loadContentCss(editor).then(function () {
  26856.           setupRtc().then(function (_rtcMode) {
  26857.             editor.setProgressState(false);
  26858.             initEditorWithInitialContent(editor);
  26859.           }, function (err) {
  26860.             editor.notificationManager.open({
  26861.               type: 'error',
  26862.               text: String(err)
  26863.             });
  26864.             initEditorWithInitialContent(editor);
  26865.           });
  26866.         });
  26867.       });
  26868.     };
  26869.  
  26870.     var DOM$5 = DOMUtils.DOM;
  26871.     var relaxDomain = function (editor, ifr) {
  26872.       if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26873.         var bodyUuid = uuid('mce');
  26874.         editor[bodyUuid] = function () {
  26875.           initContentBody(editor);
  26876.         };
  26877.         var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()';
  26878.         DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26879.         return true;
  26880.       }
  26881.       return false;
  26882.     };
  26883.     var createIframeElement = function (id, title, height, customAttrs) {
  26884.       var iframe = SugarElement.fromTag('iframe');
  26885.       setAll$1(iframe, customAttrs);
  26886.       setAll$1(iframe, {
  26887.         id: id + '_ifr',
  26888.         frameBorder: '0',
  26889.         allowTransparency: 'true',
  26890.         title: title
  26891.       });
  26892.       add$1(iframe, 'tox-edit-area__iframe');
  26893.       return iframe;
  26894.     };
  26895.     var getIframeHtml = function (editor) {
  26896.       var iframeHTML = getDocType(editor) + '<html><head>';
  26897.       if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26898.         iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26899.       }
  26900.       iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26901.       var bodyId = getBodyId(editor);
  26902.       var bodyClass = getBodyClass(editor);
  26903.       var translatedAriaText = editor.translate(getIframeAriaText(editor));
  26904.       if (getContentSecurityPolicy(editor)) {
  26905.         iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26906.       }
  26907.       iframeHTML += '</head>' + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + '<br>' + '</body></html>';
  26908.       return iframeHTML;
  26909.     };
  26910.     var createIframe = function (editor, o) {
  26911.       var iframeTitle = editor.translate('Rich Text Area');
  26912.       var ifr = createIframeElement(editor.id, iframeTitle, o.height, getIframeAttrs(editor)).dom;
  26913.       ifr.onload = function () {
  26914.         ifr.onload = null;
  26915.         editor.fire('load');
  26916.       };
  26917.       var isDomainRelaxed = relaxDomain(editor, ifr);
  26918.       editor.contentAreaContainer = o.iframeContainer;
  26919.       editor.iframeElement = ifr;
  26920.       editor.iframeHTML = getIframeHtml(editor);
  26921.       DOM$5.add(o.iframeContainer, ifr);
  26922.       return isDomainRelaxed;
  26923.     };
  26924.     var init$1 = function (editor, boxInfo) {
  26925.       var isDomainRelaxed = createIframe(editor, boxInfo);
  26926.       if (boxInfo.editorContainer) {
  26927.         DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26928.         editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26929.       }
  26930.       editor.getElement().style.display = 'none';
  26931.       DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26932.       if (!isDomainRelaxed) {
  26933.         initContentBody(editor);
  26934.       }
  26935.     };
  26936.  
  26937.     var DOM$4 = DOMUtils.DOM;
  26938.     var initPlugin = function (editor, initializedPlugins, plugin) {
  26939.       var Plugin = PluginManager.get(plugin);
  26940.       var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26941.       plugin = Tools.trim(plugin);
  26942.       if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  26943.         Tools.each(PluginManager.dependencies(plugin), function (dep) {
  26944.           initPlugin(editor, initializedPlugins, dep);
  26945.         });
  26946.         if (editor.plugins[plugin]) {
  26947.           return;
  26948.         }
  26949.         try {
  26950.           var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  26951.           editor.plugins[plugin] = pluginInstance;
  26952.           if (pluginInstance.init) {
  26953.             pluginInstance.init(editor, pluginUrl);
  26954.             initializedPlugins.push(plugin);
  26955.           }
  26956.         } catch (e) {
  26957.           pluginInitError(editor, plugin, e);
  26958.         }
  26959.       }
  26960.     };
  26961.     var trimLegacyPrefix = function (name) {
  26962.       return name.replace(/^\-/, '');
  26963.     };
  26964.     var initPlugins = function (editor) {
  26965.       var initializedPlugins = [];
  26966.       Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  26967.         initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  26968.       });
  26969.     };
  26970.     var initIcons = function (editor) {
  26971.       var iconPackName = Tools.trim(getIconPackName(editor));
  26972.       var currentIcons = editor.ui.registry.getAll().icons;
  26973.       var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  26974.       each$j(loadIcons, function (svgData, icon) {
  26975.         if (!has$2(currentIcons, icon)) {
  26976.           editor.ui.registry.addIcon(icon, svgData);
  26977.         }
  26978.       });
  26979.     };
  26980.     var initTheme = function (editor) {
  26981.       var theme = getTheme(editor);
  26982.       if (isString$1(theme)) {
  26983.         editor.settings.theme = trimLegacyPrefix(theme);
  26984.         var Theme = ThemeManager.get(theme);
  26985.         editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  26986.         if (editor.theme.init) {
  26987.           editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  26988.         }
  26989.       } else {
  26990.         editor.theme = {};
  26991.       }
  26992.     };
  26993.     var renderFromLoadedTheme = function (editor) {
  26994.       return editor.theme.renderUI();
  26995.     };
  26996.     var renderFromThemeFunc = function (editor) {
  26997.       var elm = editor.getElement();
  26998.       var theme = getTheme(editor);
  26999.       var info = theme(editor, elm);
  27000.       if (info.editorContainer.nodeType) {
  27001.         info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  27002.       }
  27003.       if (info.iframeContainer && info.iframeContainer.nodeType) {
  27004.         info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  27005.       }
  27006.       info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  27007.       return info;
  27008.     };
  27009.     var createThemeFalseResult = function (element) {
  27010.       return {
  27011.         editorContainer: element,
  27012.         iframeContainer: element,
  27013.         api: {}
  27014.       };
  27015.     };
  27016.     var renderThemeFalseIframe = function (targetElement) {
  27017.       var iframeContainer = DOM$4.create('div');
  27018.       DOM$4.insertAfter(iframeContainer, targetElement);
  27019.       return createThemeFalseResult(iframeContainer);
  27020.     };
  27021.     var renderThemeFalse = function (editor) {
  27022.       var targetElement = editor.getElement();
  27023.       return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  27024.     };
  27025.     var renderThemeUi = function (editor) {
  27026.       var elm = editor.getElement();
  27027.       editor.orgDisplay = elm.style.display;
  27028.       if (isString$1(getTheme(editor))) {
  27029.         return renderFromLoadedTheme(editor);
  27030.       } else if (isFunction(getTheme(editor))) {
  27031.         return renderFromThemeFunc(editor);
  27032.       } else {
  27033.         return renderThemeFalse(editor);
  27034.       }
  27035.     };
  27036.     var augmentEditorUiApi = function (editor, api) {
  27037.       var uiApiFacade = {
  27038.         show: Optional.from(api.show).getOr(noop),
  27039.         hide: Optional.from(api.hide).getOr(noop),
  27040.         disable: Optional.from(api.disable).getOr(noop),
  27041.         isDisabled: Optional.from(api.isDisabled).getOr(never),
  27042.         enable: function () {
  27043.           if (!editor.mode.isReadOnly()) {
  27044.             Optional.from(api.enable).map(call);
  27045.           }
  27046.         }
  27047.       };
  27048.       editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  27049.     };
  27050.     var init = function (editor) {
  27051.       editor.fire('ScriptsLoaded');
  27052.       initIcons(editor);
  27053.       initTheme(editor);
  27054.       initPlugins(editor);
  27055.       var renderInfo = renderThemeUi(editor);
  27056.       augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  27057.       var boxInfo = {
  27058.         editorContainer: renderInfo.editorContainer,
  27059.         iframeContainer: renderInfo.iframeContainer
  27060.       };
  27061.       editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  27062.       appendContentCssFromSettings(editor);
  27063.       if (editor.inline) {
  27064.         return initContentBody(editor);
  27065.       } else {
  27066.         return init$1(editor, boxInfo);
  27067.       }
  27068.     };
  27069.  
  27070.     var DOM$3 = DOMUtils.DOM;
  27071.     var hasSkipLoadPrefix = function (name) {
  27072.       return name.charAt(0) === '-';
  27073.     };
  27074.     var loadLanguage = function (scriptLoader, editor) {
  27075.       var languageCode = getLanguageCode(editor);
  27076.       var languageUrl = getLanguageUrl(editor);
  27077.       if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  27078.         var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  27079.         scriptLoader.add(url_1, noop, undefined, function () {
  27080.           languageLoadError(editor, url_1, languageCode);
  27081.         });
  27082.       }
  27083.     };
  27084.     var loadTheme = function (scriptLoader, editor, suffix, callback) {
  27085.       var theme = getTheme(editor);
  27086.       if (isString$1(theme)) {
  27087.         if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  27088.           var themeUrl = getThemeUrl(editor);
  27089.           if (themeUrl) {
  27090.             ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  27091.           } else {
  27092.             ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  27093.           }
  27094.         }
  27095.         scriptLoader.loadQueue(function () {
  27096.           ThemeManager.waitFor(theme, callback);
  27097.         });
  27098.       } else {
  27099.         callback();
  27100.       }
  27101.     };
  27102.     var getIconsUrlMetaFromUrl = function (editor) {
  27103.       return Optional.from(getIconsUrl(editor)).filter(function (url) {
  27104.         return url.length > 0;
  27105.       }).map(function (url) {
  27106.         return {
  27107.           url: url,
  27108.           name: Optional.none()
  27109.         };
  27110.       });
  27111.     };
  27112.     var getIconsUrlMetaFromName = function (editor, name, suffix) {
  27113.       return Optional.from(name).filter(function (name) {
  27114.         return name.length > 0 && !IconManager.has(name);
  27115.       }).map(function (name) {
  27116.         return {
  27117.           url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  27118.           name: Optional.some(name)
  27119.         };
  27120.       });
  27121.     };
  27122.     var loadIcons = function (scriptLoader, editor, suffix) {
  27123.       var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  27124.       var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  27125.         return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  27126.       });
  27127.       each$k(cat([
  27128.         defaultIconsUrl,
  27129.         customIconsUrl
  27130.       ]), function (urlMeta) {
  27131.         scriptLoader.add(urlMeta.url, noop, undefined, function () {
  27132.           iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  27133.         });
  27134.       });
  27135.     };
  27136.     var loadPlugins = function (editor, suffix) {
  27137.       Tools.each(getExternalPlugins$1(editor), function (url, name) {
  27138.         PluginManager.load(name, url, noop, undefined, function () {
  27139.           pluginLoadError(editor, url, name);
  27140.         });
  27141.         editor.settings.plugins += ' ' + name;
  27142.       });
  27143.       Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  27144.         plugin = Tools.trim(plugin);
  27145.         if (plugin && !PluginManager.urls[plugin]) {
  27146.           if (hasSkipLoadPrefix(plugin)) {
  27147.             plugin = plugin.substr(1, plugin.length);
  27148.             var dependencies = PluginManager.dependencies(plugin);
  27149.             Tools.each(dependencies, function (depPlugin) {
  27150.               var defaultSettings = {
  27151.                 prefix: 'plugins/',
  27152.                 resource: depPlugin,
  27153.                 suffix: '/plugin' + suffix + '.js'
  27154.               };
  27155.               var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  27156.               PluginManager.load(dep.resource, dep, noop, undefined, function () {
  27157.                 pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  27158.               });
  27159.             });
  27160.           } else {
  27161.             var url_2 = {
  27162.               prefix: 'plugins/',
  27163.               resource: plugin,
  27164.               suffix: '/plugin' + suffix + '.js'
  27165.             };
  27166.             PluginManager.load(plugin, url_2, noop, undefined, function () {
  27167.               pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  27168.             });
  27169.           }
  27170.         }
  27171.       });
  27172.     };
  27173.     var loadScripts = function (editor, suffix) {
  27174.       var scriptLoader = ScriptLoader.ScriptLoader;
  27175.       loadTheme(scriptLoader, editor, suffix, function () {
  27176.         loadLanguage(scriptLoader, editor);
  27177.         loadIcons(scriptLoader, editor, suffix);
  27178.         loadPlugins(editor, suffix);
  27179.         scriptLoader.loadQueue(function () {
  27180.           if (!editor.removed) {
  27181.             init(editor);
  27182.           }
  27183.         }, editor, function () {
  27184.           if (!editor.removed) {
  27185.             init(editor);
  27186.           }
  27187.         });
  27188.       });
  27189.     };
  27190.     var getStyleSheetLoader = function (element, editor) {
  27191.       return instance.forElement(element, {
  27192.         contentCssCors: hasContentCssCors(editor),
  27193.         referrerPolicy: getReferrerPolicy(editor)
  27194.       });
  27195.     };
  27196.     var render = function (editor) {
  27197.       var id = editor.id;
  27198.       I18n.setCode(getLanguageCode(editor));
  27199.       var readyHandler = function () {
  27200.         DOM$3.unbind(window, 'ready', readyHandler);
  27201.         editor.render();
  27202.       };
  27203.       if (!EventUtils.Event.domLoaded) {
  27204.         DOM$3.bind(window, 'ready', readyHandler);
  27205.         return;
  27206.       }
  27207.       if (!editor.getElement()) {
  27208.         return;
  27209.       }
  27210.       if (!Env.contentEditable) {
  27211.         return;
  27212.       }
  27213.       var element = SugarElement.fromDom(editor.getElement());
  27214.       var snapshot = clone$3(element);
  27215.       editor.on('remove', function () {
  27216.         eachr(element.dom.attributes, function (attr) {
  27217.           return remove$6(element, attr.name);
  27218.         });
  27219.         setAll$1(element, snapshot);
  27220.       });
  27221.       editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  27222.       if (!isInline(editor)) {
  27223.         editor.orgVisibility = editor.getElement().style.visibility;
  27224.         editor.getElement().style.visibility = 'hidden';
  27225.       } else {
  27226.         editor.inline = true;
  27227.       }
  27228.       var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  27229.       if (form) {
  27230.         editor.formElement = form;
  27231.         if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  27232.           DOM$3.insertAfter(DOM$3.create('input', {
  27233.             type: 'hidden',
  27234.             name: id
  27235.           }), id);
  27236.           editor.hasHiddenInput = true;
  27237.         }
  27238.         editor.formEventDelegate = function (e) {
  27239.           editor.fire(e.type, e);
  27240.         };
  27241.         DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  27242.         editor.on('reset', function () {
  27243.           editor.resetContent();
  27244.         });
  27245.         if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  27246.           form._mceOldSubmit = form.submit;
  27247.           form.submit = function () {
  27248.             editor.editorManager.triggerSave();
  27249.             editor.setDirty(false);
  27250.             return form._mceOldSubmit(form);
  27251.           };
  27252.         }
  27253.       }
  27254.       editor.windowManager = WindowManager(editor);
  27255.       editor.notificationManager = NotificationManager(editor);
  27256.       if (isEncodingXml(editor)) {
  27257.         editor.on('GetContent', function (e) {
  27258.           if (e.save) {
  27259.             e.content = DOM$3.encode(e.content);
  27260.           }
  27261.         });
  27262.       }
  27263.       if (shouldAddFormSubmitTrigger(editor)) {
  27264.         editor.on('submit', function () {
  27265.           if (editor.initialized) {
  27266.             editor.save();
  27267.           }
  27268.         });
  27269.       }
  27270.       if (shouldAddUnloadTrigger(editor)) {
  27271.         editor._beforeUnload = function () {
  27272.           if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  27273.             editor.save({
  27274.               format: 'raw',
  27275.               no_events: true,
  27276.               set_dirty: false
  27277.             });
  27278.           }
  27279.         };
  27280.         editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  27281.       }
  27282.       editor.editorManager.add(editor);
  27283.       loadScripts(editor, editor.suffix);
  27284.     };
  27285.  
  27286.     var addVisual = function (editor, elm) {
  27287.       return addVisual$1(editor, elm);
  27288.     };
  27289.  
  27290.     var legacyPropNames = {
  27291.       'font-size': 'size',
  27292.       'font-family': 'face'
  27293.     };
  27294.     var getSpecifiedFontProp = function (propName, rootElm, elm) {
  27295.       var getProperty = function (elm) {
  27296.         return getRaw(elm, propName).orThunk(function () {
  27297.           if (name(elm) === 'font') {
  27298.             return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  27299.               return getOpt(elm, legacyPropName);
  27300.             });
  27301.           } else {
  27302.             return Optional.none();
  27303.           }
  27304.         });
  27305.       };
  27306.       var isRoot = function (elm) {
  27307.         return eq(SugarElement.fromDom(rootElm), elm);
  27308.       };
  27309.       return closest$1(SugarElement.fromDom(elm), function (elm) {
  27310.         return getProperty(elm);
  27311.       }, isRoot);
  27312.     };
  27313.     var normalizeFontFamily = function (fontFamily) {
  27314.       return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  27315.     };
  27316.     var getComputedFontProp = function (propName, elm) {
  27317.       return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  27318.     };
  27319.     var getFontProp = function (propName) {
  27320.       return function (rootElm, elm) {
  27321.         return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  27322.           return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  27323.         }).getOr('');
  27324.       };
  27325.     };
  27326.     var getFontSize = getFontProp('font-size');
  27327.     var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  27328.  
  27329.     var findFirstCaretElement = function (editor) {
  27330.       return firstPositionIn(editor.getBody()).map(function (caret) {
  27331.         var container = caret.container();
  27332.         return isText$7(container) ? container.parentNode : container;
  27333.       });
  27334.     };
  27335.     var getCaretElement = function (editor) {
  27336.       return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27337.         var root = editor.getBody();
  27338.         var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27339.         return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27340.       });
  27341.     };
  27342.     var bindRange = function (editor, binder) {
  27343.       return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27344.     };
  27345.     var mapRange = function (editor, mapper) {
  27346.       return bindRange(editor, compose1(Optional.some, mapper));
  27347.     };
  27348.  
  27349.     var fromFontSizeNumber = function (editor, value) {
  27350.       if (/^[0-9.]+$/.test(value)) {
  27351.         var fontSizeNumber = parseInt(value, 10);
  27352.         if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27353.           var fontSizes = getFontStyleValues(editor);
  27354.           var fontClasses = getFontSizeClasses(editor);
  27355.           if (fontClasses) {
  27356.             return fontClasses[fontSizeNumber - 1] || value;
  27357.           } else {
  27358.             return fontSizes[fontSizeNumber - 1] || value;
  27359.           }
  27360.         } else {
  27361.           return value;
  27362.         }
  27363.       } else {
  27364.         return value;
  27365.       }
  27366.     };
  27367.     var normalizeFontNames = function (font) {
  27368.       var fonts = font.split(/\s*,\s*/);
  27369.       return map$3(fonts, function (font) {
  27370.         if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27371.           return '\'' + font + '\'';
  27372.         } else {
  27373.           return font;
  27374.         }
  27375.       }).join(',');
  27376.     };
  27377.     var fontNameAction = function (editor, value) {
  27378.       var font = fromFontSizeNumber(editor, value);
  27379.       editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27380.       editor.nodeChanged();
  27381.     };
  27382.     var fontNameQuery = function (editor) {
  27383.       return mapRange(editor, function (elm) {
  27384.         return getFontFamily(editor.getBody(), elm.dom);
  27385.       }).getOr('');
  27386.     };
  27387.     var fontSizeAction = function (editor, value) {
  27388.       editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27389.       editor.nodeChanged();
  27390.     };
  27391.     var fontSizeQuery = function (editor) {
  27392.       return mapRange(editor, function (elm) {
  27393.         return getFontSize(editor.getBody(), elm.dom);
  27394.       }).getOr('');
  27395.     };
  27396.  
  27397.     var lineHeightQuery = function (editor) {
  27398.       return mapRange(editor, function (elm) {
  27399.         var root = SugarElement.fromDom(editor.getBody());
  27400.         var specifiedStyle = closest$1(elm, function (elm) {
  27401.           return getRaw(elm, 'line-height');
  27402.         }, curry(eq, root));
  27403.         var computedStyle = function () {
  27404.           var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27405.           var fontSize = parseFloat(get$5(elm, 'font-size'));
  27406.           return String(lineHeight / fontSize);
  27407.         };
  27408.         return specifiedStyle.getOrThunk(computedStyle);
  27409.       }).getOr('');
  27410.     };
  27411.     var lineHeightAction = function (editor, lineHeight) {
  27412.       editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27413.       editor.nodeChanged();
  27414.     };
  27415.  
  27416.     var processValue = function (value) {
  27417.       if (typeof value !== 'string') {
  27418.         var details = Tools.extend({
  27419.           paste: value.paste,
  27420.           data: { paste: value.paste }
  27421.         }, value);
  27422.         return {
  27423.           content: value.content,
  27424.           details: details
  27425.         };
  27426.       }
  27427.       return {
  27428.         content: value,
  27429.         details: {}
  27430.       };
  27431.     };
  27432.     var insertAtCaret = function (editor, value) {
  27433.       var result = processValue(value);
  27434.       insertContent(editor, result.content, result.details);
  27435.     };
  27436.  
  27437.     var each$4 = Tools.each;
  27438.     var map = Tools.map, inArray = Tools.inArray;
  27439.     var EditorCommands = function () {
  27440.       function EditorCommands(editor) {
  27441.         this.commands = {
  27442.           state: {},
  27443.           exec: {},
  27444.           value: {}
  27445.         };
  27446.         this.editor = editor;
  27447.         this.setupCommands(editor);
  27448.       }
  27449.       EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27450.         var func, state = false;
  27451.         var self = this;
  27452.         if (self.editor.removed) {
  27453.           return;
  27454.         }
  27455.         if (command.toLowerCase() !== 'mcefocus') {
  27456.           if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27457.             self.editor.focus();
  27458.           } else {
  27459.             restore(self.editor);
  27460.           }
  27461.         }
  27462.         args = self.editor.fire('BeforeExecCommand', {
  27463.           command: command,
  27464.           ui: ui,
  27465.           value: value
  27466.         });
  27467.         if (args.isDefaultPrevented()) {
  27468.           return false;
  27469.         }
  27470.         var customCommand = command.toLowerCase();
  27471.         if (func = self.commands.exec[customCommand]) {
  27472.           func(customCommand, ui, value);
  27473.           self.editor.fire('ExecCommand', {
  27474.             command: command,
  27475.             ui: ui,
  27476.             value: value
  27477.           });
  27478.           return true;
  27479.         }
  27480.         each$4(this.editor.plugins, function (p) {
  27481.           if (p.execCommand && p.execCommand(command, ui, value)) {
  27482.             self.editor.fire('ExecCommand', {
  27483.               command: command,
  27484.               ui: ui,
  27485.               value: value
  27486.             });
  27487.             state = true;
  27488.             return false;
  27489.           }
  27490.         });
  27491.         if (state) {
  27492.           return state;
  27493.         }
  27494.         if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27495.           self.editor.fire('ExecCommand', {
  27496.             command: command,
  27497.             ui: ui,
  27498.             value: value
  27499.           });
  27500.           return true;
  27501.         }
  27502.         try {
  27503.           state = self.editor.getDoc().execCommand(command, ui, value);
  27504.         } catch (ex) {
  27505.         }
  27506.         if (state) {
  27507.           self.editor.fire('ExecCommand', {
  27508.             command: command,
  27509.             ui: ui,
  27510.             value: value
  27511.           });
  27512.           return true;
  27513.         }
  27514.         return false;
  27515.       };
  27516.       EditorCommands.prototype.queryCommandState = function (command) {
  27517.         var func;
  27518.         if (this.editor.quirks.isHidden() || this.editor.removed) {
  27519.           return;
  27520.         }
  27521.         command = command.toLowerCase();
  27522.         if (func = this.commands.state[command]) {
  27523.           return func(command);
  27524.         }
  27525.         try {
  27526.           return this.editor.getDoc().queryCommandState(command);
  27527.         } catch (ex) {
  27528.         }
  27529.         return false;
  27530.       };
  27531.       EditorCommands.prototype.queryCommandValue = function (command) {
  27532.         var func;
  27533.         if (this.editor.quirks.isHidden() || this.editor.removed) {
  27534.           return;
  27535.         }
  27536.         command = command.toLowerCase();
  27537.         if (func = this.commands.value[command]) {
  27538.           return func(command);
  27539.         }
  27540.         try {
  27541.           return this.editor.getDoc().queryCommandValue(command);
  27542.         } catch (ex) {
  27543.         }
  27544.       };
  27545.       EditorCommands.prototype.addCommands = function (commandList, type) {
  27546.         if (type === void 0) {
  27547.           type = 'exec';
  27548.         }
  27549.         var self = this;
  27550.         each$4(commandList, function (callback, command) {
  27551.           each$4(command.toLowerCase().split(','), function (command) {
  27552.             self.commands[type][command] = callback;
  27553.           });
  27554.         });
  27555.       };
  27556.       EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27557.         var _this = this;
  27558.         command = command.toLowerCase();
  27559.         this.commands.exec[command] = function (command, ui, value, args) {
  27560.           return callback.call(scope || _this.editor, ui, value, args);
  27561.         };
  27562.       };
  27563.       EditorCommands.prototype.queryCommandSupported = function (command) {
  27564.         command = command.toLowerCase();
  27565.         if (this.commands.exec[command]) {
  27566.           return true;
  27567.         }
  27568.         try {
  27569.           return this.editor.getDoc().queryCommandSupported(command);
  27570.         } catch (ex) {
  27571.         }
  27572.         return false;
  27573.       };
  27574.       EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27575.         var _this = this;
  27576.         command = command.toLowerCase();
  27577.         this.commands.state[command] = function () {
  27578.           return callback.call(scope || _this.editor);
  27579.         };
  27580.       };
  27581.       EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27582.         var _this = this;
  27583.         command = command.toLowerCase();
  27584.         this.commands.value[command] = function () {
  27585.           return callback.call(scope || _this.editor);
  27586.         };
  27587.       };
  27588.       EditorCommands.prototype.hasCustomCommand = function (command) {
  27589.         command = command.toLowerCase();
  27590.         return !!this.commands.exec[command];
  27591.       };
  27592.       EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27593.         if (ui === undefined) {
  27594.           ui = false;
  27595.         }
  27596.         if (value === undefined) {
  27597.           value = null;
  27598.         }
  27599.         return this.editor.getDoc().execCommand(command, ui, value);
  27600.       };
  27601.       EditorCommands.prototype.isFormatMatch = function (name) {
  27602.         return this.editor.formatter.match(name);
  27603.       };
  27604.       EditorCommands.prototype.toggleFormat = function (name, value) {
  27605.         this.editor.formatter.toggle(name, value);
  27606.         this.editor.nodeChanged();
  27607.       };
  27608.       EditorCommands.prototype.storeSelection = function (type) {
  27609.         this.selectionBookmark = this.editor.selection.getBookmark(type);
  27610.       };
  27611.       EditorCommands.prototype.restoreSelection = function () {
  27612.         this.editor.selection.moveToBookmark(this.selectionBookmark);
  27613.       };
  27614.       EditorCommands.prototype.setupCommands = function (editor) {
  27615.         var self = this;
  27616.         this.addCommands({
  27617.           'mceResetDesignMode,mceBeginUndoLevel': noop,
  27618.           'mceEndUndoLevel,mceAddUndoLevel': function () {
  27619.             editor.undoManager.add();
  27620.           },
  27621.           'mceFocus': function (_command, _ui, value) {
  27622.             focus(editor, value);
  27623.           },
  27624.           'Cut,Copy,Paste': function (command) {
  27625.             var doc = editor.getDoc();
  27626.             var failed;
  27627.             try {
  27628.               self.execNativeCommand(command);
  27629.             } catch (ex) {
  27630.               failed = true;
  27631.             }
  27632.             if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27633.               failed = true;
  27634.             }
  27635.             if (failed || !doc.queryCommandSupported(command)) {
  27636.               var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27637.               if (Env.mac) {
  27638.                 msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27639.               }
  27640.               editor.notificationManager.open({
  27641.                 text: msg,
  27642.                 type: 'error'
  27643.               });
  27644.             }
  27645.           },
  27646.           'unlink': function () {
  27647.             if (editor.selection.isCollapsed()) {
  27648.               var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27649.               if (elm) {
  27650.                 editor.dom.remove(elm, true);
  27651.               }
  27652.               return;
  27653.             }
  27654.             editor.formatter.remove('link');
  27655.           },
  27656.           'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27657.             var align = command.substring(7);
  27658.             if (align === 'full') {
  27659.               align = 'justify';
  27660.             }
  27661.             each$4('left,center,right,justify'.split(','), function (name) {
  27662.               if (align !== name) {
  27663.                 editor.formatter.remove('align' + name);
  27664.               }
  27665.             });
  27666.             if (align !== 'none') {
  27667.               self.toggleFormat('align' + align);
  27668.             }
  27669.           },
  27670.           'InsertUnorderedList,InsertOrderedList': function (command) {
  27671.             var listParent;
  27672.             self.execNativeCommand(command);
  27673.             var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27674.             if (listElm) {
  27675.               listParent = listElm.parentNode;
  27676.               if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27677.                 self.storeSelection();
  27678.                 editor.dom.split(listParent, listElm);
  27679.                 self.restoreSelection();
  27680.               }
  27681.             }
  27682.           },
  27683.           'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27684.             self.toggleFormat(command);
  27685.           },
  27686.           'ForeColor,HiliteColor': function (command, ui, value) {
  27687.             self.toggleFormat(command, { value: value });
  27688.           },
  27689.           'FontName': function (command, ui, value) {
  27690.             fontNameAction(editor, value);
  27691.           },
  27692.           'FontSize': function (command, ui, value) {
  27693.             fontSizeAction(editor, value);
  27694.           },
  27695.           'LineHeight': function (command, ui, value) {
  27696.             lineHeightAction(editor, value);
  27697.           },
  27698.           'Lang': function (command, ui, lang) {
  27699.             self.toggleFormat(command, {
  27700.               value: lang.code,
  27701.               customValue: lang.customCode
  27702.             });
  27703.           },
  27704.           'RemoveFormat': function (command) {
  27705.             editor.formatter.remove(command);
  27706.           },
  27707.           'mceBlockQuote': function () {
  27708.             self.toggleFormat('blockquote');
  27709.           },
  27710.           'FormatBlock': function (command, ui, value) {
  27711.             return self.toggleFormat(value || 'p');
  27712.           },
  27713.           'mceCleanup': function () {
  27714.             var bookmark = editor.selection.getBookmark();
  27715.             editor.setContent(editor.getContent());
  27716.             editor.selection.moveToBookmark(bookmark);
  27717.           },
  27718.           'mceRemoveNode': function (command, ui, value) {
  27719.             var node = value || editor.selection.getNode();
  27720.             if (node !== editor.getBody()) {
  27721.               self.storeSelection();
  27722.               editor.dom.remove(node, true);
  27723.               self.restoreSelection();
  27724.             }
  27725.           },
  27726.           'mceSelectNodeDepth': function (command, ui, value) {
  27727.             var counter = 0;
  27728.             editor.dom.getParent(editor.selection.getNode(), function (node) {
  27729.               if (node.nodeType === 1 && counter++ === value) {
  27730.                 editor.selection.select(node);
  27731.                 return false;
  27732.               }
  27733.             }, editor.getBody());
  27734.           },
  27735.           'mceSelectNode': function (command, ui, value) {
  27736.             editor.selection.select(value);
  27737.           },
  27738.           'mceInsertContent': function (command, ui, value) {
  27739.             insertAtCaret(editor, value);
  27740.           },
  27741.           'mceInsertRawHTML': function (command, ui, value) {
  27742.             editor.selection.setContent('tiny_mce_marker');
  27743.             var content = editor.getContent();
  27744.             editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27745.               return value;
  27746.             }));
  27747.           },
  27748.           'mceInsertNewLine': function (command, ui, value) {
  27749.             insert(editor, value);
  27750.           },
  27751.           'mceToggleFormat': function (command, ui, value) {
  27752.             self.toggleFormat(value);
  27753.           },
  27754.           'mceSetContent': function (command, ui, value) {
  27755.             editor.setContent(value);
  27756.           },
  27757.           'Indent,Outdent': function (command) {
  27758.             handle(editor, command);
  27759.           },
  27760.           'mceRepaint': noop,
  27761.           'InsertHorizontalRule': function () {
  27762.             editor.execCommand('mceInsertContent', false, '<hr />');
  27763.           },
  27764.           'mceToggleVisualAid': function () {
  27765.             editor.hasVisual = !editor.hasVisual;
  27766.             editor.addVisual();
  27767.           },
  27768.           'mceReplaceContent': function (command, ui, value) {
  27769.             editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27770.           },
  27771.           'mceInsertLink': function (command, ui, value) {
  27772.             if (typeof value === 'string') {
  27773.               value = { href: value };
  27774.             }
  27775.             var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27776.             value.href = value.href.replace(/ /g, '%20');
  27777.             if (!anchor || !value.href) {
  27778.               editor.formatter.remove('link');
  27779.             }
  27780.             if (value.href) {
  27781.               editor.formatter.apply('link', value, anchor);
  27782.             }
  27783.           },
  27784.           'selectAll': function () {
  27785.             var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27786.             if (editingHost) {
  27787.               var rng = editor.dom.createRng();
  27788.               rng.selectNodeContents(editingHost);
  27789.               editor.selection.setRng(rng);
  27790.             }
  27791.           },
  27792.           'mceNewDocument': function () {
  27793.             editor.setContent('');
  27794.           },
  27795.           'InsertLineBreak': function (command, ui, value) {
  27796.             insert$1(editor, value);
  27797.             return true;
  27798.           }
  27799.         });
  27800.         var alignStates = function (name) {
  27801.           return function () {
  27802.             var selection = editor.selection;
  27803.             var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27804.             var matches = map(nodes, function (node) {
  27805.               return !!editor.formatter.matchNode(node, name);
  27806.             });
  27807.             return inArray(matches, true) !== -1;
  27808.           };
  27809.         };
  27810.         self.addCommands({
  27811.           'JustifyLeft': alignStates('alignleft'),
  27812.           'JustifyCenter': alignStates('aligncenter'),
  27813.           'JustifyRight': alignStates('alignright'),
  27814.           'JustifyFull': alignStates('alignjustify'),
  27815.           'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27816.             return self.isFormatMatch(command);
  27817.           },
  27818.           'mceBlockQuote': function () {
  27819.             return self.isFormatMatch('blockquote');
  27820.           },
  27821.           'Outdent': function () {
  27822.             return canOutdent(editor);
  27823.           },
  27824.           'InsertUnorderedList,InsertOrderedList': function (command) {
  27825.             var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27826.             return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27827.           }
  27828.         }, 'state');
  27829.         self.addCommands({
  27830.           Undo: function () {
  27831.             editor.undoManager.undo();
  27832.           },
  27833.           Redo: function () {
  27834.             editor.undoManager.redo();
  27835.           }
  27836.         });
  27837.         self.addQueryValueHandler('FontName', function () {
  27838.           return fontNameQuery(editor);
  27839.         }, this);
  27840.         self.addQueryValueHandler('FontSize', function () {
  27841.           return fontSizeQuery(editor);
  27842.         }, this);
  27843.         self.addQueryValueHandler('LineHeight', function () {
  27844.           return lineHeightQuery(editor);
  27845.         }, this);
  27846.       };
  27847.       return EditorCommands;
  27848.     }();
  27849.  
  27850.     var internalContentEditableAttr = 'data-mce-contenteditable';
  27851.     var toggleClass = function (elm, cls, state) {
  27852.       if (has(elm, cls) && state === false) {
  27853.         remove$3(elm, cls);
  27854.       } else if (state) {
  27855.         add$1(elm, cls);
  27856.       }
  27857.     };
  27858.     var setEditorCommandState = function (editor, cmd, state) {
  27859.       try {
  27860.         editor.getDoc().execCommand(cmd, false, String(state));
  27861.       } catch (ex) {
  27862.       }
  27863.     };
  27864.     var setContentEditable = function (elm, state) {
  27865.       elm.dom.contentEditable = state ? 'true' : 'false';
  27866.     };
  27867.     var switchOffContentEditableTrue = function (elm) {
  27868.       each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27869.         set$1(elm, internalContentEditableAttr, 'true');
  27870.         setContentEditable(elm, false);
  27871.       });
  27872.     };
  27873.     var switchOnContentEditableTrue = function (elm) {
  27874.       each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27875.         remove$6(elm, internalContentEditableAttr);
  27876.         setContentEditable(elm, true);
  27877.       });
  27878.     };
  27879.     var removeFakeSelection = function (editor) {
  27880.       Optional.from(editor.selection.getNode()).each(function (elm) {
  27881.         elm.removeAttribute('data-mce-selected');
  27882.       });
  27883.     };
  27884.     var restoreFakeSelection = function (editor) {
  27885.       editor.selection.setRng(editor.selection.getRng());
  27886.     };
  27887.     var toggleReadOnly = function (editor, state) {
  27888.       var body = SugarElement.fromDom(editor.getBody());
  27889.       toggleClass(body, 'mce-content-readonly', state);
  27890.       if (state) {
  27891.         editor.selection.controlSelection.hideResizeRect();
  27892.         editor._selectionOverrides.hideFakeCaret();
  27893.         removeFakeSelection(editor);
  27894.         editor.readonly = true;
  27895.         setContentEditable(body, false);
  27896.         switchOffContentEditableTrue(body);
  27897.       } else {
  27898.         editor.readonly = false;
  27899.         setContentEditable(body, true);
  27900.         switchOnContentEditableTrue(body);
  27901.         setEditorCommandState(editor, 'StyleWithCSS', false);
  27902.         setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27903.         setEditorCommandState(editor, 'enableObjectResizing', false);
  27904.         if (hasEditorOrUiFocus(editor)) {
  27905.           editor.focus();
  27906.         }
  27907.         restoreFakeSelection(editor);
  27908.         editor.nodeChanged();
  27909.       }
  27910.     };
  27911.     var isReadOnly = function (editor) {
  27912.       return editor.readonly;
  27913.     };
  27914.     var registerFilters = function (editor) {
  27915.       editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27916.         if (isReadOnly(editor)) {
  27917.           each$k(nodes, function (node) {
  27918.             node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27919.             node.attr('contenteditable', 'false');
  27920.           });
  27921.         }
  27922.       });
  27923.       editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27924.         if (isReadOnly(editor)) {
  27925.           each$k(nodes, function (node) {
  27926.             node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27927.           });
  27928.         }
  27929.       });
  27930.       editor.serializer.addTempAttr(internalContentEditableAttr);
  27931.     };
  27932.     var registerReadOnlyContentFilters = function (editor) {
  27933.       if (editor.serializer) {
  27934.         registerFilters(editor);
  27935.       } else {
  27936.         editor.on('PreInit', function () {
  27937.           registerFilters(editor);
  27938.         });
  27939.       }
  27940.     };
  27941.     var isClickEvent = function (e) {
  27942.       return e.type === 'click';
  27943.     };
  27944.     var getAnchorHrefOpt = function (editor, elm) {
  27945.       var isRoot = function (elm) {
  27946.         return eq(elm, SugarElement.fromDom(editor.getBody()));
  27947.       };
  27948.       return closest$2(elm, 'a', isRoot).bind(function (a) {
  27949.         return getOpt(a, 'href');
  27950.       });
  27951.     };
  27952.     var processReadonlyEvents = function (editor, e) {
  27953.       if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  27954.         var elm = SugarElement.fromDom(e.target);
  27955.         getAnchorHrefOpt(editor, elm).each(function (href) {
  27956.           e.preventDefault();
  27957.           if (/^#/.test(href)) {
  27958.             var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  27959.             if (targetEl.length) {
  27960.               editor.selection.scrollIntoView(targetEl[0], true);
  27961.             }
  27962.           } else {
  27963.             window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  27964.           }
  27965.         });
  27966.       }
  27967.     };
  27968.     var registerReadOnlySelectionBlockers = function (editor) {
  27969.       editor.on('ShowCaret', function (e) {
  27970.         if (isReadOnly(editor)) {
  27971.           e.preventDefault();
  27972.         }
  27973.       });
  27974.       editor.on('ObjectSelected', function (e) {
  27975.         if (isReadOnly(editor)) {
  27976.           e.preventDefault();
  27977.         }
  27978.       });
  27979.     };
  27980.  
  27981.     var nativeEvents = Tools.makeMap('focus blur focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange ' + 'mouseout mouseenter mouseleave wheel keydown keypress keyup input beforeinput contextmenu dragstart dragend dragover ' + 'draggesture dragdrop drop drag submit ' + 'compositionstart compositionend compositionupdate touchstart touchmove touchend touchcancel', ' ');
  27982.     var EventDispatcher = function () {
  27983.       function EventDispatcher(settings) {
  27984.         this.bindings = {};
  27985.         this.settings = settings || {};
  27986.         this.scope = this.settings.scope || this;
  27987.         this.toggleEvent = this.settings.toggleEvent || never;
  27988.       }
  27989.       EventDispatcher.isNative = function (name) {
  27990.         return !!nativeEvents[name.toLowerCase()];
  27991.       };
  27992.       EventDispatcher.prototype.fire = function (name, args) {
  27993.         var lcName = name.toLowerCase();
  27994.         var event = normalize$3(lcName, args || {}, this.scope);
  27995.         if (this.settings.beforeFire) {
  27996.           this.settings.beforeFire(event);
  27997.         }
  27998.         var handlers = this.bindings[lcName];
  27999.         if (handlers) {
  28000.           for (var i = 0, l = handlers.length; i < l; i++) {
  28001.             var callback = handlers[i];
  28002.             if (callback.removed) {
  28003.               continue;
  28004.             }
  28005.             if (callback.once) {
  28006.               this.off(lcName, callback.func);
  28007.             }
  28008.             if (event.isImmediatePropagationStopped()) {
  28009.               return event;
  28010.             }
  28011.             if (callback.func.call(this.scope, event) === false) {
  28012.               event.preventDefault();
  28013.               return event;
  28014.             }
  28015.           }
  28016.         }
  28017.         return event;
  28018.       };
  28019.       EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  28020.         if (callback === false) {
  28021.           callback = never;
  28022.         }
  28023.         if (callback) {
  28024.           var wrappedCallback = {
  28025.             func: callback,
  28026.             removed: false
  28027.           };
  28028.           if (extra) {
  28029.             Tools.extend(wrappedCallback, extra);
  28030.           }
  28031.           var names = name.toLowerCase().split(' ');
  28032.           var i = names.length;
  28033.           while (i--) {
  28034.             var currentName = names[i];
  28035.             var handlers = this.bindings[currentName];
  28036.             if (!handlers) {
  28037.               handlers = [];
  28038.               this.toggleEvent(currentName, true);
  28039.             }
  28040.             if (prepend) {
  28041.               handlers = __spreadArray([wrappedCallback], handlers, true);
  28042.             } else {
  28043.               handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
  28044.             }
  28045.             this.bindings[currentName] = handlers;
  28046.           }
  28047.         }
  28048.         return this;
  28049.       };
  28050.       EventDispatcher.prototype.off = function (name, callback) {
  28051.         var _this = this;
  28052.         if (name) {
  28053.           var names = name.toLowerCase().split(' ');
  28054.           var i = names.length;
  28055.           while (i--) {
  28056.             var currentName = names[i];
  28057.             var handlers = this.bindings[currentName];
  28058.             if (!currentName) {
  28059.               each$j(this.bindings, function (_value, bindingName) {
  28060.                 _this.toggleEvent(bindingName, false);
  28061.                 delete _this.bindings[bindingName];
  28062.               });
  28063.               return this;
  28064.             }
  28065.             if (handlers) {
  28066.               if (!callback) {
  28067.                 handlers.length = 0;
  28068.               } else {
  28069.                 var filteredHandlers = partition(handlers, function (handler) {
  28070.                   return handler.func === callback;
  28071.                 });
  28072.                 handlers = filteredHandlers.fail;
  28073.                 this.bindings[currentName] = handlers;
  28074.                 each$k(filteredHandlers.pass, function (handler) {
  28075.                   handler.removed = true;
  28076.                 });
  28077.               }
  28078.               if (!handlers.length) {
  28079.                 this.toggleEvent(name, false);
  28080.                 delete this.bindings[currentName];
  28081.               }
  28082.             }
  28083.           }
  28084.         } else {
  28085.           each$j(this.bindings, function (_value, name) {
  28086.             _this.toggleEvent(name, false);
  28087.           });
  28088.           this.bindings = {};
  28089.         }
  28090.         return this;
  28091.       };
  28092.       EventDispatcher.prototype.once = function (name, callback, prepend) {
  28093.         return this.on(name, callback, prepend, { once: true });
  28094.       };
  28095.       EventDispatcher.prototype.has = function (name) {
  28096.         name = name.toLowerCase();
  28097.         return !(!this.bindings[name] || this.bindings[name].length === 0);
  28098.       };
  28099.       return EventDispatcher;
  28100.     }();
  28101.  
  28102.     var getEventDispatcher = function (obj) {
  28103.       if (!obj._eventDispatcher) {
  28104.         obj._eventDispatcher = new EventDispatcher({
  28105.           scope: obj,
  28106.           toggleEvent: function (name, state) {
  28107.             if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  28108.               obj.toggleNativeEvent(name, state);
  28109.             }
  28110.           }
  28111.         });
  28112.       }
  28113.       return obj._eventDispatcher;
  28114.     };
  28115.     var Observable = {
  28116.       fire: function (name, args, bubble) {
  28117.         var self = this;
  28118.         if (self.removed && name !== 'remove' && name !== 'detach') {
  28119.           return args;
  28120.         }
  28121.         var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  28122.         if (bubble !== false && self.parent) {
  28123.           var parent_1 = self.parent();
  28124.           while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  28125.             parent_1.fire(name, dispatcherArgs, false);
  28126.             parent_1 = parent_1.parent();
  28127.           }
  28128.         }
  28129.         return dispatcherArgs;
  28130.       },
  28131.       on: function (name, callback, prepend) {
  28132.         return getEventDispatcher(this).on(name, callback, prepend);
  28133.       },
  28134.       off: function (name, callback) {
  28135.         return getEventDispatcher(this).off(name, callback);
  28136.       },
  28137.       once: function (name, callback) {
  28138.         return getEventDispatcher(this).once(name, callback);
  28139.       },
  28140.       hasEventListeners: function (name) {
  28141.         return getEventDispatcher(this).has(name);
  28142.       }
  28143.     };
  28144.  
  28145.     var DOM$2 = DOMUtils.DOM;
  28146.     var customEventRootDelegates;
  28147.     var getEventTarget = function (editor, eventName) {
  28148.       if (eventName === 'selectionchange') {
  28149.         return editor.getDoc();
  28150.       }
  28151.       if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  28152.         return editor.getDoc().documentElement;
  28153.       }
  28154.       var eventRoot = getEventRoot(editor);
  28155.       if (eventRoot) {
  28156.         if (!editor.eventRoot) {
  28157.           editor.eventRoot = DOM$2.select(eventRoot)[0];
  28158.         }
  28159.         return editor.eventRoot;
  28160.       }
  28161.       return editor.getBody();
  28162.     };
  28163.     var isListening = function (editor) {
  28164.       return !editor.hidden && !isReadOnly(editor);
  28165.     };
  28166.     var fireEvent = function (editor, eventName, e) {
  28167.       if (isListening(editor)) {
  28168.         editor.fire(eventName, e);
  28169.       } else if (isReadOnly(editor)) {
  28170.         processReadonlyEvents(editor, e);
  28171.       }
  28172.     };
  28173.     var bindEventDelegate = function (editor, eventName) {
  28174.       var delegate;
  28175.       if (!editor.delegates) {
  28176.         editor.delegates = {};
  28177.       }
  28178.       if (editor.delegates[eventName] || editor.removed) {
  28179.         return;
  28180.       }
  28181.       var eventRootElm = getEventTarget(editor, eventName);
  28182.       if (getEventRoot(editor)) {
  28183.         if (!customEventRootDelegates) {
  28184.           customEventRootDelegates = {};
  28185.           editor.editorManager.on('removeEditor', function () {
  28186.             if (!editor.editorManager.activeEditor) {
  28187.               if (customEventRootDelegates) {
  28188.                 each$j(customEventRootDelegates, function (_value, name) {
  28189.                   editor.dom.unbind(getEventTarget(editor, name));
  28190.                 });
  28191.                 customEventRootDelegates = null;
  28192.               }
  28193.             }
  28194.           });
  28195.         }
  28196.         if (customEventRootDelegates[eventName]) {
  28197.           return;
  28198.         }
  28199.         delegate = function (e) {
  28200.           var target = e.target;
  28201.           var editors = editor.editorManager.get();
  28202.           var i = editors.length;
  28203.           while (i--) {
  28204.             var body = editors[i].getBody();
  28205.             if (body === target || DOM$2.isChildOf(target, body)) {
  28206.               fireEvent(editors[i], eventName, e);
  28207.             }
  28208.           }
  28209.         };
  28210.         customEventRootDelegates[eventName] = delegate;
  28211.         DOM$2.bind(eventRootElm, eventName, delegate);
  28212.       } else {
  28213.         delegate = function (e) {
  28214.           fireEvent(editor, eventName, e);
  28215.         };
  28216.         DOM$2.bind(eventRootElm, eventName, delegate);
  28217.         editor.delegates[eventName] = delegate;
  28218.       }
  28219.     };
  28220.     var EditorObservable = __assign(__assign({}, Observable), {
  28221.       bindPendingEventDelegates: function () {
  28222.         var self = this;
  28223.         Tools.each(self._pendingNativeEvents, function (name) {
  28224.           bindEventDelegate(self, name);
  28225.         });
  28226.       },
  28227.       toggleNativeEvent: function (name, state) {
  28228.         var self = this;
  28229.         if (name === 'focus' || name === 'blur') {
  28230.           return;
  28231.         }
  28232.         if (self.removed) {
  28233.           return;
  28234.         }
  28235.         if (state) {
  28236.           if (self.initialized) {
  28237.             bindEventDelegate(self, name);
  28238.           } else {
  28239.             if (!self._pendingNativeEvents) {
  28240.               self._pendingNativeEvents = [name];
  28241.             } else {
  28242.               self._pendingNativeEvents.push(name);
  28243.             }
  28244.           }
  28245.         } else if (self.initialized) {
  28246.           self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  28247.           delete self.delegates[name];
  28248.         }
  28249.       },
  28250.       unbindAllNativeEvents: function () {
  28251.         var self = this;
  28252.         var body = self.getBody();
  28253.         var dom = self.dom;
  28254.         if (self.delegates) {
  28255.           each$j(self.delegates, function (value, name) {
  28256.             self.dom.unbind(getEventTarget(self, name), name, value);
  28257.           });
  28258.           delete self.delegates;
  28259.         }
  28260.         if (!self.inline && body && dom) {
  28261.           body.onload = null;
  28262.           dom.unbind(self.getWin());
  28263.           dom.unbind(self.getDoc());
  28264.         }
  28265.         if (dom) {
  28266.           dom.unbind(body);
  28267.           dom.unbind(self.getContainer());
  28268.         }
  28269.       }
  28270.     });
  28271.  
  28272.     var defaultModes = [
  28273.       'design',
  28274.       'readonly'
  28275.     ];
  28276.     var switchToMode = function (editor, activeMode, availableModes, mode) {
  28277.       var oldMode = availableModes[activeMode.get()];
  28278.       var newMode = availableModes[mode];
  28279.       try {
  28280.         newMode.activate();
  28281.       } catch (e) {
  28282.         console.error('problem while activating editor mode ' + mode + ':', e);
  28283.         return;
  28284.       }
  28285.       oldMode.deactivate();
  28286.       if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  28287.         toggleReadOnly(editor, newMode.editorReadOnly);
  28288.       }
  28289.       activeMode.set(mode);
  28290.       fireSwitchMode(editor, mode);
  28291.     };
  28292.     var setMode = function (editor, availableModes, activeMode, mode) {
  28293.       if (mode === activeMode.get()) {
  28294.         return;
  28295.       } else if (!has$2(availableModes, mode)) {
  28296.         throw new Error('Editor mode \'' + mode + '\' is invalid');
  28297.       }
  28298.       if (editor.initialized) {
  28299.         switchToMode(editor, activeMode, availableModes, mode);
  28300.       } else {
  28301.         editor.on('init', function () {
  28302.           return switchToMode(editor, activeMode, availableModes, mode);
  28303.         });
  28304.       }
  28305.     };
  28306.     var registerMode = function (availableModes, mode, api) {
  28307.       var _a;
  28308.       if (contains$3(defaultModes, mode)) {
  28309.         throw new Error('Cannot override default mode ' + mode);
  28310.       }
  28311.       return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  28312.         deactivate: function () {
  28313.           try {
  28314.             api.deactivate();
  28315.           } catch (e) {
  28316.             console.error('problem while deactivating editor mode ' + mode + ':', e);
  28317.           }
  28318.         }
  28319.       }), _a));
  28320.     };
  28321.  
  28322.     var create$4 = function (editor) {
  28323.       var activeMode = Cell('design');
  28324.       var availableModes = Cell({
  28325.         design: {
  28326.           activate: noop,
  28327.           deactivate: noop,
  28328.           editorReadOnly: false
  28329.         },
  28330.         readonly: {
  28331.           activate: noop,
  28332.           deactivate: noop,
  28333.           editorReadOnly: true
  28334.         }
  28335.       });
  28336.       registerReadOnlyContentFilters(editor);
  28337.       registerReadOnlySelectionBlockers(editor);
  28338.       return {
  28339.         isReadOnly: function () {
  28340.           return isReadOnly(editor);
  28341.         },
  28342.         set: function (mode) {
  28343.           return setMode(editor, availableModes.get(), activeMode, mode);
  28344.         },
  28345.         get: function () {
  28346.           return activeMode.get();
  28347.         },
  28348.         register: function (mode, api) {
  28349.           availableModes.set(registerMode(availableModes.get(), mode, api));
  28350.         }
  28351.       };
  28352.     };
  28353.  
  28354.     var each$3 = Tools.each, explode$1 = Tools.explode;
  28355.     var keyCodeLookup = {
  28356.       f1: 112,
  28357.       f2: 113,
  28358.       f3: 114,
  28359.       f4: 115,
  28360.       f5: 116,
  28361.       f6: 117,
  28362.       f7: 118,
  28363.       f8: 119,
  28364.       f9: 120,
  28365.       f10: 121,
  28366.       f11: 122,
  28367.       f12: 123
  28368.     };
  28369.     var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28370.     var parseShortcut = function (pattern) {
  28371.       var key;
  28372.       var shortcut = {};
  28373.       each$3(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28374.         if (value in modifierNames) {
  28375.           shortcut[value] = true;
  28376.         } else {
  28377.           if (/^[0-9]{2,}$/.test(value)) {
  28378.             shortcut.keyCode = parseInt(value, 10);
  28379.           } else {
  28380.             shortcut.charCode = value.charCodeAt(0);
  28381.             shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28382.           }
  28383.         }
  28384.       });
  28385.       var id = [shortcut.keyCode];
  28386.       for (key in modifierNames) {
  28387.         if (shortcut[key]) {
  28388.           id.push(key);
  28389.         } else {
  28390.           shortcut[key] = false;
  28391.         }
  28392.       }
  28393.       shortcut.id = id.join(',');
  28394.       if (shortcut.access) {
  28395.         shortcut.alt = true;
  28396.         if (Env.mac) {
  28397.           shortcut.ctrl = true;
  28398.         } else {
  28399.           shortcut.shift = true;
  28400.         }
  28401.       }
  28402.       if (shortcut.meta) {
  28403.         if (Env.mac) {
  28404.           shortcut.meta = true;
  28405.         } else {
  28406.           shortcut.ctrl = true;
  28407.           shortcut.meta = false;
  28408.         }
  28409.       }
  28410.       return shortcut;
  28411.     };
  28412.     var Shortcuts = function () {
  28413.       function Shortcuts(editor) {
  28414.         this.shortcuts = {};
  28415.         this.pendingPatterns = [];
  28416.         this.editor = editor;
  28417.         var self = this;
  28418.         editor.on('keyup keypress keydown', function (e) {
  28419.           if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28420.             each$3(self.shortcuts, function (shortcut) {
  28421.               if (self.matchShortcut(e, shortcut)) {
  28422.                 self.pendingPatterns = shortcut.subpatterns.slice(0);
  28423.                 if (e.type === 'keydown') {
  28424.                   self.executeShortcutAction(shortcut);
  28425.                 }
  28426.                 return true;
  28427.               }
  28428.             });
  28429.             if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28430.               if (self.pendingPatterns.length === 1) {
  28431.                 if (e.type === 'keydown') {
  28432.                   self.executeShortcutAction(self.pendingPatterns[0]);
  28433.                 }
  28434.               }
  28435.               self.pendingPatterns.shift();
  28436.             }
  28437.           }
  28438.         });
  28439.       }
  28440.       Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28441.         var self = this;
  28442.         var func = self.normalizeCommandFunc(cmdFunc);
  28443.         each$3(explode$1(Tools.trim(pattern)), function (pattern) {
  28444.           var shortcut = self.createShortcut(pattern, desc, func, scope);
  28445.           self.shortcuts[shortcut.id] = shortcut;
  28446.         });
  28447.         return true;
  28448.       };
  28449.       Shortcuts.prototype.remove = function (pattern) {
  28450.         var shortcut = this.createShortcut(pattern);
  28451.         if (this.shortcuts[shortcut.id]) {
  28452.           delete this.shortcuts[shortcut.id];
  28453.           return true;
  28454.         }
  28455.         return false;
  28456.       };
  28457.       Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28458.         var self = this;
  28459.         var cmd = cmdFunc;
  28460.         if (typeof cmd === 'string') {
  28461.           return function () {
  28462.             self.editor.execCommand(cmd, false, null);
  28463.           };
  28464.         } else if (Tools.isArray(cmd)) {
  28465.           return function () {
  28466.             self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28467.           };
  28468.         } else {
  28469.           return cmd;
  28470.         }
  28471.       };
  28472.       Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28473.         var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28474.         shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28475.           func: cmdFunc,
  28476.           scope: scope || this.editor
  28477.         });
  28478.         return Tools.extend(shortcuts[0], {
  28479.           desc: this.editor.translate(desc),
  28480.           subpatterns: shortcuts.slice(1)
  28481.         });
  28482.       };
  28483.       Shortcuts.prototype.hasModifier = function (e) {
  28484.         return e.altKey || e.ctrlKey || e.metaKey;
  28485.       };
  28486.       Shortcuts.prototype.isFunctionKey = function (e) {
  28487.         return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28488.       };
  28489.       Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28490.         if (!shortcut) {
  28491.           return false;
  28492.         }
  28493.         if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28494.           return false;
  28495.         }
  28496.         if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28497.           return false;
  28498.         }
  28499.         if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28500.           e.preventDefault();
  28501.           return true;
  28502.         }
  28503.         return false;
  28504.       };
  28505.       Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28506.         return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28507.       };
  28508.       return Shortcuts;
  28509.     }();
  28510.  
  28511.     var create$3 = function () {
  28512.       var buttons = {};
  28513.       var menuItems = {};
  28514.       var popups = {};
  28515.       var icons = {};
  28516.       var contextMenus = {};
  28517.       var contextToolbars = {};
  28518.       var sidebars = {};
  28519.       var add = function (collection, type) {
  28520.         return function (name, spec) {
  28521.           return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28522.         };
  28523.       };
  28524.       var addIcon = function (name, svgData) {
  28525.         return icons[name.toLowerCase()] = svgData;
  28526.       };
  28527.       return {
  28528.         addButton: add(buttons, 'button'),
  28529.         addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28530.         addToggleButton: add(buttons, 'togglebutton'),
  28531.         addMenuButton: add(buttons, 'menubutton'),
  28532.         addSplitButton: add(buttons, 'splitbutton'),
  28533.         addMenuItem: add(menuItems, 'menuitem'),
  28534.         addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28535.         addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28536.         addAutocompleter: add(popups, 'autocompleter'),
  28537.         addContextMenu: add(contextMenus, 'contextmenu'),
  28538.         addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28539.         addContextForm: add(contextToolbars, 'contextform'),
  28540.         addSidebar: add(sidebars, 'sidebar'),
  28541.         addIcon: addIcon,
  28542.         getAll: function () {
  28543.           return {
  28544.             buttons: buttons,
  28545.             menuItems: menuItems,
  28546.             icons: icons,
  28547.             popups: popups,
  28548.             contextMenus: contextMenus,
  28549.             contextToolbars: contextToolbars,
  28550.             sidebars: sidebars
  28551.           };
  28552.         }
  28553.       };
  28554.     };
  28555.  
  28556.     var registry = function () {
  28557.       var bridge = create$3();
  28558.       return {
  28559.         addAutocompleter: bridge.addAutocompleter,
  28560.         addButton: bridge.addButton,
  28561.         addContextForm: bridge.addContextForm,
  28562.         addContextMenu: bridge.addContextMenu,
  28563.         addContextToolbar: bridge.addContextToolbar,
  28564.         addIcon: bridge.addIcon,
  28565.         addMenuButton: bridge.addMenuButton,
  28566.         addMenuItem: bridge.addMenuItem,
  28567.         addNestedMenuItem: bridge.addNestedMenuItem,
  28568.         addSidebar: bridge.addSidebar,
  28569.         addSplitButton: bridge.addSplitButton,
  28570.         addToggleButton: bridge.addToggleButton,
  28571.         addGroupToolbarButton: bridge.addGroupToolbarButton,
  28572.         addToggleMenuItem: bridge.addToggleMenuItem,
  28573.         getAll: bridge.getAll
  28574.       };
  28575.     };
  28576.  
  28577.     var DOM$1 = DOMUtils.DOM;
  28578.     var extend$3 = Tools.extend, each$2 = Tools.each;
  28579.     var resolve = Tools.resolve;
  28580.     var ie = Env.ie;
  28581.     var Editor = function () {
  28582.       function Editor(id, settings, editorManager) {
  28583.         var _this = this;
  28584.         this.plugins = {};
  28585.         this.contentCSS = [];
  28586.         this.contentStyles = [];
  28587.         this.loadedCSS = {};
  28588.         this.isNotDirty = false;
  28589.         this.editorManager = editorManager;
  28590.         this.documentBaseUrl = editorManager.documentBaseURL;
  28591.         extend$3(this, EditorObservable);
  28592.         this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28593.         if (this.settings.suffix) {
  28594.           editorManager.suffix = this.settings.suffix;
  28595.         }
  28596.         this.suffix = editorManager.suffix;
  28597.         if (this.settings.base_url) {
  28598.           editorManager._setBaseUrl(this.settings.base_url);
  28599.         }
  28600.         this.baseUri = editorManager.baseURI;
  28601.         if (this.settings.referrer_policy) {
  28602.           ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28603.           DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28604.         }
  28605.         AddOnManager.languageLoad = this.settings.language_load;
  28606.         AddOnManager.baseURL = editorManager.baseURL;
  28607.         this.id = id;
  28608.         this.setDirty(false);
  28609.         this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28610.         this.baseURI = this.baseUri;
  28611.         this.inline = !!this.settings.inline;
  28612.         this.shortcuts = new Shortcuts(this);
  28613.         this.editorCommands = new EditorCommands(this);
  28614.         if (this.settings.cache_suffix) {
  28615.           Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28616.         }
  28617.         this.ui = {
  28618.           registry: registry(),
  28619.           styleSheetLoader: undefined,
  28620.           show: noop,
  28621.           hide: noop,
  28622.           enable: noop,
  28623.           disable: noop,
  28624.           isDisabled: never
  28625.         };
  28626.         var self = this;
  28627.         var modeInstance = create$4(self);
  28628.         this.mode = modeInstance;
  28629.         this.setMode = modeInstance.set;
  28630.         editorManager.fire('SetupEditor', { editor: this });
  28631.         this.execCallback('setup', this);
  28632.         this.$ = DomQuery.overrideDefaults(function () {
  28633.           return {
  28634.             context: _this.inline ? _this.getBody() : _this.getDoc(),
  28635.             element: _this.getBody()
  28636.           };
  28637.         });
  28638.       }
  28639.       Editor.prototype.render = function () {
  28640.         render(this);
  28641.       };
  28642.       Editor.prototype.focus = function (skipFocus) {
  28643.         this.execCommand('mceFocus', false, skipFocus);
  28644.       };
  28645.       Editor.prototype.hasFocus = function () {
  28646.         return hasFocus(this);
  28647.       };
  28648.       Editor.prototype.execCallback = function (name) {
  28649.         var x = [];
  28650.         for (var _i = 1; _i < arguments.length; _i++) {
  28651.           x[_i - 1] = arguments[_i];
  28652.         }
  28653.         var self = this;
  28654.         var callback = self.settings[name], scope;
  28655.         if (!callback) {
  28656.           return;
  28657.         }
  28658.         if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28659.           callback = scope.func;
  28660.           scope = scope.scope;
  28661.         }
  28662.         if (typeof callback === 'string') {
  28663.           scope = callback.replace(/\.\w+$/, '');
  28664.           scope = scope ? resolve(scope) : 0;
  28665.           callback = resolve(callback);
  28666.           self.callbackLookup = self.callbackLookup || {};
  28667.           self.callbackLookup[name] = {
  28668.             func: callback,
  28669.             scope: scope
  28670.           };
  28671.         }
  28672.         return callback.apply(scope || self, x);
  28673.       };
  28674.       Editor.prototype.translate = function (text) {
  28675.         return I18n.translate(text);
  28676.       };
  28677.       Editor.prototype.getParam = function (name, defaultVal, type) {
  28678.         return getParam(this, name, defaultVal, type);
  28679.       };
  28680.       Editor.prototype.hasPlugin = function (name, loaded) {
  28681.         var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28682.         if (hasPlugin) {
  28683.           return loaded ? PluginManager.get(name) !== undefined : true;
  28684.         } else {
  28685.           return false;
  28686.         }
  28687.       };
  28688.       Editor.prototype.nodeChanged = function (args) {
  28689.         this._nodeChangeDispatcher.nodeChanged(args);
  28690.       };
  28691.       Editor.prototype.addCommand = function (name, callback, scope) {
  28692.         this.editorCommands.addCommand(name, callback, scope);
  28693.       };
  28694.       Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28695.         this.editorCommands.addQueryStateHandler(name, callback, scope);
  28696.       };
  28697.       Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28698.         this.editorCommands.addQueryValueHandler(name, callback, scope);
  28699.       };
  28700.       Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28701.         this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28702.       };
  28703.       Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28704.         return this.editorCommands.execCommand(cmd, ui, value, args);
  28705.       };
  28706.       Editor.prototype.queryCommandState = function (cmd) {
  28707.         return this.editorCommands.queryCommandState(cmd);
  28708.       };
  28709.       Editor.prototype.queryCommandValue = function (cmd) {
  28710.         return this.editorCommands.queryCommandValue(cmd);
  28711.       };
  28712.       Editor.prototype.queryCommandSupported = function (cmd) {
  28713.         return this.editorCommands.queryCommandSupported(cmd);
  28714.       };
  28715.       Editor.prototype.show = function () {
  28716.         var self = this;
  28717.         if (self.hidden) {
  28718.           self.hidden = false;
  28719.           if (self.inline) {
  28720.             self.getBody().contentEditable = 'true';
  28721.           } else {
  28722.             DOM$1.show(self.getContainer());
  28723.             DOM$1.hide(self.id);
  28724.           }
  28725.           self.load();
  28726.           self.fire('show');
  28727.         }
  28728.       };
  28729.       Editor.prototype.hide = function () {
  28730.         var self = this, doc = self.getDoc();
  28731.         if (!self.hidden) {
  28732.           if (ie && doc && !self.inline) {
  28733.             doc.execCommand('SelectAll');
  28734.           }
  28735.           self.save();
  28736.           if (self.inline) {
  28737.             self.getBody().contentEditable = 'false';
  28738.             if (self === self.editorManager.focusedEditor) {
  28739.               self.editorManager.focusedEditor = null;
  28740.             }
  28741.           } else {
  28742.             DOM$1.hide(self.getContainer());
  28743.             DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28744.           }
  28745.           self.hidden = true;
  28746.           self.fire('hide');
  28747.         }
  28748.       };
  28749.       Editor.prototype.isHidden = function () {
  28750.         return !!this.hidden;
  28751.       };
  28752.       Editor.prototype.setProgressState = function (state, time) {
  28753.         this.fire('ProgressState', {
  28754.           state: state,
  28755.           time: time
  28756.         });
  28757.       };
  28758.       Editor.prototype.load = function (args) {
  28759.         var self = this;
  28760.         var elm = self.getElement(), html;
  28761.         if (self.removed) {
  28762.           return '';
  28763.         }
  28764.         if (elm) {
  28765.           args = args || {};
  28766.           args.load = true;
  28767.           var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28768.           html = self.setContent(value, args);
  28769.           args.element = elm;
  28770.           if (!args.no_events) {
  28771.             self.fire('LoadContent', args);
  28772.           }
  28773.           args.element = elm = null;
  28774.           return html;
  28775.         }
  28776.       };
  28777.       Editor.prototype.save = function (args) {
  28778.         var self = this;
  28779.         var elm = self.getElement(), html, form;
  28780.         if (!elm || !self.initialized || self.removed) {
  28781.           return;
  28782.         }
  28783.         args = args || {};
  28784.         args.save = true;
  28785.         args.element = elm;
  28786.         html = args.content = self.getContent(args);
  28787.         if (!args.no_events) {
  28788.           self.fire('SaveContent', args);
  28789.         }
  28790.         if (args.format === 'raw') {
  28791.           self.fire('RawSaveContent', args);
  28792.         }
  28793.         html = args.content;
  28794.         if (!isTextareaOrInput(elm)) {
  28795.           if (args.is_removing || !self.inline) {
  28796.             elm.innerHTML = html;
  28797.           }
  28798.           if (form = DOM$1.getParent(self.id, 'form')) {
  28799.             each$2(form.elements, function (elm) {
  28800.               if (elm.name === self.id) {
  28801.                 elm.value = html;
  28802.                 return false;
  28803.               }
  28804.             });
  28805.           }
  28806.         } else {
  28807.           elm.value = html;
  28808.         }
  28809.         args.element = elm = null;
  28810.         if (args.set_dirty !== false) {
  28811.           self.setDirty(false);
  28812.         }
  28813.         return html;
  28814.       };
  28815.       Editor.prototype.setContent = function (content, args) {
  28816.         return setContent(this, content, args);
  28817.       };
  28818.       Editor.prototype.getContent = function (args) {
  28819.         return getContent(this, args);
  28820.       };
  28821.       Editor.prototype.insertContent = function (content, args) {
  28822.         if (args) {
  28823.           content = extend$3({ content: content }, args);
  28824.         }
  28825.         this.execCommand('mceInsertContent', false, content);
  28826.       };
  28827.       Editor.prototype.resetContent = function (initialContent) {
  28828.         if (initialContent === undefined) {
  28829.           setContent(this, this.startContent, { format: 'raw' });
  28830.         } else {
  28831.           setContent(this, initialContent);
  28832.         }
  28833.         this.undoManager.reset();
  28834.         this.setDirty(false);
  28835.         this.nodeChanged();
  28836.       };
  28837.       Editor.prototype.isDirty = function () {
  28838.         return !this.isNotDirty;
  28839.       };
  28840.       Editor.prototype.setDirty = function (state) {
  28841.         var oldState = !this.isNotDirty;
  28842.         this.isNotDirty = !state;
  28843.         if (state && state !== oldState) {
  28844.           this.fire('dirty');
  28845.         }
  28846.       };
  28847.       Editor.prototype.getContainer = function () {
  28848.         var self = this;
  28849.         if (!self.container) {
  28850.           self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28851.         }
  28852.         return self.container;
  28853.       };
  28854.       Editor.prototype.getContentAreaContainer = function () {
  28855.         return this.contentAreaContainer;
  28856.       };
  28857.       Editor.prototype.getElement = function () {
  28858.         if (!this.targetElm) {
  28859.           this.targetElm = DOM$1.get(this.id);
  28860.         }
  28861.         return this.targetElm;
  28862.       };
  28863.       Editor.prototype.getWin = function () {
  28864.         var self = this;
  28865.         var elm;
  28866.         if (!self.contentWindow) {
  28867.           elm = self.iframeElement;
  28868.           if (elm) {
  28869.             self.contentWindow = elm.contentWindow;
  28870.           }
  28871.         }
  28872.         return self.contentWindow;
  28873.       };
  28874.       Editor.prototype.getDoc = function () {
  28875.         var self = this;
  28876.         var win;
  28877.         if (!self.contentDocument) {
  28878.           win = self.getWin();
  28879.           if (win) {
  28880.             self.contentDocument = win.document;
  28881.           }
  28882.         }
  28883.         return self.contentDocument;
  28884.       };
  28885.       Editor.prototype.getBody = function () {
  28886.         var doc = this.getDoc();
  28887.         return this.bodyElement || (doc ? doc.body : null);
  28888.       };
  28889.       Editor.prototype.convertURL = function (url, name, elm) {
  28890.         var self = this, settings = self.settings;
  28891.         if (settings.urlconverter_callback) {
  28892.           return self.execCallback('urlconverter_callback', url, elm, true, name);
  28893.         }
  28894.         if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28895.           return url;
  28896.         }
  28897.         if (settings.relative_urls) {
  28898.           return self.documentBaseURI.toRelative(url);
  28899.         }
  28900.         url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28901.         return url;
  28902.       };
  28903.       Editor.prototype.addVisual = function (elm) {
  28904.         addVisual(this, elm);
  28905.       };
  28906.       Editor.prototype.remove = function () {
  28907.         remove(this);
  28908.       };
  28909.       Editor.prototype.destroy = function (automatic) {
  28910.         destroy(this, automatic);
  28911.       };
  28912.       Editor.prototype.uploadImages = function (callback) {
  28913.         return this.editorUpload.uploadImages(callback);
  28914.       };
  28915.       Editor.prototype._scanForImages = function () {
  28916.         return this.editorUpload.scanForImages();
  28917.       };
  28918.       Editor.prototype.addButton = function () {
  28919.         throw new Error('editor.addButton has been removed in tinymce 5x, use editor.ui.registry.addButton or editor.ui.registry.addToggleButton or editor.ui.registry.addSplitButton instead');
  28920.       };
  28921.       Editor.prototype.addSidebar = function () {
  28922.         throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28923.       };
  28924.       Editor.prototype.addMenuItem = function () {
  28925.         throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28926.       };
  28927.       Editor.prototype.addContextToolbar = function () {
  28928.         throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28929.       };
  28930.       return Editor;
  28931.     }();
  28932.  
  28933.     var DOM = DOMUtils.DOM;
  28934.     var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28935.     var instanceCounter = 0, boundGlobalEvents = false;
  28936.     var beforeUnloadDelegate;
  28937.     var legacyEditors = [];
  28938.     var editors = [];
  28939.     var isValidLegacyKey = function (id) {
  28940.       return id !== 'length';
  28941.     };
  28942.     var globalEventDelegate = function (e) {
  28943.       var type = e.type;
  28944.       each$1(EditorManager.get(), function (editor) {
  28945.         switch (type) {
  28946.         case 'scroll':
  28947.           editor.fire('ScrollWindow', e);
  28948.           break;
  28949.         case 'resize':
  28950.           editor.fire('ResizeWindow', e);
  28951.           break;
  28952.         }
  28953.       });
  28954.     };
  28955.     var toggleGlobalEvents = function (state) {
  28956.       if (state !== boundGlobalEvents) {
  28957.         if (state) {
  28958.           DomQuery(window).on('resize scroll', globalEventDelegate);
  28959.         } else {
  28960.           DomQuery(window).off('resize scroll', globalEventDelegate);
  28961.         }
  28962.         boundGlobalEvents = state;
  28963.       }
  28964.     };
  28965.     var removeEditorFromList = function (targetEditor) {
  28966.       var oldEditors = editors;
  28967.       delete legacyEditors[targetEditor.id];
  28968.       for (var i = 0; i < legacyEditors.length; i++) {
  28969.         if (legacyEditors[i] === targetEditor) {
  28970.           legacyEditors.splice(i, 1);
  28971.           break;
  28972.         }
  28973.       }
  28974.       editors = filter$4(editors, function (editor) {
  28975.         return targetEditor !== editor;
  28976.       });
  28977.       if (EditorManager.activeEditor === targetEditor) {
  28978.         EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  28979.       }
  28980.       if (EditorManager.focusedEditor === targetEditor) {
  28981.         EditorManager.focusedEditor = null;
  28982.       }
  28983.       return oldEditors.length !== editors.length;
  28984.     };
  28985.     var purgeDestroyedEditor = function (editor) {
  28986.       if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  28987.         removeEditorFromList(editor);
  28988.         editor.unbindAllNativeEvents();
  28989.         editor.destroy(true);
  28990.         editor.removed = true;
  28991.         editor = null;
  28992.       }
  28993.       return editor;
  28994.     };
  28995.     var isQuirksMode = document.compatMode !== 'CSS1Compat';
  28996.     var EditorManager = __assign(__assign({}, Observable), {
  28997.       baseURI: null,
  28998.       baseURL: null,
  28999.       defaultSettings: {},
  29000.       documentBaseURL: null,
  29001.       suffix: null,
  29002.       $: DomQuery,
  29003.       majorVersion: '5',
  29004.       minorVersion: '10.2',
  29005.       releaseDate: '2021-11-17',
  29006.       editors: legacyEditors,
  29007.       i18n: I18n,
  29008.       activeEditor: null,
  29009.       focusedEditor: null,
  29010.       settings: {},
  29011.       setup: function () {
  29012.         var self = this;
  29013.         var baseURL, documentBaseURL, suffix = '';
  29014.         documentBaseURL = URI.getDocumentBaseUrl(document.location);
  29015.         if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  29016.           documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  29017.           if (!/[\/\\]$/.test(documentBaseURL)) {
  29018.             documentBaseURL += '/';
  29019.           }
  29020.         }
  29021.         var preInit = window.tinymce || window.tinyMCEPreInit;
  29022.         if (preInit) {
  29023.           baseURL = preInit.base || preInit.baseURL;
  29024.           suffix = preInit.suffix;
  29025.         } else {
  29026.           var scripts = document.getElementsByTagName('script');
  29027.           for (var i = 0; i < scripts.length; i++) {
  29028.             var src = scripts[i].src || '';
  29029.             if (src === '') {
  29030.               continue;
  29031.             }
  29032.             var srcScript = src.substring(src.lastIndexOf('/'));
  29033.             if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  29034.               if (srcScript.indexOf('.min') !== -1) {
  29035.                 suffix = '.min';
  29036.               }
  29037.               baseURL = src.substring(0, src.lastIndexOf('/'));
  29038.               break;
  29039.             }
  29040.           }
  29041.           if (!baseURL && document.currentScript) {
  29042.             var src = document.currentScript.src;
  29043.             if (src.indexOf('.min') !== -1) {
  29044.               suffix = '.min';
  29045.             }
  29046.             baseURL = src.substring(0, src.lastIndexOf('/'));
  29047.           }
  29048.         }
  29049.         self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  29050.         self.documentBaseURL = documentBaseURL;
  29051.         self.baseURI = new URI(self.baseURL);
  29052.         self.suffix = suffix;
  29053.         setup$l(self);
  29054.       },
  29055.       overrideDefaults: function (defaultSettings) {
  29056.         var baseUrl = defaultSettings.base_url;
  29057.         if (baseUrl) {
  29058.           this._setBaseUrl(baseUrl);
  29059.         }
  29060.         var suffix = defaultSettings.suffix;
  29061.         if (defaultSettings.suffix) {
  29062.           this.suffix = suffix;
  29063.         }
  29064.         this.defaultSettings = defaultSettings;
  29065.         var pluginBaseUrls = defaultSettings.plugin_base_urls;
  29066.         if (pluginBaseUrls !== undefined) {
  29067.           each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  29068.             AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  29069.           });
  29070.         }
  29071.       },
  29072.       init: function (settings) {
  29073.         var self = this;
  29074.         var result;
  29075.         var invalidInlineTargets = Tools.makeMap('area base basefont br col frame hr img input isindex link meta param embed source wbr track ' + 'colgroup option table tbody tfoot thead tr th td script noscript style textarea video audio iframe object menu', ' ');
  29076.         var isInvalidInlineTarget = function (settings, elm) {
  29077.           return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  29078.         };
  29079.         var createId = function (elm) {
  29080.           var id = elm.id;
  29081.           if (!id) {
  29082.             id = get$9(elm, 'name').filter(function (name) {
  29083.               return !DOM.get(name);
  29084.             }).getOrThunk(DOM.uniqueId);
  29085.             elm.setAttribute('id', id);
  29086.           }
  29087.           return id;
  29088.         };
  29089.         var execCallback = function (name) {
  29090.           var callback = settings[name];
  29091.           if (!callback) {
  29092.             return;
  29093.           }
  29094.           return callback.apply(self, []);
  29095.         };
  29096.         var hasClass = function (elm, className) {
  29097.           return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  29098.         };
  29099.         var findTargets = function (settings) {
  29100.           var targets = [];
  29101.           if (Env.browser.isIE() && Env.browser.version.major < 11) {
  29102.             initError('TinyMCE does not support the browser you are using. For a list of supported' + ' browsers please see: https://www.tinymce.com/docs/get-started/system-requirements/');
  29103.             return [];
  29104.           } else if (isQuirksMode) {
  29105.             initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  29106.             return [];
  29107.           }
  29108.           if (settings.types) {
  29109.             each$1(settings.types, function (type) {
  29110.               targets = targets.concat(DOM.select(type.selector));
  29111.             });
  29112.             return targets;
  29113.           } else if (settings.selector) {
  29114.             return DOM.select(settings.selector);
  29115.           } else if (settings.target) {
  29116.             return [settings.target];
  29117.           }
  29118.           switch (settings.mode) {
  29119.           case 'exact':
  29120.             var l = settings.elements || '';
  29121.             if (l.length > 0) {
  29122.               each$1(explode(l), function (id) {
  29123.                 var elm = DOM.get(id);
  29124.                 if (elm) {
  29125.                   targets.push(elm);
  29126.                 } else {
  29127.                   each$1(document.forms, function (f) {
  29128.                     each$1(f.elements, function (e) {
  29129.                       if (e.name === id) {
  29130.                         id = 'mce_editor_' + instanceCounter++;
  29131.                         DOM.setAttrib(e, 'id', id);
  29132.                         targets.push(e);
  29133.                       }
  29134.                     });
  29135.                   });
  29136.                 }
  29137.               });
  29138.             }
  29139.             break;
  29140.           case 'textareas':
  29141.           case 'specific_textareas':
  29142.             each$1(DOM.select('textarea'), function (elm) {
  29143.               if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  29144.                 return;
  29145.               }
  29146.               if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  29147.                 targets.push(elm);
  29148.               }
  29149.             });
  29150.             break;
  29151.           }
  29152.           return targets;
  29153.         };
  29154.         var provideResults = function (editors) {
  29155.           result = editors;
  29156.         };
  29157.         var initEditors = function () {
  29158.           var initCount = 0;
  29159.           var editors = [];
  29160.           var targets;
  29161.           var createEditor = function (id, settings, targetElm) {
  29162.             var editor = new Editor(id, settings, self);
  29163.             editors.push(editor);
  29164.             editor.on('init', function () {
  29165.               if (++initCount === targets.length) {
  29166.                 provideResults(editors);
  29167.               }
  29168.             });
  29169.             editor.targetElm = editor.targetElm || targetElm;
  29170.             editor.render();
  29171.           };
  29172.           DOM.unbind(window, 'ready', initEditors);
  29173.           execCallback('onpageload');
  29174.           targets = DomQuery.unique(findTargets(settings));
  29175.           if (settings.types) {
  29176.             each$1(settings.types, function (type) {
  29177.               Tools.each(targets, function (elm) {
  29178.                 if (DOM.is(elm, type.selector)) {
  29179.                   createEditor(createId(elm), extend$2({}, settings, type), elm);
  29180.                   return false;
  29181.                 }
  29182.                 return true;
  29183.               });
  29184.             });
  29185.             return;
  29186.           }
  29187.           Tools.each(targets, function (elm) {
  29188.             purgeDestroyedEditor(self.get(elm.id));
  29189.           });
  29190.           targets = Tools.grep(targets, function (elm) {
  29191.             return !self.get(elm.id);
  29192.           });
  29193.           if (targets.length === 0) {
  29194.             provideResults([]);
  29195.           } else {
  29196.             each$1(targets, function (elm) {
  29197.               if (isInvalidInlineTarget(settings, elm)) {
  29198.                 initError('Could not initialize inline editor on invalid inline target element', elm);
  29199.               } else {
  29200.                 createEditor(createId(elm), settings, elm);
  29201.               }
  29202.             });
  29203.           }
  29204.         };
  29205.         self.settings = settings;
  29206.         DOM.bind(window, 'ready', initEditors);
  29207.         return new promiseObj(function (resolve) {
  29208.           if (result) {
  29209.             resolve(result);
  29210.           } else {
  29211.             provideResults = function (editors) {
  29212.               resolve(editors);
  29213.             };
  29214.           }
  29215.         });
  29216.       },
  29217.       get: function (id) {
  29218.         if (arguments.length === 0) {
  29219.           return editors.slice(0);
  29220.         } else if (isString$1(id)) {
  29221.           return find$3(editors, function (editor) {
  29222.             return editor.id === id;
  29223.           }).getOr(null);
  29224.         } else if (isNumber(id)) {
  29225.           return editors[id] ? editors[id] : null;
  29226.         } else {
  29227.           return null;
  29228.         }
  29229.       },
  29230.       add: function (editor) {
  29231.         var self = this;
  29232.         var existingEditor = legacyEditors[editor.id];
  29233.         if (existingEditor === editor) {
  29234.           return editor;
  29235.         }
  29236.         if (self.get(editor.id) === null) {
  29237.           if (isValidLegacyKey(editor.id)) {
  29238.             legacyEditors[editor.id] = editor;
  29239.           }
  29240.           legacyEditors.push(editor);
  29241.           editors.push(editor);
  29242.         }
  29243.         toggleGlobalEvents(true);
  29244.         self.activeEditor = editor;
  29245.         self.fire('AddEditor', { editor: editor });
  29246.         if (!beforeUnloadDelegate) {
  29247.           beforeUnloadDelegate = function (e) {
  29248.             var event = self.fire('BeforeUnload');
  29249.             if (event.returnValue) {
  29250.               e.preventDefault();
  29251.               e.returnValue = event.returnValue;
  29252.               return event.returnValue;
  29253.             }
  29254.           };
  29255.           window.addEventListener('beforeunload', beforeUnloadDelegate);
  29256.         }
  29257.         return editor;
  29258.       },
  29259.       createEditor: function (id, settings) {
  29260.         return this.add(new Editor(id, settings, this));
  29261.       },
  29262.       remove: function (selector) {
  29263.         var self = this;
  29264.         var i, editor;
  29265.         if (!selector) {
  29266.           for (i = editors.length - 1; i >= 0; i--) {
  29267.             self.remove(editors[i]);
  29268.           }
  29269.           return;
  29270.         }
  29271.         if (isString$1(selector)) {
  29272.           each$1(DOM.select(selector), function (elm) {
  29273.             editor = self.get(elm.id);
  29274.             if (editor) {
  29275.               self.remove(editor);
  29276.             }
  29277.           });
  29278.           return;
  29279.         }
  29280.         editor = selector;
  29281.         if (isNull(self.get(editor.id))) {
  29282.           return null;
  29283.         }
  29284.         if (removeEditorFromList(editor)) {
  29285.           self.fire('RemoveEditor', { editor: editor });
  29286.         }
  29287.         if (editors.length === 0) {
  29288.           window.removeEventListener('beforeunload', beforeUnloadDelegate);
  29289.         }
  29290.         editor.remove();
  29291.         toggleGlobalEvents(editors.length > 0);
  29292.         return editor;
  29293.       },
  29294.       execCommand: function (cmd, ui, value) {
  29295.         var self = this, editor = self.get(value);
  29296.         switch (cmd) {
  29297.         case 'mceAddEditor':
  29298.           if (!self.get(value)) {
  29299.             new Editor(value, self.settings, self).render();
  29300.           }
  29301.           return true;
  29302.         case 'mceRemoveEditor':
  29303.           if (editor) {
  29304.             editor.remove();
  29305.           }
  29306.           return true;
  29307.         case 'mceToggleEditor':
  29308.           if (!editor) {
  29309.             self.execCommand('mceAddEditor', false, value);
  29310.             return true;
  29311.           }
  29312.           if (editor.isHidden()) {
  29313.             editor.show();
  29314.           } else {
  29315.             editor.hide();
  29316.           }
  29317.           return true;
  29318.         }
  29319.         if (self.activeEditor) {
  29320.           return self.activeEditor.execCommand(cmd, ui, value);
  29321.         }
  29322.         return false;
  29323.       },
  29324.       triggerSave: function () {
  29325.         each$1(editors, function (editor) {
  29326.           editor.save();
  29327.         });
  29328.       },
  29329.       addI18n: function (code, items) {
  29330.         I18n.add(code, items);
  29331.       },
  29332.       translate: function (text) {
  29333.         return I18n.translate(text);
  29334.       },
  29335.       setActive: function (editor) {
  29336.         var activeEditor = this.activeEditor;
  29337.         if (this.activeEditor !== editor) {
  29338.           if (activeEditor) {
  29339.             activeEditor.fire('deactivate', { relatedTarget: editor });
  29340.           }
  29341.           editor.fire('activate', { relatedTarget: activeEditor });
  29342.         }
  29343.         this.activeEditor = editor;
  29344.       },
  29345.       _setBaseUrl: function (baseUrl) {
  29346.         this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29347.         this.baseURI = new URI(this.baseURL);
  29348.       }
  29349.     });
  29350.     EditorManager.setup();
  29351.  
  29352.     var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29353.     var relativePosition = function (rect, targetRect, rel) {
  29354.       var x = targetRect.x;
  29355.       var y = targetRect.y;
  29356.       var w = rect.w;
  29357.       var h = rect.h;
  29358.       var targetW = targetRect.w;
  29359.       var targetH = targetRect.h;
  29360.       var relChars = (rel || '').split('');
  29361.       if (relChars[0] === 'b') {
  29362.         y += targetH;
  29363.       }
  29364.       if (relChars[1] === 'r') {
  29365.         x += targetW;
  29366.       }
  29367.       if (relChars[0] === 'c') {
  29368.         y += round$1(targetH / 2);
  29369.       }
  29370.       if (relChars[1] === 'c') {
  29371.         x += round$1(targetW / 2);
  29372.       }
  29373.       if (relChars[3] === 'b') {
  29374.         y -= h;
  29375.       }
  29376.       if (relChars[4] === 'r') {
  29377.         x -= w;
  29378.       }
  29379.       if (relChars[3] === 'c') {
  29380.         y -= round$1(h / 2);
  29381.       }
  29382.       if (relChars[4] === 'c') {
  29383.         x -= round$1(w / 2);
  29384.       }
  29385.       return create$2(x, y, w, h);
  29386.     };
  29387.     var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29388.       var pos, i;
  29389.       for (i = 0; i < rels.length; i++) {
  29390.         pos = relativePosition(rect, targetRect, rels[i]);
  29391.         if (pos.x >= constrainRect.x && pos.x + pos.w <= constrainRect.w + constrainRect.x && pos.y >= constrainRect.y && pos.y + pos.h <= constrainRect.h + constrainRect.y) {
  29392.           return rels[i];
  29393.         }
  29394.       }
  29395.       return null;
  29396.     };
  29397.     var inflate = function (rect, w, h) {
  29398.       return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29399.     };
  29400.     var intersect = function (rect, cropRect) {
  29401.       var x1 = max$1(rect.x, cropRect.x);
  29402.       var y1 = max$1(rect.y, cropRect.y);
  29403.       var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29404.       var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29405.       if (x2 - x1 < 0 || y2 - y1 < 0) {
  29406.         return null;
  29407.       }
  29408.       return create$2(x1, y1, x2 - x1, y2 - y1);
  29409.     };
  29410.     var clamp = function (rect, clampRect, fixedSize) {
  29411.       var x1 = rect.x;
  29412.       var y1 = rect.y;
  29413.       var x2 = rect.x + rect.w;
  29414.       var y2 = rect.y + rect.h;
  29415.       var cx2 = clampRect.x + clampRect.w;
  29416.       var cy2 = clampRect.y + clampRect.h;
  29417.       var underflowX1 = max$1(0, clampRect.x - x1);
  29418.       var underflowY1 = max$1(0, clampRect.y - y1);
  29419.       var overflowX2 = max$1(0, x2 - cx2);
  29420.       var overflowY2 = max$1(0, y2 - cy2);
  29421.       x1 += underflowX1;
  29422.       y1 += underflowY1;
  29423.       if (fixedSize) {
  29424.         x2 += underflowX1;
  29425.         y2 += underflowY1;
  29426.         x1 -= overflowX2;
  29427.         y1 -= overflowY2;
  29428.       }
  29429.       x2 -= overflowX2;
  29430.       y2 -= overflowY2;
  29431.       return create$2(x1, y1, x2 - x1, y2 - y1);
  29432.     };
  29433.     var create$2 = function (x, y, w, h) {
  29434.       return {
  29435.         x: x,
  29436.         y: y,
  29437.         w: w,
  29438.         h: h
  29439.       };
  29440.     };
  29441.     var fromClientRect = function (clientRect) {
  29442.       return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29443.     };
  29444.     var Rect = {
  29445.       inflate: inflate,
  29446.       relativePosition: relativePosition,
  29447.       findBestRelativePosition: findBestRelativePosition,
  29448.       intersect: intersect,
  29449.       clamp: clamp,
  29450.       create: create$2,
  29451.       fromClientRect: fromClientRect
  29452.     };
  29453.  
  29454.     var awaiter = function (resolveCb, rejectCb, timeout) {
  29455.       if (timeout === void 0) {
  29456.         timeout = 1000;
  29457.       }
  29458.       var done = false;
  29459.       var timer = null;
  29460.       var complete = function (completer) {
  29461.         return function () {
  29462.           var args = [];
  29463.           for (var _i = 0; _i < arguments.length; _i++) {
  29464.             args[_i] = arguments[_i];
  29465.           }
  29466.           if (!done) {
  29467.             done = true;
  29468.             if (timer !== null) {
  29469.               clearTimeout(timer);
  29470.               timer = null;
  29471.             }
  29472.             completer.apply(null, args);
  29473.           }
  29474.         };
  29475.       };
  29476.       var resolve = complete(resolveCb);
  29477.       var reject = complete(rejectCb);
  29478.       var start = function () {
  29479.         var args = [];
  29480.         for (var _i = 0; _i < arguments.length; _i++) {
  29481.           args[_i] = arguments[_i];
  29482.         }
  29483.         if (!done && timer === null) {
  29484.           timer = setTimeout(function () {
  29485.             return reject.apply(null, args);
  29486.           }, timeout);
  29487.         }
  29488.       };
  29489.       return {
  29490.         start: start,
  29491.         resolve: resolve,
  29492.         reject: reject
  29493.       };
  29494.     };
  29495.     var create$1 = function () {
  29496.       var tasks = {};
  29497.       var resultFns = {};
  29498.       var load = function (id, url) {
  29499.         var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29500.         var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29501.         if (tasks[id] !== undefined) {
  29502.           return tasks[id];
  29503.         } else {
  29504.           var task = new promiseObj(function (resolve, reject) {
  29505.             var waiter = awaiter(resolve, reject);
  29506.             resultFns[id] = waiter.resolve;
  29507.             ScriptLoader.ScriptLoader.loadScript(url, function () {
  29508.               return waiter.start(runErrMsg);
  29509.             }, function () {
  29510.               return waiter.reject(loadErrMsg);
  29511.             });
  29512.           });
  29513.           tasks[id] = task;
  29514.           return task;
  29515.         }
  29516.       };
  29517.       var add = function (id, data) {
  29518.         if (resultFns[id] !== undefined) {
  29519.           resultFns[id](data);
  29520.           delete resultFns[id];
  29521.         }
  29522.         tasks[id] = promiseObj.resolve(data);
  29523.       };
  29524.       return {
  29525.         load: load,
  29526.         add: add
  29527.       };
  29528.     };
  29529.     var Resource = create$1();
  29530.  
  29531.     var each = Tools.each, extend$1 = Tools.extend;
  29532.     var extendClass, initializing;
  29533.     var Class = function () {
  29534.     };
  29535.     Class.extend = extendClass = function (props) {
  29536.       var self = this;
  29537.       var _super = self.prototype;
  29538.       var Class = function () {
  29539.         var i, mixins, mixin;
  29540.         var self = this;
  29541.         if (!initializing) {
  29542.           if (self.init) {
  29543.             self.init.apply(self, arguments);
  29544.           }
  29545.           mixins = self.Mixins;
  29546.           if (mixins) {
  29547.             i = mixins.length;
  29548.             while (i--) {
  29549.               mixin = mixins[i];
  29550.               if (mixin.init) {
  29551.                 mixin.init.apply(self, arguments);
  29552.               }
  29553.             }
  29554.           }
  29555.         }
  29556.       };
  29557.       var dummy = function () {
  29558.         return this;
  29559.       };
  29560.       var createMethod = function (name, fn) {
  29561.         return function () {
  29562.           var self = this;
  29563.           var tmp = self._super;
  29564.           self._super = _super[name];
  29565.           var ret = fn.apply(self, arguments);
  29566.           self._super = tmp;
  29567.           return ret;
  29568.         };
  29569.       };
  29570.       initializing = true;
  29571.       var prototype = new self();
  29572.       initializing = false;
  29573.       if (props.Mixins) {
  29574.         each(props.Mixins, function (mixin) {
  29575.           for (var name_1 in mixin) {
  29576.             if (name_1 !== 'init') {
  29577.               props[name_1] = mixin[name_1];
  29578.             }
  29579.           }
  29580.         });
  29581.         if (_super.Mixins) {
  29582.           props.Mixins = _super.Mixins.concat(props.Mixins);
  29583.         }
  29584.       }
  29585.       if (props.Methods) {
  29586.         each(props.Methods.split(','), function (name) {
  29587.           props[name] = dummy;
  29588.         });
  29589.       }
  29590.       if (props.Properties) {
  29591.         each(props.Properties.split(','), function (name) {
  29592.           var fieldName = '_' + name;
  29593.           props[name] = function (value) {
  29594.             var self = this;
  29595.             if (value !== undefined) {
  29596.               self[fieldName] = value;
  29597.               return self;
  29598.             }
  29599.             return self[fieldName];
  29600.           };
  29601.         });
  29602.       }
  29603.       if (props.Statics) {
  29604.         each(props.Statics, function (func, name) {
  29605.           Class[name] = func;
  29606.         });
  29607.       }
  29608.       if (props.Defaults && _super.Defaults) {
  29609.         props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29610.       }
  29611.       each$j(props, function (member, name) {
  29612.         if (typeof member === 'function' && _super[name]) {
  29613.           prototype[name] = createMethod(name, member);
  29614.         } else {
  29615.           prototype[name] = member;
  29616.         }
  29617.       });
  29618.       Class.prototype = prototype;
  29619.       Class.constructor = Class;
  29620.       Class.extend = extendClass;
  29621.       return Class;
  29622.     };
  29623.  
  29624.     var min = Math.min, max = Math.max, round = Math.round;
  29625.     var Color = function (value) {
  29626.       var self = {};
  29627.       var r = 0, g = 0, b = 0;
  29628.       var rgb2hsv = function (r, g, b) {
  29629.         var h, s, v;
  29630.         h = 0;
  29631.         s = 0;
  29632.         v = 0;
  29633.         r = r / 255;
  29634.         g = g / 255;
  29635.         b = b / 255;
  29636.         var minRGB = min(r, min(g, b));
  29637.         var maxRGB = max(r, max(g, b));
  29638.         if (minRGB === maxRGB) {
  29639.           v = minRGB;
  29640.           return {
  29641.             h: 0,
  29642.             s: 0,
  29643.             v: v * 100
  29644.           };
  29645.         }
  29646.         var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29647.         h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29648.         h = 60 * (h - d / (maxRGB - minRGB));
  29649.         s = (maxRGB - minRGB) / maxRGB;
  29650.         v = maxRGB;
  29651.         return {
  29652.           h: round(h),
  29653.           s: round(s * 100),
  29654.           v: round(v * 100)
  29655.         };
  29656.       };
  29657.       var hsvToRgb = function (hue, saturation, brightness) {
  29658.         hue = (parseInt(hue, 10) || 0) % 360;
  29659.         saturation = parseInt(saturation, 10) / 100;
  29660.         brightness = parseInt(brightness, 10) / 100;
  29661.         saturation = max(0, min(saturation, 1));
  29662.         brightness = max(0, min(brightness, 1));
  29663.         if (saturation === 0) {
  29664.           r = g = b = round(255 * brightness);
  29665.           return;
  29666.         }
  29667.         var side = hue / 60;
  29668.         var chroma = brightness * saturation;
  29669.         var x = chroma * (1 - Math.abs(side % 2 - 1));
  29670.         var match = brightness - chroma;
  29671.         switch (Math.floor(side)) {
  29672.         case 0:
  29673.           r = chroma;
  29674.           g = x;
  29675.           b = 0;
  29676.           break;
  29677.         case 1:
  29678.           r = x;
  29679.           g = chroma;
  29680.           b = 0;
  29681.           break;
  29682.         case 2:
  29683.           r = 0;
  29684.           g = chroma;
  29685.           b = x;
  29686.           break;
  29687.         case 3:
  29688.           r = 0;
  29689.           g = x;
  29690.           b = chroma;
  29691.           break;
  29692.         case 4:
  29693.           r = x;
  29694.           g = 0;
  29695.           b = chroma;
  29696.           break;
  29697.         case 5:
  29698.           r = chroma;
  29699.           g = 0;
  29700.           b = x;
  29701.           break;
  29702.         default:
  29703.           r = g = b = 0;
  29704.         }
  29705.         r = round(255 * (r + match));
  29706.         g = round(255 * (g + match));
  29707.         b = round(255 * (b + match));
  29708.       };
  29709.       var toHex = function () {
  29710.         var hex = function (val) {
  29711.           val = parseInt(val, 10).toString(16);
  29712.           return val.length > 1 ? val : '0' + val;
  29713.         };
  29714.         return '#' + hex(r) + hex(g) + hex(b);
  29715.       };
  29716.       var toRgb = function () {
  29717.         return {
  29718.           r: r,
  29719.           g: g,
  29720.           b: b
  29721.         };
  29722.       };
  29723.       var toHsv = function () {
  29724.         return rgb2hsv(r, g, b);
  29725.       };
  29726.       var parse = function (value) {
  29727.         var matches;
  29728.         if (typeof value === 'object') {
  29729.           if ('r' in value) {
  29730.             r = value.r;
  29731.             g = value.g;
  29732.             b = value.b;
  29733.           } else if ('v' in value) {
  29734.             hsvToRgb(value.h, value.s, value.v);
  29735.           }
  29736.         } else {
  29737.           if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29738.             r = parseInt(matches[1], 10);
  29739.             g = parseInt(matches[2], 10);
  29740.             b = parseInt(matches[3], 10);
  29741.           } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29742.             r = parseInt(matches[1], 16);
  29743.             g = parseInt(matches[2], 16);
  29744.             b = parseInt(matches[3], 16);
  29745.           } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29746.             r = parseInt(matches[1] + matches[1], 16);
  29747.             g = parseInt(matches[2] + matches[2], 16);
  29748.             b = parseInt(matches[3] + matches[3], 16);
  29749.           }
  29750.         }
  29751.         r = r < 0 ? 0 : r > 255 ? 255 : r;
  29752.         g = g < 0 ? 0 : g > 255 ? 255 : g;
  29753.         b = b < 0 ? 0 : b > 255 ? 255 : b;
  29754.         return self;
  29755.       };
  29756.       if (value) {
  29757.         parse(value);
  29758.       }
  29759.       self.toRgb = toRgb;
  29760.       self.toHsv = toHsv;
  29761.       self.toHex = toHex;
  29762.       self.parse = parse;
  29763.       return self;
  29764.     };
  29765.  
  29766.     var serialize = function (obj) {
  29767.       var data = JSON.stringify(obj);
  29768.       if (!isString$1(data)) {
  29769.         return data;
  29770.       }
  29771.       return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29772.         var hexCode = match.charCodeAt(0).toString(16);
  29773.         return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29774.       });
  29775.     };
  29776.     var JSONUtils = {
  29777.       serialize: serialize,
  29778.       parse: function (text) {
  29779.         try {
  29780.           return JSON.parse(text);
  29781.         } catch (ex) {
  29782.         }
  29783.       }
  29784.     };
  29785.  
  29786.     var JSONP = {
  29787.       callbacks: {},
  29788.       count: 0,
  29789.       send: function (settings) {
  29790.         var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29791.         var id = 'tinymce_jsonp_' + count;
  29792.         self.callbacks[count] = function (json) {
  29793.           dom.remove(id);
  29794.           delete self.callbacks[count];
  29795.           settings.callback(json);
  29796.         };
  29797.         dom.add(dom.doc.body, 'script', {
  29798.           id: id,
  29799.           src: settings.url,
  29800.           type: 'text/javascript'
  29801.         });
  29802.         self.count++;
  29803.       }
  29804.     };
  29805.  
  29806.     var XHR = __assign(__assign({}, Observable), {
  29807.       send: function (settings) {
  29808.         var xhr, count = 0;
  29809.         var ready = function () {
  29810.           if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29811.             if (settings.success && count < 10000 && xhr.status === 200) {
  29812.               settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29813.             } else if (settings.error) {
  29814.               settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29815.             }
  29816.             xhr = null;
  29817.           } else {
  29818.             Delay.setTimeout(ready, 10);
  29819.           }
  29820.         };
  29821.         settings.scope = settings.scope || this;
  29822.         settings.success_scope = settings.success_scope || settings.scope;
  29823.         settings.error_scope = settings.error_scope || settings.scope;
  29824.         settings.async = settings.async !== false;
  29825.         settings.data = settings.data || '';
  29826.         XHR.fire('beforeInitialize', { settings: settings });
  29827.         xhr = new XMLHttpRequest();
  29828.         if (xhr.overrideMimeType) {
  29829.           xhr.overrideMimeType(settings.content_type);
  29830.         }
  29831.         xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29832.         if (settings.crossDomain) {
  29833.           xhr.withCredentials = true;
  29834.         }
  29835.         if (settings.content_type) {
  29836.           xhr.setRequestHeader('Content-Type', settings.content_type);
  29837.         }
  29838.         if (settings.requestheaders) {
  29839.           Tools.each(settings.requestheaders, function (header) {
  29840.             xhr.setRequestHeader(header.key, header.value);
  29841.           });
  29842.         }
  29843.         xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29844.         xhr = XHR.fire('beforeSend', {
  29845.           xhr: xhr,
  29846.           settings: settings
  29847.         }).xhr;
  29848.         xhr.send(settings.data);
  29849.         if (!settings.async) {
  29850.           return ready();
  29851.         }
  29852.         Delay.setTimeout(ready, 10);
  29853.       }
  29854.     });
  29855.  
  29856.     var extend = Tools.extend;
  29857.     var JSONRequest = function () {
  29858.       function JSONRequest(settings) {
  29859.         this.settings = extend({}, settings);
  29860.         this.count = 0;
  29861.       }
  29862.       JSONRequest.sendRPC = function (o) {
  29863.         return new JSONRequest().send(o);
  29864.       };
  29865.       JSONRequest.prototype.send = function (args) {
  29866.         var ecb = args.error, scb = args.success;
  29867.         var xhrArgs = extend(this.settings, args);
  29868.         xhrArgs.success = function (c, x) {
  29869.           c = JSONUtils.parse(c);
  29870.           if (typeof c === 'undefined') {
  29871.             c = { error: 'JSON Parse error.' };
  29872.           }
  29873.           if (c.error) {
  29874.             ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29875.           } else {
  29876.             scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29877.           }
  29878.         };
  29879.         xhrArgs.error = function (ty, x) {
  29880.           if (ecb) {
  29881.             ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29882.           }
  29883.         };
  29884.         xhrArgs.data = JSONUtils.serialize({
  29885.           id: args.id || 'c' + this.count++,
  29886.           method: args.method,
  29887.           params: args.params
  29888.         });
  29889.         xhrArgs.content_type = 'application/json';
  29890.         XHR.send(xhrArgs);
  29891.       };
  29892.       return JSONRequest;
  29893.     }();
  29894.  
  29895.     var create = function () {
  29896.       return function () {
  29897.         var data = {};
  29898.         var keys = [];
  29899.         var storage = {
  29900.           getItem: function (key) {
  29901.             var item = data[key];
  29902.             return item ? item : null;
  29903.           },
  29904.           setItem: function (key, value) {
  29905.             keys.push(key);
  29906.             data[key] = String(value);
  29907.           },
  29908.           key: function (index) {
  29909.             return keys[index];
  29910.           },
  29911.           removeItem: function (key) {
  29912.             keys = keys.filter(function (k) {
  29913.               return k === key;
  29914.             });
  29915.             delete data[key];
  29916.           },
  29917.           clear: function () {
  29918.             keys = [];
  29919.             data = {};
  29920.           },
  29921.           length: 0
  29922.         };
  29923.         Object.defineProperty(storage, 'length', {
  29924.           get: function () {
  29925.             return keys.length;
  29926.           },
  29927.           configurable: false,
  29928.           enumerable: false
  29929.         });
  29930.         return storage;
  29931.       }();
  29932.     };
  29933.  
  29934.     var localStorage;
  29935.     try {
  29936.       var test = '__storage_test__';
  29937.       localStorage = window.localStorage;
  29938.       localStorage.setItem(test, test);
  29939.       localStorage.removeItem(test);
  29940.     } catch (e) {
  29941.       localStorage = create();
  29942.     }
  29943.     var LocalStorage = localStorage;
  29944.  
  29945.     var publicApi = {
  29946.       geom: { Rect: Rect },
  29947.       util: {
  29948.         Promise: promiseObj,
  29949.         Delay: Delay,
  29950.         Tools: Tools,
  29951.         VK: VK,
  29952.         URI: URI,
  29953.         Class: Class,
  29954.         EventDispatcher: EventDispatcher,
  29955.         Observable: Observable,
  29956.         I18n: I18n,
  29957.         XHR: XHR,
  29958.         JSON: JSONUtils,
  29959.         JSONRequest: JSONRequest,
  29960.         JSONP: JSONP,
  29961.         LocalStorage: LocalStorage,
  29962.         Color: Color,
  29963.         ImageUploader: ImageUploader
  29964.       },
  29965.       dom: {
  29966.         EventUtils: EventUtils,
  29967.         Sizzle: Sizzle,
  29968.         DomQuery: DomQuery,
  29969.         TreeWalker: DomTreeWalker,
  29970.         TextSeeker: TextSeeker,
  29971.         DOMUtils: DOMUtils,
  29972.         ScriptLoader: ScriptLoader,
  29973.         RangeUtils: RangeUtils,
  29974.         Serializer: DomSerializer,
  29975.         StyleSheetLoader: StyleSheetLoader,
  29976.         ControlSelection: ControlSelection,
  29977.         BookmarkManager: BookmarkManager,
  29978.         Selection: EditorSelection,
  29979.         Event: EventUtils.Event
  29980.       },
  29981.       html: {
  29982.         Styles: Styles,
  29983.         Entities: Entities,
  29984.         Node: AstNode,
  29985.         Schema: Schema,
  29986.         SaxParser: SaxParser,
  29987.         DomParser: DomParser,
  29988.         Writer: Writer,
  29989.         Serializer: HtmlSerializer
  29990.       },
  29991.       Env: Env,
  29992.       AddOnManager: AddOnManager,
  29993.       Annotator: Annotator,
  29994.       Formatter: Formatter,
  29995.       UndoManager: UndoManager,
  29996.       EditorCommands: EditorCommands,
  29997.       WindowManager: WindowManager,
  29998.       NotificationManager: NotificationManager,
  29999.       EditorObservable: EditorObservable,
  30000.       Shortcuts: Shortcuts,
  30001.       Editor: Editor,
  30002.       FocusManager: FocusManager,
  30003.       EditorManager: EditorManager,
  30004.       DOM: DOMUtils.DOM,
  30005.       ScriptLoader: ScriptLoader.ScriptLoader,
  30006.       PluginManager: PluginManager,
  30007.       ThemeManager: ThemeManager,
  30008.       IconManager: IconManager,
  30009.       Resource: Resource,
  30010.       trim: Tools.trim,
  30011.       isArray: Tools.isArray,
  30012.       is: Tools.is,
  30013.       toArray: Tools.toArray,
  30014.       makeMap: Tools.makeMap,
  30015.       each: Tools.each,
  30016.       map: Tools.map,
  30017.       grep: Tools.grep,
  30018.       inArray: Tools.inArray,
  30019.       extend: Tools.extend,
  30020.       create: Tools.create,
  30021.       walk: Tools.walk,
  30022.       createNS: Tools.createNS,
  30023.       resolve: Tools.resolve,
  30024.       explode: Tools.explode,
  30025.       _addCacheSuffix: Tools._addCacheSuffix,
  30026.       isOpera: Env.opera,
  30027.       isWebKit: Env.webkit,
  30028.       isIE: Env.ie,
  30029.       isGecko: Env.gecko,
  30030.       isMac: Env.mac
  30031.     };
  30032.     var tinymce = Tools.extend(EditorManager, publicApi);
  30033.  
  30034.     var exportToModuleLoaders = function (tinymce) {
  30035.       if (typeof module === 'object') {
  30036.         try {
  30037.           module.exports = tinymce;
  30038.         } catch (_) {
  30039.         }
  30040.       }
  30041.     };
  30042.     var exportToWindowGlobal = function (tinymce) {
  30043.       window.tinymce = tinymce;
  30044.       window.tinyMCE = tinymce;
  30045.     };
  30046.     exportToWindowGlobal(tinymce);
  30047.     exportToModuleLoaders(tinymce);
  30048.  
  30049. }());
  30050.