Subversion Repositories oidplus

Rev

Rev 1042 | 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.8 (2023-10-19)
  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$5 = 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$4 = 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$4);
  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$4,
  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$3 = 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 createMap = function (defaultValue, extendWith) {
  3545.       var value = makeMap$2(defaultValue, ' ', makeMap$2(defaultValue.toUpperCase(), ' '));
  3546.       return extend$5(value, extendWith);
  3547.     };
  3548.     var getTextRootBlockElements = function (schema) {
  3549.       return createMap('td th li dt dd figcaption caption details summary', schema.getTextBlockElements());
  3550.     };
  3551.     var compileSchema = function (type) {
  3552.       var schema = {};
  3553.       var globalAttributes, blockContent;
  3554.       var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  3555.       var add = function (name, attributes, children) {
  3556.         var ni, attributesOrder, element;
  3557.         var arrayToMap = function (array, obj) {
  3558.           var map = {};
  3559.           var i, l;
  3560.           for (i = 0, l = array.length; i < l; i++) {
  3561.             map[array[i]] = obj || {};
  3562.           }
  3563.           return map;
  3564.         };
  3565.         children = children || [];
  3566.         attributes = attributes || '';
  3567.         if (typeof children === 'string') {
  3568.           children = split$1(children);
  3569.         }
  3570.         var names = split$1(name);
  3571.         ni = names.length;
  3572.         while (ni--) {
  3573.           attributesOrder = split$1([
  3574.             globalAttributes,
  3575.             attributes
  3576.           ].join(' '));
  3577.           element = {
  3578.             attributes: arrayToMap(attributesOrder),
  3579.             attributesOrder: attributesOrder,
  3580.             children: arrayToMap(children, dummyObj)
  3581.           };
  3582.           schema[names[ni]] = element;
  3583.         }
  3584.       };
  3585.       var addAttrs = function (name, attributes) {
  3586.         var ni, schemaItem, i, l;
  3587.         var names = split$1(name);
  3588.         ni = names.length;
  3589.         var attrs = split$1(attributes);
  3590.         while (ni--) {
  3591.           schemaItem = schema[names[ni]];
  3592.           for (i = 0, l = attrs.length; i < l; i++) {
  3593.             schemaItem.attributes[attrs[i]] = {};
  3594.             schemaItem.attributesOrder.push(attrs[i]);
  3595.           }
  3596.         }
  3597.       };
  3598.       if (mapCache[type]) {
  3599.         return mapCache[type];
  3600.       }
  3601.       globalAttributes = 'id accesskey class dir lang style tabindex title role';
  3602.       blockContent = 'address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul';
  3603.       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';
  3604.       if (type !== 'html4') {
  3605.         globalAttributes += ' contenteditable contextmenu draggable dropzone ' + 'hidden spellcheck translate';
  3606.         blockContent += ' article aside details dialog figure main header footer hgroup section nav';
  3607.         phrasingContent += ' audio canvas command datalist mark meter output picture ' + 'progress time wbr video ruby bdi keygen';
  3608.       }
  3609.       if (type !== 'html5-strict') {
  3610.         globalAttributes += ' xml:lang';
  3611.         html4PhrasingContent = 'acronym applet basefont big font strike tt';
  3612.         phrasingContent = [
  3613.           phrasingContent,
  3614.           html4PhrasingContent
  3615.         ].join(' ');
  3616.         each$h(split$1(html4PhrasingContent), function (name) {
  3617.           add(name, '', phrasingContent);
  3618.         });
  3619.         html4BlockContent = 'center dir isindex noframes';
  3620.         blockContent = [
  3621.           blockContent,
  3622.           html4BlockContent
  3623.         ].join(' ');
  3624.         flowContent = [
  3625.           blockContent,
  3626.           phrasingContent
  3627.         ].join(' ');
  3628.         each$h(split$1(html4BlockContent), function (name) {
  3629.           add(name, '', flowContent);
  3630.         });
  3631.       }
  3632.       flowContent = flowContent || [
  3633.         blockContent,
  3634.         phrasingContent
  3635.       ].join(' ');
  3636.       add('html', 'manifest', 'head body');
  3637.       add('head', '', 'base command link meta noscript script style title');
  3638.       add('title hr noscript br');
  3639.       add('base', 'href target');
  3640.       add('link', 'href rel media hreflang type sizes hreflang');
  3641.       add('meta', 'name http-equiv content charset');
  3642.       add('style', 'media type scoped');
  3643.       add('script', 'src async defer type charset');
  3644.       add('body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' + 'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' + 'onpopstate onresize onscroll onstorage onunload', flowContent);
  3645.       add('address dt dd div caption', '', flowContent);
  3646.       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);
  3647.       add('blockquote', 'cite', flowContent);
  3648.       add('ol', 'reversed start type', 'li');
  3649.       add('ul', '', 'li');
  3650.       add('li', 'value', flowContent);
  3651.       add('dl', '', 'dt dd');
  3652.       add('a', 'href target rel media hreflang type', phrasingContent);
  3653.       add('q', 'cite', phrasingContent);
  3654.       add('ins del', 'cite datetime', flowContent);
  3655.       add('img', 'src sizes srcset alt usemap ismap width height');
  3656.       add('iframe', 'src name width height', flowContent);
  3657.       add('embed', 'src type width height');
  3658.       add('object', 'data type typemustmatch name usemap form width height', [
  3659.         flowContent,
  3660.         'param'
  3661.       ].join(' '));
  3662.       add('param', 'name value');
  3663.       add('map', 'name', [
  3664.         flowContent,
  3665.         'area'
  3666.       ].join(' '));
  3667.       add('area', 'alt coords shape href target rel media hreflang type');
  3668.       add('table', 'border', 'caption colgroup thead tfoot tbody tr' + (type === 'html4' ? ' col' : ''));
  3669.       add('colgroup', 'span', 'col');
  3670.       add('col', 'span');
  3671.       add('tbody thead tfoot', '', 'tr');
  3672.       add('tr', '', 'td th');
  3673.       add('td', 'colspan rowspan headers', flowContent);
  3674.       add('th', 'colspan rowspan headers scope abbr', flowContent);
  3675.       add('form', 'accept-charset action autocomplete enctype method name novalidate target', flowContent);
  3676.       add('fieldset', 'disabled form name', [
  3677.         flowContent,
  3678.         'legend'
  3679.       ].join(' '));
  3680.       add('label', 'form for', phrasingContent);
  3681.       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');
  3682.       add('button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', type === 'html4' ? flowContent : phrasingContent);
  3683.       add('select', 'disabled form multiple name required size', 'option optgroup');
  3684.       add('optgroup', 'disabled label', 'option');
  3685.       add('option', 'disabled label selected value');
  3686.       add('textarea', 'cols dirname disabled form maxlength name readonly required rows wrap');
  3687.       add('menu', 'type label', [
  3688.         flowContent,
  3689.         'li'
  3690.       ].join(' '));
  3691.       add('noscript', '', flowContent);
  3692.       if (type !== 'html4') {
  3693.         add('wbr');
  3694.         add('ruby', '', [
  3695.           phrasingContent,
  3696.           'rt rp'
  3697.         ].join(' '));
  3698.         add('figcaption', '', flowContent);
  3699.         add('mark rt rp summary bdi', '', phrasingContent);
  3700.         add('canvas', 'width height', flowContent);
  3701.         add('video', 'src crossorigin poster preload autoplay mediagroup loop ' + 'muted controls width height buffered', [
  3702.           flowContent,
  3703.           'track source'
  3704.         ].join(' '));
  3705.         add('audio', 'src crossorigin preload autoplay mediagroup loop muted controls ' + 'buffered volume', [
  3706.           flowContent,
  3707.           'track source'
  3708.         ].join(' '));
  3709.         add('picture', '', 'img source');
  3710.         add('source', 'src srcset type media sizes');
  3711.         add('track', 'kind src srclang label default');
  3712.         add('datalist', '', [
  3713.           phrasingContent,
  3714.           'option'
  3715.         ].join(' '));
  3716.         add('article section nav aside main header footer', '', flowContent);
  3717.         add('hgroup', '', 'h1 h2 h3 h4 h5 h6');
  3718.         add('figure', '', [
  3719.           flowContent,
  3720.           'figcaption'
  3721.         ].join(' '));
  3722.         add('time', 'datetime', phrasingContent);
  3723.         add('dialog', 'open', flowContent);
  3724.         add('command', 'type label icon disabled checked radiogroup command');
  3725.         add('output', 'for form name', phrasingContent);
  3726.         add('progress', 'value max', phrasingContent);
  3727.         add('meter', 'value min max low high optimum', phrasingContent);
  3728.         add('details', 'open', [
  3729.           flowContent,
  3730.           'summary'
  3731.         ].join(' '));
  3732.         add('keygen', 'autofocus challenge disabled form keytype name');
  3733.       }
  3734.       if (type !== 'html5-strict') {
  3735.         addAttrs('script', 'language xml:space');
  3736.         addAttrs('style', 'xml:space');
  3737.         addAttrs('object', 'declare classid code codebase codetype archive standby align border hspace vspace');
  3738.         addAttrs('embed', 'align name hspace vspace');
  3739.         addAttrs('param', 'valuetype type');
  3740.         addAttrs('a', 'charset name rev shape coords');
  3741.         addAttrs('br', 'clear');
  3742.         addAttrs('applet', 'codebase archive code object alt name width height align hspace vspace');
  3743.         addAttrs('img', 'name longdesc align border hspace vspace');
  3744.         addAttrs('iframe', 'longdesc frameborder marginwidth marginheight scrolling align');
  3745.         addAttrs('font basefont', 'size color face');
  3746.         addAttrs('input', 'usemap align');
  3747.         addAttrs('select');
  3748.         addAttrs('textarea');
  3749.         addAttrs('h1 h2 h3 h4 h5 h6 div p legend caption', 'align');
  3750.         addAttrs('ul', 'type compact');
  3751.         addAttrs('li', 'type');
  3752.         addAttrs('ol dl menu dir', 'compact');
  3753.         addAttrs('pre', 'width xml:space');
  3754.         addAttrs('hr', 'align noshade size width');
  3755.         addAttrs('isindex', 'prompt');
  3756.         addAttrs('table', 'summary width frame rules cellspacing cellpadding align bgcolor');
  3757.         addAttrs('col', 'width align char charoff valign');
  3758.         addAttrs('colgroup', 'width align char charoff valign');
  3759.         addAttrs('thead', 'align char charoff valign');
  3760.         addAttrs('tr', 'align char charoff valign bgcolor');
  3761.         addAttrs('th', 'axis align char charoff valign nowrap bgcolor width height');
  3762.         addAttrs('form', 'accept');
  3763.         addAttrs('td', 'abbr axis scope align char charoff valign nowrap bgcolor width height');
  3764.         addAttrs('tfoot', 'align char charoff valign');
  3765.         addAttrs('tbody', 'align char charoff valign');
  3766.         addAttrs('area', 'nohref');
  3767.         addAttrs('body', 'background bgcolor text link vlink alink');
  3768.       }
  3769.       if (type !== 'html4') {
  3770.         addAttrs('input button select textarea', 'autofocus');
  3771.         addAttrs('input textarea', 'placeholder');
  3772.         addAttrs('a', 'download');
  3773.         addAttrs('link script img', 'crossorigin');
  3774.         addAttrs('img', 'loading');
  3775.         addAttrs('iframe', 'sandbox seamless allowfullscreen loading');
  3776.       }
  3777.       each$h(split$1('a form meter progress dfn'), function (name) {
  3778.         if (schema[name]) {
  3779.           delete schema[name].children[name];
  3780.         }
  3781.       });
  3782.       delete schema.caption.children.table;
  3783.       delete schema.script;
  3784.       mapCache[type] = schema;
  3785.       return schema;
  3786.     };
  3787.     var compileElementMap = function (value, mode) {
  3788.       var styles;
  3789.       if (value) {
  3790.         styles = {};
  3791.         if (typeof value === 'string') {
  3792.           value = { '*': value };
  3793.         }
  3794.         each$h(value, function (value, key) {
  3795.           styles[key] = styles[key.toUpperCase()] = mode === 'map' ? makeMap$2(value, /[, ]/) : explode$3(value, /[, ]/);
  3796.         });
  3797.       }
  3798.       return styles;
  3799.     };
  3800.     var Schema = function (settings) {
  3801.       var elements = {};
  3802.       var children = {};
  3803.       var patternElements = [];
  3804.       var customElementsMap = {}, specialElements = {};
  3805.       var createLookupTable = function (option, defaultValue, extendWith) {
  3806.         var value = settings[option];
  3807.         if (!value) {
  3808.           value = mapCache[option];
  3809.           if (!value) {
  3810.             value = createMap(defaultValue, extendWith);
  3811.             mapCache[option] = value;
  3812.           }
  3813.         } else {
  3814.           value = makeMap$2(value, /[, ]/, makeMap$2(value.toUpperCase(), /[, ]/));
  3815.         }
  3816.         return value;
  3817.       };
  3818.       settings = settings || {};
  3819.       var schemaItems = compileSchema(settings.schema);
  3820.       if (settings.verify_html === false) {
  3821.         settings.valid_elements = '*[*]';
  3822.       }
  3823.       var validStyles = compileElementMap(settings.valid_styles);
  3824.       var invalidStyles = compileElementMap(settings.invalid_styles, 'map');
  3825.       var validClasses = compileElementMap(settings.valid_classes, 'map');
  3826.       var whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object code');
  3827.       var selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  3828.       var shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' + 'meta param embed source wbr track');
  3829.       var boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' + 'noshade nowrap readonly selected autoplay loop controls');
  3830.       var nonEmptyOrMoveCaretBeforeOnEnter = 'td th iframe video audio object script code';
  3831.       var nonEmptyElementsMap = createLookupTable('non_empty_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' pre', shortEndedElementsMap);
  3832.       var moveCaretBeforeOnEnterElementsMap = createLookupTable('move_caret_before_on_enter_elements', nonEmptyOrMoveCaretBeforeOnEnter + ' table', shortEndedElementsMap);
  3833.       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');
  3834.       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);
  3835.       var textInlineElementsMap = createLookupTable('text_inline_elements', 'span strong b em i font s strike u var cite ' + 'dfn code mark q sup sub samp');
  3836.       each$h((settings.special || 'script noscript iframe noframes noembed title style textarea xmp').split(' '), function (name) {
  3837.         specialElements[name] = new RegExp('</' + name + '[^>]*>', 'gi');
  3838.       });
  3839.       var patternToRegExp = function (str) {
  3840.         return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  3841.       };
  3842.       var addValidElements = function (validElements) {
  3843.         var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value;
  3844.         var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
  3845.         if (validElements) {
  3846.           var validElementsArr = split$1(validElements, ',');
  3847.           if (elements['@']) {
  3848.             globalAttributes = elements['@'].attributes;
  3849.             globalAttributesOrder = elements['@'].attributesOrder;
  3850.           }
  3851.           for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
  3852.             matches = elementRuleRegExp.exec(validElementsArr[ei]);
  3853.             if (matches) {
  3854.               prefix = matches[1];
  3855.               elementName = matches[2];
  3856.               outputName = matches[3];
  3857.               attrData = matches[5];
  3858.               attributes = {};
  3859.               attributesOrder = [];
  3860.               element = {
  3861.                 attributes: attributes,
  3862.                 attributesOrder: attributesOrder
  3863.               };
  3864.               if (prefix === '#') {
  3865.                 element.paddEmpty = true;
  3866.               }
  3867.               if (prefix === '-') {
  3868.                 element.removeEmpty = true;
  3869.               }
  3870.               if (matches[4] === '!') {
  3871.                 element.removeEmptyAttrs = true;
  3872.               }
  3873.               if (globalAttributes) {
  3874.                 each$j(globalAttributes, function (value, key) {
  3875.                   attributes[key] = value;
  3876.                 });
  3877.                 attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  3878.               }
  3879.               if (attrData) {
  3880.                 attrData = split$1(attrData, '|');
  3881.                 for (ai = 0, al = attrData.length; ai < al; ai++) {
  3882.                   matches = attrRuleRegExp.exec(attrData[ai]);
  3883.                   if (matches) {
  3884.                     attr = {};
  3885.                     attrType = matches[1];
  3886.                     attrName = matches[2].replace(/[\\:]:/g, ':');
  3887.                     prefix = matches[3];
  3888.                     value = matches[4];
  3889.                     if (attrType === '!') {
  3890.                       element.attributesRequired = element.attributesRequired || [];
  3891.                       element.attributesRequired.push(attrName);
  3892.                       attr.required = true;
  3893.                     }
  3894.                     if (attrType === '-') {
  3895.                       delete attributes[attrName];
  3896.                       attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
  3897.                       continue;
  3898.                     }
  3899.                     if (prefix) {
  3900.                       if (prefix === '=') {
  3901.                         element.attributesDefault = element.attributesDefault || [];
  3902.                         element.attributesDefault.push({
  3903.                           name: attrName,
  3904.                           value: value
  3905.                         });
  3906.                         attr.defaultValue = value;
  3907.                       }
  3908.                       if (prefix === ':') {
  3909.                         element.attributesForced = element.attributesForced || [];
  3910.                         element.attributesForced.push({
  3911.                           name: attrName,
  3912.                           value: value
  3913.                         });
  3914.                         attr.forcedValue = value;
  3915.                       }
  3916.                       if (prefix === '<') {
  3917.                         attr.validValues = makeMap$2(value, '?');
  3918.                       }
  3919.                     }
  3920.                     if (hasPatternsRegExp.test(attrName)) {
  3921.                       element.attributePatterns = element.attributePatterns || [];
  3922.                       attr.pattern = patternToRegExp(attrName);
  3923.                       element.attributePatterns.push(attr);
  3924.                     } else {
  3925.                       if (!attributes[attrName]) {
  3926.                         attributesOrder.push(attrName);
  3927.                       }
  3928.                       attributes[attrName] = attr;
  3929.                     }
  3930.                   }
  3931.                 }
  3932.               }
  3933.               if (!globalAttributes && elementName === '@') {
  3934.                 globalAttributes = attributes;
  3935.                 globalAttributesOrder = attributesOrder;
  3936.               }
  3937.               if (outputName) {
  3938.                 element.outputName = elementName;
  3939.                 elements[outputName] = element;
  3940.               }
  3941.               if (hasPatternsRegExp.test(elementName)) {
  3942.                 element.pattern = patternToRegExp(elementName);
  3943.                 patternElements.push(element);
  3944.               } else {
  3945.                 elements[elementName] = element;
  3946.               }
  3947.             }
  3948.           }
  3949.         }
  3950.       };
  3951.       var setValidElements = function (validElements) {
  3952.         elements = {};
  3953.         patternElements = [];
  3954.         addValidElements(validElements);
  3955.         each$h(schemaItems, function (element, name) {
  3956.           children[name] = element.children;
  3957.         });
  3958.       };
  3959.       var addCustomElements = function (customElements) {
  3960.         var customElementRegExp = /^(~)?(.+)$/;
  3961.         if (customElements) {
  3962.           mapCache.text_block_elements = mapCache.block_elements = null;
  3963.           each$h(split$1(customElements, ','), function (rule) {
  3964.             var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2];
  3965.             children[name] = children[cloneName];
  3966.             customElementsMap[name] = cloneName;
  3967.             if (!inline) {
  3968.               blockElementsMap[name.toUpperCase()] = {};
  3969.               blockElementsMap[name] = {};
  3970.             }
  3971.             if (!elements[name]) {
  3972.               var customRule = elements[cloneName];
  3973.               customRule = extend$5({}, customRule);
  3974.               delete customRule.removeEmptyAttrs;
  3975.               delete customRule.removeEmpty;
  3976.               elements[name] = customRule;
  3977.             }
  3978.             each$h(children, function (element, elmName) {
  3979.               if (element[cloneName]) {
  3980.                 children[elmName] = element = extend$5({}, children[elmName]);
  3981.                 element[name] = element[cloneName];
  3982.               }
  3983.             });
  3984.           });
  3985.         }
  3986.       };
  3987.       var addValidChildren = function (validChildren) {
  3988.         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]+)\[([^\]]+)]$/;
  3989.         mapCache[settings.schema] = null;
  3990.         if (validChildren) {
  3991.           each$h(split$1(validChildren, ','), function (rule) {
  3992.             var matches = childRuleRegExp.exec(rule);
  3993.             var parent, prefix;
  3994.             if (matches) {
  3995.               prefix = matches[1];
  3996.               if (prefix) {
  3997.                 parent = children[matches[2]];
  3998.               } else {
  3999.                 parent = children[matches[2]] = { '#comment': {} };
  4000.               }
  4001.               parent = children[matches[2]];
  4002.               each$h(split$1(matches[3], '|'), function (child) {
  4003.                 if (prefix === '-') {
  4004.                   delete parent[child];
  4005.                 } else {
  4006.                   parent[child] = {};
  4007.                 }
  4008.               });
  4009.             }
  4010.           });
  4011.         }
  4012.       };
  4013.       var getElementRule = function (name) {
  4014.         var element = elements[name], i;
  4015.         if (element) {
  4016.           return element;
  4017.         }
  4018.         i = patternElements.length;
  4019.         while (i--) {
  4020.           element = patternElements[i];
  4021.           if (element.pattern.test(name)) {
  4022.             return element;
  4023.           }
  4024.         }
  4025.       };
  4026.       if (!settings.valid_elements) {
  4027.         each$h(schemaItems, function (element, name) {
  4028.           elements[name] = {
  4029.             attributes: element.attributes,
  4030.             attributesOrder: element.attributesOrder
  4031.           };
  4032.           children[name] = element.children;
  4033.         });
  4034.         if (settings.schema !== 'html5') {
  4035.           each$h(split$1('strong/b em/i'), function (item) {
  4036.             var items = split$1(item, '/');
  4037.             elements[items[1]].outputName = items[0];
  4038.           });
  4039.         }
  4040.         each$h(textInlineElementsMap, function (_val, name) {
  4041.           if (elements[name]) {
  4042.             if (settings.padd_empty_block_inline_children) {
  4043.               elements[name].paddInEmptyBlock = true;
  4044.             }
  4045.             elements[name].removeEmpty = true;
  4046.           }
  4047.         });
  4048.         each$h(split$1('ol ul blockquote a table tbody'), function (name) {
  4049.           if (elements[name]) {
  4050.             elements[name].removeEmpty = true;
  4051.           }
  4052.         });
  4053.         each$h(split$1('p h1 h2 h3 h4 h5 h6 th td pre div address caption li'), function (name) {
  4054.           elements[name].paddEmpty = true;
  4055.         });
  4056.         each$h(split$1('span'), function (name) {
  4057.           elements[name].removeEmptyAttrs = true;
  4058.         });
  4059.       } else {
  4060.         setValidElements(settings.valid_elements);
  4061.       }
  4062.       addCustomElements(settings.custom_elements);
  4063.       addValidChildren(settings.valid_children);
  4064.       addValidElements(settings.extended_valid_elements);
  4065.       addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  4066.       each$h({
  4067.         dd: 'dl',
  4068.         dt: 'dl',
  4069.         li: 'ul ol',
  4070.         td: 'tr',
  4071.         th: 'tr',
  4072.         tr: 'tbody thead tfoot',
  4073.         tbody: 'table',
  4074.         thead: 'table',
  4075.         tfoot: 'table',
  4076.         legend: 'fieldset',
  4077.         area: 'map',
  4078.         param: 'video audio object'
  4079.       }, function (parents, item) {
  4080.         if (elements[item]) {
  4081.           elements[item].parentsRequired = split$1(parents);
  4082.         }
  4083.       });
  4084.       if (settings.invalid_elements) {
  4085.         each$h(explode$3(settings.invalid_elements), function (item) {
  4086.           if (elements[item]) {
  4087.             delete elements[item];
  4088.           }
  4089.         });
  4090.       }
  4091.       if (!getElementRule('span')) {
  4092.         addValidElements('span[!data-mce-type|*]');
  4093.       }
  4094.       var getValidStyles = constant(validStyles);
  4095.       var getInvalidStyles = constant(invalidStyles);
  4096.       var getValidClasses = constant(validClasses);
  4097.       var getBoolAttrs = constant(boolAttrMap);
  4098.       var getBlockElements = constant(blockElementsMap);
  4099.       var getTextBlockElements = constant(textBlockElementsMap);
  4100.       var getTextInlineElements = constant(textInlineElementsMap);
  4101.       var getShortEndedElements = constant(shortEndedElementsMap);
  4102.       var getSelfClosingElements = constant(selfClosingElementsMap);
  4103.       var getNonEmptyElements = constant(nonEmptyElementsMap);
  4104.       var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
  4105.       var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
  4106.       var getSpecialElements = constant(specialElements);
  4107.       var isValidChild = function (name, child) {
  4108.         var parent = children[name.toLowerCase()];
  4109.         return !!(parent && parent[child.toLowerCase()]);
  4110.       };
  4111.       var isValid = function (name, attr) {
  4112.         var attrPatterns, i;
  4113.         var rule = getElementRule(name);
  4114.         if (rule) {
  4115.           if (attr) {
  4116.             if (rule.attributes[attr]) {
  4117.               return true;
  4118.             }
  4119.             attrPatterns = rule.attributePatterns;
  4120.             if (attrPatterns) {
  4121.               i = attrPatterns.length;
  4122.               while (i--) {
  4123.                 if (attrPatterns[i].pattern.test(name)) {
  4124.                   return true;
  4125.                 }
  4126.               }
  4127.             }
  4128.           } else {
  4129.             return true;
  4130.           }
  4131.         }
  4132.         return false;
  4133.       };
  4134.       var getCustomElements = constant(customElementsMap);
  4135.       return {
  4136.         children: children,
  4137.         elements: elements,
  4138.         getValidStyles: getValidStyles,
  4139.         getValidClasses: getValidClasses,
  4140.         getBlockElements: getBlockElements,
  4141.         getInvalidStyles: getInvalidStyles,
  4142.         getShortEndedElements: getShortEndedElements,
  4143.         getTextBlockElements: getTextBlockElements,
  4144.         getTextInlineElements: getTextInlineElements,
  4145.         getBoolAttrs: getBoolAttrs,
  4146.         getElementRule: getElementRule,
  4147.         getSelfClosingElements: getSelfClosingElements,
  4148.         getNonEmptyElements: getNonEmptyElements,
  4149.         getMoveCaretBeforeOnEnterElements: getMoveCaretBeforeOnEnterElements,
  4150.         getWhiteSpaceElements: getWhiteSpaceElements,
  4151.         getSpecialElements: getSpecialElements,
  4152.         isValidChild: isValidChild,
  4153.         isValid: isValid,
  4154.         getCustomElements: getCustomElements,
  4155.         addValidElements: addValidElements,
  4156.         setValidElements: setValidElements,
  4157.         addCustomElements: addCustomElements,
  4158.         addValidChildren: addValidChildren
  4159.       };
  4160.     };
  4161.  
  4162.     var toHex = function (match, r, g, b) {
  4163.       var hex = function (val) {
  4164.         val = parseInt(val, 10).toString(16);
  4165.         return val.length > 1 ? val : '0' + val;
  4166.       };
  4167.       return '#' + hex(r) + hex(g) + hex(b);
  4168.     };
  4169.     var Styles = function (settings, schema) {
  4170.       var _this = this;
  4171.       var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
  4172.       var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
  4173.       var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
  4174.       var trimRightRegExp = /\s+$/;
  4175.       var i;
  4176.       var encodingLookup = {};
  4177.       var validStyles;
  4178.       var invalidStyles;
  4179.       var invisibleChar = zeroWidth;
  4180.       settings = settings || {};
  4181.       if (schema) {
  4182.         validStyles = schema.getValidStyles();
  4183.         invalidStyles = schema.getInvalidStyles();
  4184.       }
  4185.       var encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  4186.       for (i = 0; i < encodingItems.length; i++) {
  4187.         encodingLookup[encodingItems[i]] = invisibleChar + i;
  4188.         encodingLookup[invisibleChar + i] = encodingItems[i];
  4189.       }
  4190.       return {
  4191.         toHex: function (color) {
  4192.           return color.replace(rgbRegExp, toHex);
  4193.         },
  4194.         parse: function (css) {
  4195.           var styles = {};
  4196.           var matches, name, value, isEncoded;
  4197.           var urlConverter = settings.url_converter;
  4198.           var urlConverterScope = settings.url_converter_scope || _this;
  4199.           var compress = function (prefix, suffix, noJoin) {
  4200.             var top = styles[prefix + '-top' + suffix];
  4201.             if (!top) {
  4202.               return;
  4203.             }
  4204.             var right = styles[prefix + '-right' + suffix];
  4205.             if (!right) {
  4206.               return;
  4207.             }
  4208.             var bottom = styles[prefix + '-bottom' + suffix];
  4209.             if (!bottom) {
  4210.               return;
  4211.             }
  4212.             var left = styles[prefix + '-left' + suffix];
  4213.             if (!left) {
  4214.               return;
  4215.             }
  4216.             var box = [
  4217.               top,
  4218.               right,
  4219.               bottom,
  4220.               left
  4221.             ];
  4222.             i = box.length - 1;
  4223.             while (i--) {
  4224.               if (box[i] !== box[i + 1]) {
  4225.                 break;
  4226.               }
  4227.             }
  4228.             if (i > -1 && noJoin) {
  4229.               return;
  4230.             }
  4231.             styles[prefix + suffix] = i === -1 ? box[0] : box.join(' ');
  4232.             delete styles[prefix + '-top' + suffix];
  4233.             delete styles[prefix + '-right' + suffix];
  4234.             delete styles[prefix + '-bottom' + suffix];
  4235.             delete styles[prefix + '-left' + suffix];
  4236.           };
  4237.           var canCompress = function (key) {
  4238.             var value = styles[key], i;
  4239.             if (!value) {
  4240.               return;
  4241.             }
  4242.             value = value.split(' ');
  4243.             i = value.length;
  4244.             while (i--) {
  4245.               if (value[i] !== value[0]) {
  4246.                 return false;
  4247.               }
  4248.             }
  4249.             styles[key] = value[0];
  4250.             return true;
  4251.           };
  4252.           var compress2 = function (target, a, b, c) {
  4253.             if (!canCompress(a)) {
  4254.               return;
  4255.             }
  4256.             if (!canCompress(b)) {
  4257.               return;
  4258.             }
  4259.             if (!canCompress(c)) {
  4260.               return;
  4261.             }
  4262.             styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  4263.             delete styles[a];
  4264.             delete styles[b];
  4265.             delete styles[c];
  4266.           };
  4267.           var encode = function (str) {
  4268.             isEncoded = true;
  4269.             return encodingLookup[str];
  4270.           };
  4271.           var decode = function (str, keepSlashes) {
  4272.             if (isEncoded) {
  4273.               str = str.replace(/\uFEFF[0-9]/g, function (str) {
  4274.                 return encodingLookup[str];
  4275.               });
  4276.             }
  4277.             if (!keepSlashes) {
  4278.               str = str.replace(/\\([\'\";:])/g, '$1');
  4279.             }
  4280.             return str;
  4281.           };
  4282.           var decodeSingleHexSequence = function (escSeq) {
  4283.             return String.fromCharCode(parseInt(escSeq.slice(1), 16));
  4284.           };
  4285.           var decodeHexSequences = function (value) {
  4286.             return value.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
  4287.           };
  4288.           var processUrl = function (match, url, url2, url3, str, str2) {
  4289.             str = str || str2;
  4290.             if (str) {
  4291.               str = decode(str);
  4292.               return '\'' + str.replace(/\'/g, '\\\'') + '\'';
  4293.             }
  4294.             url = decode(url || url2 || url3);
  4295.             if (!settings.allow_script_urls) {
  4296.               var scriptUrl = url.replace(/[\s\r\n]+/g, '');
  4297.               if (/(java|vb)script:/i.test(scriptUrl)) {
  4298.                 return '';
  4299.               }
  4300.               if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  4301.                 return '';
  4302.               }
  4303.             }
  4304.             if (urlConverter) {
  4305.               url = urlConverter.call(urlConverterScope, url, 'style');
  4306.             }
  4307.             return 'url(\'' + url.replace(/\'/g, '\\\'') + '\')';
  4308.           };
  4309.           if (css) {
  4310.             css = css.replace(/[\u0000-\u001F]/g, '');
  4311.             css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function (str) {
  4312.               return str.replace(/[;:]/g, encode);
  4313.             });
  4314.             while (matches = styleRegExp.exec(css)) {
  4315.               styleRegExp.lastIndex = matches.index + matches[0].length;
  4316.               name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  4317.               value = matches[2].replace(trimRightRegExp, '');
  4318.               if (name && value) {
  4319.                 name = decodeHexSequences(name);
  4320.                 value = decodeHexSequences(value);
  4321.                 if (name.indexOf(invisibleChar) !== -1 || name.indexOf('"') !== -1) {
  4322.                   continue;
  4323.                 }
  4324.                 if (!settings.allow_script_urls && (name === 'behavior' || /expression\s*\(|\/\*|\*\//.test(value))) {
  4325.                   continue;
  4326.                 }
  4327.                 if (name === 'font-weight' && value === '700') {
  4328.                   value = 'bold';
  4329.                 } else if (name === 'color' || name === 'background-color') {
  4330.                   value = value.toLowerCase();
  4331.                 }
  4332.                 value = value.replace(rgbRegExp, toHex);
  4333.                 value = value.replace(urlOrStrRegExp, processUrl);
  4334.                 styles[name] = isEncoded ? decode(value, true) : value;
  4335.               }
  4336.             }
  4337.             compress('border', '', true);
  4338.             compress('border', '-width');
  4339.             compress('border', '-color');
  4340.             compress('border', '-style');
  4341.             compress('padding', '');
  4342.             compress('margin', '');
  4343.             compress2('border', 'border-width', 'border-style', 'border-color');
  4344.             if (styles.border === 'medium none') {
  4345.               delete styles.border;
  4346.             }
  4347.             if (styles['border-image'] === 'none') {
  4348.               delete styles['border-image'];
  4349.             }
  4350.           }
  4351.           return styles;
  4352.         },
  4353.         serialize: function (styles, elementName) {
  4354.           var css = '';
  4355.           var serializeStyles = function (name) {
  4356.             var value;
  4357.             var styleList = validStyles[name];
  4358.             if (styleList) {
  4359.               for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
  4360.                 name = styleList[i_1];
  4361.                 value = styles[name];
  4362.                 if (value) {
  4363.                   css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4364.                 }
  4365.               }
  4366.             }
  4367.           };
  4368.           var isValid = function (name, elementName) {
  4369.             var styleMap = invalidStyles['*'];
  4370.             if (styleMap && styleMap[name]) {
  4371.               return false;
  4372.             }
  4373.             styleMap = invalidStyles[elementName];
  4374.             return !(styleMap && styleMap[name]);
  4375.           };
  4376.           if (elementName && validStyles) {
  4377.             serializeStyles('*');
  4378.             serializeStyles(elementName);
  4379.           } else {
  4380.             each$j(styles, function (value, name) {
  4381.               if (value && (!invalidStyles || isValid(name, elementName))) {
  4382.                 css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  4383.               }
  4384.             });
  4385.           }
  4386.           return css;
  4387.         }
  4388.       };
  4389.     };
  4390.  
  4391.     var deprecated = {
  4392.       keyLocation: true,
  4393.       layerX: true,
  4394.       layerY: true,
  4395.       returnValue: true,
  4396.       webkitMovementX: true,
  4397.       webkitMovementY: true,
  4398.       keyIdentifier: true,
  4399.       mozPressure: true
  4400.     };
  4401.     var isNativeEvent = function (event) {
  4402.       return event instanceof Event || isFunction(event.initEvent);
  4403.     };
  4404.     var hasIsDefaultPrevented = function (event) {
  4405.       return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
  4406.     };
  4407.     var needsNormalizing = function (event) {
  4408.       return isNullable(event.preventDefault) || isNativeEvent(event);
  4409.     };
  4410.     var clone$2 = function (originalEvent, data) {
  4411.       var event = data !== null && data !== void 0 ? data : {};
  4412.       for (var name_1 in originalEvent) {
  4413.         if (!has$2(deprecated, name_1)) {
  4414.           event[name_1] = originalEvent[name_1];
  4415.         }
  4416.       }
  4417.       if (isNonNullable(event.composedPath)) {
  4418.         event.composedPath = function () {
  4419.           return originalEvent.composedPath();
  4420.         };
  4421.       }
  4422.       return event;
  4423.     };
  4424.     var normalize$3 = function (type, originalEvent, fallbackTarget, data) {
  4425.       var _a;
  4426.       var event = clone$2(originalEvent, data);
  4427.       event.type = type;
  4428.       if (isNullable(event.target)) {
  4429.         event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
  4430.       }
  4431.       if (needsNormalizing(originalEvent)) {
  4432.         event.preventDefault = function () {
  4433.           event.defaultPrevented = true;
  4434.           event.isDefaultPrevented = always;
  4435.           if (isFunction(originalEvent.preventDefault)) {
  4436.             originalEvent.preventDefault();
  4437.           } else if (isNativeEvent(originalEvent)) {
  4438.             originalEvent.returnValue = false;
  4439.           }
  4440.         };
  4441.         event.stopPropagation = function () {
  4442.           event.cancelBubble = true;
  4443.           event.isPropagationStopped = always;
  4444.           if (isFunction(originalEvent.stopPropagation)) {
  4445.             originalEvent.stopPropagation();
  4446.           } else if (isNativeEvent(originalEvent)) {
  4447.             originalEvent.cancelBubble = true;
  4448.           }
  4449.         };
  4450.         event.stopImmediatePropagation = function () {
  4451.           event.isImmediatePropagationStopped = always;
  4452.           event.stopPropagation();
  4453.         };
  4454.         if (!hasIsDefaultPrevented(event)) {
  4455.           event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
  4456.           event.isPropagationStopped = event.cancelBubble === true ? always : never;
  4457.           event.isImmediatePropagationStopped = never;
  4458.         }
  4459.       }
  4460.       return event;
  4461.     };
  4462.  
  4463.     var eventExpandoPrefix = 'mce-data-';
  4464.     var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  4465.     var addEvent = function (target, name, callback, capture) {
  4466.       if (target.addEventListener) {
  4467.         target.addEventListener(name, callback, capture || false);
  4468.       } else if (target.attachEvent) {
  4469.         target.attachEvent('on' + name, callback);
  4470.       }
  4471.     };
  4472.     var removeEvent = function (target, name, callback, capture) {
  4473.       if (target.removeEventListener) {
  4474.         target.removeEventListener(name, callback, capture || false);
  4475.       } else if (target.detachEvent) {
  4476.         target.detachEvent('on' + name, callback);
  4477.       }
  4478.     };
  4479.     var isMouseEvent = function (event) {
  4480.       return isNonNullable(event) && mouseEventRe.test(event.type);
  4481.     };
  4482.     var fix = function (originalEvent, data) {
  4483.       var event = normalize$3(originalEvent.type, originalEvent, document, data);
  4484.       if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
  4485.         var eventDoc = event.target.ownerDocument || document;
  4486.         var doc = eventDoc.documentElement;
  4487.         var body = eventDoc.body;
  4488.         var mouseEvent = event;
  4489.         mouseEvent.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  4490.         mouseEvent.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  4491.       }
  4492.       if (isUndefined(event.metaKey)) {
  4493.         event.metaKey = false;
  4494.       }
  4495.       return event;
  4496.     };
  4497.     var bindOnReady = function (win, callback, eventUtils) {
  4498.       var doc = win.document, event = { type: 'ready' };
  4499.       if (eventUtils.domLoaded) {
  4500.         callback(event);
  4501.         return;
  4502.       }
  4503.       var isDocReady = function () {
  4504.         return doc.readyState === 'complete' || doc.readyState === 'interactive' && doc.body;
  4505.       };
  4506.       var readyHandler = function () {
  4507.         removeEvent(win, 'DOMContentLoaded', readyHandler);
  4508.         removeEvent(win, 'load', readyHandler);
  4509.         if (!eventUtils.domLoaded) {
  4510.           eventUtils.domLoaded = true;
  4511.           callback(event);
  4512.         }
  4513.         win = null;
  4514.       };
  4515.       if (isDocReady()) {
  4516.         readyHandler();
  4517.       } else {
  4518.         addEvent(win, 'DOMContentLoaded', readyHandler);
  4519.       }
  4520.       if (!eventUtils.domLoaded) {
  4521.         addEvent(win, 'load', readyHandler);
  4522.       }
  4523.     };
  4524.     var EventUtils = function () {
  4525.       function EventUtils() {
  4526.         this.domLoaded = false;
  4527.         this.events = {};
  4528.         this.count = 1;
  4529.         this.expando = eventExpandoPrefix + (+new Date()).toString(32);
  4530.         this.hasMouseEnterLeave = 'onmouseenter' in document.documentElement;
  4531.         this.hasFocusIn = 'onfocusin' in document.documentElement;
  4532.         this.count = 1;
  4533.       }
  4534.       EventUtils.prototype.bind = function (target, names, callback, scope) {
  4535.         var self = this;
  4536.         var id, callbackList, i, name, fakeName, nativeHandler, capture;
  4537.         var win = window;
  4538.         var defaultNativeHandler = function (evt) {
  4539.           self.executeHandlers(fix(evt || win.event), id);
  4540.         };
  4541.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4542.           return;
  4543.         }
  4544.         if (!target[self.expando]) {
  4545.           id = self.count++;
  4546.           target[self.expando] = id;
  4547.           self.events[id] = {};
  4548.         } else {
  4549.           id = target[self.expando];
  4550.         }
  4551.         scope = scope || target;
  4552.         var namesList = names.split(' ');
  4553.         i = namesList.length;
  4554.         while (i--) {
  4555.           name = namesList[i];
  4556.           nativeHandler = defaultNativeHandler;
  4557.           fakeName = capture = false;
  4558.           if (name === 'DOMContentLoaded') {
  4559.             name = 'ready';
  4560.           }
  4561.           if (self.domLoaded && name === 'ready' && target.readyState === 'complete') {
  4562.             callback.call(scope, fix({ type: name }));
  4563.             continue;
  4564.           }
  4565.           if (!self.hasMouseEnterLeave) {
  4566.             fakeName = self.mouseEnterLeave[name];
  4567.             if (fakeName) {
  4568.               nativeHandler = function (evt) {
  4569.                 var current = evt.currentTarget;
  4570.                 var related = evt.relatedTarget;
  4571.                 if (related && current.contains) {
  4572.                   related = current.contains(related);
  4573.                 } else {
  4574.                   while (related && related !== current) {
  4575.                     related = related.parentNode;
  4576.                   }
  4577.                 }
  4578.                 if (!related) {
  4579.                   evt = fix(evt || win.event);
  4580.                   evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  4581.                   evt.target = current;
  4582.                   self.executeHandlers(evt, id);
  4583.                 }
  4584.               };
  4585.             }
  4586.           }
  4587.           if (!self.hasFocusIn && (name === 'focusin' || name === 'focusout')) {
  4588.             capture = true;
  4589.             fakeName = name === 'focusin' ? 'focus' : 'blur';
  4590.             nativeHandler = function (evt) {
  4591.               evt = fix(evt || win.event);
  4592.               evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  4593.               self.executeHandlers(evt, id);
  4594.             };
  4595.           }
  4596.           callbackList = self.events[id][name];
  4597.           if (!callbackList) {
  4598.             self.events[id][name] = callbackList = [{
  4599.                 func: callback,
  4600.                 scope: scope
  4601.               }];
  4602.             callbackList.fakeName = fakeName;
  4603.             callbackList.capture = capture;
  4604.             callbackList.nativeHandler = nativeHandler;
  4605.             if (name === 'ready') {
  4606.               bindOnReady(target, nativeHandler, self);
  4607.             } else {
  4608.               addEvent(target, fakeName || name, nativeHandler, capture);
  4609.             }
  4610.           } else {
  4611.             if (name === 'ready' && self.domLoaded) {
  4612.               callback(fix({ type: name }));
  4613.             } else {
  4614.               callbackList.push({
  4615.                 func: callback,
  4616.                 scope: scope
  4617.               });
  4618.             }
  4619.           }
  4620.         }
  4621.         target = callbackList = null;
  4622.         return callback;
  4623.       };
  4624.       EventUtils.prototype.unbind = function (target, names, callback) {
  4625.         var callbackList, i, ci, name, eventMap;
  4626.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4627.           return this;
  4628.         }
  4629.         var id = target[this.expando];
  4630.         if (id) {
  4631.           eventMap = this.events[id];
  4632.           if (names) {
  4633.             var namesList = names.split(' ');
  4634.             i = namesList.length;
  4635.             while (i--) {
  4636.               name = namesList[i];
  4637.               callbackList = eventMap[name];
  4638.               if (callbackList) {
  4639.                 if (callback) {
  4640.                   ci = callbackList.length;
  4641.                   while (ci--) {
  4642.                     if (callbackList[ci].func === callback) {
  4643.                       var nativeHandler = callbackList.nativeHandler;
  4644.                       var fakeName = callbackList.fakeName, capture = callbackList.capture;
  4645.                       callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  4646.                       callbackList.nativeHandler = nativeHandler;
  4647.                       callbackList.fakeName = fakeName;
  4648.                       callbackList.capture = capture;
  4649.                       eventMap[name] = callbackList;
  4650.                     }
  4651.                   }
  4652.                 }
  4653.                 if (!callback || callbackList.length === 0) {
  4654.                   delete eventMap[name];
  4655.                   removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4656.                 }
  4657.               }
  4658.             }
  4659.           } else {
  4660.             each$j(eventMap, function (callbackList, name) {
  4661.               removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  4662.             });
  4663.             eventMap = {};
  4664.           }
  4665.           for (name in eventMap) {
  4666.             if (has$2(eventMap, name)) {
  4667.               return this;
  4668.             }
  4669.           }
  4670.           delete this.events[id];
  4671.           try {
  4672.             delete target[this.expando];
  4673.           } catch (ex) {
  4674.             target[this.expando] = null;
  4675.           }
  4676.         }
  4677.         return this;
  4678.       };
  4679.       EventUtils.prototype.fire = function (target, name, args) {
  4680.         var id;
  4681.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4682.           return this;
  4683.         }
  4684.         var event = fix({
  4685.           type: name,
  4686.           target: target
  4687.         }, args);
  4688.         do {
  4689.           id = target[this.expando];
  4690.           if (id) {
  4691.             this.executeHandlers(event, id);
  4692.           }
  4693.           target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  4694.         } while (target && !event.isPropagationStopped());
  4695.         return this;
  4696.       };
  4697.       EventUtils.prototype.clean = function (target) {
  4698.         var i, children;
  4699.         if (!target || target.nodeType === 3 || target.nodeType === 8) {
  4700.           return this;
  4701.         }
  4702.         if (target[this.expando]) {
  4703.           this.unbind(target);
  4704.         }
  4705.         if (!target.getElementsByTagName) {
  4706.           target = target.document;
  4707.         }
  4708.         if (target && target.getElementsByTagName) {
  4709.           this.unbind(target);
  4710.           children = target.getElementsByTagName('*');
  4711.           i = children.length;
  4712.           while (i--) {
  4713.             target = children[i];
  4714.             if (target[this.expando]) {
  4715.               this.unbind(target);
  4716.             }
  4717.           }
  4718.         }
  4719.         return this;
  4720.       };
  4721.       EventUtils.prototype.destroy = function () {
  4722.         this.events = {};
  4723.       };
  4724.       EventUtils.prototype.cancel = function (e) {
  4725.         if (e) {
  4726.           e.preventDefault();
  4727.           e.stopImmediatePropagation();
  4728.         }
  4729.         return false;
  4730.       };
  4731.       EventUtils.prototype.executeHandlers = function (evt, id) {
  4732.         var container = this.events[id];
  4733.         var callbackList = container && container[evt.type];
  4734.         if (callbackList) {
  4735.           for (var i = 0, l = callbackList.length; i < l; i++) {
  4736.             var callback = callbackList[i];
  4737.             if (callback && callback.func.call(callback.scope, evt) === false) {
  4738.               evt.preventDefault();
  4739.             }
  4740.             if (evt.isImmediatePropagationStopped()) {
  4741.               return;
  4742.             }
  4743.           }
  4744.         }
  4745.       };
  4746.       EventUtils.Event = new EventUtils();
  4747.       return EventUtils;
  4748.     }();
  4749.  
  4750.     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) {
  4751.         if (a === b) {
  4752.           hasDuplicate = true;
  4753.         }
  4754.         return 0;
  4755.       }, 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) {
  4756.         var i = 0, len = this.length;
  4757.         for (; i < len; i++) {
  4758.           if (this[i] === elem) {
  4759.             return i;
  4760.           }
  4761.         }
  4762.         return -1;
  4763.       }, 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 = {
  4764.         ID: new RegExp('^#(' + identifier + ')'),
  4765.         CLASS: new RegExp('^\\.(' + identifier + ')'),
  4766.         TAG: new RegExp('^(' + identifier + '|[*])'),
  4767.         ATTR: new RegExp('^' + attributes),
  4768.         PSEUDO: new RegExp('^' + pseudos),
  4769.         CHILD: new RegExp('^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(' + whitespace + '*(even|odd|(([+-]|)(\\d*)n|)' + whitespace + '*(?:([+-]|)' + whitespace + '*(\\d+)|))' + whitespace + '*\\)|)', 'i'),
  4770.         bool: new RegExp('^(?:' + booleans + ')$', 'i'),
  4771.         needsContext: new RegExp('^' + whitespace + '*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(' + whitespace + '*((?:-\\d)?\\d*)' + whitespace + '*\\)|)(?=[^-]|$)', 'i')
  4772.       }, 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) {
  4773.         var high = '0x' + escaped - 65536;
  4774.         return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
  4775.       };
  4776.     try {
  4777.       push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
  4778.       arr[preferredDoc.childNodes.length].nodeType;
  4779.     } catch (e) {
  4780.       push$1 = {
  4781.         apply: arr.length ? function (target, els) {
  4782.           push_native.apply(target, slice$1.call(els));
  4783.         } : function (target, els) {
  4784.           var j = target.length, i = 0;
  4785.           while (target[j++] = els[i++]) {
  4786.           }
  4787.           target.length = j - 1;
  4788.         }
  4789.       };
  4790.     }
  4791.     var Sizzle = function (selector, context, results, seed) {
  4792.       var match, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
  4793.       if ((context ? context.ownerDocument || context : preferredDoc) !== document$1) {
  4794.         setDocument(context);
  4795.       }
  4796.       context = context || document$1;
  4797.       results = results || [];
  4798.       if (!selector || typeof selector !== 'string') {
  4799.         return results;
  4800.       }
  4801.       if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
  4802.         return [];
  4803.       }
  4804.       if (documentIsHTML && !seed) {
  4805.         if (match = rquickExpr$1.exec(selector)) {
  4806.           if (m = match[1]) {
  4807.             if (nodeType === 9) {
  4808.               elem = context.getElementById(m);
  4809.               if (elem && elem.parentNode) {
  4810.                 if (elem.id === m) {
  4811.                   results.push(elem);
  4812.                   return results;
  4813.                 }
  4814.               } else {
  4815.                 return results;
  4816.               }
  4817.             } else {
  4818.               if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
  4819.                 results.push(elem);
  4820.                 return results;
  4821.               }
  4822.             }
  4823.           } else if (match[2]) {
  4824.             push$1.apply(results, context.getElementsByTagName(selector));
  4825.             return results;
  4826.           } else if ((m = match[3]) && support.getElementsByClassName) {
  4827.             push$1.apply(results, context.getElementsByClassName(m));
  4828.             return results;
  4829.           }
  4830.         }
  4831.         if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
  4832.           nid = old = expando;
  4833.           newContext = context;
  4834.           newSelector = nodeType === 9 && selector;
  4835.           if (nodeType === 1 && context.nodeName.toLowerCase() !== 'object') {
  4836.             groups = tokenize(selector);
  4837.             if (old = context.getAttribute('id')) {
  4838.               nid = old.replace(rescape, '\\$&');
  4839.             } else {
  4840.               context.setAttribute('id', nid);
  4841.             }
  4842.             nid = '[id=\'' + nid + '\'] ';
  4843.             i = groups.length;
  4844.             while (i--) {
  4845.               groups[i] = nid + toSelector(groups[i]);
  4846.             }
  4847.             newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
  4848.             newSelector = groups.join(',');
  4849.           }
  4850.           if (newSelector) {
  4851.             try {
  4852.               push$1.apply(results, newContext.querySelectorAll(newSelector));
  4853.               return results;
  4854.             } catch (qsaError) {
  4855.             } finally {
  4856.               if (!old) {
  4857.                 context.removeAttribute('id');
  4858.               }
  4859.             }
  4860.           }
  4861.         }
  4862.       }
  4863.       return select$1(selector.replace(rtrim, '$1'), context, results, seed);
  4864.     };
  4865.     function createCache() {
  4866.       var keys = [];
  4867.       function cache(key, value) {
  4868.         if (keys.push(key + ' ') > Expr.cacheLength) {
  4869.           delete cache[keys.shift()];
  4870.         }
  4871.         return cache[key + ' '] = value;
  4872.       }
  4873.       return cache;
  4874.     }
  4875.     function markFunction(fn) {
  4876.       fn[expando] = true;
  4877.       return fn;
  4878.     }
  4879.     function siblingCheck(a, b) {
  4880.       var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
  4881.       if (diff) {
  4882.         return diff;
  4883.       }
  4884.       if (cur) {
  4885.         while (cur = cur.nextSibling) {
  4886.           if (cur === b) {
  4887.             return -1;
  4888.           }
  4889.         }
  4890.       }
  4891.       return a ? 1 : -1;
  4892.     }
  4893.     function createInputPseudo(type) {
  4894.       return function (elem) {
  4895.         var name = elem.nodeName.toLowerCase();
  4896.         return name === 'input' && elem.type === type;
  4897.       };
  4898.     }
  4899.     function createButtonPseudo(type) {
  4900.       return function (elem) {
  4901.         var name = elem.nodeName.toLowerCase();
  4902.         return (name === 'input' || name === 'button') && elem.type === type;
  4903.       };
  4904.     }
  4905.     function createPositionalPseudo(fn) {
  4906.       return markFunction(function (argument) {
  4907.         argument = +argument;
  4908.         return markFunction(function (seed, matches) {
  4909.           var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length;
  4910.           while (i--) {
  4911.             if (seed[j = matchIndexes[i]]) {
  4912.               seed[j] = !(matches[j] = seed[j]);
  4913.             }
  4914.           }
  4915.         });
  4916.       });
  4917.     }
  4918.     function testContext(context) {
  4919.       return context && typeof context.getElementsByTagName !== strundefined && context;
  4920.     }
  4921.     support = Sizzle.support = {};
  4922.     isXML = Sizzle.isXML = function (elem) {
  4923.       var documentElement = elem && (elem.ownerDocument || elem).documentElement;
  4924.       return documentElement ? documentElement.nodeName !== 'HTML' : false;
  4925.     };
  4926.     setDocument = Sizzle.setDocument = function (node) {
  4927.       var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView;
  4928.       function getTop(win) {
  4929.         try {
  4930.           return win.top;
  4931.         } catch (ex) {
  4932.         }
  4933.         return null;
  4934.       }
  4935.       if (doc === document$1 || doc.nodeType !== 9 || !doc.documentElement) {
  4936.         return document$1;
  4937.       }
  4938.       document$1 = doc;
  4939.       docElem = doc.documentElement;
  4940.       documentIsHTML = !isXML(doc);
  4941.       if (parent && parent !== getTop(parent)) {
  4942.         if (parent.addEventListener) {
  4943.           parent.addEventListener('unload', function () {
  4944.             setDocument();
  4945.           }, false);
  4946.         } else if (parent.attachEvent) {
  4947.           parent.attachEvent('onunload', function () {
  4948.             setDocument();
  4949.           });
  4950.         }
  4951.       }
  4952.       support.attributes = true;
  4953.       support.getElementsByTagName = true;
  4954.       support.getElementsByClassName = rnative.test(doc.getElementsByClassName);
  4955.       support.getById = true;
  4956.       Expr.find.ID = function (id, context) {
  4957.         if (typeof context.getElementById !== strundefined && documentIsHTML) {
  4958.           var m = context.getElementById(id);
  4959.           return m && m.parentNode ? [m] : [];
  4960.         }
  4961.       };
  4962.       Expr.filter.ID = function (id) {
  4963.         var attrId = id.replace(runescape, funescape);
  4964.         return function (elem) {
  4965.           return elem.getAttribute('id') === attrId;
  4966.         };
  4967.       };
  4968.       Expr.find.TAG = support.getElementsByTagName ? function (tag, context) {
  4969.         if (typeof context.getElementsByTagName !== strundefined) {
  4970.           return context.getElementsByTagName(tag);
  4971.         }
  4972.       } : function (tag, context) {
  4973.         var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag);
  4974.         if (tag === '*') {
  4975.           while (elem = results[i++]) {
  4976.             if (elem.nodeType === 1) {
  4977.               tmp.push(elem);
  4978.             }
  4979.           }
  4980.           return tmp;
  4981.         }
  4982.         return results;
  4983.       };
  4984.       Expr.find.CLASS = support.getElementsByClassName && function (className, context) {
  4985.         if (documentIsHTML) {
  4986.           return context.getElementsByClassName(className);
  4987.         }
  4988.       };
  4989.       rbuggyMatches = [];
  4990.       rbuggyQSA = [];
  4991.       support.disconnectedMatch = true;
  4992.       rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join('|'));
  4993.       rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join('|'));
  4994.       hasCompare = rnative.test(docElem.compareDocumentPosition);
  4995.       contains = hasCompare || rnative.test(docElem.contains) ? function (a, b) {
  4996.         var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
  4997.         return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
  4998.       } : function (a, b) {
  4999.         if (b) {
  5000.           while (b = b.parentNode) {
  5001.             if (b === a) {
  5002.               return true;
  5003.             }
  5004.           }
  5005.         }
  5006.         return false;
  5007.       };
  5008.       sortOrder = hasCompare ? function (a, b) {
  5009.         if (a === b) {
  5010.           hasDuplicate = true;
  5011.           return 0;
  5012.         }
  5013.         var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
  5014.         if (compare) {
  5015.           return compare;
  5016.         }
  5017.         compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
  5018.         if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
  5019.           if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
  5020.             return -1;
  5021.           }
  5022.           if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
  5023.             return 1;
  5024.           }
  5025.           return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5026.         }
  5027.         return compare & 4 ? -1 : 1;
  5028.       } : function (a, b) {
  5029.         if (a === b) {
  5030.           hasDuplicate = true;
  5031.           return 0;
  5032.         }
  5033.         var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
  5034.         if (!aup || !bup) {
  5035.           return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
  5036.         } else if (aup === bup) {
  5037.           return siblingCheck(a, b);
  5038.         }
  5039.         cur = a;
  5040.         while (cur = cur.parentNode) {
  5041.           ap.unshift(cur);
  5042.         }
  5043.         cur = b;
  5044.         while (cur = cur.parentNode) {
  5045.           bp.unshift(cur);
  5046.         }
  5047.         while (ap[i] === bp[i]) {
  5048.           i++;
  5049.         }
  5050.         return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
  5051.       };
  5052.       return doc;
  5053.     };
  5054.     Sizzle.matches = function (expr, elements) {
  5055.       return Sizzle(expr, null, null, elements);
  5056.     };
  5057.     Sizzle.matchesSelector = function (elem, expr) {
  5058.       if ((elem.ownerDocument || elem) !== document$1) {
  5059.         setDocument(elem);
  5060.       }
  5061.       expr = expr.replace(rattributeQuotes, '=\'$1\']');
  5062.       if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
  5063.         try {
  5064.           var ret = matches.call(elem, expr);
  5065.           if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
  5066.             return ret;
  5067.           }
  5068.         } catch (e) {
  5069.         }
  5070.       }
  5071.       return Sizzle(expr, document$1, null, [elem]).length > 0;
  5072.     };
  5073.     Sizzle.contains = function (context, elem) {
  5074.       if ((context.ownerDocument || context) !== document$1) {
  5075.         setDocument(context);
  5076.       }
  5077.       return contains(context, elem);
  5078.     };
  5079.     Sizzle.attr = function (elem, name) {
  5080.       if ((elem.ownerDocument || elem) !== document$1) {
  5081.         setDocument(elem);
  5082.       }
  5083.       var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
  5084.       return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
  5085.     };
  5086.     Sizzle.error = function (msg) {
  5087.       throw new Error('Syntax error, unrecognized expression: ' + msg);
  5088.     };
  5089.     Sizzle.uniqueSort = function (results) {
  5090.       var elem, duplicates = [], j = 0, i = 0;
  5091.       hasDuplicate = !support.detectDuplicates;
  5092.       sortInput = !support.sortStable && results.slice(0);
  5093.       results.sort(sortOrder);
  5094.       if (hasDuplicate) {
  5095.         while (elem = results[i++]) {
  5096.           if (elem === results[i]) {
  5097.             j = duplicates.push(i);
  5098.           }
  5099.         }
  5100.         while (j--) {
  5101.           results.splice(duplicates[j], 1);
  5102.         }
  5103.       }
  5104.       sortInput = null;
  5105.       return results;
  5106.     };
  5107.     getText = Sizzle.getText = function (elem) {
  5108.       var node, ret = '', i = 0, nodeType = elem.nodeType;
  5109.       if (!nodeType) {
  5110.         while (node = elem[i++]) {
  5111.           ret += getText(node);
  5112.         }
  5113.       } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
  5114.         if (typeof elem.textContent === 'string') {
  5115.           return elem.textContent;
  5116.         } else {
  5117.           for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5118.             ret += getText(elem);
  5119.           }
  5120.         }
  5121.       } else if (nodeType === 3 || nodeType === 4) {
  5122.         return elem.nodeValue;
  5123.       }
  5124.       return ret;
  5125.     };
  5126.     Expr = Sizzle.selectors = {
  5127.       cacheLength: 50,
  5128.       createPseudo: markFunction,
  5129.       match: matchExpr,
  5130.       attrHandle: {},
  5131.       find: {},
  5132.       relative: {
  5133.         '>': {
  5134.           dir: 'parentNode',
  5135.           first: true
  5136.         },
  5137.         ' ': { dir: 'parentNode' },
  5138.         '+': {
  5139.           dir: 'previousSibling',
  5140.           first: true
  5141.         },
  5142.         '~': { dir: 'previousSibling' }
  5143.       },
  5144.       preFilter: {
  5145.         ATTR: function (match) {
  5146.           match[1] = match[1].replace(runescape, funescape);
  5147.           match[3] = (match[3] || match[4] || match[5] || '').replace(runescape, funescape);
  5148.           if (match[2] === '~=') {
  5149.             match[3] = ' ' + match[3] + ' ';
  5150.           }
  5151.           return match.slice(0, 4);
  5152.         },
  5153.         CHILD: function (match) {
  5154.           match[1] = match[1].toLowerCase();
  5155.           if (match[1].slice(0, 3) === 'nth') {
  5156.             if (!match[3]) {
  5157.               Sizzle.error(match[0]);
  5158.             }
  5159.             match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === 'even' || match[3] === 'odd'));
  5160.             match[5] = +(match[7] + match[8] || match[3] === 'odd');
  5161.           } else if (match[3]) {
  5162.             Sizzle.error(match[0]);
  5163.           }
  5164.           return match;
  5165.         },
  5166.         PSEUDO: function (match) {
  5167.           var excess, unquoted = !match[6] && match[2];
  5168.           if (matchExpr.CHILD.test(match[0])) {
  5169.             return null;
  5170.           }
  5171.           if (match[3]) {
  5172.             match[2] = match[4] || match[5] || '';
  5173.           } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(')', unquoted.length - excess) - unquoted.length)) {
  5174.             match[0] = match[0].slice(0, excess);
  5175.             match[2] = unquoted.slice(0, excess);
  5176.           }
  5177.           return match.slice(0, 3);
  5178.         }
  5179.       },
  5180.       filter: {
  5181.         TAG: function (nodeNameSelector) {
  5182.           var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
  5183.           return nodeNameSelector === '*' ? function () {
  5184.             return true;
  5185.           } : function (elem) {
  5186.             return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
  5187.           };
  5188.         },
  5189.         CLASS: function (className) {
  5190.           var pattern = classCache[className + ' '];
  5191.           return pattern || (pattern = new RegExp('(^|' + whitespace + ')' + className + '(' + whitespace + '|$)')) && classCache(className, function (elem) {
  5192.             return pattern.test(typeof elem.className === 'string' && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute('class') || '');
  5193.           });
  5194.         },
  5195.         ATTR: function (name, operator, check) {
  5196.           return function (elem) {
  5197.             var result = Sizzle.attr(elem, name);
  5198.             if (result == null) {
  5199.               return operator === '!=';
  5200.             }
  5201.             if (!operator) {
  5202.               return true;
  5203.             }
  5204.             result += '';
  5205.             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;
  5206.           };
  5207.         },
  5208.         CHILD: function (type, what, argument, first, last) {
  5209.           var simple = type.slice(0, 3) !== 'nth', forward = type.slice(-4) !== 'last', ofType = what === 'of-type';
  5210.           return first === 1 && last === 0 ? function (elem) {
  5211.             return !!elem.parentNode;
  5212.           } : function (elem, context, xml) {
  5213.             var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? 'nextSibling' : 'previousSibling', parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
  5214.             if (parent) {
  5215.               if (simple) {
  5216.                 while (dir) {
  5217.                   node = elem;
  5218.                   while (node = node[dir]) {
  5219.                     if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
  5220.                       return false;
  5221.                     }
  5222.                   }
  5223.                   start = dir = type === 'only' && !start && 'nextSibling';
  5224.                 }
  5225.                 return true;
  5226.               }
  5227.               start = [forward ? parent.firstChild : parent.lastChild];
  5228.               if (forward && useCache) {
  5229.                 outerCache = parent[expando] || (parent[expando] = {});
  5230.                 cache = outerCache[type] || [];
  5231.                 nodeIndex = cache[0] === dirruns && cache[1];
  5232.                 diff = cache[0] === dirruns && cache[2];
  5233.                 node = nodeIndex && parent.childNodes[nodeIndex];
  5234.                 while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5235.                   if (node.nodeType === 1 && ++diff && node === elem) {
  5236.                     outerCache[type] = [
  5237.                       dirruns,
  5238.                       nodeIndex,
  5239.                       diff
  5240.                     ];
  5241.                     break;
  5242.                   }
  5243.                 }
  5244.               } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
  5245.                 diff = cache[1];
  5246.               } else {
  5247.                 while (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) {
  5248.                   if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
  5249.                     if (useCache) {
  5250.                       (node[expando] || (node[expando] = {}))[type] = [
  5251.                         dirruns,
  5252.                         diff
  5253.                       ];
  5254.                     }
  5255.                     if (node === elem) {
  5256.                       break;
  5257.                     }
  5258.                   }
  5259.                 }
  5260.               }
  5261.               diff -= last;
  5262.               return diff === first || diff % first === 0 && diff / first >= 0;
  5263.             }
  5264.           };
  5265.         },
  5266.         PSEUDO: function (pseudo, argument) {
  5267.           var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error('unsupported pseudo: ' + pseudo);
  5268.           if (fn[expando]) {
  5269.             return fn(argument);
  5270.           }
  5271.           if (fn.length > 1) {
  5272.             args = [
  5273.               pseudo,
  5274.               pseudo,
  5275.               '',
  5276.               argument
  5277.             ];
  5278.             return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function (seed, matches) {
  5279.               var idx, matched = fn(seed, argument), i = matched.length;
  5280.               while (i--) {
  5281.                 idx = indexOf.call(seed, matched[i]);
  5282.                 seed[idx] = !(matches[idx] = matched[i]);
  5283.               }
  5284.             }) : function (elem) {
  5285.               return fn(elem, 0, args);
  5286.             };
  5287.           }
  5288.           return fn;
  5289.         }
  5290.       },
  5291.       pseudos: {
  5292.         not: markFunction(function (selector) {
  5293.           var input = [], results = [], matcher = compile(selector.replace(rtrim, '$1'));
  5294.           return matcher[expando] ? markFunction(function (seed, matches, context, xml) {
  5295.             var elem, unmatched = matcher(seed, null, xml, []), i = seed.length;
  5296.             while (i--) {
  5297.               if (elem = unmatched[i]) {
  5298.                 seed[i] = !(matches[i] = elem);
  5299.               }
  5300.             }
  5301.           }) : function (elem, context, xml) {
  5302.             input[0] = elem;
  5303.             matcher(input, null, xml, results);
  5304.             input[0] = null;
  5305.             return !results.pop();
  5306.           };
  5307.         }),
  5308.         has: markFunction(function (selector) {
  5309.           return function (elem) {
  5310.             return Sizzle(selector, elem).length > 0;
  5311.           };
  5312.         }),
  5313.         contains: markFunction(function (text) {
  5314.           text = text.replace(runescape, funescape);
  5315.           return function (elem) {
  5316.             return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
  5317.           };
  5318.         }),
  5319.         lang: markFunction(function (lang) {
  5320.           if (!ridentifier.test(lang || '')) {
  5321.             Sizzle.error('unsupported lang: ' + lang);
  5322.           }
  5323.           lang = lang.replace(runescape, funescape).toLowerCase();
  5324.           return function (elem) {
  5325.             var elemLang;
  5326.             do {
  5327.               if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute('xml:lang') || elem.getAttribute('lang')) {
  5328.                 elemLang = elemLang.toLowerCase();
  5329.                 return elemLang === lang || elemLang.indexOf(lang + '-') === 0;
  5330.               }
  5331.             } while ((elem = elem.parentNode) && elem.nodeType === 1);
  5332.             return false;
  5333.           };
  5334.         }),
  5335.         target: function (elem) {
  5336.           var hash = window.location && window.location.hash;
  5337.           return hash && hash.slice(1) === elem.id;
  5338.         },
  5339.         root: function (elem) {
  5340.           return elem === docElem;
  5341.         },
  5342.         focus: function (elem) {
  5343.           return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
  5344.         },
  5345.         enabled: function (elem) {
  5346.           return elem.disabled === false;
  5347.         },
  5348.         disabled: function (elem) {
  5349.           return elem.disabled === true;
  5350.         },
  5351.         checked: function (elem) {
  5352.           var nodeName = elem.nodeName.toLowerCase();
  5353.           return nodeName === 'input' && !!elem.checked || nodeName === 'option' && !!elem.selected;
  5354.         },
  5355.         selected: function (elem) {
  5356.           if (elem.parentNode) {
  5357.             elem.parentNode.selectedIndex;
  5358.           }
  5359.           return elem.selected === true;
  5360.         },
  5361.         empty: function (elem) {
  5362.           for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
  5363.             if (elem.nodeType < 6) {
  5364.               return false;
  5365.             }
  5366.           }
  5367.           return true;
  5368.         },
  5369.         parent: function (elem) {
  5370.           return !Expr.pseudos.empty(elem);
  5371.         },
  5372.         header: function (elem) {
  5373.           return rheader.test(elem.nodeName);
  5374.         },
  5375.         input: function (elem) {
  5376.           return rinputs.test(elem.nodeName);
  5377.         },
  5378.         button: function (elem) {
  5379.           var name = elem.nodeName.toLowerCase();
  5380.           return name === 'input' && elem.type === 'button' || name === 'button';
  5381.         },
  5382.         text: function (elem) {
  5383.           var attr;
  5384.           return elem.nodeName.toLowerCase() === 'input' && elem.type === 'text' && ((attr = elem.getAttribute('type')) == null || attr.toLowerCase() === 'text');
  5385.         },
  5386.         first: createPositionalPseudo(function () {
  5387.           return [0];
  5388.         }),
  5389.         last: createPositionalPseudo(function (matchIndexes, length) {
  5390.           return [length - 1];
  5391.         }),
  5392.         eq: createPositionalPseudo(function (matchIndexes, length, argument) {
  5393.           return [argument < 0 ? argument + length : argument];
  5394.         }),
  5395.         even: createPositionalPseudo(function (matchIndexes, length) {
  5396.           var i = 0;
  5397.           for (; i < length; i += 2) {
  5398.             matchIndexes.push(i);
  5399.           }
  5400.           return matchIndexes;
  5401.         }),
  5402.         odd: createPositionalPseudo(function (matchIndexes, length) {
  5403.           var i = 1;
  5404.           for (; i < length; i += 2) {
  5405.             matchIndexes.push(i);
  5406.           }
  5407.           return matchIndexes;
  5408.         }),
  5409.         lt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5410.           var i = argument < 0 ? argument + length : argument;
  5411.           for (; --i >= 0;) {
  5412.             matchIndexes.push(i);
  5413.           }
  5414.           return matchIndexes;
  5415.         }),
  5416.         gt: createPositionalPseudo(function (matchIndexes, length, argument) {
  5417.           var i = argument < 0 ? argument + length : argument;
  5418.           for (; ++i < length;) {
  5419.             matchIndexes.push(i);
  5420.           }
  5421.           return matchIndexes;
  5422.         })
  5423.       }
  5424.     };
  5425.     Expr.pseudos.nth = Expr.pseudos.eq;
  5426.     each$k([
  5427.       'radio',
  5428.       'checkbox',
  5429.       'file',
  5430.       'password',
  5431.       'image'
  5432.     ], function (i) {
  5433.       Expr.pseudos[i] = createInputPseudo(i);
  5434.     });
  5435.     each$k([
  5436.       'submit',
  5437.       'reset'
  5438.     ], function (i) {
  5439.       Expr.pseudos[i] = createButtonPseudo(i);
  5440.     });
  5441.     function setFilters() {
  5442.     }
  5443.     setFilters.prototype = Expr.filters = Expr.pseudos;
  5444.     Expr.setFilters = new setFilters();
  5445.     tokenize = Sizzle.tokenize = function (selector, parseOnly) {
  5446.       var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + ' '];
  5447.       if (cached) {
  5448.         return parseOnly ? 0 : cached.slice(0);
  5449.       }
  5450.       soFar = selector;
  5451.       groups = [];
  5452.       preFilters = Expr.preFilter;
  5453.       while (soFar) {
  5454.         if (!matched || (match = rcomma.exec(soFar))) {
  5455.           if (match) {
  5456.             soFar = soFar.slice(match[0].length) || soFar;
  5457.           }
  5458.           groups.push(tokens = []);
  5459.         }
  5460.         matched = false;
  5461.         if (match = rcombinators.exec(soFar)) {
  5462.           matched = match.shift();
  5463.           tokens.push({
  5464.             value: matched,
  5465.             type: match[0].replace(rtrim, ' ')
  5466.           });
  5467.           soFar = soFar.slice(matched.length);
  5468.         }
  5469.         for (type in Expr.filter) {
  5470.           if (!Expr.filter.hasOwnProperty(type)) {
  5471.             continue;
  5472.           }
  5473.           if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
  5474.             matched = match.shift();
  5475.             tokens.push({
  5476.               value: matched,
  5477.               type: type,
  5478.               matches: match
  5479.             });
  5480.             soFar = soFar.slice(matched.length);
  5481.           }
  5482.         }
  5483.         if (!matched) {
  5484.           break;
  5485.         }
  5486.       }
  5487.       return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
  5488.     };
  5489.     function toSelector(tokens) {
  5490.       var i = 0, len = tokens.length, selector = '';
  5491.       for (; i < len; i++) {
  5492.         selector += tokens[i].value;
  5493.       }
  5494.       return selector;
  5495.     }
  5496.     function addCombinator(matcher, combinator, base) {
  5497.       var dir = combinator.dir, checkNonElements = base && dir === 'parentNode', doneName = done++;
  5498.       return combinator.first ? function (elem, context, xml) {
  5499.         while (elem = elem[dir]) {
  5500.           if (elem.nodeType === 1 || checkNonElements) {
  5501.             return matcher(elem, context, xml);
  5502.           }
  5503.         }
  5504.       } : function (elem, context, xml) {
  5505.         var oldCache, outerCache, newCache = [
  5506.             dirruns,
  5507.             doneName
  5508.           ];
  5509.         if (xml) {
  5510.           while (elem = elem[dir]) {
  5511.             if (elem.nodeType === 1 || checkNonElements) {
  5512.               if (matcher(elem, context, xml)) {
  5513.                 return true;
  5514.               }
  5515.             }
  5516.           }
  5517.         } else {
  5518.           while (elem = elem[dir]) {
  5519.             if (elem.nodeType === 1 || checkNonElements) {
  5520.               outerCache = elem[expando] || (elem[expando] = {});
  5521.               if ((oldCache = outerCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
  5522.                 return newCache[2] = oldCache[2];
  5523.               } else {
  5524.                 outerCache[dir] = newCache;
  5525.                 if (newCache[2] = matcher(elem, context, xml)) {
  5526.                   return true;
  5527.                 }
  5528.               }
  5529.             }
  5530.           }
  5531.         }
  5532.       };
  5533.     }
  5534.     function elementMatcher(matchers) {
  5535.       return matchers.length > 1 ? function (elem, context, xml) {
  5536.         var i = matchers.length;
  5537.         while (i--) {
  5538.           if (!matchers[i](elem, context, xml)) {
  5539.             return false;
  5540.           }
  5541.         }
  5542.         return true;
  5543.       } : matchers[0];
  5544.     }
  5545.     function multipleContexts(selector, contexts, results) {
  5546.       var i = 0, len = contexts.length;
  5547.       for (; i < len; i++) {
  5548.         Sizzle(selector, contexts[i], results);
  5549.       }
  5550.       return results;
  5551.     }
  5552.     function condense(unmatched, map, filter, context, xml) {
  5553.       var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null;
  5554.       for (; i < len; i++) {
  5555.         if (elem = unmatched[i]) {
  5556.           if (!filter || filter(elem, context, xml)) {
  5557.             newUnmatched.push(elem);
  5558.             if (mapped) {
  5559.               map.push(i);
  5560.             }
  5561.           }
  5562.         }
  5563.       }
  5564.       return newUnmatched;
  5565.     }
  5566.     function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
  5567.       if (postFilter && !postFilter[expando]) {
  5568.         postFilter = setMatcher(postFilter);
  5569.       }
  5570.       if (postFinder && !postFinder[expando]) {
  5571.         postFinder = setMatcher(postFinder, postSelector);
  5572.       }
  5573.       return markFunction(function (seed, results, context, xml) {
  5574.         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;
  5575.         if (matcher) {
  5576.           matcher(matcherIn, matcherOut, context, xml);
  5577.         }
  5578.         if (postFilter) {
  5579.           temp = condense(matcherOut, postMap);
  5580.           postFilter(temp, [], context, xml);
  5581.           i = temp.length;
  5582.           while (i--) {
  5583.             if (elem = temp[i]) {
  5584.               matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
  5585.             }
  5586.           }
  5587.         }
  5588.         if (seed) {
  5589.           if (postFinder || preFilter) {
  5590.             if (postFinder) {
  5591.               temp = [];
  5592.               i = matcherOut.length;
  5593.               while (i--) {
  5594.                 if (elem = matcherOut[i]) {
  5595.                   temp.push(matcherIn[i] = elem);
  5596.                 }
  5597.               }
  5598.               postFinder(null, matcherOut = [], temp, xml);
  5599.             }
  5600.             i = matcherOut.length;
  5601.             while (i--) {
  5602.               if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
  5603.                 seed[temp] = !(results[temp] = elem);
  5604.               }
  5605.             }
  5606.           }
  5607.         } else {
  5608.           matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
  5609.           if (postFinder) {
  5610.             postFinder(null, results, matcherOut, xml);
  5611.           } else {
  5612.             push$1.apply(results, matcherOut);
  5613.           }
  5614.         }
  5615.       });
  5616.     }
  5617.     function matcherFromTokens(tokens) {
  5618.       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) {
  5619.           return elem === checkContext;
  5620.         }, implicitRelative, true), matchAnyContext = addCombinator(function (elem) {
  5621.           return indexOf.call(checkContext, elem) > -1;
  5622.         }, implicitRelative, true), matchers = [function (elem, context, xml) {
  5623.             var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
  5624.             checkContext = null;
  5625.             return ret;
  5626.           }];
  5627.       for (; i < len; i++) {
  5628.         if (matcher = Expr.relative[tokens[i].type]) {
  5629.           matchers = [addCombinator(elementMatcher(matchers), matcher)];
  5630.         } else {
  5631.           matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
  5632.           if (matcher[expando]) {
  5633.             j = ++i;
  5634.             for (; j < len; j++) {
  5635.               if (Expr.relative[tokens[j].type]) {
  5636.                 break;
  5637.               }
  5638.             }
  5639.             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));
  5640.           }
  5641.           matchers.push(matcher);
  5642.         }
  5643.       }
  5644.       return elementMatcher(matchers);
  5645.     }
  5646.     function matcherFromGroupMatchers(elementMatchers, setMatchers) {
  5647.       var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function (seed, context, xml, results, outermost) {
  5648.           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;
  5649.           if (outermost) {
  5650.             outermostContext = context !== document$1 && context;
  5651.           }
  5652.           for (; i !== len && (elem = elems[i]) != null; i++) {
  5653.             if (byElement && elem) {
  5654.               j = 0;
  5655.               while (matcher = elementMatchers[j++]) {
  5656.                 if (matcher(elem, context, xml)) {
  5657.                   results.push(elem);
  5658.                   break;
  5659.                 }
  5660.               }
  5661.               if (outermost) {
  5662.                 dirruns = dirrunsUnique;
  5663.               }
  5664.             }
  5665.             if (bySet) {
  5666.               if (elem = !matcher && elem) {
  5667.                 matchedCount--;
  5668.               }
  5669.               if (seed) {
  5670.                 unmatched.push(elem);
  5671.               }
  5672.             }
  5673.           }
  5674.           matchedCount += i;
  5675.           if (bySet && i !== matchedCount) {
  5676.             j = 0;
  5677.             while (matcher = setMatchers[j++]) {
  5678.               matcher(unmatched, setMatched, context, xml);
  5679.             }
  5680.             if (seed) {
  5681.               if (matchedCount > 0) {
  5682.                 while (i--) {
  5683.                   if (!(unmatched[i] || setMatched[i])) {
  5684.                     setMatched[i] = pop.call(results);
  5685.                   }
  5686.                 }
  5687.               }
  5688.               setMatched = condense(setMatched);
  5689.             }
  5690.             push$1.apply(results, setMatched);
  5691.             if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
  5692.               Sizzle.uniqueSort(results);
  5693.             }
  5694.           }
  5695.           if (outermost) {
  5696.             dirruns = dirrunsUnique;
  5697.             outermostContext = contextBackup;
  5698.           }
  5699.           return unmatched;
  5700.         };
  5701.       return bySet ? markFunction(superMatcher) : superMatcher;
  5702.     }
  5703.     compile = Sizzle.compile = function (selector, match) {
  5704.       var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + ' '];
  5705.       if (!cached) {
  5706.         if (!match) {
  5707.           match = tokenize(selector);
  5708.         }
  5709.         i = match.length;
  5710.         while (i--) {
  5711.           cached = matcherFromTokens(match[i]);
  5712.           if (cached[expando]) {
  5713.             setMatchers.push(cached);
  5714.           } else {
  5715.             elementMatchers.push(cached);
  5716.           }
  5717.         }
  5718.         cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
  5719.         cached.selector = selector;
  5720.       }
  5721.       return cached;
  5722.     };
  5723.     select$1 = Sizzle.select = function (selector, context, results, seed) {
  5724.       var i, tokens, token, type, find, compiled = typeof selector === 'function' && selector, match = !seed && tokenize(selector = compiled.selector || selector);
  5725.       results = results || [];
  5726.       if (match.length === 1) {
  5727.         tokens = match[0] = match[0].slice(0);
  5728.         if (tokens.length > 2 && (token = tokens[0]).type === 'ID' && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
  5729.           context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0];
  5730.           if (!context) {
  5731.             return results;
  5732.           } else if (compiled) {
  5733.             context = context.parentNode;
  5734.           }
  5735.           selector = selector.slice(tokens.shift().value.length);
  5736.         }
  5737.         i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
  5738.         while (i--) {
  5739.           token = tokens[i];
  5740.           if (Expr.relative[type = token.type]) {
  5741.             break;
  5742.           }
  5743.           if (find = Expr.find[type]) {
  5744.             if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
  5745.               tokens.splice(i, 1);
  5746.               selector = seed.length && toSelector(tokens);
  5747.               if (!selector) {
  5748.                 push$1.apply(results, seed);
  5749.                 return results;
  5750.               }
  5751.               break;
  5752.             }
  5753.           }
  5754.         }
  5755.       }
  5756.       (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, rsibling.test(selector) && testContext(context.parentNode) || context);
  5757.       return results;
  5758.     };
  5759.     support.sortStable = expando.split('').sort(sortOrder).join('') === expando;
  5760.     support.detectDuplicates = !!hasDuplicate;
  5761.     setDocument();
  5762.     support.sortDetached = true;
  5763.  
  5764.     var doc = document;
  5765.     var push = Array.prototype.push;
  5766.     var slice = Array.prototype.slice;
  5767.     var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
  5768.     var Event$1 = EventUtils.Event;
  5769.     var skipUniques = Tools.makeMap('children,contents,next,prev');
  5770.     var isDefined = function (obj) {
  5771.       return typeof obj !== 'undefined';
  5772.     };
  5773.     var isString = function (obj) {
  5774.       return typeof obj === 'string';
  5775.     };
  5776.     var isWindow = function (obj) {
  5777.       return obj && obj === obj.window;
  5778.     };
  5779.     var createFragment$1 = function (html, fragDoc) {
  5780.       fragDoc = fragDoc || doc;
  5781.       var container = fragDoc.createElement('div');
  5782.       var frag = fragDoc.createDocumentFragment();
  5783.       container.innerHTML = html;
  5784.       var node;
  5785.       while (node = container.firstChild) {
  5786.         frag.appendChild(node);
  5787.       }
  5788.       return frag;
  5789.     };
  5790.     var domManipulate = function (targetNodes, sourceItem, callback, reverse) {
  5791.       var i;
  5792.       if (isString(sourceItem)) {
  5793.         sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
  5794.       } else if (sourceItem.length && !sourceItem.nodeType) {
  5795.         sourceItem = DomQuery.makeArray(sourceItem);
  5796.         if (reverse) {
  5797.           for (i = sourceItem.length - 1; i >= 0; i--) {
  5798.             domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5799.           }
  5800.         } else {
  5801.           for (i = 0; i < sourceItem.length; i++) {
  5802.             domManipulate(targetNodes, sourceItem[i], callback, reverse);
  5803.           }
  5804.         }
  5805.         return targetNodes;
  5806.       }
  5807.       if (sourceItem.nodeType) {
  5808.         i = targetNodes.length;
  5809.         while (i--) {
  5810.           callback.call(targetNodes[i], sourceItem);
  5811.         }
  5812.       }
  5813.       return targetNodes;
  5814.     };
  5815.     var hasClass = function (node, className) {
  5816.       return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1;
  5817.     };
  5818.     var wrap$2 = function (elements, wrapper, all) {
  5819.       var lastParent, newWrapper;
  5820.       wrapper = DomQuery(wrapper)[0];
  5821.       elements.each(function () {
  5822.         var self = this;
  5823.         if (!all || lastParent !== self.parentNode) {
  5824.           lastParent = self.parentNode;
  5825.           newWrapper = wrapper.cloneNode(false);
  5826.           self.parentNode.insertBefore(newWrapper, self);
  5827.           newWrapper.appendChild(self);
  5828.         } else {
  5829.           newWrapper.appendChild(self);
  5830.         }
  5831.       });
  5832.       return elements;
  5833.     };
  5834.     var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  5835.     var booleanMap = Tools.makeMap('checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected', ' ');
  5836.     var propFix = {
  5837.       for: 'htmlFor',
  5838.       class: 'className',
  5839.       readonly: 'readOnly'
  5840.     };
  5841.     var cssFix = { float: 'cssFloat' };
  5842.     var attrHooks = {}, cssHooks = {};
  5843.     var DomQueryConstructor = function (selector, context) {
  5844.       return new DomQuery.fn.init(selector, context);
  5845.     };
  5846.     var inArray$1 = function (item, array) {
  5847.       var i;
  5848.       if (array.indexOf) {
  5849.         return array.indexOf(item);
  5850.       }
  5851.       i = array.length;
  5852.       while (i--) {
  5853.         if (array[i] === item) {
  5854.           return i;
  5855.         }
  5856.       }
  5857.       return -1;
  5858.     };
  5859.     var whiteSpaceRegExp = /^\s*|\s*$/g;
  5860.     var trim$2 = function (str) {
  5861.       return str === null || str === undefined ? '' : ('' + str).replace(whiteSpaceRegExp, '');
  5862.     };
  5863.     var each$g = function (obj, callback) {
  5864.       var length, key, i, value;
  5865.       if (obj) {
  5866.         length = obj.length;
  5867.         if (length === undefined) {
  5868.           for (key in obj) {
  5869.             if (obj.hasOwnProperty(key)) {
  5870.               value = obj[key];
  5871.               if (callback.call(value, key, value) === false) {
  5872.                 break;
  5873.               }
  5874.             }
  5875.           }
  5876.         } else {
  5877.           for (i = 0; i < length; i++) {
  5878.             value = obj[i];
  5879.             if (callback.call(value, i, value) === false) {
  5880.               break;
  5881.             }
  5882.           }
  5883.         }
  5884.       }
  5885.       return obj;
  5886.     };
  5887.     var grep$2 = function (array, callback) {
  5888.       var out = [];
  5889.       each$g(array, function (i, item) {
  5890.         if (callback(item, i)) {
  5891.           out.push(item);
  5892.         }
  5893.       });
  5894.       return out;
  5895.     };
  5896.     var getElementDocument = function (element) {
  5897.       if (!element) {
  5898.         return doc;
  5899.       }
  5900.       if (element.nodeType === 9) {
  5901.         return element;
  5902.       }
  5903.       return element.ownerDocument;
  5904.     };
  5905.     DomQueryConstructor.fn = DomQueryConstructor.prototype = {
  5906.       constructor: DomQueryConstructor,
  5907.       selector: '',
  5908.       context: null,
  5909.       length: 0,
  5910.       init: function (selector, context) {
  5911.         var self = this;
  5912.         var match, node;
  5913.         if (!selector) {
  5914.           return self;
  5915.         }
  5916.         if (selector.nodeType) {
  5917.           self.context = self[0] = selector;
  5918.           self.length = 1;
  5919.           return self;
  5920.         }
  5921.         if (context && context.nodeType) {
  5922.           self.context = context;
  5923.         } else {
  5924.           if (context) {
  5925.             return DomQuery(selector).attr(context);
  5926.           }
  5927.           self.context = context = document;
  5928.         }
  5929.         if (isString(selector)) {
  5930.           self.selector = selector;
  5931.           if (selector.charAt(0) === '<' && selector.charAt(selector.length - 1) === '>' && selector.length >= 3) {
  5932.             match = [
  5933.               null,
  5934.               selector,
  5935.               null
  5936.             ];
  5937.           } else {
  5938.             match = rquickExpr.exec(selector);
  5939.           }
  5940.           if (match) {
  5941.             if (match[1]) {
  5942.               node = createFragment$1(selector, getElementDocument(context)).firstChild;
  5943.               while (node) {
  5944.                 push.call(self, node);
  5945.                 node = node.nextSibling;
  5946.               }
  5947.             } else {
  5948.               node = getElementDocument(context).getElementById(match[2]);
  5949.               if (!node) {
  5950.                 return self;
  5951.               }
  5952.               if (node.id !== match[2]) {
  5953.                 return self.find(selector);
  5954.               }
  5955.               self.length = 1;
  5956.               self[0] = node;
  5957.             }
  5958.           } else {
  5959.             return DomQuery(context).find(selector);
  5960.           }
  5961.         } else {
  5962.           this.add(selector, false);
  5963.         }
  5964.         return self;
  5965.       },
  5966.       toArray: function () {
  5967.         return Tools.toArray(this);
  5968.       },
  5969.       add: function (items, sort) {
  5970.         var self = this;
  5971.         var nodes, i;
  5972.         if (isString(items)) {
  5973.           return self.add(DomQuery(items));
  5974.         }
  5975.         if (sort !== false) {
  5976.           nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items)));
  5977.           self.length = nodes.length;
  5978.           for (i = 0; i < nodes.length; i++) {
  5979.             self[i] = nodes[i];
  5980.           }
  5981.         } else {
  5982.           push.apply(self, DomQuery.makeArray(items));
  5983.         }
  5984.         return self;
  5985.       },
  5986.       attr: function (name, value) {
  5987.         var self = this;
  5988.         var hook;
  5989.         if (typeof name === 'object') {
  5990.           each$g(name, function (name, value) {
  5991.             self.attr(name, value);
  5992.           });
  5993.         } else if (isDefined(value)) {
  5994.           this.each(function () {
  5995.             var hook;
  5996.             if (this.nodeType === 1) {
  5997.               hook = attrHooks[name];
  5998.               if (hook && hook.set) {
  5999.                 hook.set(this, value);
  6000.                 return;
  6001.               }
  6002.               if (value === null) {
  6003.                 this.removeAttribute(name, 2);
  6004.               } else {
  6005.                 this.setAttribute(name, value, 2);
  6006.               }
  6007.             }
  6008.           });
  6009.         } else {
  6010.           if (self[0] && self[0].nodeType === 1) {
  6011.             hook = attrHooks[name];
  6012.             if (hook && hook.get) {
  6013.               return hook.get(self[0], name);
  6014.             }
  6015.             if (booleanMap[name]) {
  6016.               return self.prop(name) ? name : undefined;
  6017.             }
  6018.             value = self[0].getAttribute(name, 2);
  6019.             if (value === null) {
  6020.               value = undefined;
  6021.             }
  6022.           }
  6023.           return value;
  6024.         }
  6025.         return self;
  6026.       },
  6027.       removeAttr: function (name) {
  6028.         return this.attr(name, null);
  6029.       },
  6030.       prop: function (name, value) {
  6031.         var self = this;
  6032.         name = propFix[name] || name;
  6033.         if (typeof name === 'object') {
  6034.           each$g(name, function (name, value) {
  6035.             self.prop(name, value);
  6036.           });
  6037.         } else if (isDefined(value)) {
  6038.           this.each(function () {
  6039.             if (this.nodeType === 1) {
  6040.               this[name] = value;
  6041.             }
  6042.           });
  6043.         } else {
  6044.           if (self[0] && self[0].nodeType && name in self[0]) {
  6045.             return self[0][name];
  6046.           }
  6047.           return value;
  6048.         }
  6049.         return self;
  6050.       },
  6051.       css: function (name, value) {
  6052.         var self = this;
  6053.         var elm, hook;
  6054.         var camel = function (name) {
  6055.           return name.replace(/-(\D)/g, function (a, b) {
  6056.             return b.toUpperCase();
  6057.           });
  6058.         };
  6059.         var dashed = function (name) {
  6060.           return name.replace(/[A-Z]/g, function (a) {
  6061.             return '-' + a;
  6062.           });
  6063.         };
  6064.         if (typeof name === 'object') {
  6065.           each$g(name, function (name, value) {
  6066.             self.css(name, value);
  6067.           });
  6068.         } else {
  6069.           if (isDefined(value)) {
  6070.             name = camel(name);
  6071.             if (typeof value === 'number' && !numericCssMap[name]) {
  6072.               value = value.toString() + 'px';
  6073.             }
  6074.             self.each(function () {
  6075.               var style = this.style;
  6076.               hook = cssHooks[name];
  6077.               if (hook && hook.set) {
  6078.                 hook.set(this, value);
  6079.                 return;
  6080.               }
  6081.               try {
  6082.                 this.style[cssFix[name] || name] = value;
  6083.               } catch (ex) {
  6084.               }
  6085.               if (value === null || value === '') {
  6086.                 if (style.removeProperty) {
  6087.                   style.removeProperty(dashed(name));
  6088.                 } else {
  6089.                   style.removeAttribute(name);
  6090.                 }
  6091.               }
  6092.             });
  6093.           } else {
  6094.             elm = self[0];
  6095.             hook = cssHooks[name];
  6096.             if (hook && hook.get) {
  6097.               return hook.get(elm);
  6098.             }
  6099.             if (elm.ownerDocument.defaultView) {
  6100.               try {
  6101.                 return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name));
  6102.               } catch (ex) {
  6103.                 return undefined;
  6104.               }
  6105.             } else if (elm.currentStyle) {
  6106.               return elm.currentStyle[camel(name)];
  6107.             } else {
  6108.               return '';
  6109.             }
  6110.           }
  6111.         }
  6112.         return self;
  6113.       },
  6114.       remove: function () {
  6115.         var self = this;
  6116.         var node, i = this.length;
  6117.         while (i--) {
  6118.           node = self[i];
  6119.           Event$1.clean(node);
  6120.           if (node.parentNode) {
  6121.             node.parentNode.removeChild(node);
  6122.           }
  6123.         }
  6124.         return this;
  6125.       },
  6126.       empty: function () {
  6127.         var self = this;
  6128.         var node, i = this.length;
  6129.         while (i--) {
  6130.           node = self[i];
  6131.           while (node.firstChild) {
  6132.             node.removeChild(node.firstChild);
  6133.           }
  6134.         }
  6135.         return this;
  6136.       },
  6137.       html: function (value) {
  6138.         var self = this;
  6139.         var i;
  6140.         if (isDefined(value)) {
  6141.           i = self.length;
  6142.           try {
  6143.             while (i--) {
  6144.               self[i].innerHTML = value;
  6145.             }
  6146.           } catch (ex) {
  6147.             DomQuery(self[i]).empty().append(value);
  6148.           }
  6149.           return self;
  6150.         }
  6151.         return self[0] ? self[0].innerHTML : '';
  6152.       },
  6153.       text: function (value) {
  6154.         var self = this;
  6155.         var i;
  6156.         if (isDefined(value)) {
  6157.           i = self.length;
  6158.           while (i--) {
  6159.             if ('innerText' in self[i]) {
  6160.               self[i].innerText = value;
  6161.             } else {
  6162.               self[0].textContent = value;
  6163.             }
  6164.           }
  6165.           return self;
  6166.         }
  6167.         return self[0] ? self[0].innerText || self[0].textContent : '';
  6168.       },
  6169.       append: function () {
  6170.         return domManipulate(this, arguments, function (node) {
  6171.           if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6172.             this.appendChild(node);
  6173.           }
  6174.         });
  6175.       },
  6176.       prepend: function () {
  6177.         return domManipulate(this, arguments, function (node) {
  6178.           if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
  6179.             this.insertBefore(node, this.firstChild);
  6180.           }
  6181.         }, true);
  6182.       },
  6183.       before: function () {
  6184.         var self = this;
  6185.         if (self[0] && self[0].parentNode) {
  6186.           return domManipulate(self, arguments, function (node) {
  6187.             this.parentNode.insertBefore(node, this);
  6188.           });
  6189.         }
  6190.         return self;
  6191.       },
  6192.       after: function () {
  6193.         var self = this;
  6194.         if (self[0] && self[0].parentNode) {
  6195.           return domManipulate(self, arguments, function (node) {
  6196.             this.parentNode.insertBefore(node, this.nextSibling);
  6197.           }, true);
  6198.         }
  6199.         return self;
  6200.       },
  6201.       appendTo: function (val) {
  6202.         DomQuery(val).append(this);
  6203.         return this;
  6204.       },
  6205.       prependTo: function (val) {
  6206.         DomQuery(val).prepend(this);
  6207.         return this;
  6208.       },
  6209.       replaceWith: function (content) {
  6210.         return this.before(content).remove();
  6211.       },
  6212.       wrap: function (content) {
  6213.         return wrap$2(this, content);
  6214.       },
  6215.       wrapAll: function (content) {
  6216.         return wrap$2(this, content, true);
  6217.       },
  6218.       wrapInner: function (content) {
  6219.         this.each(function () {
  6220.           DomQuery(this).contents().wrapAll(content);
  6221.         });
  6222.         return this;
  6223.       },
  6224.       unwrap: function () {
  6225.         return this.parent().each(function () {
  6226.           DomQuery(this).replaceWith(this.childNodes);
  6227.         });
  6228.       },
  6229.       clone: function () {
  6230.         var result = [];
  6231.         this.each(function () {
  6232.           result.push(this.cloneNode(true));
  6233.         });
  6234.         return DomQuery(result);
  6235.       },
  6236.       addClass: function (className) {
  6237.         return this.toggleClass(className, true);
  6238.       },
  6239.       removeClass: function (className) {
  6240.         return this.toggleClass(className, false);
  6241.       },
  6242.       toggleClass: function (className, state) {
  6243.         var self = this;
  6244.         if (typeof className !== 'string') {
  6245.           return self;
  6246.         }
  6247.         if (className.indexOf(' ') !== -1) {
  6248.           each$g(className.split(' '), function () {
  6249.             self.toggleClass(this, state);
  6250.           });
  6251.         } else {
  6252.           self.each(function (index, node) {
  6253.             var classState = hasClass(node, className);
  6254.             if (classState !== state) {
  6255.               var existingClassName = node.className;
  6256.               if (classState) {
  6257.                 node.className = trim$2((' ' + existingClassName + ' ').replace(' ' + className + ' ', ' '));
  6258.               } else {
  6259.                 node.className += existingClassName ? ' ' + className : className;
  6260.               }
  6261.             }
  6262.           });
  6263.         }
  6264.         return self;
  6265.       },
  6266.       hasClass: function (className) {
  6267.         return hasClass(this[0], className);
  6268.       },
  6269.       each: function (callback) {
  6270.         return each$g(this, callback);
  6271.       },
  6272.       on: function (name, callback) {
  6273.         return this.each(function () {
  6274.           Event$1.bind(this, name, callback);
  6275.         });
  6276.       },
  6277.       off: function (name, callback) {
  6278.         return this.each(function () {
  6279.           Event$1.unbind(this, name, callback);
  6280.         });
  6281.       },
  6282.       trigger: function (name) {
  6283.         return this.each(function () {
  6284.           if (typeof name === 'object') {
  6285.             Event$1.fire(this, name.type, name);
  6286.           } else {
  6287.             Event$1.fire(this, name);
  6288.           }
  6289.         });
  6290.       },
  6291.       show: function () {
  6292.         return this.css('display', '');
  6293.       },
  6294.       hide: function () {
  6295.         return this.css('display', 'none');
  6296.       },
  6297.       slice: function () {
  6298.         return DomQuery(slice.apply(this, arguments));
  6299.       },
  6300.       eq: function (index) {
  6301.         return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  6302.       },
  6303.       first: function () {
  6304.         return this.eq(0);
  6305.       },
  6306.       last: function () {
  6307.         return this.eq(-1);
  6308.       },
  6309.       find: function (selector) {
  6310.         var i, l;
  6311.         var ret = [];
  6312.         for (i = 0, l = this.length; i < l; i++) {
  6313.           DomQuery.find(selector, this[i], ret);
  6314.         }
  6315.         return DomQuery(ret);
  6316.       },
  6317.       filter: function (selector) {
  6318.         if (typeof selector === 'function') {
  6319.           return DomQuery(grep$2(this.toArray(), function (item, i) {
  6320.             return selector(i, item);
  6321.           }));
  6322.         }
  6323.         return DomQuery(DomQuery.filter(selector, this.toArray()));
  6324.       },
  6325.       closest: function (selector) {
  6326.         var result = [];
  6327.         if (selector instanceof DomQuery) {
  6328.           selector = selector[0];
  6329.         }
  6330.         this.each(function (i, node) {
  6331.           while (node) {
  6332.             if (typeof selector === 'string' && DomQuery(node).is(selector)) {
  6333.               result.push(node);
  6334.               break;
  6335.             } else if (node === selector) {
  6336.               result.push(node);
  6337.               break;
  6338.             }
  6339.             node = node.parentNode;
  6340.           }
  6341.         });
  6342.         return DomQuery(result);
  6343.       },
  6344.       offset: function (offset) {
  6345.         var elm, doc, docElm;
  6346.         var x = 0, y = 0, pos;
  6347.         if (!offset) {
  6348.           elm = this[0];
  6349.           if (elm) {
  6350.             doc = elm.ownerDocument;
  6351.             docElm = doc.documentElement;
  6352.             if (elm.getBoundingClientRect) {
  6353.               pos = elm.getBoundingClientRect();
  6354.               x = pos.left + (docElm.scrollLeft || doc.body.scrollLeft) - docElm.clientLeft;
  6355.               y = pos.top + (docElm.scrollTop || doc.body.scrollTop) - docElm.clientTop;
  6356.             }
  6357.           }
  6358.           return {
  6359.             left: x,
  6360.             top: y
  6361.           };
  6362.         }
  6363.         return this.css(offset);
  6364.       },
  6365.       push: push,
  6366.       sort: Array.prototype.sort,
  6367.       splice: Array.prototype.splice
  6368.     };
  6369.     Tools.extend(DomQueryConstructor, {
  6370.       extend: Tools.extend,
  6371.       makeArray: function (object) {
  6372.         if (isWindow(object) || object.nodeType) {
  6373.           return [object];
  6374.         }
  6375.         return Tools.toArray(object);
  6376.       },
  6377.       inArray: inArray$1,
  6378.       isArray: Tools.isArray,
  6379.       each: each$g,
  6380.       trim: trim$2,
  6381.       grep: grep$2,
  6382.       find: Sizzle,
  6383.       expr: Sizzle.selectors,
  6384.       unique: Sizzle.uniqueSort,
  6385.       text: Sizzle.getText,
  6386.       contains: Sizzle.contains,
  6387.       filter: function (expr, elems, not) {
  6388.         var i = elems.length;
  6389.         if (not) {
  6390.           expr = ':not(' + expr + ')';
  6391.         }
  6392.         while (i--) {
  6393.           if (elems[i].nodeType !== 1) {
  6394.             elems.splice(i, 1);
  6395.           }
  6396.         }
  6397.         if (elems.length === 1) {
  6398.           elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
  6399.         } else {
  6400.           elems = DomQuery.find.matches(expr, elems);
  6401.         }
  6402.         return elems;
  6403.       }
  6404.     });
  6405.     var dir = function (el, prop, until) {
  6406.       var matched = [];
  6407.       var cur = el[prop];
  6408.       if (typeof until !== 'string' && until instanceof DomQuery) {
  6409.         until = until[0];
  6410.       }
  6411.       while (cur && cur.nodeType !== 9) {
  6412.         if (until !== undefined) {
  6413.           if (cur === until) {
  6414.             break;
  6415.           }
  6416.           if (typeof until === 'string' && DomQuery(cur).is(until)) {
  6417.             break;
  6418.           }
  6419.         }
  6420.         if (cur.nodeType === 1) {
  6421.           matched.push(cur);
  6422.         }
  6423.         cur = cur[prop];
  6424.       }
  6425.       return matched;
  6426.     };
  6427.     var sibling$1 = function (node, siblingName, nodeType, until) {
  6428.       var result = [];
  6429.       if (until instanceof DomQuery) {
  6430.         until = until[0];
  6431.       }
  6432.       for (; node; node = node[siblingName]) {
  6433.         if (nodeType && node.nodeType !== nodeType) {
  6434.           continue;
  6435.         }
  6436.         if (until !== undefined) {
  6437.           if (node === until) {
  6438.             break;
  6439.           }
  6440.           if (typeof until === 'string' && DomQuery(node).is(until)) {
  6441.             break;
  6442.           }
  6443.         }
  6444.         result.push(node);
  6445.       }
  6446.       return result;
  6447.     };
  6448.     var firstSibling = function (node, siblingName, nodeType) {
  6449.       for (node = node[siblingName]; node; node = node[siblingName]) {
  6450.         if (node.nodeType === nodeType) {
  6451.           return node;
  6452.         }
  6453.       }
  6454.       return null;
  6455.     };
  6456.     each$g({
  6457.       parent: function (node) {
  6458.         var parent = node.parentNode;
  6459.         return parent && parent.nodeType !== 11 ? parent : null;
  6460.       },
  6461.       parents: function (node) {
  6462.         return dir(node, 'parentNode');
  6463.       },
  6464.       next: function (node) {
  6465.         return firstSibling(node, 'nextSibling', 1);
  6466.       },
  6467.       prev: function (node) {
  6468.         return firstSibling(node, 'previousSibling', 1);
  6469.       },
  6470.       children: function (node) {
  6471.         return sibling$1(node.firstChild, 'nextSibling', 1);
  6472.       },
  6473.       contents: function (node) {
  6474.         return Tools.toArray((node.nodeName === 'iframe' ? node.contentDocument || node.contentWindow.document : node).childNodes);
  6475.       }
  6476.     }, function (name, fn) {
  6477.       DomQueryConstructor.fn[name] = function (selector) {
  6478.         var self = this;
  6479.         var result = [];
  6480.         self.each(function () {
  6481.           var nodes = fn.call(result, this, selector, result);
  6482.           if (nodes) {
  6483.             if (DomQuery.isArray(nodes)) {
  6484.               result.push.apply(result, nodes);
  6485.             } else {
  6486.               result.push(nodes);
  6487.             }
  6488.           }
  6489.         });
  6490.         if (this.length > 1) {
  6491.           if (!skipUniques[name]) {
  6492.             result = DomQuery.unique(result);
  6493.           }
  6494.           if (name.indexOf('parents') === 0) {
  6495.             result = result.reverse();
  6496.           }
  6497.         }
  6498.         var wrappedResult = DomQuery(result);
  6499.         if (selector) {
  6500.           return wrappedResult.filter(selector);
  6501.         }
  6502.         return wrappedResult;
  6503.       };
  6504.     });
  6505.     each$g({
  6506.       parentsUntil: function (node, until) {
  6507.         return dir(node, 'parentNode', until);
  6508.       },
  6509.       nextUntil: function (node, until) {
  6510.         return sibling$1(node, 'nextSibling', 1, until).slice(1);
  6511.       },
  6512.       prevUntil: function (node, until) {
  6513.         return sibling$1(node, 'previousSibling', 1, until).slice(1);
  6514.       }
  6515.     }, function (name, fn) {
  6516.       DomQueryConstructor.fn[name] = function (selector, filter) {
  6517.         var self = this;
  6518.         var result = [];
  6519.         self.each(function () {
  6520.           var nodes = fn.call(result, this, selector, result);
  6521.           if (nodes) {
  6522.             if (DomQuery.isArray(nodes)) {
  6523.               result.push.apply(result, nodes);
  6524.             } else {
  6525.               result.push(nodes);
  6526.             }
  6527.           }
  6528.         });
  6529.         if (this.length > 1) {
  6530.           result = DomQuery.unique(result);
  6531.           if (name.indexOf('parents') === 0 || name === 'prevUntil') {
  6532.             result = result.reverse();
  6533.           }
  6534.         }
  6535.         var wrappedResult = DomQuery(result);
  6536.         if (filter) {
  6537.           return wrappedResult.filter(filter);
  6538.         }
  6539.         return wrappedResult;
  6540.       };
  6541.     });
  6542.     DomQueryConstructor.fn.is = function (selector) {
  6543.       return !!selector && this.filter(selector).length > 0;
  6544.     };
  6545.     DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
  6546.     DomQueryConstructor.overrideDefaults = function (callback) {
  6547.       var defaults;
  6548.       var sub = function (selector, context) {
  6549.         defaults = defaults || callback();
  6550.         if (arguments.length === 0) {
  6551.           selector = defaults.element;
  6552.         }
  6553.         if (!context) {
  6554.           context = defaults.context;
  6555.         }
  6556.         return new sub.fn.init(selector, context);
  6557.       };
  6558.       DomQuery.extend(sub, this);
  6559.       return sub;
  6560.     };
  6561.     DomQueryConstructor.attrHooks = attrHooks;
  6562.     DomQueryConstructor.cssHooks = cssHooks;
  6563.     var DomQuery = DomQueryConstructor;
  6564.  
  6565.     var each$f = Tools.each;
  6566.     var grep$1 = Tools.grep;
  6567.     var isIE = Env.ie;
  6568.     var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  6569.     var setupAttrHooks = function (styles, settings, getContext) {
  6570.       var keepValues = settings.keep_values;
  6571.       var keepUrlHook = {
  6572.         set: function ($elm, value, name) {
  6573.           if (settings.url_converter && value !== null) {
  6574.             value = settings.url_converter.call(settings.url_converter_scope || getContext(), value, name, $elm[0]);
  6575.           }
  6576.           $elm.attr('data-mce-' + name, value).attr(name, value);
  6577.         },
  6578.         get: function ($elm, name) {
  6579.           return $elm.attr('data-mce-' + name) || $elm.attr(name);
  6580.         }
  6581.       };
  6582.       var attrHooks = {
  6583.         style: {
  6584.           set: function ($elm, value) {
  6585.             if (value !== null && typeof value === 'object') {
  6586.               $elm.css(value);
  6587.               return;
  6588.             }
  6589.             if (keepValues) {
  6590.               $elm.attr('data-mce-style', value);
  6591.             }
  6592.             if (value !== null && typeof value === 'string') {
  6593.               $elm.removeAttr('style');
  6594.               $elm.css(styles.parse(value));
  6595.             } else {
  6596.               $elm.attr('style', value);
  6597.             }
  6598.           },
  6599.           get: function ($elm) {
  6600.             var value = $elm.attr('data-mce-style') || $elm.attr('style');
  6601.             value = styles.serialize(styles.parse(value), $elm[0].nodeName);
  6602.             return value;
  6603.           }
  6604.         }
  6605.       };
  6606.       if (keepValues) {
  6607.         attrHooks.href = attrHooks.src = keepUrlHook;
  6608.       }
  6609.       return attrHooks;
  6610.     };
  6611.     var updateInternalStyleAttr = function (styles, $elm) {
  6612.       var rawValue = $elm.attr('style');
  6613.       var value = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
  6614.       if (!value) {
  6615.         value = null;
  6616.       }
  6617.       $elm.attr('data-mce-style', value);
  6618.     };
  6619.     var findNodeIndex = function (node, normalized) {
  6620.       var idx = 0, lastNodeType, nodeType;
  6621.       if (node) {
  6622.         for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  6623.           nodeType = node.nodeType;
  6624.           if (normalized && nodeType === 3) {
  6625.             if (nodeType === lastNodeType || !node.nodeValue.length) {
  6626.               continue;
  6627.             }
  6628.           }
  6629.           idx++;
  6630.           lastNodeType = nodeType;
  6631.         }
  6632.       }
  6633.       return idx;
  6634.     };
  6635.     var DOMUtils = function (doc, settings) {
  6636.       if (settings === void 0) {
  6637.         settings = {};
  6638.       }
  6639.       var addedStyles = {};
  6640.       var win = window;
  6641.       var files = {};
  6642.       var counter = 0;
  6643.       var stdMode = true;
  6644.       var boxModel = true;
  6645.       var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc), {
  6646.         contentCssCors: settings.contentCssCors,
  6647.         referrerPolicy: settings.referrerPolicy
  6648.       });
  6649.       var boundEvents = [];
  6650.       var schema = settings.schema ? settings.schema : Schema({});
  6651.       var styles = Styles({
  6652.         url_converter: settings.url_converter,
  6653.         url_converter_scope: settings.url_converter_scope
  6654.       }, settings.schema);
  6655.       var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
  6656.       var blockElementsMap = schema.getBlockElements();
  6657.       var $ = DomQuery.overrideDefaults(function () {
  6658.         return {
  6659.           context: doc,
  6660.           element: self.getRoot()
  6661.         };
  6662.       });
  6663.       var isBlock = function (node) {
  6664.         if (typeof node === 'string') {
  6665.           return !!blockElementsMap[node];
  6666.         } else if (node) {
  6667.           var type = node.nodeType;
  6668.           if (type) {
  6669.             return !!(type === 1 && blockElementsMap[node.nodeName]);
  6670.           }
  6671.         }
  6672.         return false;
  6673.       };
  6674.       var get = function (elm) {
  6675.         return elm && doc && isString$1(elm) ? doc.getElementById(elm) : elm;
  6676.       };
  6677.       var $$ = function (elm) {
  6678.         return $(typeof elm === 'string' ? get(elm) : elm);
  6679.       };
  6680.       var getAttrib = function (elm, name, defaultVal) {
  6681.         var hook, value;
  6682.         var $elm = $$(elm);
  6683.         if ($elm.length) {
  6684.           hook = attrHooks[name];
  6685.           if (hook && hook.get) {
  6686.             value = hook.get($elm, name);
  6687.           } else {
  6688.             value = $elm.attr(name);
  6689.           }
  6690.         }
  6691.         if (typeof value === 'undefined') {
  6692.           value = defaultVal || '';
  6693.         }
  6694.         return value;
  6695.       };
  6696.       var getAttribs = function (elm) {
  6697.         var node = get(elm);
  6698.         if (!node) {
  6699.           return [];
  6700.         }
  6701.         return node.attributes;
  6702.       };
  6703.       var setAttrib = function (elm, name, value) {
  6704.         if (value === '') {
  6705.           value = null;
  6706.         }
  6707.         var $elm = $$(elm);
  6708.         var originalValue = $elm.attr(name);
  6709.         if (!$elm.length) {
  6710.           return;
  6711.         }
  6712.         var hook = attrHooks[name];
  6713.         if (hook && hook.set) {
  6714.           hook.set($elm, value, name);
  6715.         } else {
  6716.           $elm.attr(name, value);
  6717.         }
  6718.         if (originalValue !== value && settings.onSetAttrib) {
  6719.           settings.onSetAttrib({
  6720.             attrElm: $elm,
  6721.             attrName: name,
  6722.             attrValue: value
  6723.           });
  6724.         }
  6725.       };
  6726.       var clone = function (node, deep) {
  6727.         if (!isIE || node.nodeType !== 1 || deep) {
  6728.           return node.cloneNode(deep);
  6729.         } else {
  6730.           var clone_1 = doc.createElement(node.nodeName);
  6731.           each$f(getAttribs(node), function (attr) {
  6732.             setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
  6733.           });
  6734.           return clone_1;
  6735.         }
  6736.       };
  6737.       var getRoot = function () {
  6738.         return settings.root_element || doc.body;
  6739.       };
  6740.       var getViewPort = function (argWin) {
  6741.         var vp = getBounds(argWin);
  6742.         return {
  6743.           x: vp.x,
  6744.           y: vp.y,
  6745.           w: vp.width,
  6746.           h: vp.height
  6747.         };
  6748.       };
  6749.       var getPos$1 = function (elm, rootElm) {
  6750.         return getPos(doc.body, get(elm), rootElm);
  6751.       };
  6752.       var setStyle = function (elm, name, value) {
  6753.         var $elm = isString$1(name) ? $$(elm).css(name, value) : $$(elm).css(name);
  6754.         if (settings.update_styles) {
  6755.           updateInternalStyleAttr(styles, $elm);
  6756.         }
  6757.       };
  6758.       var setStyles = function (elm, stylesArg) {
  6759.         var $elm = $$(elm).css(stylesArg);
  6760.         if (settings.update_styles) {
  6761.           updateInternalStyleAttr(styles, $elm);
  6762.         }
  6763.       };
  6764.       var getStyle = function (elm, name, computed) {
  6765.         var $elm = $$(elm);
  6766.         if (computed) {
  6767.           return $elm.css(name);
  6768.         }
  6769.         name = name.replace(/-(\D)/g, function (a, b) {
  6770.           return b.toUpperCase();
  6771.         });
  6772.         if (name === 'float') {
  6773.           name = Env.browser.isIE() ? 'styleFloat' : 'cssFloat';
  6774.         }
  6775.         return $elm[0] && $elm[0].style ? $elm[0].style[name] : undefined;
  6776.       };
  6777.       var getSize = function (elm) {
  6778.         var w, h;
  6779.         elm = get(elm);
  6780.         w = getStyle(elm, 'width');
  6781.         h = getStyle(elm, 'height');
  6782.         if (w.indexOf('px') === -1) {
  6783.           w = 0;
  6784.         }
  6785.         if (h.indexOf('px') === -1) {
  6786.           h = 0;
  6787.         }
  6788.         return {
  6789.           w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  6790.           h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  6791.         };
  6792.       };
  6793.       var getRect = function (elm) {
  6794.         elm = get(elm);
  6795.         var pos = getPos$1(elm);
  6796.         var size = getSize(elm);
  6797.         return {
  6798.           x: pos.x,
  6799.           y: pos.y,
  6800.           w: size.w,
  6801.           h: size.h
  6802.         };
  6803.       };
  6804.       var is = function (elm, selector) {
  6805.         var i;
  6806.         if (!elm) {
  6807.           return false;
  6808.         }
  6809.         if (!Array.isArray(elm)) {
  6810.           if (selector === '*') {
  6811.             return elm.nodeType === 1;
  6812.           }
  6813.           if (simpleSelectorRe.test(selector)) {
  6814.             var selectors = selector.toLowerCase().split(/,/);
  6815.             var elmName = elm.nodeName.toLowerCase();
  6816.             for (i = selectors.length - 1; i >= 0; i--) {
  6817.               if (selectors[i] === elmName) {
  6818.                 return true;
  6819.               }
  6820.             }
  6821.             return false;
  6822.           }
  6823.           if (elm.nodeType && elm.nodeType !== 1) {
  6824.             return false;
  6825.           }
  6826.         }
  6827.         var elms = !Array.isArray(elm) ? [elm] : elm;
  6828.         return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  6829.       };
  6830.       var getParents = function (elm, selector, root, collect) {
  6831.         var result = [];
  6832.         var selectorVal;
  6833.         var node = get(elm);
  6834.         collect = collect === undefined;
  6835.         root = root || (getRoot().nodeName !== 'BODY' ? getRoot().parentNode : null);
  6836.         if (Tools.is(selector, 'string')) {
  6837.           selectorVal = selector;
  6838.           if (selector === '*') {
  6839.             selector = function (node) {
  6840.               return node.nodeType === 1;
  6841.             };
  6842.           } else {
  6843.             selector = function (node) {
  6844.               return is(node, selectorVal);
  6845.             };
  6846.           }
  6847.         }
  6848.         while (node) {
  6849.           if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
  6850.             break;
  6851.           }
  6852.           if (!selector || typeof selector === 'function' && selector(node)) {
  6853.             if (collect) {
  6854.               result.push(node);
  6855.             } else {
  6856.               return [node];
  6857.             }
  6858.           }
  6859.           node = node.parentNode;
  6860.         }
  6861.         return collect ? result : null;
  6862.       };
  6863.       var getParent = function (node, selector, root) {
  6864.         var parents = getParents(node, selector, root, false);
  6865.         return parents && parents.length > 0 ? parents[0] : null;
  6866.       };
  6867.       var _findSib = function (node, selector, name) {
  6868.         var func = selector;
  6869.         if (node) {
  6870.           if (typeof selector === 'string') {
  6871.             func = function (node) {
  6872.               return is(node, selector);
  6873.             };
  6874.           }
  6875.           for (node = node[name]; node; node = node[name]) {
  6876.             if (typeof func === 'function' && func(node)) {
  6877.               return node;
  6878.             }
  6879.           }
  6880.         }
  6881.         return null;
  6882.       };
  6883.       var getNext = function (node, selector) {
  6884.         return _findSib(node, selector, 'nextSibling');
  6885.       };
  6886.       var getPrev = function (node, selector) {
  6887.         return _findSib(node, selector, 'previousSibling');
  6888.       };
  6889.       var select = function (selector, scope) {
  6890.         return Sizzle(selector, get(scope) || settings.root_element || doc, []);
  6891.       };
  6892.       var run = function (elm, func, scope) {
  6893.         var result;
  6894.         var node = typeof elm === 'string' ? get(elm) : elm;
  6895.         if (!node) {
  6896.           return false;
  6897.         }
  6898.         if (Tools.isArray(node) && (node.length || node.length === 0)) {
  6899.           result = [];
  6900.           each$f(node, function (elm, i) {
  6901.             if (elm) {
  6902.               result.push(func.call(scope, typeof elm === 'string' ? get(elm) : elm, i));
  6903.             }
  6904.           });
  6905.           return result;
  6906.         }
  6907.         var context = scope ? scope : this;
  6908.         return func.call(context, node);
  6909.       };
  6910.       var setAttribs = function (elm, attrs) {
  6911.         $$(elm).each(function (i, node) {
  6912.           each$f(attrs, function (value, name) {
  6913.             setAttrib(node, name, value);
  6914.           });
  6915.         });
  6916.       };
  6917.       var setHTML = function (elm, html) {
  6918.         var $elm = $$(elm);
  6919.         if (isIE) {
  6920.           $elm.each(function (i, target) {
  6921.             if (target.canHaveHTML === false) {
  6922.               return;
  6923.             }
  6924.             while (target.firstChild) {
  6925.               target.removeChild(target.firstChild);
  6926.             }
  6927.             try {
  6928.               target.innerHTML = '<br>' + html;
  6929.               target.removeChild(target.firstChild);
  6930.             } catch (ex) {
  6931.               DomQuery('<div></div>').html('<br>' + html).contents().slice(1).appendTo(target);
  6932.             }
  6933.             return html;
  6934.           });
  6935.         } else {
  6936.           $elm.html(html);
  6937.         }
  6938.       };
  6939.       var add = function (parentElm, name, attrs, html, create) {
  6940.         return run(parentElm, function (parentElm) {
  6941.           var newElm = typeof name === 'string' ? doc.createElement(name) : name;
  6942.           setAttribs(newElm, attrs);
  6943.           if (html) {
  6944.             if (typeof html !== 'string' && html.nodeType) {
  6945.               newElm.appendChild(html);
  6946.             } else if (typeof html === 'string') {
  6947.               setHTML(newElm, html);
  6948.             }
  6949.           }
  6950.           return !create ? parentElm.appendChild(newElm) : newElm;
  6951.         });
  6952.       };
  6953.       var create = function (name, attrs, html) {
  6954.         return add(doc.createElement(name), name, attrs, html, true);
  6955.       };
  6956.       var decode = Entities.decode;
  6957.       var encode = Entities.encodeAllRaw;
  6958.       var createHTML = function (name, attrs, html) {
  6959.         var outHtml = '', key;
  6960.         outHtml += '<' + name;
  6961.         for (key in attrs) {
  6962.           if (hasNonNullableKey(attrs, key)) {
  6963.             outHtml += ' ' + key + '="' + encode(attrs[key]) + '"';
  6964.           }
  6965.         }
  6966.         if (typeof html !== 'undefined') {
  6967.           return outHtml + '>' + html + '</' + name + '>';
  6968.         }
  6969.         return outHtml + ' />';
  6970.       };
  6971.       var createFragment = function (html) {
  6972.         var node;
  6973.         var container = doc.createElement('div');
  6974.         var frag = doc.createDocumentFragment();
  6975.         frag.appendChild(container);
  6976.         if (html) {
  6977.           container.innerHTML = html;
  6978.         }
  6979.         while (node = container.firstChild) {
  6980.           frag.appendChild(node);
  6981.         }
  6982.         frag.removeChild(container);
  6983.         return frag;
  6984.       };
  6985.       var remove = function (node, keepChildren) {
  6986.         var $node = $$(node);
  6987.         if (keepChildren) {
  6988.           $node.each(function () {
  6989.             var child;
  6990.             while (child = this.firstChild) {
  6991.               if (child.nodeType === 3 && child.data.length === 0) {
  6992.                 this.removeChild(child);
  6993.               } else {
  6994.                 this.parentNode.insertBefore(child, this);
  6995.               }
  6996.             }
  6997.           }).remove();
  6998.         } else {
  6999.           $node.remove();
  7000.         }
  7001.         return $node.length > 1 ? $node.toArray() : $node[0];
  7002.       };
  7003.       var removeAllAttribs = function (e) {
  7004.         return run(e, function (e) {
  7005.           var i;
  7006.           var attrs = e.attributes;
  7007.           for (i = attrs.length - 1; i >= 0; i--) {
  7008.             e.removeAttributeNode(attrs.item(i));
  7009.           }
  7010.         });
  7011.       };
  7012.       var parseStyle = function (cssText) {
  7013.         return styles.parse(cssText);
  7014.       };
  7015.       var serializeStyle = function (stylesArg, name) {
  7016.         return styles.serialize(stylesArg, name);
  7017.       };
  7018.       var addStyle = function (cssText) {
  7019.         var head, styleElm;
  7020.         if (self !== DOMUtils.DOM && doc === document) {
  7021.           if (addedStyles[cssText]) {
  7022.             return;
  7023.           }
  7024.           addedStyles[cssText] = true;
  7025.         }
  7026.         styleElm = doc.getElementById('mceDefaultStyles');
  7027.         if (!styleElm) {
  7028.           styleElm = doc.createElement('style');
  7029.           styleElm.id = 'mceDefaultStyles';
  7030.           styleElm.type = 'text/css';
  7031.           head = doc.getElementsByTagName('head')[0];
  7032.           if (head.firstChild) {
  7033.             head.insertBefore(styleElm, head.firstChild);
  7034.           } else {
  7035.             head.appendChild(styleElm);
  7036.           }
  7037.         }
  7038.         if (styleElm.styleSheet) {
  7039.           styleElm.styleSheet.cssText += cssText;
  7040.         } else {
  7041.           styleElm.appendChild(doc.createTextNode(cssText));
  7042.         }
  7043.       };
  7044.       var loadCSS = function (urls) {
  7045.         if (!urls) {
  7046.           urls = '';
  7047.         }
  7048.         each$k(urls.split(','), function (url) {
  7049.           files[url] = true;
  7050.           styleSheetLoader.load(url, noop);
  7051.         });
  7052.       };
  7053.       var toggleClass = function (elm, cls, state) {
  7054.         $$(elm).toggleClass(cls, state).each(function () {
  7055.           if (this.className === '') {
  7056.             DomQuery(this).attr('class', null);
  7057.           }
  7058.         });
  7059.       };
  7060.       var addClass = function (elm, cls) {
  7061.         $$(elm).addClass(cls);
  7062.       };
  7063.       var removeClass = function (elm, cls) {
  7064.         toggleClass(elm, cls, false);
  7065.       };
  7066.       var hasClass = function (elm, cls) {
  7067.         return $$(elm).hasClass(cls);
  7068.       };
  7069.       var show = function (elm) {
  7070.         $$(elm).show();
  7071.       };
  7072.       var hide = function (elm) {
  7073.         $$(elm).hide();
  7074.       };
  7075.       var isHidden = function (elm) {
  7076.         return $$(elm).css('display') === 'none';
  7077.       };
  7078.       var uniqueId = function (prefix) {
  7079.         return (!prefix ? 'mce_' : prefix) + counter++;
  7080.       };
  7081.       var getOuterHTML = function (elm) {
  7082.         var node = typeof elm === 'string' ? get(elm) : elm;
  7083.         return isElement$5(node) ? node.outerHTML : DomQuery('<div></div>').append(DomQuery(node).clone()).html();
  7084.       };
  7085.       var setOuterHTML = function (elm, html) {
  7086.         $$(elm).each(function () {
  7087.           try {
  7088.             if ('outerHTML' in this) {
  7089.               this.outerHTML = html;
  7090.               return;
  7091.             }
  7092.           } catch (ex) {
  7093.           }
  7094.           remove(DomQuery(this).html(html), true);
  7095.         });
  7096.       };
  7097.       var insertAfter = function (node, reference) {
  7098.         var referenceNode = get(reference);
  7099.         return run(node, function (node) {
  7100.           var parent = referenceNode.parentNode;
  7101.           var nextSibling = referenceNode.nextSibling;
  7102.           if (nextSibling) {
  7103.             parent.insertBefore(node, nextSibling);
  7104.           } else {
  7105.             parent.appendChild(node);
  7106.           }
  7107.           return node;
  7108.         });
  7109.       };
  7110.       var replace = function (newElm, oldElm, keepChildren) {
  7111.         return run(oldElm, function (oldElm) {
  7112.           if (Tools.is(oldElm, 'array')) {
  7113.             newElm = newElm.cloneNode(true);
  7114.           }
  7115.           if (keepChildren) {
  7116.             each$f(grep$1(oldElm.childNodes), function (node) {
  7117.               newElm.appendChild(node);
  7118.             });
  7119.           }
  7120.           return oldElm.parentNode.replaceChild(newElm, oldElm);
  7121.         });
  7122.       };
  7123.       var rename = function (elm, name) {
  7124.         var newElm;
  7125.         if (elm.nodeName !== name.toUpperCase()) {
  7126.           newElm = create(name);
  7127.           each$f(getAttribs(elm), function (attrNode) {
  7128.             setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
  7129.           });
  7130.           replace(newElm, elm, true);
  7131.         }
  7132.         return newElm || elm;
  7133.       };
  7134.       var findCommonAncestor = function (a, b) {
  7135.         var ps = a, pe;
  7136.         while (ps) {
  7137.           pe = b;
  7138.           while (pe && ps !== pe) {
  7139.             pe = pe.parentNode;
  7140.           }
  7141.           if (ps === pe) {
  7142.             break;
  7143.           }
  7144.           ps = ps.parentNode;
  7145.         }
  7146.         if (!ps && a.ownerDocument) {
  7147.           return a.ownerDocument.documentElement;
  7148.         }
  7149.         return ps;
  7150.       };
  7151.       var toHex = function (rgbVal) {
  7152.         return styles.toHex(Tools.trim(rgbVal));
  7153.       };
  7154.       var isNonEmptyElement = function (node) {
  7155.         if (isElement$5(node)) {
  7156.           var isNamedAnchor = node.nodeName.toLowerCase() === 'a' && !getAttrib(node, 'href') && getAttrib(node, 'id');
  7157.           if (getAttrib(node, 'name') || getAttrib(node, 'data-mce-bookmark') || isNamedAnchor) {
  7158.             return true;
  7159.           }
  7160.         }
  7161.         return false;
  7162.       };
  7163.       var isEmpty = function (node, elements) {
  7164.         var type, name, brCount = 0;
  7165.         if (isNonEmptyElement(node)) {
  7166.           return false;
  7167.         }
  7168.         node = node.firstChild;
  7169.         if (node) {
  7170.           var walker = new DomTreeWalker(node, node.parentNode);
  7171.           var whitespace = schema ? schema.getWhiteSpaceElements() : {};
  7172.           elements = elements || (schema ? schema.getNonEmptyElements() : null);
  7173.           do {
  7174.             type = node.nodeType;
  7175.             if (isElement$5(node)) {
  7176.               var bogusVal = node.getAttribute('data-mce-bogus');
  7177.               if (bogusVal) {
  7178.                 node = walker.next(bogusVal === 'all');
  7179.                 continue;
  7180.               }
  7181.               name = node.nodeName.toLowerCase();
  7182.               if (elements && elements[name]) {
  7183.                 if (name === 'br') {
  7184.                   brCount++;
  7185.                   node = walker.next();
  7186.                   continue;
  7187.                 }
  7188.                 return false;
  7189.               }
  7190.               if (isNonEmptyElement(node)) {
  7191.                 return false;
  7192.               }
  7193.             }
  7194.             if (type === 8) {
  7195.               return false;
  7196.             }
  7197.             if (type === 3 && !isWhitespaceText(node.nodeValue)) {
  7198.               return false;
  7199.             }
  7200.             if (type === 3 && node.parentNode && whitespace[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
  7201.               return false;
  7202.             }
  7203.             node = walker.next();
  7204.           } while (node);
  7205.         }
  7206.         return brCount <= 1;
  7207.       };
  7208.       var createRng = function () {
  7209.         return doc.createRange();
  7210.       };
  7211.       var split = function (parentElm, splitElm, replacementElm) {
  7212.         var range = createRng();
  7213.         var beforeFragment;
  7214.         var afterFragment;
  7215.         var parentNode;
  7216.         if (parentElm && splitElm) {
  7217.           range.setStart(parentElm.parentNode, findNodeIndex(parentElm));
  7218.           range.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
  7219.           beforeFragment = range.extractContents();
  7220.           range = createRng();
  7221.           range.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
  7222.           range.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
  7223.           afterFragment = range.extractContents();
  7224.           parentNode = parentElm.parentNode;
  7225.           parentNode.insertBefore(trimNode(self, beforeFragment), parentElm);
  7226.           if (replacementElm) {
  7227.             parentNode.insertBefore(replacementElm, parentElm);
  7228.           } else {
  7229.             parentNode.insertBefore(splitElm, parentElm);
  7230.           }
  7231.           parentNode.insertBefore(trimNode(self, afterFragment), parentElm);
  7232.           remove(parentElm);
  7233.           return replacementElm || splitElm;
  7234.         }
  7235.       };
  7236.       var bind = function (target, name, func, scope) {
  7237.         if (Tools.isArray(target)) {
  7238.           var i = target.length;
  7239.           var rv = [];
  7240.           while (i--) {
  7241.             rv[i] = bind(target[i], name, func, scope);
  7242.           }
  7243.           return rv;
  7244.         }
  7245.         if (settings.collect && (target === doc || target === win)) {
  7246.           boundEvents.push([
  7247.             target,
  7248.             name,
  7249.             func,
  7250.             scope
  7251.           ]);
  7252.         }
  7253.         var output = events.bind(target, name, func, scope || self);
  7254.         return output;
  7255.       };
  7256.       var unbind = function (target, name, func) {
  7257.         if (Tools.isArray(target)) {
  7258.           var i = target.length;
  7259.           var rv = [];
  7260.           while (i--) {
  7261.             rv[i] = unbind(target[i], name, func);
  7262.           }
  7263.           return rv;
  7264.         } else {
  7265.           if (boundEvents.length > 0 && (target === doc || target === win)) {
  7266.             var i = boundEvents.length;
  7267.             while (i--) {
  7268.               var item = boundEvents[i];
  7269.               if (target === item[0] && (!name || name === item[1]) && (!func || func === item[2])) {
  7270.                 events.unbind(item[0], item[1], item[2]);
  7271.               }
  7272.             }
  7273.           }
  7274.           return events.unbind(target, name, func);
  7275.         }
  7276.       };
  7277.       var fire = function (target, name, evt) {
  7278.         return events.fire(target, name, evt);
  7279.       };
  7280.       var getContentEditable = function (node) {
  7281.         if (node && isElement$5(node)) {
  7282.           var contentEditable = node.getAttribute('data-mce-contenteditable');
  7283.           if (contentEditable && contentEditable !== 'inherit') {
  7284.             return contentEditable;
  7285.           }
  7286.           return node.contentEditable !== 'inherit' ? node.contentEditable : null;
  7287.         } else {
  7288.           return null;
  7289.         }
  7290.       };
  7291.       var getContentEditableParent = function (node) {
  7292.         var root = getRoot();
  7293.         var state = null;
  7294.         for (; node && node !== root; node = node.parentNode) {
  7295.           state = getContentEditable(node);
  7296.           if (state !== null) {
  7297.             break;
  7298.           }
  7299.         }
  7300.         return state;
  7301.       };
  7302.       var destroy = function () {
  7303.         if (boundEvents.length > 0) {
  7304.           var i = boundEvents.length;
  7305.           while (i--) {
  7306.             var item = boundEvents[i];
  7307.             events.unbind(item[0], item[1], item[2]);
  7308.           }
  7309.         }
  7310.         each$j(files, function (_, url) {
  7311.           styleSheetLoader.unload(url);
  7312.           delete files[url];
  7313.         });
  7314.         if (Sizzle.setDocument) {
  7315.           Sizzle.setDocument();
  7316.         }
  7317.       };
  7318.       var isChildOf = function (node, parent) {
  7319.         if (!isIE) {
  7320.           return node === parent || parent.contains(node);
  7321.         } else {
  7322.           while (node) {
  7323.             if (parent === node) {
  7324.               return true;
  7325.             }
  7326.             node = node.parentNode;
  7327.           }
  7328.           return false;
  7329.         }
  7330.       };
  7331.       var dumpRng = function (r) {
  7332.         return 'startContainer: ' + r.startContainer.nodeName + ', startOffset: ' + r.startOffset + ', endContainer: ' + r.endContainer.nodeName + ', endOffset: ' + r.endOffset;
  7333.       };
  7334.       var self = {
  7335.         doc: doc,
  7336.         settings: settings,
  7337.         win: win,
  7338.         files: files,
  7339.         stdMode: stdMode,
  7340.         boxModel: boxModel,
  7341.         styleSheetLoader: styleSheetLoader,
  7342.         boundEvents: boundEvents,
  7343.         styles: styles,
  7344.         schema: schema,
  7345.         events: events,
  7346.         isBlock: isBlock,
  7347.         $: $,
  7348.         $$: $$,
  7349.         root: null,
  7350.         clone: clone,
  7351.         getRoot: getRoot,
  7352.         getViewPort: getViewPort,
  7353.         getRect: getRect,
  7354.         getSize: getSize,
  7355.         getParent: getParent,
  7356.         getParents: getParents,
  7357.         get: get,
  7358.         getNext: getNext,
  7359.         getPrev: getPrev,
  7360.         select: select,
  7361.         is: is,
  7362.         add: add,
  7363.         create: create,
  7364.         createHTML: createHTML,
  7365.         createFragment: createFragment,
  7366.         remove: remove,
  7367.         setStyle: setStyle,
  7368.         getStyle: getStyle,
  7369.         setStyles: setStyles,
  7370.         removeAllAttribs: removeAllAttribs,
  7371.         setAttrib: setAttrib,
  7372.         setAttribs: setAttribs,
  7373.         getAttrib: getAttrib,
  7374.         getPos: getPos$1,
  7375.         parseStyle: parseStyle,
  7376.         serializeStyle: serializeStyle,
  7377.         addStyle: addStyle,
  7378.         loadCSS: loadCSS,
  7379.         addClass: addClass,
  7380.         removeClass: removeClass,
  7381.         hasClass: hasClass,
  7382.         toggleClass: toggleClass,
  7383.         show: show,
  7384.         hide: hide,
  7385.         isHidden: isHidden,
  7386.         uniqueId: uniqueId,
  7387.         setHTML: setHTML,
  7388.         getOuterHTML: getOuterHTML,
  7389.         setOuterHTML: setOuterHTML,
  7390.         decode: decode,
  7391.         encode: encode,
  7392.         insertAfter: insertAfter,
  7393.         replace: replace,
  7394.         rename: rename,
  7395.         findCommonAncestor: findCommonAncestor,
  7396.         toHex: toHex,
  7397.         run: run,
  7398.         getAttribs: getAttribs,
  7399.         isEmpty: isEmpty,
  7400.         createRng: createRng,
  7401.         nodeIndex: findNodeIndex,
  7402.         split: split,
  7403.         bind: bind,
  7404.         unbind: unbind,
  7405.         fire: fire,
  7406.         getContentEditable: getContentEditable,
  7407.         getContentEditableParent: getContentEditableParent,
  7408.         destroy: destroy,
  7409.         isChildOf: isChildOf,
  7410.         dumpRng: dumpRng
  7411.       };
  7412.       var attrHooks = setupAttrHooks(styles, settings, constant(self));
  7413.       return self;
  7414.     };
  7415.     DOMUtils.DOM = DOMUtils(document);
  7416.     DOMUtils.nodeIndex = findNodeIndex;
  7417.  
  7418.     var DOM$a = DOMUtils.DOM;
  7419.     var each$e = Tools.each, grep = Tools.grep;
  7420.     var QUEUED = 0;
  7421.     var LOADING = 1;
  7422.     var LOADED = 2;
  7423.     var FAILED = 3;
  7424.     var ScriptLoader = function () {
  7425.       function ScriptLoader(settings) {
  7426.         if (settings === void 0) {
  7427.           settings = {};
  7428.         }
  7429.         this.states = {};
  7430.         this.queue = [];
  7431.         this.scriptLoadedCallbacks = {};
  7432.         this.queueLoadedCallbacks = [];
  7433.         this.loading = 0;
  7434.         this.settings = settings;
  7435.       }
  7436.       ScriptLoader.prototype._setReferrerPolicy = function (referrerPolicy) {
  7437.         this.settings.referrerPolicy = referrerPolicy;
  7438.       };
  7439.       ScriptLoader.prototype.loadScript = function (url, success, failure) {
  7440.         var dom = DOM$a;
  7441.         var elm;
  7442.         var cleanup = function () {
  7443.           dom.remove(id);
  7444.           if (elm) {
  7445.             elm.onerror = elm.onload = elm = null;
  7446.           }
  7447.         };
  7448.         var done = function () {
  7449.           cleanup();
  7450.           success();
  7451.         };
  7452.         var error = function () {
  7453.           cleanup();
  7454.           if (isFunction(failure)) {
  7455.             failure();
  7456.           } else {
  7457.             if (typeof console !== 'undefined' && console.log) {
  7458.               console.log('Failed to load script: ' + url);
  7459.             }
  7460.           }
  7461.         };
  7462.         var id = dom.uniqueId();
  7463.         elm = document.createElement('script');
  7464.         elm.id = id;
  7465.         elm.type = 'text/javascript';
  7466.         elm.src = Tools._addCacheSuffix(url);
  7467.         if (this.settings.referrerPolicy) {
  7468.           dom.setAttrib(elm, 'referrerpolicy', this.settings.referrerPolicy);
  7469.         }
  7470.         elm.onload = done;
  7471.         elm.onerror = error;
  7472.         (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  7473.       };
  7474.       ScriptLoader.prototype.isDone = function (url) {
  7475.         return this.states[url] === LOADED;
  7476.       };
  7477.       ScriptLoader.prototype.markDone = function (url) {
  7478.         this.states[url] = LOADED;
  7479.       };
  7480.       ScriptLoader.prototype.add = function (url, success, scope, failure) {
  7481.         var state = this.states[url];
  7482.         this.queue.push(url);
  7483.         if (state === undefined) {
  7484.           this.states[url] = QUEUED;
  7485.         }
  7486.         if (success) {
  7487.           if (!this.scriptLoadedCallbacks[url]) {
  7488.             this.scriptLoadedCallbacks[url] = [];
  7489.           }
  7490.           this.scriptLoadedCallbacks[url].push({
  7491.             success: success,
  7492.             failure: failure,
  7493.             scope: scope || this
  7494.           });
  7495.         }
  7496.       };
  7497.       ScriptLoader.prototype.load = function (url, success, scope, failure) {
  7498.         return this.add(url, success, scope, failure);
  7499.       };
  7500.       ScriptLoader.prototype.remove = function (url) {
  7501.         delete this.states[url];
  7502.         delete this.scriptLoadedCallbacks[url];
  7503.       };
  7504.       ScriptLoader.prototype.loadQueue = function (success, scope, failure) {
  7505.         this.loadScripts(this.queue, success, scope, failure);
  7506.       };
  7507.       ScriptLoader.prototype.loadScripts = function (scripts, success, scope, failure) {
  7508.         var self = this;
  7509.         var failures = [];
  7510.         var execCallbacks = function (name, url) {
  7511.           each$e(self.scriptLoadedCallbacks[url], function (callback) {
  7512.             if (isFunction(callback[name])) {
  7513.               callback[name].call(callback.scope);
  7514.             }
  7515.           });
  7516.           self.scriptLoadedCallbacks[url] = undefined;
  7517.         };
  7518.         self.queueLoadedCallbacks.push({
  7519.           success: success,
  7520.           failure: failure,
  7521.           scope: scope || this
  7522.         });
  7523.         var loadScripts = function () {
  7524.           var loadingScripts = grep(scripts);
  7525.           scripts.length = 0;
  7526.           each$e(loadingScripts, function (url) {
  7527.             if (self.states[url] === LOADED) {
  7528.               execCallbacks('success', url);
  7529.               return;
  7530.             }
  7531.             if (self.states[url] === FAILED) {
  7532.               execCallbacks('failure', url);
  7533.               return;
  7534.             }
  7535.             if (self.states[url] !== LOADING) {
  7536.               self.states[url] = LOADING;
  7537.               self.loading++;
  7538.               self.loadScript(url, function () {
  7539.                 self.states[url] = LOADED;
  7540.                 self.loading--;
  7541.                 execCallbacks('success', url);
  7542.                 loadScripts();
  7543.               }, function () {
  7544.                 self.states[url] = FAILED;
  7545.                 self.loading--;
  7546.                 failures.push(url);
  7547.                 execCallbacks('failure', url);
  7548.                 loadScripts();
  7549.               });
  7550.             }
  7551.           });
  7552.           if (!self.loading) {
  7553.             var notifyCallbacks = self.queueLoadedCallbacks.slice(0);
  7554.             self.queueLoadedCallbacks.length = 0;
  7555.             each$e(notifyCallbacks, function (callback) {
  7556.               if (failures.length === 0) {
  7557.                 if (isFunction(callback.success)) {
  7558.                   callback.success.call(callback.scope);
  7559.                 }
  7560.               } else {
  7561.                 if (isFunction(callback.failure)) {
  7562.                   callback.failure.call(callback.scope, failures);
  7563.                 }
  7564.               }
  7565.             });
  7566.           }
  7567.         };
  7568.         loadScripts();
  7569.       };
  7570.       ScriptLoader.ScriptLoader = new ScriptLoader();
  7571.       return ScriptLoader;
  7572.     }();
  7573.  
  7574.     var Cell = function (initial) {
  7575.       var value = initial;
  7576.       var get = function () {
  7577.         return value;
  7578.       };
  7579.       var set = function (v) {
  7580.         value = v;
  7581.       };
  7582.       return {
  7583.         get: get,
  7584.         set: set
  7585.       };
  7586.     };
  7587.  
  7588.     var isRaw = function (str) {
  7589.       return isObject(str) && has$2(str, 'raw');
  7590.     };
  7591.     var isTokenised = function (str) {
  7592.       return isArray$1(str) && str.length > 1;
  7593.     };
  7594.     var data = {};
  7595.     var currentCode = Cell('en');
  7596.     var getLanguageData = function () {
  7597.       return get$9(data, currentCode.get());
  7598.     };
  7599.     var getData = function () {
  7600.       return map$2(data, function (value) {
  7601.         return __assign({}, value);
  7602.       });
  7603.     };
  7604.     var setCode = function (newCode) {
  7605.       if (newCode) {
  7606.         currentCode.set(newCode);
  7607.       }
  7608.     };
  7609.     var getCode = function () {
  7610.       return currentCode.get();
  7611.     };
  7612.     var add$4 = function (code, items) {
  7613.       var langData = data[code];
  7614.       if (!langData) {
  7615.         data[code] = langData = {};
  7616.       }
  7617.       each$j(items, function (translation, name) {
  7618.         langData[name.toLowerCase()] = translation;
  7619.       });
  7620.     };
  7621.     var translate = function (text) {
  7622.       var langData = getLanguageData().getOr({});
  7623.       var toString = function (obj) {
  7624.         if (isFunction(obj)) {
  7625.           return Object.prototype.toString.call(obj);
  7626.         }
  7627.         return !isEmpty(obj) ? '' + obj : '';
  7628.       };
  7629.       var isEmpty = function (text) {
  7630.         return text === '' || text === null || text === undefined;
  7631.       };
  7632.       var getLangData = function (text) {
  7633.         var textstr = toString(text);
  7634.         return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
  7635.       };
  7636.       var removeContext = function (str) {
  7637.         return str.replace(/{context:\w+}$/, '');
  7638.       };
  7639.       if (isEmpty(text)) {
  7640.         return '';
  7641.       }
  7642.       if (isRaw(text)) {
  7643.         return toString(text.raw);
  7644.       }
  7645.       if (isTokenised(text)) {
  7646.         var values_1 = text.slice(1);
  7647.         var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function ($1, $2) {
  7648.           return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
  7649.         });
  7650.         return removeContext(substitued);
  7651.       }
  7652.       return removeContext(getLangData(text));
  7653.     };
  7654.     var isRtl$1 = function () {
  7655.       return getLanguageData().bind(function (items) {
  7656.         return get$9(items, '_dir');
  7657.       }).exists(function (dir) {
  7658.         return dir === 'rtl';
  7659.       });
  7660.     };
  7661.     var hasCode = function (code) {
  7662.       return has$2(data, code);
  7663.     };
  7664.     var I18n = {
  7665.       getData: getData,
  7666.       setCode: setCode,
  7667.       getCode: getCode,
  7668.       add: add$4,
  7669.       translate: translate,
  7670.       isRtl: isRtl$1,
  7671.       hasCode: hasCode
  7672.     };
  7673.  
  7674.     var AddOnManager = function () {
  7675.       var items = [];
  7676.       var urls = {};
  7677.       var lookup = {};
  7678.       var _listeners = [];
  7679.       var runListeners = function (name, state) {
  7680.         var matchedListeners = filter$4(_listeners, function (listener) {
  7681.           return listener.name === name && listener.state === state;
  7682.         });
  7683.         each$k(matchedListeners, function (listener) {
  7684.           return listener.callback();
  7685.         });
  7686.       };
  7687.       var get = function (name) {
  7688.         if (lookup[name]) {
  7689.           return lookup[name].instance;
  7690.         }
  7691.         return undefined;
  7692.       };
  7693.       var dependencies = function (name) {
  7694.         var result;
  7695.         if (lookup[name]) {
  7696.           result = lookup[name].dependencies;
  7697.         }
  7698.         return result || [];
  7699.       };
  7700.       var requireLangPack = function (name, languages) {
  7701.         if (AddOnManager.languageLoad !== false) {
  7702.           waitFor(name, function () {
  7703.             var language = I18n.getCode();
  7704.             var wrappedLanguages = ',' + (languages || '') + ',';
  7705.             if (!language || languages && wrappedLanguages.indexOf(',' + language + ',') === -1) {
  7706.               return;
  7707.             }
  7708.             ScriptLoader.ScriptLoader.add(urls[name] + '/langs/' + language + '.js');
  7709.           }, 'loaded');
  7710.         }
  7711.       };
  7712.       var add = function (id, addOn, dependencies) {
  7713.         var addOnConstructor = addOn;
  7714.         items.push(addOnConstructor);
  7715.         lookup[id] = {
  7716.           instance: addOnConstructor,
  7717.           dependencies: dependencies
  7718.         };
  7719.         runListeners(id, 'added');
  7720.         return addOnConstructor;
  7721.       };
  7722.       var remove = function (name) {
  7723.         delete urls[name];
  7724.         delete lookup[name];
  7725.       };
  7726.       var createUrl = function (baseUrl, dep) {
  7727.         if (typeof dep === 'object') {
  7728.           return dep;
  7729.         }
  7730.         return typeof baseUrl === 'string' ? {
  7731.           prefix: '',
  7732.           resource: dep,
  7733.           suffix: ''
  7734.         } : {
  7735.           prefix: baseUrl.prefix,
  7736.           resource: dep,
  7737.           suffix: baseUrl.suffix
  7738.         };
  7739.       };
  7740.       var addComponents = function (pluginName, scripts) {
  7741.         var pluginUrl = urls[pluginName];
  7742.         each$k(scripts, function (script) {
  7743.           ScriptLoader.ScriptLoader.add(pluginUrl + '/' + script);
  7744.         });
  7745.       };
  7746.       var loadDependencies = function (name, addOnUrl, success, scope) {
  7747.         var deps = dependencies(name);
  7748.         each$k(deps, function (dep) {
  7749.           var newUrl = createUrl(addOnUrl, dep);
  7750.           load(newUrl.resource, newUrl, undefined, undefined);
  7751.         });
  7752.         if (success) {
  7753.           if (scope) {
  7754.             success.call(scope);
  7755.           } else {
  7756.             success.call(ScriptLoader);
  7757.           }
  7758.         }
  7759.       };
  7760.       var load = function (name, addOnUrl, success, scope, failure) {
  7761.         if (urls[name]) {
  7762.           return;
  7763.         }
  7764.         var urlString = typeof addOnUrl === 'string' ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  7765.         if (urlString.indexOf('/') !== 0 && urlString.indexOf('://') === -1) {
  7766.           urlString = AddOnManager.baseURL + '/' + urlString;
  7767.         }
  7768.         urls[name] = urlString.substring(0, urlString.lastIndexOf('/'));
  7769.         var done = function () {
  7770.           runListeners(name, 'loaded');
  7771.           loadDependencies(name, addOnUrl, success, scope);
  7772.         };
  7773.         if (lookup[name]) {
  7774.           done();
  7775.         } else {
  7776.           ScriptLoader.ScriptLoader.add(urlString, done, scope, failure);
  7777.         }
  7778.       };
  7779.       var waitFor = function (name, callback, state) {
  7780.         if (state === void 0) {
  7781.           state = 'added';
  7782.         }
  7783.         if (has$2(lookup, name) && state === 'added') {
  7784.           callback();
  7785.         } else if (has$2(urls, name) && state === 'loaded') {
  7786.           callback();
  7787.         } else {
  7788.           _listeners.push({
  7789.             name: name,
  7790.             state: state,
  7791.             callback: callback
  7792.           });
  7793.         }
  7794.       };
  7795.       return {
  7796.         items: items,
  7797.         urls: urls,
  7798.         lookup: lookup,
  7799.         _listeners: _listeners,
  7800.         get: get,
  7801.         dependencies: dependencies,
  7802.         requireLangPack: requireLangPack,
  7803.         add: add,
  7804.         remove: remove,
  7805.         createUrl: createUrl,
  7806.         addComponents: addComponents,
  7807.         load: load,
  7808.         waitFor: waitFor
  7809.       };
  7810.     };
  7811.     AddOnManager.languageLoad = true;
  7812.     AddOnManager.baseURL = '';
  7813.     AddOnManager.PluginManager = AddOnManager();
  7814.     AddOnManager.ThemeManager = AddOnManager();
  7815.  
  7816.     var singleton = function (doRevoke) {
  7817.       var subject = Cell(Optional.none());
  7818.       var revoke = function () {
  7819.         return subject.get().each(doRevoke);
  7820.       };
  7821.       var clear = function () {
  7822.         revoke();
  7823.         subject.set(Optional.none());
  7824.       };
  7825.       var isSet = function () {
  7826.         return subject.get().isSome();
  7827.       };
  7828.       var get = function () {
  7829.         return subject.get();
  7830.       };
  7831.       var set = function (s) {
  7832.         revoke();
  7833.         subject.set(Optional.some(s));
  7834.       };
  7835.       return {
  7836.         clear: clear,
  7837.         isSet: isSet,
  7838.         get: get,
  7839.         set: set
  7840.       };
  7841.     };
  7842.     var value = function () {
  7843.       var subject = singleton(noop);
  7844.       var on = function (f) {
  7845.         return subject.get().each(f);
  7846.       };
  7847.       return __assign(__assign({}, subject), { on: on });
  7848.     };
  7849.  
  7850.     var first = function (fn, rate) {
  7851.       var timer = null;
  7852.       var cancel = function () {
  7853.         if (!isNull(timer)) {
  7854.           clearTimeout(timer);
  7855.           timer = null;
  7856.         }
  7857.       };
  7858.       var throttle = function () {
  7859.         var args = [];
  7860.         for (var _i = 0; _i < arguments.length; _i++) {
  7861.           args[_i] = arguments[_i];
  7862.         }
  7863.         if (isNull(timer)) {
  7864.           timer = setTimeout(function () {
  7865.             timer = null;
  7866.             fn.apply(null, args);
  7867.           }, rate);
  7868.         }
  7869.       };
  7870.       return {
  7871.         cancel: cancel,
  7872.         throttle: throttle
  7873.       };
  7874.     };
  7875.     var last = function (fn, rate) {
  7876.       var timer = null;
  7877.       var cancel = function () {
  7878.         if (!isNull(timer)) {
  7879.           clearTimeout(timer);
  7880.           timer = null;
  7881.         }
  7882.       };
  7883.       var throttle = function () {
  7884.         var args = [];
  7885.         for (var _i = 0; _i < arguments.length; _i++) {
  7886.           args[_i] = arguments[_i];
  7887.         }
  7888.         cancel();
  7889.         timer = setTimeout(function () {
  7890.           timer = null;
  7891.           fn.apply(null, args);
  7892.         }, rate);
  7893.       };
  7894.       return {
  7895.         cancel: cancel,
  7896.         throttle: throttle
  7897.       };
  7898.     };
  7899.  
  7900.     var read$4 = function (element, attr) {
  7901.       var value = get$6(element, attr);
  7902.       return value === undefined || value === '' ? [] : value.split(' ');
  7903.     };
  7904.     var add$3 = function (element, attr, id) {
  7905.       var old = read$4(element, attr);
  7906.       var nu = old.concat([id]);
  7907.       set$1(element, attr, nu.join(' '));
  7908.       return true;
  7909.     };
  7910.     var remove$5 = function (element, attr, id) {
  7911.       var nu = filter$4(read$4(element, attr), function (v) {
  7912.         return v !== id;
  7913.       });
  7914.       if (nu.length > 0) {
  7915.         set$1(element, attr, nu.join(' '));
  7916.       } else {
  7917.         remove$6(element, attr);
  7918.       }
  7919.       return false;
  7920.     };
  7921.  
  7922.     var supports = function (element) {
  7923.       return element.dom.classList !== undefined;
  7924.     };
  7925.     var get$4 = function (element) {
  7926.       return read$4(element, 'class');
  7927.     };
  7928.     var add$2 = function (element, clazz) {
  7929.       return add$3(element, 'class', clazz);
  7930.     };
  7931.     var remove$4 = function (element, clazz) {
  7932.       return remove$5(element, 'class', clazz);
  7933.     };
  7934.  
  7935.     var add$1 = function (element, clazz) {
  7936.       if (supports(element)) {
  7937.         element.dom.classList.add(clazz);
  7938.       } else {
  7939.         add$2(element, clazz);
  7940.       }
  7941.     };
  7942.     var cleanClass = function (element) {
  7943.       var classList = supports(element) ? element.dom.classList : get$4(element);
  7944.       if (classList.length === 0) {
  7945.         remove$6(element, 'class');
  7946.       }
  7947.     };
  7948.     var remove$3 = function (element, clazz) {
  7949.       if (supports(element)) {
  7950.         var classList = element.dom.classList;
  7951.         classList.remove(clazz);
  7952.       } else {
  7953.         remove$4(element, clazz);
  7954.       }
  7955.       cleanClass(element);
  7956.     };
  7957.     var has = function (element, clazz) {
  7958.       return supports(element) && element.dom.classList.contains(clazz);
  7959.     };
  7960.  
  7961.     var descendants$1 = function (scope, predicate) {
  7962.       var result = [];
  7963.       each$k(children(scope), function (x) {
  7964.         if (predicate(x)) {
  7965.           result = result.concat([x]);
  7966.         }
  7967.         result = result.concat(descendants$1(x, predicate));
  7968.       });
  7969.       return result;
  7970.     };
  7971.  
  7972.     var descendants = function (scope, selector) {
  7973.       return all(selector, scope);
  7974.     };
  7975.  
  7976.     var annotation = constant('mce-annotation');
  7977.     var dataAnnotation = constant('data-mce-annotation');
  7978.     var dataAnnotationId = constant('data-mce-annotation-uid');
  7979.  
  7980.     var identify = function (editor, annotationName) {
  7981.       var rng = editor.selection.getRng();
  7982.       var start = SugarElement.fromDom(rng.startContainer);
  7983.       var root = SugarElement.fromDom(editor.getBody());
  7984.       var selector = annotationName.fold(function () {
  7985.         return '.' + annotation();
  7986.       }, function (an) {
  7987.         return '[' + dataAnnotation() + '="' + an + '"]';
  7988.       });
  7989.       var newStart = child$1(start, rng.startOffset).getOr(start);
  7990.       var closest = closest$2(newStart, selector, function (n) {
  7991.         return eq(n, root);
  7992.       });
  7993.       var getAttr = function (c, property) {
  7994.         if (has$1(c, property)) {
  7995.           return Optional.some(get$6(c, property));
  7996.         } else {
  7997.           return Optional.none();
  7998.         }
  7999.       };
  8000.       return closest.bind(function (c) {
  8001.         return getAttr(c, '' + dataAnnotationId()).bind(function (uid) {
  8002.           return getAttr(c, '' + dataAnnotation()).map(function (name) {
  8003.             var elements = findMarkers(editor, uid);
  8004.             return {
  8005.               uid: uid,
  8006.               name: name,
  8007.               elements: elements
  8008.             };
  8009.           });
  8010.         });
  8011.       });
  8012.     };
  8013.     var isAnnotation = function (elem) {
  8014.       return isElement$6(elem) && has(elem, annotation());
  8015.     };
  8016.     var findMarkers = function (editor, uid) {
  8017.       var body = SugarElement.fromDom(editor.getBody());
  8018.       return descendants(body, '[' + dataAnnotationId() + '="' + uid + '"]');
  8019.     };
  8020.     var findAll = function (editor, name) {
  8021.       var body = SugarElement.fromDom(editor.getBody());
  8022.       var markers = descendants(body, '[' + dataAnnotation() + '="' + name + '"]');
  8023.       var directory = {};
  8024.       each$k(markers, function (m) {
  8025.         var uid = get$6(m, dataAnnotationId());
  8026.         var nodesAlready = get$9(directory, uid).getOr([]);
  8027.         directory[uid] = nodesAlready.concat([m]);
  8028.       });
  8029.       return directory;
  8030.     };
  8031.  
  8032.     var setup$n = function (editor, _registry) {
  8033.       var changeCallbacks = Cell({});
  8034.       var initData = function () {
  8035.         return {
  8036.           listeners: [],
  8037.           previous: value()
  8038.         };
  8039.       };
  8040.       var withCallbacks = function (name, f) {
  8041.         updateCallbacks(name, function (data) {
  8042.           f(data);
  8043.           return data;
  8044.         });
  8045.       };
  8046.       var updateCallbacks = function (name, f) {
  8047.         var callbackMap = changeCallbacks.get();
  8048.         var data = get$9(callbackMap, name).getOrThunk(initData);
  8049.         var outputData = f(data);
  8050.         callbackMap[name] = outputData;
  8051.         changeCallbacks.set(callbackMap);
  8052.       };
  8053.       var fireCallbacks = function (name, uid, elements) {
  8054.         withCallbacks(name, function (data) {
  8055.           each$k(data.listeners, function (f) {
  8056.             return f(true, name, {
  8057.               uid: uid,
  8058.               nodes: map$3(elements, function (elem) {
  8059.                 return elem.dom;
  8060.               })
  8061.             });
  8062.           });
  8063.         });
  8064.       };
  8065.       var fireNoAnnotation = function (name) {
  8066.         withCallbacks(name, function (data) {
  8067.           each$k(data.listeners, function (f) {
  8068.             return f(false, name);
  8069.           });
  8070.         });
  8071.       };
  8072.       var onNodeChange = last(function () {
  8073.         var callbackMap = changeCallbacks.get();
  8074.         var annotations = sort(keys(callbackMap));
  8075.         each$k(annotations, function (name) {
  8076.           updateCallbacks(name, function (data) {
  8077.             var prev = data.previous.get();
  8078.             identify(editor, Optional.some(name)).fold(function () {
  8079.               if (prev.isSome()) {
  8080.                 fireNoAnnotation(name);
  8081.                 data.previous.clear();
  8082.               }
  8083.             }, function (_a) {
  8084.               var uid = _a.uid, name = _a.name, elements = _a.elements;
  8085.               if (!is$1(prev, uid)) {
  8086.                 fireCallbacks(name, uid, elements);
  8087.                 data.previous.set(uid);
  8088.               }
  8089.             });
  8090.             return {
  8091.               previous: data.previous,
  8092.               listeners: data.listeners
  8093.             };
  8094.           });
  8095.         });
  8096.       }, 30);
  8097.       editor.on('remove', function () {
  8098.         onNodeChange.cancel();
  8099.       });
  8100.       editor.on('NodeChange', function () {
  8101.         onNodeChange.throttle();
  8102.       });
  8103.       var addListener = function (name, f) {
  8104.         updateCallbacks(name, function (data) {
  8105.           return {
  8106.             previous: data.previous,
  8107.             listeners: data.listeners.concat([f])
  8108.           };
  8109.         });
  8110.       };
  8111.       return { addListener: addListener };
  8112.     };
  8113.  
  8114.     var setup$m = function (editor, registry) {
  8115.       var identifyParserNode = function (span) {
  8116.         return Optional.from(span.attr(dataAnnotation())).bind(registry.lookup);
  8117.       };
  8118.       editor.on('init', function () {
  8119.         editor.serializer.addNodeFilter('span', function (spans) {
  8120.           each$k(spans, function (span) {
  8121.             identifyParserNode(span).each(function (settings) {
  8122.               if (settings.persistent === false) {
  8123.                 span.unwrap();
  8124.               }
  8125.             });
  8126.           });
  8127.         });
  8128.       });
  8129.     };
  8130.  
  8131.     var create$7 = function () {
  8132.       var annotations = {};
  8133.       var register = function (name, settings) {
  8134.         annotations[name] = {
  8135.           name: name,
  8136.           settings: settings
  8137.         };
  8138.       };
  8139.       var lookup = function (name) {
  8140.         return get$9(annotations, name).map(function (a) {
  8141.           return a.settings;
  8142.         });
  8143.       };
  8144.       return {
  8145.         register: register,
  8146.         lookup: lookup
  8147.       };
  8148.     };
  8149.  
  8150.     var unique = 0;
  8151.     var generate = function (prefix) {
  8152.       var date = new Date();
  8153.       var time = date.getTime();
  8154.       var random = Math.floor(Math.random() * 1000000000);
  8155.       unique++;
  8156.       return prefix + '_' + random + unique + String(time);
  8157.     };
  8158.  
  8159.     var add = function (element, classes) {
  8160.       each$k(classes, function (x) {
  8161.         add$1(element, x);
  8162.       });
  8163.     };
  8164.  
  8165.     var fromHtml = function (html, scope) {
  8166.       var doc = scope || document;
  8167.       var div = doc.createElement('div');
  8168.       div.innerHTML = html;
  8169.       return children(SugarElement.fromDom(div));
  8170.     };
  8171.     var fromDom$1 = function (nodes) {
  8172.       return map$3(nodes, SugarElement.fromDom);
  8173.     };
  8174.  
  8175.     var get$3 = function (element) {
  8176.       return element.dom.innerHTML;
  8177.     };
  8178.     var set = function (element, content) {
  8179.       var owner = owner$1(element);
  8180.       var docDom = owner.dom;
  8181.       var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  8182.       var contentElements = fromHtml(content, docDom);
  8183.       append(fragment, contentElements);
  8184.       empty(element);
  8185.       append$1(element, fragment);
  8186.     };
  8187.  
  8188.     var clone$1 = function (original, isDeep) {
  8189.       return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  8190.     };
  8191.     var shallow = function (original) {
  8192.       return clone$1(original, false);
  8193.     };
  8194.     var deep$1 = function (original) {
  8195.       return clone$1(original, true);
  8196.     };
  8197.  
  8198.     var TextWalker = function (startNode, rootNode, isBoundary) {
  8199.       if (isBoundary === void 0) {
  8200.         isBoundary = never;
  8201.       }
  8202.       var walker = new DomTreeWalker(startNode, rootNode);
  8203.       var walk = function (direction) {
  8204.         var next;
  8205.         do {
  8206.           next = walker[direction]();
  8207.         } while (next && !isText$7(next) && !isBoundary(next));
  8208.         return Optional.from(next).filter(isText$7);
  8209.       };
  8210.       return {
  8211.         current: function () {
  8212.           return Optional.from(walker.current()).filter(isText$7);
  8213.         },
  8214.         next: function () {
  8215.           return walk('next');
  8216.         },
  8217.         prev: function () {
  8218.           return walk('prev');
  8219.         },
  8220.         prev2: function () {
  8221.           return walk('prev2');
  8222.         }
  8223.       };
  8224.     };
  8225.  
  8226.     var TextSeeker = function (dom, isBoundary) {
  8227.       var isBlockBoundary = isBoundary ? isBoundary : function (node) {
  8228.         return dom.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
  8229.       };
  8230.       var walk = function (node, offset, walker, process) {
  8231.         if (isText$7(node)) {
  8232.           var newOffset = process(node, offset, node.data);
  8233.           if (newOffset !== -1) {
  8234.             return Optional.some({
  8235.               container: node,
  8236.               offset: newOffset
  8237.             });
  8238.           }
  8239.         }
  8240.         return walker().bind(function (next) {
  8241.           return walk(next.container, next.offset, walker, process);
  8242.         });
  8243.       };
  8244.       var backwards = function (node, offset, process, root) {
  8245.         var walker = TextWalker(node, root, isBlockBoundary);
  8246.         return walk(node, offset, function () {
  8247.           return walker.prev().map(function (prev) {
  8248.             return {
  8249.               container: prev,
  8250.               offset: prev.length
  8251.             };
  8252.           });
  8253.         }, process).getOrNull();
  8254.       };
  8255.       var forwards = function (node, offset, process, root) {
  8256.         var walker = TextWalker(node, root, isBlockBoundary);
  8257.         return walk(node, offset, function () {
  8258.           return walker.next().map(function (next) {
  8259.             return {
  8260.               container: next,
  8261.               offset: 0
  8262.             };
  8263.           });
  8264.         }, process).getOrNull();
  8265.       };
  8266.       return {
  8267.         backwards: backwards,
  8268.         forwards: forwards
  8269.       };
  8270.     };
  8271.  
  8272.     var round$2 = Math.round;
  8273.     var clone = function (rect) {
  8274.       if (!rect) {
  8275.         return {
  8276.           left: 0,
  8277.           top: 0,
  8278.           bottom: 0,
  8279.           right: 0,
  8280.           width: 0,
  8281.           height: 0
  8282.         };
  8283.       }
  8284.       return {
  8285.         left: round$2(rect.left),
  8286.         top: round$2(rect.top),
  8287.         bottom: round$2(rect.bottom),
  8288.         right: round$2(rect.right),
  8289.         width: round$2(rect.width),
  8290.         height: round$2(rect.height)
  8291.       };
  8292.     };
  8293.     var collapse = function (rect, toStart) {
  8294.       rect = clone(rect);
  8295.       if (toStart) {
  8296.         rect.right = rect.left;
  8297.       } else {
  8298.         rect.left = rect.left + rect.width;
  8299.         rect.right = rect.left;
  8300.       }
  8301.       rect.width = 0;
  8302.       return rect;
  8303.     };
  8304.     var isEqual = function (rect1, rect2) {
  8305.       return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
  8306.     };
  8307.     var isValidOverflow = function (overflowY, rect1, rect2) {
  8308.       return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
  8309.     };
  8310.     var isAbove$1 = function (rect1, rect2) {
  8311.       var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
  8312.       if (rect1.bottom - halfHeight < rect2.top) {
  8313.         return true;
  8314.       }
  8315.       if (rect1.top > rect2.bottom) {
  8316.         return false;
  8317.       }
  8318.       return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
  8319.     };
  8320.     var isBelow$1 = function (rect1, rect2) {
  8321.       if (rect1.top > rect2.bottom) {
  8322.         return true;
  8323.       }
  8324.       if (rect1.bottom < rect2.top) {
  8325.         return false;
  8326.       }
  8327.       return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
  8328.     };
  8329.     var containsXY = function (rect, clientX, clientY) {
  8330.       return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
  8331.     };
  8332.  
  8333.     var clamp$2 = function (value, min, max) {
  8334.       return Math.min(Math.max(value, min), max);
  8335.     };
  8336.  
  8337.     var getSelectedNode = function (range) {
  8338.       var startContainer = range.startContainer, startOffset = range.startOffset;
  8339.       if (startContainer.hasChildNodes() && range.endOffset === startOffset + 1) {
  8340.         return startContainer.childNodes[startOffset];
  8341.       }
  8342.       return null;
  8343.     };
  8344.     var getNode$1 = function (container, offset) {
  8345.       if (isElement$5(container) && container.hasChildNodes()) {
  8346.         var childNodes = container.childNodes;
  8347.         var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
  8348.         return childNodes[safeOffset];
  8349.       } else {
  8350.         return container;
  8351.       }
  8352.     };
  8353.     var getNodeUnsafe = function (container, offset) {
  8354.       if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
  8355.         return undefined;
  8356.       } else {
  8357.         return getNode$1(container, offset);
  8358.       }
  8359.     };
  8360.  
  8361.     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]');
  8362.     var isExtendingChar = function (ch) {
  8363.       return typeof ch === 'string' && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
  8364.     };
  8365.  
  8366.     var or = 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 true;
  8375.           }
  8376.         }
  8377.         return false;
  8378.       };
  8379.     };
  8380.     var and = function () {
  8381.       var args = [];
  8382.       for (var _i = 0; _i < arguments.length; _i++) {
  8383.         args[_i] = arguments[_i];
  8384.       }
  8385.       return function (x) {
  8386.         for (var i = 0; i < args.length; i++) {
  8387.           if (!args[i](x)) {
  8388.             return false;
  8389.           }
  8390.         }
  8391.         return true;
  8392.       };
  8393.     };
  8394.  
  8395.     var isElement$3 = isElement$5;
  8396.     var isCaretCandidate$2 = isCaretCandidate$3;
  8397.     var isBlock$1 = matchStyleValues('display', 'block table');
  8398.     var isFloated = matchStyleValues('float', 'left right');
  8399.     var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
  8400.     var isNotPre = not(matchStyleValues('white-space', 'pre pre-line pre-wrap'));
  8401.     var isText$4 = isText$7;
  8402.     var isBr$2 = isBr$5;
  8403.     var nodeIndex$1 = DOMUtils.nodeIndex;
  8404.     var resolveIndex$1 = getNodeUnsafe;
  8405.     var createRange$1 = function (doc) {
  8406.       return 'createRange' in doc ? doc.createRange() : DOMUtils.DOM.createRng();
  8407.     };
  8408.     var isWhiteSpace$1 = function (chr) {
  8409.       return chr && /[\r\n\t ]/.test(chr);
  8410.     };
  8411.     var isRange = function (rng) {
  8412.       return !!rng.setStart && !!rng.setEnd;
  8413.     };
  8414.     var isHiddenWhiteSpaceRange = function (range) {
  8415.       var container = range.startContainer;
  8416.       var offset = range.startOffset;
  8417.       if (isWhiteSpace$1(range.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
  8418.         var text = container.data;
  8419.         if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
  8420.           return true;
  8421.         }
  8422.       }
  8423.       return false;
  8424.     };
  8425.     var getBrClientRect = function (brNode) {
  8426.       var doc = brNode.ownerDocument;
  8427.       var rng = createRange$1(doc);
  8428.       var nbsp$1 = doc.createTextNode(nbsp);
  8429.       var parentNode = brNode.parentNode;
  8430.       parentNode.insertBefore(nbsp$1, brNode);
  8431.       rng.setStart(nbsp$1, 0);
  8432.       rng.setEnd(nbsp$1, 1);
  8433.       var clientRect = clone(rng.getBoundingClientRect());
  8434.       parentNode.removeChild(nbsp$1);
  8435.       return clientRect;
  8436.     };
  8437.     var getBoundingClientRectWebKitText = function (rng) {
  8438.       var sc = rng.startContainer;
  8439.       var ec = rng.endContainer;
  8440.       var so = rng.startOffset;
  8441.       var eo = rng.endOffset;
  8442.       if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
  8443.         var newRng = rng.cloneRange();
  8444.         newRng.setEndAfter(ec);
  8445.         return getBoundingClientRect$1(newRng);
  8446.       } else {
  8447.         return null;
  8448.       }
  8449.     };
  8450.     var isZeroRect = function (r) {
  8451.       return r.left === 0 && r.right === 0 && r.top === 0 && r.bottom === 0;
  8452.     };
  8453.     var getBoundingClientRect$1 = function (item) {
  8454.       var clientRect;
  8455.       var clientRects = item.getClientRects();
  8456.       if (clientRects.length > 0) {
  8457.         clientRect = clone(clientRects[0]);
  8458.       } else {
  8459.         clientRect = clone(item.getBoundingClientRect());
  8460.       }
  8461.       if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
  8462.         return getBrClientRect(item);
  8463.       }
  8464.       if (isZeroRect(clientRect) && isRange(item)) {
  8465.         return getBoundingClientRectWebKitText(item);
  8466.       }
  8467.       return clientRect;
  8468.     };
  8469.     var collapseAndInflateWidth = function (clientRect, toStart) {
  8470.       var newClientRect = collapse(clientRect, toStart);
  8471.       newClientRect.width = 1;
  8472.       newClientRect.right = newClientRect.left + 1;
  8473.       return newClientRect;
  8474.     };
  8475.     var getCaretPositionClientRects = function (caretPosition) {
  8476.       var clientRects = [];
  8477.       var addUniqueAndValidRect = function (clientRect) {
  8478.         if (clientRect.height === 0) {
  8479.           return;
  8480.         }
  8481.         if (clientRects.length > 0) {
  8482.           if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
  8483.             return;
  8484.           }
  8485.         }
  8486.         clientRects.push(clientRect);
  8487.       };
  8488.       var addCharacterOffset = function (container, offset) {
  8489.         var range = createRange$1(container.ownerDocument);
  8490.         if (offset < container.data.length) {
  8491.           if (isExtendingChar(container.data[offset])) {
  8492.             return clientRects;
  8493.           }
  8494.           if (isExtendingChar(container.data[offset - 1])) {
  8495.             range.setStart(container, offset);
  8496.             range.setEnd(container, offset + 1);
  8497.             if (!isHiddenWhiteSpaceRange(range)) {
  8498.               addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8499.               return clientRects;
  8500.             }
  8501.           }
  8502.         }
  8503.         if (offset > 0) {
  8504.           range.setStart(container, offset - 1);
  8505.           range.setEnd(container, offset);
  8506.           if (!isHiddenWhiteSpaceRange(range)) {
  8507.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), false));
  8508.           }
  8509.         }
  8510.         if (offset < container.data.length) {
  8511.           range.setStart(container, offset);
  8512.           range.setEnd(container, offset + 1);
  8513.           if (!isHiddenWhiteSpaceRange(range)) {
  8514.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range), true));
  8515.           }
  8516.         }
  8517.       };
  8518.       var container = caretPosition.container();
  8519.       var offset = caretPosition.offset();
  8520.       if (isText$4(container)) {
  8521.         addCharacterOffset(container, offset);
  8522.         return clientRects;
  8523.       }
  8524.       if (isElement$3(container)) {
  8525.         if (caretPosition.isAtEnd()) {
  8526.           var node = resolveIndex$1(container, offset);
  8527.           if (isText$4(node)) {
  8528.             addCharacterOffset(node, node.data.length);
  8529.           }
  8530.           if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
  8531.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8532.           }
  8533.         } else {
  8534.           var node = resolveIndex$1(container, offset);
  8535.           if (isText$4(node)) {
  8536.             addCharacterOffset(node, 0);
  8537.           }
  8538.           if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
  8539.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
  8540.             return clientRects;
  8541.           }
  8542.           var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
  8543.           if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
  8544.             if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
  8545.               addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
  8546.             }
  8547.           }
  8548.           if (isValidElementCaretCandidate(node)) {
  8549.             addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
  8550.           }
  8551.         }
  8552.       }
  8553.       return clientRects;
  8554.     };
  8555.     var CaretPosition = function (container, offset, clientRects) {
  8556.       var isAtStart = function () {
  8557.         if (isText$4(container)) {
  8558.           return offset === 0;
  8559.         }
  8560.         return offset === 0;
  8561.       };
  8562.       var isAtEnd = function () {
  8563.         if (isText$4(container)) {
  8564.           return offset >= container.data.length;
  8565.         }
  8566.         return offset >= container.childNodes.length;
  8567.       };
  8568.       var toRange = function () {
  8569.         var range = createRange$1(container.ownerDocument);
  8570.         range.setStart(container, offset);
  8571.         range.setEnd(container, offset);
  8572.         return range;
  8573.       };
  8574.       var getClientRects = function () {
  8575.         if (!clientRects) {
  8576.           clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
  8577.         }
  8578.         return clientRects;
  8579.       };
  8580.       var isVisible = function () {
  8581.         return getClientRects().length > 0;
  8582.       };
  8583.       var isEqual = function (caretPosition) {
  8584.         return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
  8585.       };
  8586.       var getNode = function (before) {
  8587.         return resolveIndex$1(container, before ? offset - 1 : offset);
  8588.       };
  8589.       return {
  8590.         container: constant(container),
  8591.         offset: constant(offset),
  8592.         toRange: toRange,
  8593.         getClientRects: getClientRects,
  8594.         isVisible: isVisible,
  8595.         isAtStart: isAtStart,
  8596.         isAtEnd: isAtEnd,
  8597.         isEqual: isEqual,
  8598.         getNode: getNode
  8599.       };
  8600.     };
  8601.     CaretPosition.fromRangeStart = function (range) {
  8602.       return CaretPosition(range.startContainer, range.startOffset);
  8603.     };
  8604.     CaretPosition.fromRangeEnd = function (range) {
  8605.       return CaretPosition(range.endContainer, range.endOffset);
  8606.     };
  8607.     CaretPosition.after = function (node) {
  8608.       return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
  8609.     };
  8610.     CaretPosition.before = function (node) {
  8611.       return CaretPosition(node.parentNode, nodeIndex$1(node));
  8612.     };
  8613.     CaretPosition.isAbove = function (pos1, pos2) {
  8614.       return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
  8615.     };
  8616.     CaretPosition.isBelow = function (pos1, pos2) {
  8617.       return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
  8618.     };
  8619.     CaretPosition.isAtStart = function (pos) {
  8620.       return pos ? pos.isAtStart() : false;
  8621.     };
  8622.     CaretPosition.isAtEnd = function (pos) {
  8623.       return pos ? pos.isAtEnd() : false;
  8624.     };
  8625.     CaretPosition.isTextPosition = function (pos) {
  8626.       return pos ? isText$7(pos.container()) : false;
  8627.     };
  8628.     CaretPosition.isElementPosition = function (pos) {
  8629.       return CaretPosition.isTextPosition(pos) === false;
  8630.     };
  8631.  
  8632.     var trimEmptyTextNode$1 = function (dom, node) {
  8633.       if (isText$7(node) && node.data.length === 0) {
  8634.         dom.remove(node);
  8635.       }
  8636.     };
  8637.     var insertNode = function (dom, rng, node) {
  8638.       rng.insertNode(node);
  8639.       trimEmptyTextNode$1(dom, node.previousSibling);
  8640.       trimEmptyTextNode$1(dom, node.nextSibling);
  8641.     };
  8642.     var insertFragment = function (dom, rng, frag) {
  8643.       var firstChild = Optional.from(frag.firstChild);
  8644.       var lastChild = Optional.from(frag.lastChild);
  8645.       rng.insertNode(frag);
  8646.       firstChild.each(function (child) {
  8647.         return trimEmptyTextNode$1(dom, child.previousSibling);
  8648.       });
  8649.       lastChild.each(function (child) {
  8650.         return trimEmptyTextNode$1(dom, child.nextSibling);
  8651.       });
  8652.     };
  8653.     var rangeInsertNode = function (dom, rng, node) {
  8654.       if (isDocumentFragment(node)) {
  8655.         insertFragment(dom, rng, node);
  8656.       } else {
  8657.         insertNode(dom, rng, node);
  8658.       }
  8659.     };
  8660.  
  8661.     var isText$3 = isText$7;
  8662.     var isBogus = isBogus$2;
  8663.     var nodeIndex = DOMUtils.nodeIndex;
  8664.     var normalizedParent = function (node) {
  8665.       var parentNode = node.parentNode;
  8666.       if (isBogus(parentNode)) {
  8667.         return normalizedParent(parentNode);
  8668.       }
  8669.       return parentNode;
  8670.     };
  8671.     var getChildNodes = function (node) {
  8672.       if (!node) {
  8673.         return [];
  8674.       }
  8675.       return reduce(node.childNodes, function (result, node) {
  8676.         if (isBogus(node) && node.nodeName !== 'BR') {
  8677.           result = result.concat(getChildNodes(node));
  8678.         } else {
  8679.           result.push(node);
  8680.         }
  8681.         return result;
  8682.       }, []);
  8683.     };
  8684.     var normalizedTextOffset = function (node, offset) {
  8685.       while (node = node.previousSibling) {
  8686.         if (!isText$3(node)) {
  8687.           break;
  8688.         }
  8689.         offset += node.data.length;
  8690.       }
  8691.       return offset;
  8692.     };
  8693.     var equal = function (a) {
  8694.       return function (b) {
  8695.         return a === b;
  8696.       };
  8697.     };
  8698.     var normalizedNodeIndex = function (node) {
  8699.       var nodes, index;
  8700.       nodes = getChildNodes(normalizedParent(node));
  8701.       index = findIndex$1(nodes, equal(node), node);
  8702.       nodes = nodes.slice(0, index + 1);
  8703.       var numTextFragments = reduce(nodes, function (result, node, i) {
  8704.         if (isText$3(node) && isText$3(nodes[i - 1])) {
  8705.           result++;
  8706.         }
  8707.         return result;
  8708.       }, 0);
  8709.       nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
  8710.       index = findIndex$1(nodes, equal(node), node);
  8711.       return index - numTextFragments;
  8712.     };
  8713.     var createPathItem = function (node) {
  8714.       var name;
  8715.       if (isText$3(node)) {
  8716.         name = 'text()';
  8717.       } else {
  8718.         name = node.nodeName.toLowerCase();
  8719.       }
  8720.       return name + '[' + normalizedNodeIndex(node) + ']';
  8721.     };
  8722.     var parentsUntil$1 = function (root, node, predicate) {
  8723.       var parents = [];
  8724.       for (node = node.parentNode; node !== root; node = node.parentNode) {
  8725.         if (predicate && predicate(node)) {
  8726.           break;
  8727.         }
  8728.         parents.push(node);
  8729.       }
  8730.       return parents;
  8731.     };
  8732.     var create$6 = function (root, caretPosition) {
  8733.       var container, offset, path = [], outputOffset, childNodes, parents;
  8734.       container = caretPosition.container();
  8735.       offset = caretPosition.offset();
  8736.       if (isText$3(container)) {
  8737.         outputOffset = normalizedTextOffset(container, offset);
  8738.       } else {
  8739.         childNodes = container.childNodes;
  8740.         if (offset >= childNodes.length) {
  8741.           outputOffset = 'after';
  8742.           offset = childNodes.length - 1;
  8743.         } else {
  8744.           outputOffset = 'before';
  8745.         }
  8746.         container = childNodes[offset];
  8747.       }
  8748.       path.push(createPathItem(container));
  8749.       parents = parentsUntil$1(root, container);
  8750.       parents = filter$2(parents, not(isBogus$2));
  8751.       path = path.concat(map$1(parents, function (node) {
  8752.         return createPathItem(node);
  8753.       }));
  8754.       return path.reverse().join('/') + ',' + outputOffset;
  8755.     };
  8756.     var resolvePathItem = function (node, name, index) {
  8757.       var nodes = getChildNodes(node);
  8758.       nodes = filter$2(nodes, function (node, index) {
  8759.         return !isText$3(node) || !isText$3(nodes[index - 1]);
  8760.       });
  8761.       nodes = filter$2(nodes, matchNodeNames([name]));
  8762.       return nodes[index];
  8763.     };
  8764.     var findTextPosition = function (container, offset) {
  8765.       var node = container, targetOffset = 0, dataLen;
  8766.       while (isText$3(node)) {
  8767.         dataLen = node.data.length;
  8768.         if (offset >= targetOffset && offset <= targetOffset + dataLen) {
  8769.           container = node;
  8770.           offset = offset - targetOffset;
  8771.           break;
  8772.         }
  8773.         if (!isText$3(node.nextSibling)) {
  8774.           container = node;
  8775.           offset = dataLen;
  8776.           break;
  8777.         }
  8778.         targetOffset += dataLen;
  8779.         node = node.nextSibling;
  8780.       }
  8781.       if (isText$3(container) && offset > container.data.length) {
  8782.         offset = container.data.length;
  8783.       }
  8784.       return CaretPosition(container, offset);
  8785.     };
  8786.     var resolve$2 = function (root, path) {
  8787.       var offset;
  8788.       if (!path) {
  8789.         return null;
  8790.       }
  8791.       var parts = path.split(',');
  8792.       var paths = parts[0].split('/');
  8793.       offset = parts.length > 1 ? parts[1] : 'before';
  8794.       var container = reduce(paths, function (result, value) {
  8795.         var match = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value);
  8796.         if (!match) {
  8797.           return null;
  8798.         }
  8799.         if (match[1] === 'text()') {
  8800.           match[1] = '#text';
  8801.         }
  8802.         return resolvePathItem(result, match[1], parseInt(match[2], 10));
  8803.       }, root);
  8804.       if (!container) {
  8805.         return null;
  8806.       }
  8807.       if (!isText$3(container)) {
  8808.         if (offset === 'after') {
  8809.           offset = nodeIndex(container) + 1;
  8810.         } else {
  8811.           offset = nodeIndex(container);
  8812.         }
  8813.         return CaretPosition(container.parentNode, offset);
  8814.       }
  8815.       return findTextPosition(container, parseInt(offset, 10));
  8816.     };
  8817.  
  8818.     var isContentEditableFalse$9 = isContentEditableFalse$b;
  8819.     var getNormalizedTextOffset = function (trim, container, offset) {
  8820.       var node, trimmedOffset;
  8821.       trimmedOffset = trim(container.data.slice(0, offset)).length;
  8822.       for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
  8823.         trimmedOffset += trim(node.data).length;
  8824.       }
  8825.       return trimmedOffset;
  8826.     };
  8827.     var getPoint = function (dom, trim, normalized, rng, start) {
  8828.       var container = rng[start ? 'startContainer' : 'endContainer'];
  8829.       var offset = rng[start ? 'startOffset' : 'endOffset'];
  8830.       var point = [];
  8831.       var childNodes, after = 0;
  8832.       var root = dom.getRoot();
  8833.       if (isText$7(container)) {
  8834.         point.push(normalized ? getNormalizedTextOffset(trim, container, offset) : offset);
  8835.       } else {
  8836.         childNodes = container.childNodes;
  8837.         if (offset >= childNodes.length && childNodes.length) {
  8838.           after = 1;
  8839.           offset = Math.max(0, childNodes.length - 1);
  8840.         }
  8841.         point.push(dom.nodeIndex(childNodes[offset], normalized) + after);
  8842.       }
  8843.       for (; container && container !== root; container = container.parentNode) {
  8844.         point.push(dom.nodeIndex(container, normalized));
  8845.       }
  8846.       return point;
  8847.     };
  8848.     var getLocation = function (trim, selection, normalized, rng) {
  8849.       var dom = selection.dom, bookmark = {};
  8850.       bookmark.start = getPoint(dom, trim, normalized, rng, true);
  8851.       if (!selection.isCollapsed()) {
  8852.         bookmark.end = getPoint(dom, trim, normalized, rng, false);
  8853.       }
  8854.       if (isRangeInCaretContainerBlock(rng)) {
  8855.         bookmark.isFakeCaret = true;
  8856.       }
  8857.       return bookmark;
  8858.     };
  8859.     var findIndex = function (dom, name, element) {
  8860.       var count = 0;
  8861.       Tools.each(dom.select(name), function (node) {
  8862.         if (node.getAttribute('data-mce-bogus') === 'all') {
  8863.           return;
  8864.         }
  8865.         if (node === element) {
  8866.           return false;
  8867.         }
  8868.         count++;
  8869.       });
  8870.       return count;
  8871.     };
  8872.     var moveEndPoint$1 = function (rng, start) {
  8873.       var container, offset, childNodes;
  8874.       var prefix = start ? 'start' : 'end';
  8875.       container = rng[prefix + 'Container'];
  8876.       offset = rng[prefix + 'Offset'];
  8877.       if (isElement$5(container) && container.nodeName === 'TR') {
  8878.         childNodes = container.childNodes;
  8879.         container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  8880.         if (container) {
  8881.           offset = start ? 0 : container.childNodes.length;
  8882.           rng['set' + (start ? 'Start' : 'End')](container, offset);
  8883.         }
  8884.       }
  8885.     };
  8886.     var normalizeTableCellSelection = function (rng) {
  8887.       moveEndPoint$1(rng, true);
  8888.       moveEndPoint$1(rng, false);
  8889.       return rng;
  8890.     };
  8891.     var findSibling = function (node, offset) {
  8892.       var sibling;
  8893.       if (isElement$5(node)) {
  8894.         node = getNode$1(node, offset);
  8895.         if (isContentEditableFalse$9(node)) {
  8896.           return node;
  8897.         }
  8898.       }
  8899.       if (isCaretContainer$2(node)) {
  8900.         if (isText$7(node) && isCaretContainerBlock$1(node)) {
  8901.           node = node.parentNode;
  8902.         }
  8903.         sibling = node.previousSibling;
  8904.         if (isContentEditableFalse$9(sibling)) {
  8905.           return sibling;
  8906.         }
  8907.         sibling = node.nextSibling;
  8908.         if (isContentEditableFalse$9(sibling)) {
  8909.           return sibling;
  8910.         }
  8911.       }
  8912.     };
  8913.     var findAdjacentContentEditableFalseElm = function (rng) {
  8914.       return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
  8915.     };
  8916.     var getOffsetBookmark = function (trim, normalized, selection) {
  8917.       var element = selection.getNode();
  8918.       var name = element ? element.nodeName : null;
  8919.       var rng = selection.getRng();
  8920.       if (isContentEditableFalse$9(element) || name === 'IMG') {
  8921.         return {
  8922.           name: name,
  8923.           index: findIndex(selection.dom, name, element)
  8924.         };
  8925.       }
  8926.       var sibling = findAdjacentContentEditableFalseElm(rng);
  8927.       if (sibling) {
  8928.         name = sibling.tagName;
  8929.         return {
  8930.           name: name,
  8931.           index: findIndex(selection.dom, name, sibling)
  8932.         };
  8933.       }
  8934.       return getLocation(trim, selection, normalized, rng);
  8935.     };
  8936.     var getCaretBookmark = function (selection) {
  8937.       var rng = selection.getRng();
  8938.       return {
  8939.         start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
  8940.         end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
  8941.       };
  8942.     };
  8943.     var getRangeBookmark = function (selection) {
  8944.       return { rng: selection.getRng() };
  8945.     };
  8946.     var createBookmarkSpan = function (dom, id, filled) {
  8947.       var args = {
  8948.         'data-mce-type': 'bookmark',
  8949.         id: id,
  8950.         'style': 'overflow:hidden;line-height:0px'
  8951.       };
  8952.       return filled ? dom.create('span', args, '&#xFEFF;') : dom.create('span', args);
  8953.     };
  8954.     var getPersistentBookmark = function (selection, filled) {
  8955.       var dom = selection.dom;
  8956.       var rng = selection.getRng();
  8957.       var id = dom.uniqueId();
  8958.       var collapsed = selection.isCollapsed();
  8959.       var element = selection.getNode();
  8960.       var name = element.nodeName;
  8961.       if (name === 'IMG') {
  8962.         return {
  8963.           name: name,
  8964.           index: findIndex(dom, name, element)
  8965.         };
  8966.       }
  8967.       var rng2 = normalizeTableCellSelection(rng.cloneRange());
  8968.       if (!collapsed) {
  8969.         rng2.collapse(false);
  8970.         var endBookmarkNode = createBookmarkSpan(dom, id + '_end', filled);
  8971.         rangeInsertNode(dom, rng2, endBookmarkNode);
  8972.       }
  8973.       rng = normalizeTableCellSelection(rng);
  8974.       rng.collapse(true);
  8975.       var startBookmarkNode = createBookmarkSpan(dom, id + '_start', filled);
  8976.       rangeInsertNode(dom, rng, startBookmarkNode);
  8977.       selection.moveToBookmark({
  8978.         id: id,
  8979.         keep: true
  8980.       });
  8981.       return { id: id };
  8982.     };
  8983.     var getBookmark$2 = function (selection, type, normalized) {
  8984.       if (type === 2) {
  8985.         return getOffsetBookmark(trim$3, normalized, selection);
  8986.       } else if (type === 3) {
  8987.         return getCaretBookmark(selection);
  8988.       } else if (type) {
  8989.         return getRangeBookmark(selection);
  8990.       } else {
  8991.         return getPersistentBookmark(selection, false);
  8992.       }
  8993.     };
  8994.     var getUndoBookmark = curry(getOffsetBookmark, identity, true);
  8995.  
  8996.     var DOM$9 = DOMUtils.DOM;
  8997.     var defaultPreviewStyles = 'font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow';
  8998.     var getBodySetting = function (editor, name, defaultValue) {
  8999.       var value = editor.getParam(name, defaultValue);
  9000.       if (value.indexOf('=') !== -1) {
  9001.         var bodyObj = editor.getParam(name, '', 'hash');
  9002.         return get$9(bodyObj, editor.id).getOr(defaultValue);
  9003.       } else {
  9004.         return value;
  9005.       }
  9006.     };
  9007.     var getIframeAttrs = function (editor) {
  9008.       return editor.getParam('iframe_attrs', {});
  9009.     };
  9010.     var getDocType = function (editor) {
  9011.       return editor.getParam('doctype', '<!DOCTYPE html>');
  9012.     };
  9013.     var getDocumentBaseUrl = function (editor) {
  9014.       return editor.getParam('document_base_url', '');
  9015.     };
  9016.     var getBodyId = function (editor) {
  9017.       return getBodySetting(editor, 'body_id', 'tinymce');
  9018.     };
  9019.     var getBodyClass = function (editor) {
  9020.       return getBodySetting(editor, 'body_class', '');
  9021.     };
  9022.     var getContentSecurityPolicy = function (editor) {
  9023.       return editor.getParam('content_security_policy', '');
  9024.     };
  9025.     var shouldPutBrInPre$1 = function (editor) {
  9026.       return editor.getParam('br_in_pre', true);
  9027.     };
  9028.     var getForcedRootBlock = function (editor) {
  9029.       if (editor.getParam('force_p_newlines', false)) {
  9030.         return 'p';
  9031.       }
  9032.       var block = editor.getParam('forced_root_block', 'p');
  9033.       if (block === false) {
  9034.         return '';
  9035.       } else if (block === true) {
  9036.         return 'p';
  9037.       } else {
  9038.         return block;
  9039.       }
  9040.     };
  9041.     var getForcedRootBlockAttrs = function (editor) {
  9042.       return editor.getParam('forced_root_block_attrs', {});
  9043.     };
  9044.     var getBrNewLineSelector = function (editor) {
  9045.       return editor.getParam('br_newline_selector', '.mce-toc h2,figcaption,caption');
  9046.     };
  9047.     var getNoNewLineSelector = function (editor) {
  9048.       return editor.getParam('no_newline_selector', '');
  9049.     };
  9050.     var shouldKeepStyles = function (editor) {
  9051.       return editor.getParam('keep_styles', true);
  9052.     };
  9053.     var shouldEndContainerOnEmptyBlock = function (editor) {
  9054.       return editor.getParam('end_container_on_empty_block', false);
  9055.     };
  9056.     var getFontStyleValues = function (editor) {
  9057.       return Tools.explode(editor.getParam('font_size_style_values', 'xx-small,x-small,small,medium,large,x-large,xx-large'));
  9058.     };
  9059.     var getFontSizeClasses = function (editor) {
  9060.       return Tools.explode(editor.getParam('font_size_classes', ''));
  9061.     };
  9062.     var getImagesDataImgFilter = function (editor) {
  9063.       return editor.getParam('images_dataimg_filter', always, 'function');
  9064.     };
  9065.     var isAutomaticUploadsEnabled = function (editor) {
  9066.       return editor.getParam('automatic_uploads', true, 'boolean');
  9067.     };
  9068.     var shouldReuseFileName = function (editor) {
  9069.       return editor.getParam('images_reuse_filename', false, 'boolean');
  9070.     };
  9071.     var shouldReplaceBlobUris = function (editor) {
  9072.       return editor.getParam('images_replace_blob_uris', true, 'boolean');
  9073.     };
  9074.     var getIconPackName = function (editor) {
  9075.       return editor.getParam('icons', '', 'string');
  9076.     };
  9077.     var getIconsUrl = function (editor) {
  9078.       return editor.getParam('icons_url', '', 'string');
  9079.     };
  9080.     var getImageUploadUrl = function (editor) {
  9081.       return editor.getParam('images_upload_url', '', 'string');
  9082.     };
  9083.     var getImageUploadBasePath = function (editor) {
  9084.       return editor.getParam('images_upload_base_path', '', 'string');
  9085.     };
  9086.     var getImagesUploadCredentials = function (editor) {
  9087.       return editor.getParam('images_upload_credentials', false, 'boolean');
  9088.     };
  9089.     var getImagesUploadHandler = function (editor) {
  9090.       return editor.getParam('images_upload_handler', null, 'function');
  9091.     };
  9092.     var shouldUseContentCssCors = function (editor) {
  9093.       return editor.getParam('content_css_cors', false, 'boolean');
  9094.     };
  9095.     var getReferrerPolicy = function (editor) {
  9096.       return editor.getParam('referrer_policy', '', 'string');
  9097.     };
  9098.     var getLanguageCode = function (editor) {
  9099.       return editor.getParam('language', 'en', 'string');
  9100.     };
  9101.     var getLanguageUrl = function (editor) {
  9102.       return editor.getParam('language_url', '', 'string');
  9103.     };
  9104.     var shouldIndentUseMargin = function (editor) {
  9105.       return editor.getParam('indent_use_margin', false);
  9106.     };
  9107.     var getIndentation = function (editor) {
  9108.       return editor.getParam('indentation', '40px', 'string');
  9109.     };
  9110.     var getContentCss = function (editor) {
  9111.       var contentCss = editor.getParam('content_css');
  9112.       if (isString$1(contentCss)) {
  9113.         return map$3(contentCss.split(','), trim$5);
  9114.       } else if (isArray$1(contentCss)) {
  9115.         return contentCss;
  9116.       } else if (contentCss === false || editor.inline) {
  9117.         return [];
  9118.       } else {
  9119.         return ['default'];
  9120.       }
  9121.     };
  9122.     var getFontCss = function (editor) {
  9123.       var fontCss = editor.getParam('font_css', []);
  9124.       return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(','), trim$5);
  9125.     };
  9126.     var getDirectionality = function (editor) {
  9127.       return editor.getParam('directionality', I18n.isRtl() ? 'rtl' : undefined);
  9128.     };
  9129.     var getInlineBoundarySelector = function (editor) {
  9130.       return editor.getParam('inline_boundaries_selector', 'a[href],code,.mce-annotation', 'string');
  9131.     };
  9132.     var getObjectResizing = function (editor) {
  9133.       var selector = editor.getParam('object_resizing');
  9134.       if (selector === false || Env.iOS) {
  9135.         return false;
  9136.       } else {
  9137.         return isString$1(selector) ? selector : 'table,img,figure.image,div,video,iframe';
  9138.       }
  9139.     };
  9140.     var getResizeImgProportional = function (editor) {
  9141.       return editor.getParam('resize_img_proportional', true, 'boolean');
  9142.     };
  9143.     var getPlaceholder = function (editor) {
  9144.       return editor.getParam('placeholder', DOM$9.getAttrib(editor.getElement(), 'placeholder'), 'string');
  9145.     };
  9146.     var getEventRoot = function (editor) {
  9147.       return editor.getParam('event_root');
  9148.     };
  9149.     var getServiceMessage = function (editor) {
  9150.       return editor.getParam('service_message');
  9151.     };
  9152.     var getTheme = function (editor) {
  9153.       return editor.getParam('theme');
  9154.     };
  9155.     var shouldValidate = function (editor) {
  9156.       return editor.getParam('validate');
  9157.     };
  9158.     var isInlineBoundariesEnabled = function (editor) {
  9159.       return editor.getParam('inline_boundaries') !== false;
  9160.     };
  9161.     var getFormats = function (editor) {
  9162.       return editor.getParam('formats');
  9163.     };
  9164.     var getPreviewStyles = function (editor) {
  9165.       var style = editor.getParam('preview_styles', defaultPreviewStyles);
  9166.       if (isString$1(style)) {
  9167.         return style;
  9168.       } else {
  9169.         return '';
  9170.       }
  9171.     };
  9172.     var canFormatEmptyLines = function (editor) {
  9173.       return editor.getParam('format_empty_lines', false, 'boolean');
  9174.     };
  9175.     var getCustomUiSelector = function (editor) {
  9176.       return editor.getParam('custom_ui_selector', '', 'string');
  9177.     };
  9178.     var getThemeUrl = function (editor) {
  9179.       return editor.getParam('theme_url');
  9180.     };
  9181.     var isInline = function (editor) {
  9182.       return editor.getParam('inline');
  9183.     };
  9184.     var hasHiddenInput = function (editor) {
  9185.       return editor.getParam('hidden_input');
  9186.     };
  9187.     var shouldPatchSubmit = function (editor) {
  9188.       return editor.getParam('submit_patch');
  9189.     };
  9190.     var isEncodingXml = function (editor) {
  9191.       return editor.getParam('encoding') === 'xml';
  9192.     };
  9193.     var shouldAddFormSubmitTrigger = function (editor) {
  9194.       return editor.getParam('add_form_submit_trigger');
  9195.     };
  9196.     var shouldAddUnloadTrigger = function (editor) {
  9197.       return editor.getParam('add_unload_trigger');
  9198.     };
  9199.     var hasForcedRootBlock = function (editor) {
  9200.       return getForcedRootBlock(editor) !== '';
  9201.     };
  9202.     var getCustomUndoRedoLevels = function (editor) {
  9203.       return editor.getParam('custom_undo_redo_levels', 0, 'number');
  9204.     };
  9205.     var shouldDisableNodeChange = function (editor) {
  9206.       return editor.getParam('disable_nodechange');
  9207.     };
  9208.     var isReadOnly$1 = function (editor) {
  9209.       return editor.getParam('readonly');
  9210.     };
  9211.     var hasContentCssCors = function (editor) {
  9212.       return editor.getParam('content_css_cors');
  9213.     };
  9214.     var getPlugins = function (editor) {
  9215.       return editor.getParam('plugins', '', 'string');
  9216.     };
  9217.     var getExternalPlugins$1 = function (editor) {
  9218.       return editor.getParam('external_plugins');
  9219.     };
  9220.     var shouldBlockUnsupportedDrop = function (editor) {
  9221.       return editor.getParam('block_unsupported_drop', true, 'boolean');
  9222.     };
  9223.     var isVisualAidsEnabled = function (editor) {
  9224.       return editor.getParam('visual', true, 'boolean');
  9225.     };
  9226.     var getVisualAidsTableClass = function (editor) {
  9227.       return editor.getParam('visual_table_class', 'mce-item-table', 'string');
  9228.     };
  9229.     var getVisualAidsAnchorClass = function (editor) {
  9230.       return editor.getParam('visual_anchor_class', 'mce-item-anchor', 'string');
  9231.     };
  9232.     var getIframeAriaText = function (editor) {
  9233.       return editor.getParam('iframe_aria_text', 'Rich Text Area. Press ALT-0 for help.', 'string');
  9234.     };
  9235.  
  9236.     var isElement$2 = isElement$5;
  9237.     var isText$2 = isText$7;
  9238.     var removeNode$1 = function (node) {
  9239.       var parentNode = node.parentNode;
  9240.       if (parentNode) {
  9241.         parentNode.removeChild(node);
  9242.       }
  9243.     };
  9244.     var trimCount = function (text) {
  9245.       var trimmedText = trim$3(text);
  9246.       return {
  9247.         count: text.length - trimmedText.length,
  9248.         text: trimmedText
  9249.       };
  9250.     };
  9251.     var deleteZwspChars = function (caretContainer) {
  9252.       var idx;
  9253.       while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
  9254.         caretContainer.deleteData(idx, 1);
  9255.       }
  9256.     };
  9257.     var removeUnchanged = function (caretContainer, pos) {
  9258.       remove$2(caretContainer);
  9259.       return pos;
  9260.     };
  9261.     var removeTextAndReposition = function (caretContainer, pos) {
  9262.       var before = trimCount(caretContainer.data.substr(0, pos.offset()));
  9263.       var after = trimCount(caretContainer.data.substr(pos.offset()));
  9264.       var text = before.text + after.text;
  9265.       if (text.length > 0) {
  9266.         deleteZwspChars(caretContainer);
  9267.         return CaretPosition(caretContainer, pos.offset() - before.count);
  9268.       } else {
  9269.         return pos;
  9270.       }
  9271.     };
  9272.     var removeElementAndReposition = function (caretContainer, pos) {
  9273.       var parentNode = pos.container();
  9274.       var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function (index) {
  9275.         return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
  9276.       }).getOr(pos);
  9277.       remove$2(caretContainer);
  9278.       return newPosition;
  9279.     };
  9280.     var removeTextCaretContainer = function (caretContainer, pos) {
  9281.       return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9282.     };
  9283.     var removeElementCaretContainer = function (caretContainer, pos) {
  9284.       return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
  9285.     };
  9286.     var removeAndReposition = function (container, pos) {
  9287.       return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
  9288.     };
  9289.     var remove$2 = function (caretContainerNode) {
  9290.       if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
  9291.         if (hasContent(caretContainerNode)) {
  9292.           caretContainerNode.removeAttribute('data-mce-caret');
  9293.         } else {
  9294.           removeNode$1(caretContainerNode);
  9295.         }
  9296.       }
  9297.       if (isText$2(caretContainerNode)) {
  9298.         deleteZwspChars(caretContainerNode);
  9299.         if (caretContainerNode.data.length === 0) {
  9300.           removeNode$1(caretContainerNode);
  9301.         }
  9302.       }
  9303.     };
  9304.  
  9305.     var browser$2 = detect().browser;
  9306.     var isContentEditableFalse$8 = isContentEditableFalse$b;
  9307.     var isMedia$1 = isMedia$2;
  9308.     var isTableCell$3 = isTableCell$5;
  9309.     var inlineFakeCaretSelector = '*[contentEditable=false],video,audio,embed,object';
  9310.     var getAbsoluteClientRect = function (root, element, before) {
  9311.       var clientRect = collapse(element.getBoundingClientRect(), before);
  9312.       var scrollX;
  9313.       var scrollY;
  9314.       if (root.tagName === 'BODY') {
  9315.         var docElm = root.ownerDocument.documentElement;
  9316.         scrollX = root.scrollLeft || docElm.scrollLeft;
  9317.         scrollY = root.scrollTop || docElm.scrollTop;
  9318.       } else {
  9319.         var rootRect = root.getBoundingClientRect();
  9320.         scrollX = root.scrollLeft - rootRect.left;
  9321.         scrollY = root.scrollTop - rootRect.top;
  9322.       }
  9323.       clientRect.left += scrollX;
  9324.       clientRect.right += scrollX;
  9325.       clientRect.top += scrollY;
  9326.       clientRect.bottom += scrollY;
  9327.       clientRect.width = 1;
  9328.       var margin = element.offsetWidth - element.clientWidth;
  9329.       if (margin > 0) {
  9330.         if (before) {
  9331.           margin *= -1;
  9332.         }
  9333.         clientRect.left += margin;
  9334.         clientRect.right += margin;
  9335.       }
  9336.       return clientRect;
  9337.     };
  9338.     var trimInlineCaretContainers = function (root) {
  9339.       var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
  9340.       for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
  9341.         var node = fakeCaretTargetNodes[i].dom;
  9342.         var sibling = node.previousSibling;
  9343.         if (endsWithCaretContainer$1(sibling)) {
  9344.           var data = sibling.data;
  9345.           if (data.length === 1) {
  9346.             sibling.parentNode.removeChild(sibling);
  9347.           } else {
  9348.             sibling.deleteData(data.length - 1, 1);
  9349.           }
  9350.         }
  9351.         sibling = node.nextSibling;
  9352.         if (startsWithCaretContainer$1(sibling)) {
  9353.           var data = sibling.data;
  9354.           if (data.length === 1) {
  9355.             sibling.parentNode.removeChild(sibling);
  9356.           } else {
  9357.             sibling.deleteData(0, 1);
  9358.           }
  9359.         }
  9360.       }
  9361.     };
  9362.     var FakeCaret = function (editor, root, isBlock, hasFocus) {
  9363.       var lastVisualCaret = value();
  9364.       var cursorInterval;
  9365.       var caretContainerNode;
  9366.       var rootBlock = getForcedRootBlock(editor);
  9367.       var caretBlock = rootBlock.length > 0 ? rootBlock : 'p';
  9368.       var show = function (before, element) {
  9369.         var rng;
  9370.         hide();
  9371.         if (isTableCell$3(element)) {
  9372.           return null;
  9373.         }
  9374.         if (isBlock(element)) {
  9375.           caretContainerNode = insertBlock$1(caretBlock, element, before);
  9376.           var clientRect = getAbsoluteClientRect(root, element, before);
  9377.           DomQuery(caretContainerNode).css('top', clientRect.top);
  9378.           var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
  9379.           lastVisualCaret.set({
  9380.             caret: caret,
  9381.             element: element,
  9382.             before: before
  9383.           });
  9384.           if (before) {
  9385.             DomQuery(caret).addClass('mce-visual-caret-before');
  9386.           }
  9387.           startBlink();
  9388.           rng = element.ownerDocument.createRange();
  9389.           rng.setStart(caretContainerNode, 0);
  9390.           rng.setEnd(caretContainerNode, 0);
  9391.         } else {
  9392.           caretContainerNode = insertInline$1(element, before);
  9393.           rng = element.ownerDocument.createRange();
  9394.           if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
  9395.             rng.setStart(caretContainerNode, 0);
  9396.             rng.setEnd(caretContainerNode, 0);
  9397.           } else {
  9398.             rng.setStart(caretContainerNode, 1);
  9399.             rng.setEnd(caretContainerNode, 1);
  9400.           }
  9401.           return rng;
  9402.         }
  9403.         return rng;
  9404.       };
  9405.       var hide = function () {
  9406.         trimInlineCaretContainers(root);
  9407.         if (caretContainerNode) {
  9408.           remove$2(caretContainerNode);
  9409.           caretContainerNode = null;
  9410.         }
  9411.         lastVisualCaret.on(function (caretState) {
  9412.           DomQuery(caretState.caret).remove();
  9413.           lastVisualCaret.clear();
  9414.         });
  9415.         if (cursorInterval) {
  9416.           Delay.clearInterval(cursorInterval);
  9417.           cursorInterval = undefined;
  9418.         }
  9419.       };
  9420.       var startBlink = function () {
  9421.         cursorInterval = Delay.setInterval(function () {
  9422.           if (hasFocus()) {
  9423.             DomQuery('div.mce-visual-caret', root).toggleClass('mce-visual-caret-hidden');
  9424.           } else {
  9425.             DomQuery('div.mce-visual-caret', root).addClass('mce-visual-caret-hidden');
  9426.           }
  9427.         }, 500);
  9428.       };
  9429.       var reposition = function () {
  9430.         lastVisualCaret.on(function (caretState) {
  9431.           var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
  9432.           DomQuery(caretState.caret).css(__assign({}, clientRect));
  9433.         });
  9434.       };
  9435.       var destroy = function () {
  9436.         return Delay.clearInterval(cursorInterval);
  9437.       };
  9438.       var getCss = function () {
  9439.         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;' + '}';
  9440.       };
  9441.       return {
  9442.         show: show,
  9443.         hide: hide,
  9444.         getCss: getCss,
  9445.         reposition: reposition,
  9446.         destroy: destroy
  9447.       };
  9448.     };
  9449.     var isFakeCaretTableBrowser = function () {
  9450.       return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
  9451.     };
  9452.     var isInlineFakeCaretTarget = function (node) {
  9453.       return isContentEditableFalse$8(node) || isMedia$1(node);
  9454.     };
  9455.     var isFakeCaretTarget = function (node) {
  9456.       return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
  9457.     };
  9458.  
  9459.     var isContentEditableFalse$7 = isContentEditableFalse$b;
  9460.     var isMedia = isMedia$2;
  9461.     var isBlockLike = matchStyleValues('display', 'block table table-cell table-caption list-item');
  9462.     var isCaretContainer = isCaretContainer$2;
  9463.     var isCaretContainerBlock = isCaretContainerBlock$1;
  9464.     var isElement$1 = isElement$5;
  9465.     var isCaretCandidate$1 = isCaretCandidate$3;
  9466.     var isForwards = function (direction) {
  9467.       return direction > 0;
  9468.     };
  9469.     var isBackwards = function (direction) {
  9470.       return direction < 0;
  9471.     };
  9472.     var skipCaretContainers = function (walk, shallow) {
  9473.       var node;
  9474.       while (node = walk(shallow)) {
  9475.         if (!isCaretContainerBlock(node)) {
  9476.           return node;
  9477.         }
  9478.       }
  9479.       return null;
  9480.     };
  9481.     var findNode$1 = function (node, direction, predicateFn, rootNode, shallow) {
  9482.       var walker = new DomTreeWalker(node, rootNode);
  9483.       var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
  9484.       if (isBackwards(direction)) {
  9485.         if (isCefOrCaretContainer) {
  9486.           node = skipCaretContainers(walker.prev.bind(walker), true);
  9487.           if (predicateFn(node)) {
  9488.             return node;
  9489.           }
  9490.         }
  9491.         while (node = skipCaretContainers(walker.prev.bind(walker), shallow)) {
  9492.           if (predicateFn(node)) {
  9493.             return node;
  9494.           }
  9495.         }
  9496.       }
  9497.       if (isForwards(direction)) {
  9498.         if (isCefOrCaretContainer) {
  9499.           node = skipCaretContainers(walker.next.bind(walker), true);
  9500.           if (predicateFn(node)) {
  9501.             return node;
  9502.           }
  9503.         }
  9504.         while (node = skipCaretContainers(walker.next.bind(walker), shallow)) {
  9505.           if (predicateFn(node)) {
  9506.             return node;
  9507.           }
  9508.         }
  9509.       }
  9510.       return null;
  9511.     };
  9512.     var getParentBlock$2 = function (node, rootNode) {
  9513.       while (node && node !== rootNode) {
  9514.         if (isBlockLike(node)) {
  9515.           return node;
  9516.         }
  9517.         node = node.parentNode;
  9518.       }
  9519.       return null;
  9520.     };
  9521.     var isInSameBlock = function (caretPosition1, caretPosition2, rootNode) {
  9522.       return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
  9523.     };
  9524.     var getChildNodeAtRelativeOffset = function (relativeOffset, caretPosition) {
  9525.       if (!caretPosition) {
  9526.         return null;
  9527.       }
  9528.       var container = caretPosition.container();
  9529.       var offset = caretPosition.offset();
  9530.       if (!isElement$1(container)) {
  9531.         return null;
  9532.       }
  9533.       return container.childNodes[offset + relativeOffset];
  9534.     };
  9535.     var beforeAfter = function (before, node) {
  9536.       var range = node.ownerDocument.createRange();
  9537.       if (before) {
  9538.         range.setStartBefore(node);
  9539.         range.setEndBefore(node);
  9540.       } else {
  9541.         range.setStartAfter(node);
  9542.         range.setEndAfter(node);
  9543.       }
  9544.       return range;
  9545.     };
  9546.     var isNodesInSameBlock = function (root, node1, node2) {
  9547.       return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
  9548.     };
  9549.     var lean = function (left, root, node) {
  9550.       var siblingName = left ? 'previousSibling' : 'nextSibling';
  9551.       while (node && node !== root) {
  9552.         var sibling = node[siblingName];
  9553.         if (isCaretContainer(sibling)) {
  9554.           sibling = sibling[siblingName];
  9555.         }
  9556.         if (isContentEditableFalse$7(sibling) || isMedia(sibling)) {
  9557.           if (isNodesInSameBlock(root, sibling, node)) {
  9558.             return sibling;
  9559.           }
  9560.           break;
  9561.         }
  9562.         if (isCaretCandidate$1(sibling)) {
  9563.           break;
  9564.         }
  9565.         node = node.parentNode;
  9566.       }
  9567.       return null;
  9568.     };
  9569.     var before$2 = curry(beforeAfter, true);
  9570.     var after$2 = curry(beforeAfter, false);
  9571.     var normalizeRange = function (direction, root, range) {
  9572.       var node;
  9573.       var leanLeft = curry(lean, true, root);
  9574.       var leanRight = curry(lean, false, root);
  9575.       var container = range.startContainer;
  9576.       var offset = range.startOffset;
  9577.       if (isCaretContainerBlock$1(container)) {
  9578.         if (!isElement$1(container)) {
  9579.           container = container.parentNode;
  9580.         }
  9581.         var location_1 = container.getAttribute('data-mce-caret');
  9582.         if (location_1 === 'before') {
  9583.           node = container.nextSibling;
  9584.           if (isFakeCaretTarget(node)) {
  9585.             return before$2(node);
  9586.           }
  9587.         }
  9588.         if (location_1 === 'after') {
  9589.           node = container.previousSibling;
  9590.           if (isFakeCaretTarget(node)) {
  9591.             return after$2(node);
  9592.           }
  9593.         }
  9594.       }
  9595.       if (!range.collapsed) {
  9596.         return range;
  9597.       }
  9598.       if (isText$7(container)) {
  9599.         if (isCaretContainer(container)) {
  9600.           if (direction === 1) {
  9601.             node = leanRight(container);
  9602.             if (node) {
  9603.               return before$2(node);
  9604.             }
  9605.             node = leanLeft(container);
  9606.             if (node) {
  9607.               return after$2(node);
  9608.             }
  9609.           }
  9610.           if (direction === -1) {
  9611.             node = leanLeft(container);
  9612.             if (node) {
  9613.               return after$2(node);
  9614.             }
  9615.             node = leanRight(container);
  9616.             if (node) {
  9617.               return before$2(node);
  9618.             }
  9619.           }
  9620.           return range;
  9621.         }
  9622.         if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
  9623.           if (direction === 1) {
  9624.             node = leanRight(container);
  9625.             if (node) {
  9626.               return before$2(node);
  9627.             }
  9628.           }
  9629.           return range;
  9630.         }
  9631.         if (startsWithCaretContainer$1(container) && offset <= 1) {
  9632.           if (direction === -1) {
  9633.             node = leanLeft(container);
  9634.             if (node) {
  9635.               return after$2(node);
  9636.             }
  9637.           }
  9638.           return range;
  9639.         }
  9640.         if (offset === container.data.length) {
  9641.           node = leanRight(container);
  9642.           if (node) {
  9643.             return before$2(node);
  9644.           }
  9645.           return range;
  9646.         }
  9647.         if (offset === 0) {
  9648.           node = leanLeft(container);
  9649.           if (node) {
  9650.             return after$2(node);
  9651.           }
  9652.           return range;
  9653.         }
  9654.       }
  9655.       return range;
  9656.     };
  9657.     var getRelativeCefElm = function (forward, caretPosition) {
  9658.       return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
  9659.     };
  9660.     var getNormalizedRangeEndPoint = function (direction, root, range) {
  9661.       var normalizedRange = normalizeRange(direction, root, range);
  9662.       if (direction === -1) {
  9663.         return CaretPosition.fromRangeStart(normalizedRange);
  9664.       }
  9665.       return CaretPosition.fromRangeEnd(normalizedRange);
  9666.     };
  9667.     var getElementFromPosition = function (pos) {
  9668.       return Optional.from(pos.getNode()).map(SugarElement.fromDom);
  9669.     };
  9670.     var getElementFromPrevPosition = function (pos) {
  9671.       return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
  9672.     };
  9673.     var getVisualCaretPosition = function (walkFn, caretPosition) {
  9674.       while (caretPosition = walkFn(caretPosition)) {
  9675.         if (caretPosition.isVisible()) {
  9676.           return caretPosition;
  9677.         }
  9678.       }
  9679.       return caretPosition;
  9680.     };
  9681.     var isMoveInsideSameBlock = function (from, to) {
  9682.       var inSameBlock = isInSameBlock(from, to);
  9683.       if (!inSameBlock && isBr$5(from.getNode())) {
  9684.         return true;
  9685.       }
  9686.       return inSameBlock;
  9687.     };
  9688.  
  9689.     var HDirection;
  9690.     (function (HDirection) {
  9691.       HDirection[HDirection['Backwards'] = -1] = 'Backwards';
  9692.       HDirection[HDirection['Forwards'] = 1] = 'Forwards';
  9693.     }(HDirection || (HDirection = {})));
  9694.     var isContentEditableFalse$6 = isContentEditableFalse$b;
  9695.     var isText$1 = isText$7;
  9696.     var isElement = isElement$5;
  9697.     var isBr$1 = isBr$5;
  9698.     var isCaretCandidate = isCaretCandidate$3;
  9699.     var isAtomic = isAtomic$1;
  9700.     var isEditableCaretCandidate = isEditableCaretCandidate$1;
  9701.     var getParents$3 = function (node, root) {
  9702.       var parents = [];
  9703.       while (node && node !== root) {
  9704.         parents.push(node);
  9705.         node = node.parentNode;
  9706.       }
  9707.       return parents;
  9708.     };
  9709.     var nodeAtIndex = function (container, offset) {
  9710.       if (container.hasChildNodes() && offset < container.childNodes.length) {
  9711.         return container.childNodes[offset];
  9712.       }
  9713.       return null;
  9714.     };
  9715.     var getCaretCandidatePosition = function (direction, node) {
  9716.       if (isForwards(direction)) {
  9717.         if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
  9718.           return CaretPosition.before(node);
  9719.         }
  9720.         if (isText$1(node)) {
  9721.           return CaretPosition(node, 0);
  9722.         }
  9723.       }
  9724.       if (isBackwards(direction)) {
  9725.         if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
  9726.           return CaretPosition.after(node);
  9727.         }
  9728.         if (isText$1(node)) {
  9729.           return CaretPosition(node, node.data.length);
  9730.         }
  9731.       }
  9732.       if (isBackwards(direction)) {
  9733.         if (isBr$1(node)) {
  9734.           return CaretPosition.before(node);
  9735.         }
  9736.         return CaretPosition.after(node);
  9737.       }
  9738.       return CaretPosition.before(node);
  9739.     };
  9740.     var moveForwardFromBr = function (root, nextNode) {
  9741.       var nextSibling = nextNode.nextSibling;
  9742.       if (nextSibling && isCaretCandidate(nextSibling)) {
  9743.         if (isText$1(nextSibling)) {
  9744.           return CaretPosition(nextSibling, 0);
  9745.         } else {
  9746.           return CaretPosition.before(nextSibling);
  9747.         }
  9748.       } else {
  9749.         return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
  9750.       }
  9751.     };
  9752.     var findCaretPosition$1 = function (direction, startPos, root) {
  9753.       var node;
  9754.       var nextNode;
  9755.       var innerNode;
  9756.       var caretPosition;
  9757.       if (!isElement(root) || !startPos) {
  9758.         return null;
  9759.       }
  9760.       if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
  9761.         caretPosition = CaretPosition.after(root.lastChild);
  9762.         if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
  9763.           return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
  9764.         }
  9765.       } else {
  9766.         caretPosition = startPos;
  9767.       }
  9768.       var container = caretPosition.container();
  9769.       var offset = caretPosition.offset();
  9770.       if (isText$1(container)) {
  9771.         if (isBackwards(direction) && offset > 0) {
  9772.           return CaretPosition(container, --offset);
  9773.         }
  9774.         if (isForwards(direction) && offset < container.length) {
  9775.           return CaretPosition(container, ++offset);
  9776.         }
  9777.         node = container;
  9778.       } else {
  9779.         if (isBackwards(direction) && offset > 0) {
  9780.           nextNode = nodeAtIndex(container, offset - 1);
  9781.           if (isCaretCandidate(nextNode)) {
  9782.             if (!isAtomic(nextNode)) {
  9783.               innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9784.               if (innerNode) {
  9785.                 if (isText$1(innerNode)) {
  9786.                   return CaretPosition(innerNode, innerNode.data.length);
  9787.                 }
  9788.                 return CaretPosition.after(innerNode);
  9789.               }
  9790.             }
  9791.             if (isText$1(nextNode)) {
  9792.               return CaretPosition(nextNode, nextNode.data.length);
  9793.             }
  9794.             return CaretPosition.before(nextNode);
  9795.           }
  9796.         }
  9797.         if (isForwards(direction) && offset < container.childNodes.length) {
  9798.           nextNode = nodeAtIndex(container, offset);
  9799.           if (isCaretCandidate(nextNode)) {
  9800.             if (isBr$1(nextNode)) {
  9801.               return moveForwardFromBr(root, nextNode);
  9802.             }
  9803.             if (!isAtomic(nextNode)) {
  9804.               innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
  9805.               if (innerNode) {
  9806.                 if (isText$1(innerNode)) {
  9807.                   return CaretPosition(innerNode, 0);
  9808.                 }
  9809.                 return CaretPosition.before(innerNode);
  9810.               }
  9811.             }
  9812.             if (isText$1(nextNode)) {
  9813.               return CaretPosition(nextNode, 0);
  9814.             }
  9815.             return CaretPosition.after(nextNode);
  9816.           }
  9817.         }
  9818.         node = nextNode ? nextNode : caretPosition.getNode();
  9819.       }
  9820.       if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
  9821.         node = findNode$1(node, direction, always, root, true);
  9822.         if (isEditableCaretCandidate(node, root)) {
  9823.           return getCaretCandidatePosition(direction, node);
  9824.         }
  9825.       }
  9826.       nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
  9827.       var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
  9828.       if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
  9829.         if (isForwards(direction)) {
  9830.           caretPosition = CaretPosition.after(rootContentEditableFalseElm);
  9831.         } else {
  9832.           caretPosition = CaretPosition.before(rootContentEditableFalseElm);
  9833.         }
  9834.         return caretPosition;
  9835.       }
  9836.       if (nextNode) {
  9837.         return getCaretCandidatePosition(direction, nextNode);
  9838.       }
  9839.       return null;
  9840.     };
  9841.     var CaretWalker = function (root) {
  9842.       return {
  9843.         next: function (caretPosition) {
  9844.           return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
  9845.         },
  9846.         prev: function (caretPosition) {
  9847.           return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
  9848.         }
  9849.       };
  9850.     };
  9851.  
  9852.     var walkToPositionIn = function (forward, root, start) {
  9853.       var position = forward ? CaretPosition.before(start) : CaretPosition.after(start);
  9854.       return fromPosition(forward, root, position);
  9855.     };
  9856.     var afterElement = function (node) {
  9857.       return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
  9858.     };
  9859.     var isBeforeOrStart = function (position) {
  9860.       if (CaretPosition.isTextPosition(position)) {
  9861.         return position.offset() === 0;
  9862.       } else {
  9863.         return isCaretCandidate$3(position.getNode());
  9864.       }
  9865.     };
  9866.     var isAfterOrEnd = function (position) {
  9867.       if (CaretPosition.isTextPosition(position)) {
  9868.         var container = position.container();
  9869.         return position.offset() === container.data.length;
  9870.       } else {
  9871.         return isCaretCandidate$3(position.getNode(true));
  9872.       }
  9873.     };
  9874.     var isBeforeAfterSameElement = function (from, to) {
  9875.       return !CaretPosition.isTextPosition(from) && !CaretPosition.isTextPosition(to) && from.getNode() === to.getNode(true);
  9876.     };
  9877.     var isAtBr = function (position) {
  9878.       return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
  9879.     };
  9880.     var shouldSkipPosition = function (forward, from, to) {
  9881.       if (forward) {
  9882.         return !isBeforeAfterSameElement(from, to) && !isAtBr(from) && isAfterOrEnd(from) && isBeforeOrStart(to);
  9883.       } else {
  9884.         return !isBeforeAfterSameElement(to, from) && isBeforeOrStart(from) && isAfterOrEnd(to);
  9885.       }
  9886.     };
  9887.     var fromPosition = function (forward, root, pos) {
  9888.       var walker = CaretWalker(root);
  9889.       return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
  9890.     };
  9891.     var navigate = function (forward, root, from) {
  9892.       return fromPosition(forward, root, from).bind(function (to) {
  9893.         if (isInSameBlock(from, to, root) && shouldSkipPosition(forward, from, to)) {
  9894.           return fromPosition(forward, root, to);
  9895.         } else {
  9896.           return Optional.some(to);
  9897.         }
  9898.       });
  9899.     };
  9900.     var navigateIgnore = function (forward, root, from, ignoreFilter) {
  9901.       return navigate(forward, root, from).bind(function (pos) {
  9902.         return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
  9903.       });
  9904.     };
  9905.     var positionIn = function (forward, element) {
  9906.       var startNode = forward ? element.firstChild : element.lastChild;
  9907.       if (isText$7(startNode)) {
  9908.         return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
  9909.       } else if (startNode) {
  9910.         if (isCaretCandidate$3(startNode)) {
  9911.           return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
  9912.         } else {
  9913.           return walkToPositionIn(forward, element, startNode);
  9914.         }
  9915.       } else {
  9916.         return Optional.none();
  9917.       }
  9918.     };
  9919.     var nextPosition = curry(fromPosition, true);
  9920.     var prevPosition = curry(fromPosition, false);
  9921.     var firstPositionIn = curry(positionIn, true);
  9922.     var lastPositionIn = curry(positionIn, false);
  9923.  
  9924.     var CARET_ID$1 = '_mce_caret';
  9925.     var isCaretNode = function (node) {
  9926.       return isElement$5(node) && node.id === CARET_ID$1;
  9927.     };
  9928.     var getParentCaretContainer = function (body, node) {
  9929.       while (node && node !== body) {
  9930.         if (node.id === CARET_ID$1) {
  9931.           return node;
  9932.         }
  9933.         node = node.parentNode;
  9934.       }
  9935.       return null;
  9936.     };
  9937.  
  9938.     var isStringPathBookmark = function (bookmark) {
  9939.       return isString$1(bookmark.start);
  9940.     };
  9941.     var isRangeBookmark = function (bookmark) {
  9942.       return has$2(bookmark, 'rng');
  9943.     };
  9944.     var isIdBookmark = function (bookmark) {
  9945.       return has$2(bookmark, 'id');
  9946.     };
  9947.     var isIndexBookmark = function (bookmark) {
  9948.       return has$2(bookmark, 'name');
  9949.     };
  9950.     var isPathBookmark = function (bookmark) {
  9951.       return Tools.isArray(bookmark.start);
  9952.     };
  9953.  
  9954.     var addBogus = function (dom, node) {
  9955.       if (isElement$5(node) && dom.isBlock(node) && !node.innerHTML && !Env.ie) {
  9956.         node.innerHTML = '<br data-mce-bogus="1" />';
  9957.       }
  9958.       return node;
  9959.     };
  9960.     var resolveCaretPositionBookmark = function (dom, bookmark) {
  9961.       var pos;
  9962.       var rng = dom.createRng();
  9963.       pos = resolve$2(dom.getRoot(), bookmark.start);
  9964.       rng.setStart(pos.container(), pos.offset());
  9965.       pos = resolve$2(dom.getRoot(), bookmark.end);
  9966.       rng.setEnd(pos.container(), pos.offset());
  9967.       return rng;
  9968.     };
  9969.     var insertZwsp = function (node, rng) {
  9970.       var textNode = node.ownerDocument.createTextNode(ZWSP$1);
  9971.       node.appendChild(textNode);
  9972.       rng.setStart(textNode, 0);
  9973.       rng.setEnd(textNode, 0);
  9974.     };
  9975.     var isEmpty$1 = function (node) {
  9976.       return node.hasChildNodes() === false;
  9977.     };
  9978.     var tryFindRangePosition = function (node, rng) {
  9979.       return lastPositionIn(node).fold(never, function (pos) {
  9980.         rng.setStart(pos.container(), pos.offset());
  9981.         rng.setEnd(pos.container(), pos.offset());
  9982.         return true;
  9983.       });
  9984.     };
  9985.     var padEmptyCaretContainer = function (root, node, rng) {
  9986.       if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
  9987.         insertZwsp(node, rng);
  9988.         return true;
  9989.       } else {
  9990.         return false;
  9991.       }
  9992.     };
  9993.     var setEndPoint = function (dom, start, bookmark, rng) {
  9994.       var point = bookmark[start ? 'start' : 'end'];
  9995.       var i, node, offset, children;
  9996.       var root = dom.getRoot();
  9997.       if (point) {
  9998.         offset = point[0];
  9999.         for (node = root, i = point.length - 1; i >= 1; i--) {
  10000.           children = node.childNodes;
  10001.           if (padEmptyCaretContainer(root, node, rng)) {
  10002.             return true;
  10003.           }
  10004.           if (point[i] > children.length - 1) {
  10005.             if (padEmptyCaretContainer(root, node, rng)) {
  10006.               return true;
  10007.             }
  10008.             return tryFindRangePosition(node, rng);
  10009.           }
  10010.           node = children[point[i]];
  10011.         }
  10012.         if (node.nodeType === 3) {
  10013.           offset = Math.min(point[0], node.nodeValue.length);
  10014.         }
  10015.         if (node.nodeType === 1) {
  10016.           offset = Math.min(point[0], node.childNodes.length);
  10017.         }
  10018.         if (start) {
  10019.           rng.setStart(node, offset);
  10020.         } else {
  10021.           rng.setEnd(node, offset);
  10022.         }
  10023.       }
  10024.       return true;
  10025.     };
  10026.     var isValidTextNode = function (node) {
  10027.       return isText$7(node) && node.data.length > 0;
  10028.     };
  10029.     var restoreEndPoint = function (dom, suffix, bookmark) {
  10030.       var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev;
  10031.       var keep = bookmark.keep;
  10032.       var container, offset;
  10033.       if (marker) {
  10034.         node = marker.parentNode;
  10035.         if (suffix === 'start') {
  10036.           if (!keep) {
  10037.             idx = dom.nodeIndex(marker);
  10038.           } else {
  10039.             if (marker.hasChildNodes()) {
  10040.               node = marker.firstChild;
  10041.               idx = 1;
  10042.             } else if (isValidTextNode(marker.nextSibling)) {
  10043.               node = marker.nextSibling;
  10044.               idx = 0;
  10045.             } else if (isValidTextNode(marker.previousSibling)) {
  10046.               node = marker.previousSibling;
  10047.               idx = marker.previousSibling.data.length;
  10048.             } else {
  10049.               node = marker.parentNode;
  10050.               idx = dom.nodeIndex(marker) + 1;
  10051.             }
  10052.           }
  10053.           container = node;
  10054.           offset = idx;
  10055.         } else {
  10056.           if (!keep) {
  10057.             idx = dom.nodeIndex(marker);
  10058.           } else {
  10059.             if (marker.hasChildNodes()) {
  10060.               node = marker.firstChild;
  10061.               idx = 1;
  10062.             } else if (isValidTextNode(marker.previousSibling)) {
  10063.               node = marker.previousSibling;
  10064.               idx = marker.previousSibling.data.length;
  10065.             } else {
  10066.               node = marker.parentNode;
  10067.               idx = dom.nodeIndex(marker);
  10068.             }
  10069.           }
  10070.           container = node;
  10071.           offset = idx;
  10072.         }
  10073.         if (!keep) {
  10074.           prev = marker.previousSibling;
  10075.           next = marker.nextSibling;
  10076.           Tools.each(Tools.grep(marker.childNodes), function (node) {
  10077.             if (isText$7(node)) {
  10078.               node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  10079.             }
  10080.           });
  10081.           while (marker = dom.get(bookmark.id + '_' + suffix)) {
  10082.             dom.remove(marker, true);
  10083.           }
  10084.           if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
  10085.             idx = prev.nodeValue.length;
  10086.             prev.appendData(next.nodeValue);
  10087.             dom.remove(next);
  10088.             container = prev;
  10089.             offset = idx;
  10090.           }
  10091.         }
  10092.         return Optional.some(CaretPosition(container, offset));
  10093.       } else {
  10094.         return Optional.none();
  10095.       }
  10096.     };
  10097.     var resolvePaths = function (dom, bookmark) {
  10098.       var rng = dom.createRng();
  10099.       if (setEndPoint(dom, true, bookmark, rng) && setEndPoint(dom, false, bookmark, rng)) {
  10100.         return Optional.some(rng);
  10101.       } else {
  10102.         return Optional.none();
  10103.       }
  10104.     };
  10105.     var resolveId = function (dom, bookmark) {
  10106.       var startPos = restoreEndPoint(dom, 'start', bookmark);
  10107.       var endPos = restoreEndPoint(dom, 'end', bookmark);
  10108.       return lift2(startPos, endPos.or(startPos), function (spos, epos) {
  10109.         var rng = dom.createRng();
  10110.         rng.setStart(addBogus(dom, spos.container()), spos.offset());
  10111.         rng.setEnd(addBogus(dom, epos.container()), epos.offset());
  10112.         return rng;
  10113.       });
  10114.     };
  10115.     var resolveIndex = function (dom, bookmark) {
  10116.       return Optional.from(dom.select(bookmark.name)[bookmark.index]).map(function (elm) {
  10117.         var rng = dom.createRng();
  10118.         rng.selectNode(elm);
  10119.         return rng;
  10120.       });
  10121.     };
  10122.     var resolve$1 = function (selection, bookmark) {
  10123.       var dom = selection.dom;
  10124.       if (bookmark) {
  10125.         if (isPathBookmark(bookmark)) {
  10126.           return resolvePaths(dom, bookmark);
  10127.         } else if (isStringPathBookmark(bookmark)) {
  10128.           return Optional.some(resolveCaretPositionBookmark(dom, bookmark));
  10129.         } else if (isIdBookmark(bookmark)) {
  10130.           return resolveId(dom, bookmark);
  10131.         } else if (isIndexBookmark(bookmark)) {
  10132.           return resolveIndex(dom, bookmark);
  10133.         } else if (isRangeBookmark(bookmark)) {
  10134.           return Optional.some(bookmark.rng);
  10135.         }
  10136.       }
  10137.       return Optional.none();
  10138.     };
  10139.  
  10140.     var getBookmark$1 = function (selection, type, normalized) {
  10141.       return getBookmark$2(selection, type, normalized);
  10142.     };
  10143.     var moveToBookmark = function (selection, bookmark) {
  10144.       resolve$1(selection, bookmark).each(function (rng) {
  10145.         selection.setRng(rng);
  10146.       });
  10147.     };
  10148.     var isBookmarkNode$1 = function (node) {
  10149.       return isElement$5(node) && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
  10150.     };
  10151.  
  10152.     var is = function (expected) {
  10153.       return function (actual) {
  10154.         return expected === actual;
  10155.       };
  10156.     };
  10157.     var isNbsp = is(nbsp);
  10158.     var isWhiteSpace = function (chr) {
  10159.       return chr !== '' && ' \f\n\r\t\x0B'.indexOf(chr) !== -1;
  10160.     };
  10161.     var isContent = function (chr) {
  10162.       return !isWhiteSpace(chr) && !isNbsp(chr);
  10163.     };
  10164.  
  10165.     var isNode = function (node) {
  10166.       return !!node.nodeType;
  10167.     };
  10168.     var isInlineBlock = function (node) {
  10169.       return node && /^(IMG)$/.test(node.nodeName);
  10170.     };
  10171.     var moveStart = function (dom, selection, rng) {
  10172.       var offset = rng.startOffset;
  10173.       var container = rng.startContainer;
  10174.       if (container === rng.endContainer) {
  10175.         if (isInlineBlock(container.childNodes[offset])) {
  10176.           return;
  10177.         }
  10178.       }
  10179.       if (isElement$5(container)) {
  10180.         var nodes = container.childNodes;
  10181.         var walker = void 0;
  10182.         if (offset < nodes.length) {
  10183.           container = nodes[offset];
  10184.           walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10185.         } else {
  10186.           container = nodes[nodes.length - 1];
  10187.           walker = new DomTreeWalker(container, dom.getParent(container, dom.isBlock));
  10188.           walker.next(true);
  10189.         }
  10190.         for (var node = walker.current(); node; node = walker.next()) {
  10191.           if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
  10192.             rng.setStart(node, 0);
  10193.             selection.setRng(rng);
  10194.             return;
  10195.           }
  10196.         }
  10197.       }
  10198.     };
  10199.     var getNonWhiteSpaceSibling = function (node, next, inc) {
  10200.       if (node) {
  10201.         var nextName = next ? 'nextSibling' : 'previousSibling';
  10202.         for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
  10203.           if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
  10204.             return node;
  10205.           }
  10206.         }
  10207.       }
  10208.     };
  10209.     var isTextBlock$1 = function (editor, name) {
  10210.       if (isNode(name)) {
  10211.         name = name.nodeName;
  10212.       }
  10213.       return !!editor.schema.getTextBlockElements()[name.toLowerCase()];
  10214.     };
  10215.     var isValid = function (ed, parent, child) {
  10216.       return ed.schema.isValidChild(parent, child);
  10217.     };
  10218.     var isWhiteSpaceNode$1 = function (node, allowSpaces) {
  10219.       if (allowSpaces === void 0) {
  10220.         allowSpaces = false;
  10221.       }
  10222.       if (isNonNullable(node) && isText$7(node)) {
  10223.         var data = allowSpaces ? node.data.replace(/ /g, '\xA0') : node.data;
  10224.         return isWhitespaceText(data);
  10225.       } else {
  10226.         return false;
  10227.       }
  10228.     };
  10229.     var isEmptyTextNode$1 = function (node) {
  10230.       return isNonNullable(node) && isText$7(node) && node.length === 0;
  10231.     };
  10232.     var replaceVars = function (value, vars) {
  10233.       if (isFunction(value)) {
  10234.         value = value(vars);
  10235.       } else if (isNonNullable(vars)) {
  10236.         value = value.replace(/%(\w+)/g, function (str, name) {
  10237.           return vars[name] || str;
  10238.         });
  10239.       }
  10240.       return value;
  10241.     };
  10242.     var isEq$5 = function (str1, str2) {
  10243.       str1 = str1 || '';
  10244.       str2 = str2 || '';
  10245.       str1 = '' + (str1.nodeName || str1);
  10246.       str2 = '' + (str2.nodeName || str2);
  10247.       return str1.toLowerCase() === str2.toLowerCase();
  10248.     };
  10249.     var normalizeStyleValue = function (dom, value, name) {
  10250.       if (name === 'color' || name === 'backgroundColor') {
  10251.         value = dom.toHex(value);
  10252.       }
  10253.       if (name === 'fontWeight' && value === 700) {
  10254.         value = 'bold';
  10255.       }
  10256.       if (name === 'fontFamily') {
  10257.         value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  10258.       }
  10259.       return '' + value;
  10260.     };
  10261.     var getStyle = function (dom, node, name) {
  10262.       return normalizeStyleValue(dom, dom.getStyle(node, name), name);
  10263.     };
  10264.     var getTextDecoration = function (dom, node) {
  10265.       var decoration;
  10266.       dom.getParent(node, function (n) {
  10267.         decoration = dom.getStyle(n, 'text-decoration');
  10268.         return decoration && decoration !== 'none';
  10269.       });
  10270.       return decoration;
  10271.     };
  10272.     var getParents$2 = function (dom, node, selector) {
  10273.       return dom.getParents(node, selector, dom.getRoot());
  10274.     };
  10275.     var isVariableFormatName = function (editor, formatName) {
  10276.       var hasVariableValues = function (format) {
  10277.         var isVariableValue = function (val) {
  10278.           return val.length > 1 && val.charAt(0) === '%';
  10279.         };
  10280.         return exists([
  10281.           'styles',
  10282.           'attributes'
  10283.         ], function (key) {
  10284.           return get$9(format, key).exists(function (field) {
  10285.             var fieldValues = isArray$1(field) ? field : values(field);
  10286.             return exists(fieldValues, isVariableValue);
  10287.           });
  10288.         });
  10289.       };
  10290.       return exists(editor.formatter.get(formatName), hasVariableValues);
  10291.     };
  10292.     var areSimilarFormats = function (editor, formatName, otherFormatName) {
  10293.       var validKeys = [
  10294.         'inline',
  10295.         'block',
  10296.         'selector',
  10297.         'attributes',
  10298.         'styles',
  10299.         'classes'
  10300.       ];
  10301.       var filterObj = function (format) {
  10302.         return filter$3(format, function (_, key) {
  10303.           return exists(validKeys, function (validKey) {
  10304.             return validKey === key;
  10305.           });
  10306.         });
  10307.       };
  10308.       return exists(editor.formatter.get(formatName), function (fmt1) {
  10309.         var filteredFmt1 = filterObj(fmt1);
  10310.         return exists(editor.formatter.get(otherFormatName), function (fmt2) {
  10311.           var filteredFmt2 = filterObj(fmt2);
  10312.           return equal$1(filteredFmt1, filteredFmt2);
  10313.         });
  10314.       });
  10315.     };
  10316.     var isBlockFormat = function (format) {
  10317.       return hasNonNullableKey(format, 'block');
  10318.     };
  10319.     var isSelectorFormat = function (format) {
  10320.       return hasNonNullableKey(format, 'selector');
  10321.     };
  10322.     var isInlineFormat = function (format) {
  10323.       return hasNonNullableKey(format, 'inline');
  10324.     };
  10325.     var isMixedFormat = function (format) {
  10326.       return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, 'mixed'), true);
  10327.     };
  10328.     var shouldExpandToSelector = function (format) {
  10329.       return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
  10330.     };
  10331.  
  10332.     var isBookmarkNode = isBookmarkNode$1;
  10333.     var getParents$1 = getParents$2;
  10334.     var isWhiteSpaceNode = isWhiteSpaceNode$1;
  10335.     var isTextBlock = isTextBlock$1;
  10336.     var isBogusBr = function (node) {
  10337.       return isBr$5(node) && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  10338.     };
  10339.     var findParentContentEditable = function (dom, node) {
  10340.       var parent = node;
  10341.       while (parent) {
  10342.         if (isElement$5(parent) && dom.getContentEditable(parent)) {
  10343.           return dom.getContentEditable(parent) === 'false' ? parent : node;
  10344.         }
  10345.         parent = parent.parentNode;
  10346.       }
  10347.       return node;
  10348.     };
  10349.     var walkText = function (start, node, offset, predicate) {
  10350.       var str = node.data;
  10351.       for (var i = offset; start ? i >= 0 : i < str.length; start ? i-- : i++) {
  10352.         if (predicate(str.charAt(i))) {
  10353.           return start ? i + 1 : i;
  10354.         }
  10355.       }
  10356.       return -1;
  10357.     };
  10358.     var findSpace = function (start, node, offset) {
  10359.       return walkText(start, node, offset, function (c) {
  10360.         return isNbsp(c) || isWhiteSpace(c);
  10361.       });
  10362.     };
  10363.     var findContent = function (start, node, offset) {
  10364.       return walkText(start, node, offset, isContent);
  10365.     };
  10366.     var findWordEndPoint = function (dom, body, container, offset, start, includeTrailingSpaces) {
  10367.       var lastTextNode;
  10368.       var rootNode = dom.getParent(container, dom.isBlock) || body;
  10369.       var walk = function (container, offset, pred) {
  10370.         var textSeeker = TextSeeker(dom);
  10371.         var walker = start ? textSeeker.backwards : textSeeker.forwards;
  10372.         return Optional.from(walker(container, offset, function (text, textOffset) {
  10373.           if (isBookmarkNode(text.parentNode)) {
  10374.             return -1;
  10375.           } else {
  10376.             lastTextNode = text;
  10377.             return pred(start, text, textOffset);
  10378.           }
  10379.         }, rootNode));
  10380.       };
  10381.       var spaceResult = walk(container, offset, findSpace);
  10382.       return spaceResult.bind(function (result) {
  10383.         return includeTrailingSpaces ? walk(result.container, result.offset + (start ? -1 : 0), findContent) : Optional.some(result);
  10384.       }).orThunk(function () {
  10385.         return lastTextNode ? Optional.some({
  10386.           container: lastTextNode,
  10387.           offset: start ? 0 : lastTextNode.length
  10388.         }) : Optional.none();
  10389.       });
  10390.     };
  10391.     var findSelectorEndPoint = function (dom, formatList, rng, container, siblingName) {
  10392.       if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
  10393.         container = container[siblingName];
  10394.       }
  10395.       var parents = getParents$1(dom, container);
  10396.       for (var i = 0; i < parents.length; i++) {
  10397.         for (var y = 0; y < formatList.length; y++) {
  10398.           var curFormat = formatList[y];
  10399.           if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
  10400.             continue;
  10401.           }
  10402.           if (isSelectorFormat(curFormat) && dom.is(parents[i], curFormat.selector)) {
  10403.             return parents[i];
  10404.           }
  10405.         }
  10406.       }
  10407.       return container;
  10408.     };
  10409.     var findBlockEndPoint = function (editor, formatList, container, siblingName) {
  10410.       var node = container;
  10411.       var dom = editor.dom;
  10412.       var root = dom.getRoot();
  10413.       var format = formatList[0];
  10414.       if (isBlockFormat(format)) {
  10415.         node = format.wrapper ? null : dom.getParent(container, format.block, root);
  10416.       }
  10417.       if (!node) {
  10418.         var scopeRoot = dom.getParent(container, 'LI,TD,TH');
  10419.         node = dom.getParent(isText$7(container) ? container.parentNode : container, function (node) {
  10420.           return node !== root && isTextBlock(editor, node);
  10421.         }, scopeRoot);
  10422.       }
  10423.       if (node && isBlockFormat(format) && format.wrapper) {
  10424.         node = getParents$1(dom, node, 'ul,ol').reverse()[0] || node;
  10425.       }
  10426.       if (!node) {
  10427.         node = container;
  10428.         while (node[siblingName] && !dom.isBlock(node[siblingName])) {
  10429.           node = node[siblingName];
  10430.           if (isEq$5(node, 'br')) {
  10431.             break;
  10432.           }
  10433.         }
  10434.       }
  10435.       return node || container;
  10436.     };
  10437.     var isAtBlockBoundary$1 = function (dom, root, container, siblingName) {
  10438.       var parent = container.parentNode;
  10439.       if (isNonNullable(container[siblingName])) {
  10440.         return false;
  10441.       } else if (parent === root || isNullable(parent) || dom.isBlock(parent)) {
  10442.         return true;
  10443.       } else {
  10444.         return isAtBlockBoundary$1(dom, root, parent, siblingName);
  10445.       }
  10446.     };
  10447.     var findParentContainer = function (dom, formatList, container, offset, start) {
  10448.       var parent = container;
  10449.       var siblingName = start ? 'previousSibling' : 'nextSibling';
  10450.       var root = dom.getRoot();
  10451.       if (isText$7(container) && !isWhiteSpaceNode(container)) {
  10452.         if (start ? offset > 0 : offset < container.data.length) {
  10453.           return container;
  10454.         }
  10455.       }
  10456.       while (true) {
  10457.         if (!formatList[0].block_expand && dom.isBlock(parent)) {
  10458.           return parent;
  10459.         }
  10460.         for (var sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  10461.           var allowSpaces = isText$7(sibling) && !isAtBlockBoundary$1(dom, root, sibling, siblingName);
  10462.           if (!isBookmarkNode(sibling) && !isBogusBr(sibling) && !isWhiteSpaceNode(sibling, allowSpaces)) {
  10463.             return parent;
  10464.           }
  10465.         }
  10466.         if (parent === root || parent.parentNode === root) {
  10467.           container = parent;
  10468.           break;
  10469.         }
  10470.         parent = parent.parentNode;
  10471.       }
  10472.       return container;
  10473.     };
  10474.     var isSelfOrParentBookmark = function (container) {
  10475.       return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
  10476.     };
  10477.     var expandRng = function (editor, rng, formatList, includeTrailingSpace) {
  10478.       if (includeTrailingSpace === void 0) {
  10479.         includeTrailingSpace = false;
  10480.       }
  10481.       var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  10482.       var dom = editor.dom;
  10483.       var format = formatList[0];
  10484.       if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
  10485.         startContainer = getNode$1(startContainer, startOffset);
  10486.         if (isText$7(startContainer)) {
  10487.           startOffset = 0;
  10488.         }
  10489.       }
  10490.       if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
  10491.         endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
  10492.         if (isText$7(endContainer)) {
  10493.           endOffset = endContainer.nodeValue.length;
  10494.         }
  10495.       }
  10496.       startContainer = findParentContentEditable(dom, startContainer);
  10497.       endContainer = findParentContentEditable(dom, endContainer);
  10498.       if (isSelfOrParentBookmark(startContainer)) {
  10499.         startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  10500.         if (rng.collapsed) {
  10501.           startContainer = startContainer.previousSibling || startContainer;
  10502.         } else {
  10503.           startContainer = startContainer.nextSibling || startContainer;
  10504.         }
  10505.         if (isText$7(startContainer)) {
  10506.           startOffset = rng.collapsed ? startContainer.length : 0;
  10507.         }
  10508.       }
  10509.       if (isSelfOrParentBookmark(endContainer)) {
  10510.         endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  10511.         if (rng.collapsed) {
  10512.           endContainer = endContainer.nextSibling || endContainer;
  10513.         } else {
  10514.           endContainer = endContainer.previousSibling || endContainer;
  10515.         }
  10516.         if (isText$7(endContainer)) {
  10517.           endOffset = rng.collapsed ? 0 : endContainer.length;
  10518.         }
  10519.       }
  10520.       if (rng.collapsed) {
  10521.         var startPoint = findWordEndPoint(dom, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
  10522.         startPoint.each(function (_a) {
  10523.           var container = _a.container, offset = _a.offset;
  10524.           startContainer = container;
  10525.           startOffset = offset;
  10526.         });
  10527.         var endPoint = findWordEndPoint(dom, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
  10528.         endPoint.each(function (_a) {
  10529.           var container = _a.container, offset = _a.offset;
  10530.           endContainer = container;
  10531.           endOffset = offset;
  10532.         });
  10533.       }
  10534.       if (isInlineFormat(format) || format.block_expand) {
  10535.         if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
  10536.           startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10537.         }
  10538.         if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
  10539.           endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10540.         }
  10541.       }
  10542.       if (shouldExpandToSelector(format)) {
  10543.         startContainer = findSelectorEndPoint(dom, formatList, rng, startContainer, 'previousSibling');
  10544.         endContainer = findSelectorEndPoint(dom, formatList, rng, endContainer, 'nextSibling');
  10545.       }
  10546.       if (isBlockFormat(format) || isSelectorFormat(format)) {
  10547.         startContainer = findBlockEndPoint(editor, formatList, startContainer, 'previousSibling');
  10548.         endContainer = findBlockEndPoint(editor, formatList, endContainer, 'nextSibling');
  10549.         if (isBlockFormat(format)) {
  10550.           if (!dom.isBlock(startContainer)) {
  10551.             startContainer = findParentContainer(dom, formatList, startContainer, startOffset, true);
  10552.           }
  10553.           if (!dom.isBlock(endContainer)) {
  10554.             endContainer = findParentContainer(dom, formatList, endContainer, endOffset, false);
  10555.           }
  10556.         }
  10557.       }
  10558.       if (isElement$5(startContainer)) {
  10559.         startOffset = dom.nodeIndex(startContainer);
  10560.         startContainer = startContainer.parentNode;
  10561.       }
  10562.       if (isElement$5(endContainer)) {
  10563.         endOffset = dom.nodeIndex(endContainer) + 1;
  10564.         endContainer = endContainer.parentNode;
  10565.       }
  10566.       return {
  10567.         startContainer: startContainer,
  10568.         startOffset: startOffset,
  10569.         endContainer: endContainer,
  10570.         endOffset: endOffset
  10571.       };
  10572.     };
  10573.  
  10574.     var walk$2 = function (dom, rng, callback) {
  10575.       var startOffset = rng.startOffset;
  10576.       var startContainer = getNode$1(rng.startContainer, startOffset);
  10577.       var endOffset = rng.endOffset;
  10578.       var endContainer = getNode$1(rng.endContainer, endOffset - 1);
  10579.       var exclude = function (nodes) {
  10580.         var firstNode = nodes[0];
  10581.         if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
  10582.           nodes.splice(0, 1);
  10583.         }
  10584.         var lastNode = nodes[nodes.length - 1];
  10585.         if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
  10586.           nodes.splice(nodes.length - 1, 1);
  10587.         }
  10588.         return nodes;
  10589.       };
  10590.       var collectSiblings = function (node, name, endNode) {
  10591.         var siblings = [];
  10592.         for (; node && node !== endNode; node = node[name]) {
  10593.           siblings.push(node);
  10594.         }
  10595.         return siblings;
  10596.       };
  10597.       var findEndPoint = function (node, root) {
  10598.         return dom.getParent(node, function (node) {
  10599.           return node.parentNode === root;
  10600.         }, root);
  10601.       };
  10602.       var walkBoundary = function (startNode, endNode, next) {
  10603.         var siblingName = next ? 'nextSibling' : 'previousSibling';
  10604.         for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
  10605.           parent_1 = node.parentNode;
  10606.           var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
  10607.           if (siblings_1.length) {
  10608.             if (!next) {
  10609.               siblings_1.reverse();
  10610.             }
  10611.             callback(exclude(siblings_1));
  10612.           }
  10613.         }
  10614.       };
  10615.       if (startContainer === endContainer) {
  10616.         return callback(exclude([startContainer]));
  10617.       }
  10618.       var ancestor = dom.findCommonAncestor(startContainer, endContainer);
  10619.       if (dom.isChildOf(startContainer, endContainer)) {
  10620.         return walkBoundary(startContainer, ancestor, true);
  10621.       }
  10622.       if (dom.isChildOf(endContainer, startContainer)) {
  10623.         return walkBoundary(endContainer, ancestor);
  10624.       }
  10625.       var startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  10626.       var endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  10627.       walkBoundary(startContainer, startPoint, true);
  10628.       var siblings = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint === endContainer ? endPoint.nextSibling : endPoint);
  10629.       if (siblings.length) {
  10630.         callback(exclude(siblings));
  10631.       }
  10632.       walkBoundary(endContainer, endPoint);
  10633.     };
  10634.  
  10635.     var getRanges = function (selection) {
  10636.       var ranges = [];
  10637.       if (selection) {
  10638.         for (var i = 0; i < selection.rangeCount; i++) {
  10639.           ranges.push(selection.getRangeAt(i));
  10640.         }
  10641.       }
  10642.       return ranges;
  10643.     };
  10644.     var getSelectedNodes = function (ranges) {
  10645.       return bind(ranges, function (range) {
  10646.         var node = getSelectedNode(range);
  10647.         return node ? [SugarElement.fromDom(node)] : [];
  10648.       });
  10649.     };
  10650.     var hasMultipleRanges = function (selection) {
  10651.       return getRanges(selection).length > 1;
  10652.     };
  10653.  
  10654.     var getCellsFromRanges = function (ranges) {
  10655.       return filter$4(getSelectedNodes(ranges), isTableCell$4);
  10656.     };
  10657.     var getCellsFromElement = function (elm) {
  10658.       return descendants(elm, 'td[data-mce-selected],th[data-mce-selected]');
  10659.     };
  10660.     var getCellsFromElementOrRanges = function (ranges, element) {
  10661.       var selectedCells = getCellsFromElement(element);
  10662.       return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
  10663.     };
  10664.     var getCellsFromEditor = function (editor) {
  10665.       return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
  10666.     };
  10667.     var getClosestTable = function (cell, isRoot) {
  10668.       return ancestor$2(cell, 'table', isRoot);
  10669.     };
  10670.  
  10671.     var getStartNode = function (rng) {
  10672.       var sc = rng.startContainer, so = rng.startOffset;
  10673.       if (isText$7(sc)) {
  10674.         return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
  10675.       } else {
  10676.         return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
  10677.       }
  10678.     };
  10679.     var getEndNode = function (rng) {
  10680.       var ec = rng.endContainer, eo = rng.endOffset;
  10681.       if (isText$7(ec)) {
  10682.         return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
  10683.       } else {
  10684.         return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
  10685.       }
  10686.     };
  10687.     var getFirstChildren = function (node) {
  10688.       return firstChild(node).fold(constant([node]), function (child) {
  10689.         return [node].concat(getFirstChildren(child));
  10690.       });
  10691.     };
  10692.     var getLastChildren$1 = function (node) {
  10693.       return lastChild(node).fold(constant([node]), function (child) {
  10694.         if (name(child) === 'br') {
  10695.           return prevSibling(child).map(function (sibling) {
  10696.             return [node].concat(getLastChildren$1(sibling));
  10697.           }).getOr([]);
  10698.         } else {
  10699.           return [node].concat(getLastChildren$1(child));
  10700.         }
  10701.       });
  10702.     };
  10703.     var hasAllContentsSelected = function (elm, rng) {
  10704.       return lift2(getStartNode(rng), getEndNode(rng), function (startNode, endNode) {
  10705.         var start = find$3(getFirstChildren(elm), curry(eq, startNode));
  10706.         var end = find$3(getLastChildren$1(elm), curry(eq, endNode));
  10707.         return start.isSome() && end.isSome();
  10708.       }).getOr(false);
  10709.     };
  10710.     var moveEndPoint = function (dom, rng, node, start) {
  10711.       var root = node, walker = new DomTreeWalker(node, root);
  10712.       var moveCaretBeforeOnEnterElementsMap = filter$3(dom.schema.getMoveCaretBeforeOnEnterElements(), function (_, name) {
  10713.         return !contains$3([
  10714.           'td',
  10715.           'th',
  10716.           'table'
  10717.         ], name.toLowerCase());
  10718.       });
  10719.       do {
  10720.         if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
  10721.           if (start) {
  10722.             rng.setStart(node, 0);
  10723.           } else {
  10724.             rng.setEnd(node, node.nodeValue.length);
  10725.           }
  10726.           return;
  10727.         }
  10728.         if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
  10729.           if (start) {
  10730.             rng.setStartBefore(node);
  10731.           } else {
  10732.             if (node.nodeName === 'BR') {
  10733.               rng.setEndBefore(node);
  10734.             } else {
  10735.               rng.setEndAfter(node);
  10736.             }
  10737.           }
  10738.           return;
  10739.         }
  10740.       } while (node = start ? walker.next() : walker.prev());
  10741.       if (root.nodeName === 'BODY') {
  10742.         if (start) {
  10743.           rng.setStart(root, 0);
  10744.         } else {
  10745.           rng.setEnd(root, root.childNodes.length);
  10746.         }
  10747.       }
  10748.     };
  10749.     var hasAnyRanges = function (editor) {
  10750.       var sel = editor.selection.getSel();
  10751.       return sel && sel.rangeCount > 0;
  10752.     };
  10753.     var runOnRanges = function (editor, executor) {
  10754.       var fakeSelectionNodes = getCellsFromEditor(editor);
  10755.       if (fakeSelectionNodes.length > 0) {
  10756.         each$k(fakeSelectionNodes, function (elem) {
  10757.           var node = elem.dom;
  10758.           var fakeNodeRng = editor.dom.createRng();
  10759.           fakeNodeRng.setStartBefore(node);
  10760.           fakeNodeRng.setEndAfter(node);
  10761.           executor(fakeNodeRng, true);
  10762.         });
  10763.       } else {
  10764.         executor(editor.selection.getRng(), false);
  10765.       }
  10766.     };
  10767.     var preserve = function (selection, fillBookmark, executor) {
  10768.       var bookmark = getPersistentBookmark(selection, fillBookmark);
  10769.       executor(bookmark);
  10770.       selection.moveToBookmark(bookmark);
  10771.     };
  10772.  
  10773.     var NodeValue = function (is, name) {
  10774.       var get = function (element) {
  10775.         if (!is(element)) {
  10776.           throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  10777.         }
  10778.         return getOption(element).getOr('');
  10779.       };
  10780.       var getOption = function (element) {
  10781.         return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  10782.       };
  10783.       var set = function (element, value) {
  10784.         if (!is(element)) {
  10785.           throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  10786.         }
  10787.         element.dom.nodeValue = value;
  10788.       };
  10789.       return {
  10790.         get: get,
  10791.         getOption: getOption,
  10792.         set: set
  10793.       };
  10794.     };
  10795.  
  10796.     var api$1 = NodeValue(isText$8, 'text');
  10797.     var get$2 = function (element) {
  10798.       return api$1.get(element);
  10799.     };
  10800.  
  10801.     var isZeroWidth = function (elem) {
  10802.       return isText$8(elem) && get$2(elem) === ZWSP$1;
  10803.     };
  10804.     var context = function (editor, elem, wrapName, nodeName) {
  10805.       return parent(elem).fold(function () {
  10806.         return 'skipping';
  10807.       }, function (parent) {
  10808.         if (nodeName === 'br' || isZeroWidth(elem)) {
  10809.           return 'valid';
  10810.         } else if (isAnnotation(elem)) {
  10811.           return 'existing';
  10812.         } else if (isCaretNode(elem.dom)) {
  10813.           return 'caret';
  10814.         } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent), wrapName)) {
  10815.           return 'invalid-child';
  10816.         } else {
  10817.           return 'valid';
  10818.         }
  10819.       });
  10820.     };
  10821.  
  10822.     var applyWordGrab = function (editor, rng) {
  10823.       var r = expandRng(editor, rng, [{ inline: 'span' }]);
  10824.       rng.setStart(r.startContainer, r.startOffset);
  10825.       rng.setEnd(r.endContainer, r.endOffset);
  10826.       editor.selection.setRng(rng);
  10827.     };
  10828.     var makeAnnotation = function (eDoc, _a, annotationName, decorate) {
  10829.       var _b = _a.uid, uid = _b === void 0 ? generate('mce-annotation') : _b, data = __rest(_a, ['uid']);
  10830.       var master = SugarElement.fromTag('span', eDoc);
  10831.       add$1(master, annotation());
  10832.       set$1(master, '' + dataAnnotationId(), uid);
  10833.       set$1(master, '' + dataAnnotation(), annotationName);
  10834.       var _c = decorate(uid, data), _d = _c.attributes, attributes = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
  10835.       setAll$1(master, attributes);
  10836.       add(master, classes);
  10837.       return master;
  10838.     };
  10839.     var annotate = function (editor, rng, annotationName, decorate, data) {
  10840.       var newWrappers = [];
  10841.       var master = makeAnnotation(editor.getDoc(), data, annotationName, decorate);
  10842.       var wrapper = value();
  10843.       var finishWrapper = function () {
  10844.         wrapper.clear();
  10845.       };
  10846.       var getOrOpenWrapper = function () {
  10847.         return wrapper.get().getOrThunk(function () {
  10848.           var nu = shallow(master);
  10849.           newWrappers.push(nu);
  10850.           wrapper.set(nu);
  10851.           return nu;
  10852.         });
  10853.       };
  10854.       var processElements = function (elems) {
  10855.         each$k(elems, processElement);
  10856.       };
  10857.       var processElement = function (elem) {
  10858.         var ctx = context(editor, elem, 'span', name(elem));
  10859.         switch (ctx) {
  10860.         case 'invalid-child': {
  10861.             finishWrapper();
  10862.             var children$1 = children(elem);
  10863.             processElements(children$1);
  10864.             finishWrapper();
  10865.             break;
  10866.           }
  10867.         case 'valid': {
  10868.             var w = getOrOpenWrapper();
  10869.             wrap$3(elem, w);
  10870.             break;
  10871.           }
  10872.         }
  10873.       };
  10874.       var processNodes = function (nodes) {
  10875.         var elems = map$3(nodes, SugarElement.fromDom);
  10876.         processElements(elems);
  10877.       };
  10878.       walk$2(editor.dom, rng, function (nodes) {
  10879.         finishWrapper();
  10880.         processNodes(nodes);
  10881.       });
  10882.       return newWrappers;
  10883.     };
  10884.     var annotateWithBookmark = function (editor, name, settings, data) {
  10885.       editor.undoManager.transact(function () {
  10886.         var selection = editor.selection;
  10887.         var initialRng = selection.getRng();
  10888.         var hasFakeSelection = getCellsFromEditor(editor).length > 0;
  10889.         if (initialRng.collapsed && !hasFakeSelection) {
  10890.           applyWordGrab(editor, initialRng);
  10891.         }
  10892.         if (selection.getRng().collapsed && !hasFakeSelection) {
  10893.           var wrapper = makeAnnotation(editor.getDoc(), data, name, settings.decorate);
  10894.           set(wrapper, nbsp);
  10895.           selection.getRng().insertNode(wrapper.dom);
  10896.           selection.select(wrapper.dom);
  10897.         } else {
  10898.           preserve(selection, false, function () {
  10899.             runOnRanges(editor, function (selectionRng) {
  10900.               annotate(editor, selectionRng, name, settings.decorate, data);
  10901.             });
  10902.           });
  10903.         }
  10904.       });
  10905.     };
  10906.  
  10907.     var Annotator = function (editor) {
  10908.       var registry = create$7();
  10909.       setup$m(editor, registry);
  10910.       var changes = setup$n(editor);
  10911.       return {
  10912.         register: function (name, settings) {
  10913.           registry.register(name, settings);
  10914.         },
  10915.         annotate: function (name, data) {
  10916.           registry.lookup(name).each(function (settings) {
  10917.             annotateWithBookmark(editor, name, settings, data);
  10918.           });
  10919.         },
  10920.         annotationChanged: function (name, callback) {
  10921.           changes.addListener(name, callback);
  10922.         },
  10923.         remove: function (name) {
  10924.           identify(editor, Optional.some(name)).each(function (_a) {
  10925.             var elements = _a.elements;
  10926.             each$k(elements, unwrap);
  10927.           });
  10928.         },
  10929.         getAll: function (name) {
  10930.           var directory = findAll(editor, name);
  10931.           return map$2(directory, function (elems) {
  10932.             return map$3(elems, function (elem) {
  10933.               return elem.dom;
  10934.             });
  10935.           });
  10936.         }
  10937.       };
  10938.     };
  10939.  
  10940.     var BookmarkManager = function (selection) {
  10941.       return {
  10942.         getBookmark: curry(getBookmark$1, selection),
  10943.         moveToBookmark: curry(moveToBookmark, selection)
  10944.       };
  10945.     };
  10946.     BookmarkManager.isBookmarkNode = isBookmarkNode$1;
  10947.  
  10948.     var getContentEditableRoot$1 = function (root, node) {
  10949.       while (node && node !== root) {
  10950.         if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
  10951.           return node;
  10952.         }
  10953.         node = node.parentNode;
  10954.       }
  10955.       return null;
  10956.     };
  10957.  
  10958.     var isXYWithinRange = function (clientX, clientY, range) {
  10959.       if (range.collapsed) {
  10960.         return false;
  10961.       }
  10962.       if (Env.browser.isIE() && range.startOffset === range.endOffset - 1 && range.startContainer === range.endContainer) {
  10963.         var elm = range.startContainer.childNodes[range.startOffset];
  10964.         if (isElement$5(elm)) {
  10965.           return exists(elm.getClientRects(), function (rect) {
  10966.             return containsXY(rect, clientX, clientY);
  10967.           });
  10968.         }
  10969.       }
  10970.       return exists(range.getClientRects(), function (rect) {
  10971.         return containsXY(rect, clientX, clientY);
  10972.       });
  10973.     };
  10974.  
  10975.     var firePreProcess = function (editor, args) {
  10976.       return editor.fire('PreProcess', args);
  10977.     };
  10978.     var firePostProcess = function (editor, args) {
  10979.       return editor.fire('PostProcess', args);
  10980.     };
  10981.     var fireRemove = function (editor) {
  10982.       return editor.fire('remove');
  10983.     };
  10984.     var fireDetach = function (editor) {
  10985.       return editor.fire('detach');
  10986.     };
  10987.     var fireSwitchMode = function (editor, mode) {
  10988.       return editor.fire('SwitchMode', { mode: mode });
  10989.     };
  10990.     var fireObjectResizeStart = function (editor, target, width, height, origin) {
  10991.       editor.fire('ObjectResizeStart', {
  10992.         target: target,
  10993.         width: width,
  10994.         height: height,
  10995.         origin: origin
  10996.       });
  10997.     };
  10998.     var fireObjectResized = function (editor, target, width, height, origin) {
  10999.       editor.fire('ObjectResized', {
  11000.         target: target,
  11001.         width: width,
  11002.         height: height,
  11003.         origin: origin
  11004.       });
  11005.     };
  11006.     var firePreInit = function (editor) {
  11007.       return editor.fire('PreInit');
  11008.     };
  11009.     var firePostRender = function (editor) {
  11010.       return editor.fire('PostRender');
  11011.     };
  11012.     var fireInit = function (editor) {
  11013.       return editor.fire('Init');
  11014.     };
  11015.     var firePlaceholderToggle = function (editor, state) {
  11016.       return editor.fire('PlaceholderToggle', { state: state });
  11017.     };
  11018.     var fireError = function (editor, errorType, error) {
  11019.       return editor.fire(errorType, error);
  11020.     };
  11021.     var fireFormatApply = function (editor, format, node, vars) {
  11022.       return editor.fire('FormatApply', {
  11023.         format: format,
  11024.         node: node,
  11025.         vars: vars
  11026.       });
  11027.     };
  11028.     var fireFormatRemove = function (editor, format, node, vars) {
  11029.       return editor.fire('FormatRemove', {
  11030.         format: format,
  11031.         node: node,
  11032.         vars: vars
  11033.       });
  11034.     };
  11035.  
  11036.     var VK = {
  11037.       BACKSPACE: 8,
  11038.       DELETE: 46,
  11039.       DOWN: 40,
  11040.       ENTER: 13,
  11041.       ESC: 27,
  11042.       LEFT: 37,
  11043.       RIGHT: 39,
  11044.       SPACEBAR: 32,
  11045.       TAB: 9,
  11046.       UP: 38,
  11047.       PAGE_UP: 33,
  11048.       PAGE_DOWN: 34,
  11049.       END: 35,
  11050.       HOME: 36,
  11051.       modifierPressed: function (e) {
  11052.         return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
  11053.       },
  11054.       metaKeyPressed: function (e) {
  11055.         return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
  11056.       }
  11057.     };
  11058.  
  11059.     var isContentEditableFalse$5 = isContentEditableFalse$b;
  11060.     var ControlSelection = function (selection, editor) {
  11061.       var elementSelectionAttr = 'data-mce-selected';
  11062.       var dom = editor.dom, each = Tools.each;
  11063.       var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
  11064.       var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  11065.       var width, height;
  11066.       var editableDoc = editor.getDoc(), rootDocument = document;
  11067.       var abs = Math.abs, round = Math.round, rootElement = editor.getBody();
  11068.       var startScrollWidth, startScrollHeight;
  11069.       var resizeHandles = {
  11070.         nw: [
  11071.           0,
  11072.           0,
  11073.           -1,
  11074.           -1
  11075.         ],
  11076.         ne: [
  11077.           1,
  11078.           0,
  11079.           1,
  11080.           -1
  11081.         ],
  11082.         se: [
  11083.           1,
  11084.           1,
  11085.           1,
  11086.           1
  11087.         ],
  11088.         sw: [
  11089.           0,
  11090.           1,
  11091.           -1,
  11092.           1
  11093.         ]
  11094.       };
  11095.       var isImage = function (elm) {
  11096.         return elm && (elm.nodeName === 'IMG' || editor.dom.is(elm, 'figure.image'));
  11097.       };
  11098.       var isMedia = function (elm) {
  11099.         return isMedia$2(elm) || dom.hasClass(elm, 'mce-preview-object');
  11100.       };
  11101.       var isEventOnImageOutsideRange = function (evt, range) {
  11102.         if (evt.type === 'longpress' || evt.type.indexOf('touch') === 0) {
  11103.           var touch = evt.touches[0];
  11104.           return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range);
  11105.         } else {
  11106.           return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range);
  11107.         }
  11108.       };
  11109.       var contextMenuSelectImage = function (evt) {
  11110.         var target = evt.target;
  11111.         if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
  11112.           editor.selection.select(target);
  11113.         }
  11114.       };
  11115.       var getResizeTargets = function (elm) {
  11116.         if (dom.is(elm, 'figure.image')) {
  11117.           return [elm.querySelector('img')];
  11118.         } else if (dom.hasClass(elm, 'mce-preview-object') && isNonNullable(elm.firstElementChild)) {
  11119.           return [
  11120.             elm,
  11121.             elm.firstElementChild
  11122.           ];
  11123.         } else {
  11124.           return [elm];
  11125.         }
  11126.       };
  11127.       var isResizable = function (elm) {
  11128.         var selector = getObjectResizing(editor);
  11129.         if (!selector) {
  11130.           return false;
  11131.         }
  11132.         if (elm.getAttribute('data-mce-resize') === 'false') {
  11133.           return false;
  11134.         }
  11135.         if (elm === editor.getBody()) {
  11136.           return false;
  11137.         }
  11138.         if (dom.hasClass(elm, 'mce-preview-object')) {
  11139.           return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
  11140.         } else {
  11141.           return is$2(SugarElement.fromDom(elm), selector);
  11142.         }
  11143.       };
  11144.       var createGhostElement = function (elm) {
  11145.         if (isMedia(elm)) {
  11146.           return dom.create('img', { src: Env.transparentSrc });
  11147.         } else {
  11148.           return elm.cloneNode(true);
  11149.         }
  11150.       };
  11151.       var setSizeProp = function (element, name, value) {
  11152.         if (isNonNullable(value)) {
  11153.           var targets = getResizeTargets(element);
  11154.           each$k(targets, function (target) {
  11155.             if (target.style[name] || !editor.schema.isValid(target.nodeName.toLowerCase(), name)) {
  11156.               dom.setStyle(target, name, value);
  11157.             } else {
  11158.               dom.setAttrib(target, name, '' + value);
  11159.             }
  11160.           });
  11161.         }
  11162.       };
  11163.       var setGhostElmSize = function (ghostElm, width, height) {
  11164.         setSizeProp(ghostElm, 'width', width);
  11165.         setSizeProp(ghostElm, 'height', height);
  11166.       };
  11167.       var resizeGhostElement = function (e) {
  11168.         var deltaX, deltaY, proportional;
  11169.         var resizeHelperX, resizeHelperY;
  11170.         deltaX = e.screenX - startX;
  11171.         deltaY = e.screenY - startY;
  11172.         width = deltaX * selectedHandle[2] + startW;
  11173.         height = deltaY * selectedHandle[3] + startH;
  11174.         width = width < 5 ? 5 : width;
  11175.         height = height < 5 ? 5 : height;
  11176.         if ((isImage(selectedElm) || isMedia(selectedElm)) && getResizeImgProportional(editor) !== false) {
  11177.           proportional = !VK.modifierPressed(e);
  11178.         } else {
  11179.           proportional = VK.modifierPressed(e);
  11180.         }
  11181.         if (proportional) {
  11182.           if (abs(deltaX) > abs(deltaY)) {
  11183.             height = round(width * ratio);
  11184.             width = round(height / ratio);
  11185.           } else {
  11186.             width = round(height / ratio);
  11187.             height = round(width * ratio);
  11188.           }
  11189.         }
  11190.         setGhostElmSize(selectedElmGhost, width, height);
  11191.         resizeHelperX = selectedHandle.startPos.x + deltaX;
  11192.         resizeHelperY = selectedHandle.startPos.y + deltaY;
  11193.         resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
  11194.         resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
  11195.         dom.setStyles(resizeHelper, {
  11196.           left: resizeHelperX,
  11197.           top: resizeHelperY,
  11198.           display: 'block'
  11199.         });
  11200.         resizeHelper.innerHTML = width + ' &times; ' + height;
  11201.         if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  11202.           dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  11203.         }
  11204.         if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  11205.           dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  11206.         }
  11207.         deltaX = rootElement.scrollWidth - startScrollWidth;
  11208.         deltaY = rootElement.scrollHeight - startScrollHeight;
  11209.         if (deltaX + deltaY !== 0) {
  11210.           dom.setStyles(resizeHelper, {
  11211.             left: resizeHelperX - deltaX,
  11212.             top: resizeHelperY - deltaY
  11213.           });
  11214.         }
  11215.         if (!resizeStarted) {
  11216.           fireObjectResizeStart(editor, selectedElm, startW, startH, 'corner-' + selectedHandle.name);
  11217.           resizeStarted = true;
  11218.         }
  11219.       };
  11220.       var endGhostResize = function () {
  11221.         var wasResizeStarted = resizeStarted;
  11222.         resizeStarted = false;
  11223.         if (wasResizeStarted) {
  11224.           setSizeProp(selectedElm, 'width', width);
  11225.           setSizeProp(selectedElm, 'height', height);
  11226.         }
  11227.         dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  11228.         dom.unbind(editableDoc, 'mouseup', endGhostResize);
  11229.         if (rootDocument !== editableDoc) {
  11230.           dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  11231.           dom.unbind(rootDocument, 'mouseup', endGhostResize);
  11232.         }
  11233.         dom.remove(selectedElmGhost);
  11234.         dom.remove(resizeHelper);
  11235.         dom.remove(resizeBackdrop);
  11236.         showResizeRect(selectedElm);
  11237.         if (wasResizeStarted) {
  11238.           fireObjectResized(editor, selectedElm, width, height, 'corner-' + selectedHandle.name);
  11239.           dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
  11240.         }
  11241.         editor.nodeChanged();
  11242.       };
  11243.       var showResizeRect = function (targetElm) {
  11244.         unbindResizeHandleEvents();
  11245.         var position = dom.getPos(targetElm, rootElement);
  11246.         var selectedElmX = position.x;
  11247.         var selectedElmY = position.y;
  11248.         var rect = targetElm.getBoundingClientRect();
  11249.         var targetWidth = rect.width || rect.right - rect.left;
  11250.         var targetHeight = rect.height || rect.bottom - rect.top;
  11251.         if (selectedElm !== targetElm) {
  11252.           hideResizeRect();
  11253.           selectedElm = targetElm;
  11254.           width = height = 0;
  11255.         }
  11256.         var e = editor.fire('ObjectSelected', { target: targetElm });
  11257.         var selectedValue = dom.getAttrib(selectedElm, elementSelectionAttr, '1');
  11258.         if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  11259.           each(resizeHandles, function (handle, name) {
  11260.             var handleElm;
  11261.             var startDrag = function (e) {
  11262.               var target = getResizeTargets(selectedElm)[0];
  11263.               startX = e.screenX;
  11264.               startY = e.screenY;
  11265.               startW = target.clientWidth;
  11266.               startH = target.clientHeight;
  11267.               ratio = startH / startW;
  11268.               selectedHandle = handle;
  11269.               selectedHandle.name = name;
  11270.               selectedHandle.startPos = {
  11271.                 x: targetWidth * handle[0] + selectedElmX,
  11272.                 y: targetHeight * handle[1] + selectedElmY
  11273.               };
  11274.               startScrollWidth = rootElement.scrollWidth;
  11275.               startScrollHeight = rootElement.scrollHeight;
  11276.               resizeBackdrop = dom.add(rootElement, 'div', {
  11277.                 'class': 'mce-resize-backdrop',
  11278.                 'data-mce-bogus': 'all'
  11279.               });
  11280.               dom.setStyles(resizeBackdrop, {
  11281.                 position: 'fixed',
  11282.                 left: '0',
  11283.                 top: '0',
  11284.                 width: '100%',
  11285.                 height: '100%'
  11286.               });
  11287.               selectedElmGhost = createGhostElement(selectedElm);
  11288.               dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  11289.               dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
  11290.               selectedElmGhost.contentEditable = 'false';
  11291.               dom.setStyles(selectedElmGhost, {
  11292.                 left: selectedElmX,
  11293.                 top: selectedElmY,
  11294.                 margin: 0
  11295.               });
  11296.               setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
  11297.               selectedElmGhost.removeAttribute(elementSelectionAttr);
  11298.               rootElement.appendChild(selectedElmGhost);
  11299.               dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  11300.               dom.bind(editableDoc, 'mouseup', endGhostResize);
  11301.               if (rootDocument !== editableDoc) {
  11302.                 dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  11303.                 dom.bind(rootDocument, 'mouseup', endGhostResize);
  11304.               }
  11305.               resizeHelper = dom.add(rootElement, 'div', {
  11306.                 'class': 'mce-resize-helper',
  11307.                 'data-mce-bogus': 'all'
  11308.               }, startW + ' &times; ' + startH);
  11309.             };
  11310.             handleElm = dom.get('mceResizeHandle' + name);
  11311.             if (handleElm) {
  11312.               dom.remove(handleElm);
  11313.             }
  11314.             handleElm = dom.add(rootElement, 'div', {
  11315.               'id': 'mceResizeHandle' + name,
  11316.               'data-mce-bogus': 'all',
  11317.               'class': 'mce-resizehandle',
  11318.               'unselectable': true,
  11319.               'style': 'cursor:' + name + '-resize; margin:0; padding:0'
  11320.             });
  11321.             if (Env.ie === 11) {
  11322.               handleElm.contentEditable = false;
  11323.             }
  11324.             dom.bind(handleElm, 'mousedown', function (e) {
  11325.               e.stopImmediatePropagation();
  11326.               e.preventDefault();
  11327.               startDrag(e);
  11328.             });
  11329.             handle.elm = handleElm;
  11330.             dom.setStyles(handleElm, {
  11331.               left: targetWidth * handle[0] + selectedElmX - handleElm.offsetWidth / 2,
  11332.               top: targetHeight * handle[1] + selectedElmY - handleElm.offsetHeight / 2
  11333.             });
  11334.           });
  11335.         } else {
  11336.           hideResizeRect();
  11337.         }
  11338.         if (!dom.getAttrib(selectedElm, elementSelectionAttr)) {
  11339.           selectedElm.setAttribute(elementSelectionAttr, selectedValue);
  11340.         }
  11341.       };
  11342.       var hideResizeRect = function () {
  11343.         unbindResizeHandleEvents();
  11344.         if (selectedElm) {
  11345.           selectedElm.removeAttribute(elementSelectionAttr);
  11346.         }
  11347.         each$j(resizeHandles, function (value, name) {
  11348.           var handleElm = dom.get('mceResizeHandle' + name);
  11349.           if (handleElm) {
  11350.             dom.unbind(handleElm);
  11351.             dom.remove(handleElm);
  11352.           }
  11353.         });
  11354.       };
  11355.       var updateResizeRect = function (e) {
  11356.         var startElm, controlElm;
  11357.         var isChildOrEqual = function (node, parent) {
  11358.           if (node) {
  11359.             do {
  11360.               if (node === parent) {
  11361.                 return true;
  11362.               }
  11363.             } while (node = node.parentNode);
  11364.           }
  11365.         };
  11366.         if (resizeStarted || editor.removed) {
  11367.           return;
  11368.         }
  11369.         each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function (img) {
  11370.           img.removeAttribute(elementSelectionAttr);
  11371.         });
  11372.         controlElm = e.type === 'mousedown' ? e.target : selection.getNode();
  11373.         controlElm = dom.$(controlElm).closest('table,img,figure.image,hr,video,span.mce-preview-object')[0];
  11374.         if (isChildOrEqual(controlElm, rootElement)) {
  11375.           disableGeckoResize();
  11376.           startElm = selection.getStart(true);
  11377.           if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
  11378.             showResizeRect(controlElm);
  11379.             return;
  11380.           }
  11381.         }
  11382.         hideResizeRect();
  11383.       };
  11384.       var isWithinContentEditableFalse = function (elm) {
  11385.         return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
  11386.       };
  11387.       var unbindResizeHandleEvents = function () {
  11388.         each$j(resizeHandles, function (handle) {
  11389.           if (handle.elm) {
  11390.             dom.unbind(handle.elm);
  11391.             delete handle.elm;
  11392.           }
  11393.         });
  11394.       };
  11395.       var disableGeckoResize = function () {
  11396.         try {
  11397.           editor.getDoc().execCommand('enableObjectResizing', false, 'false');
  11398.         } catch (ex) {
  11399.         }
  11400.       };
  11401.       editor.on('init', function () {
  11402.         disableGeckoResize();
  11403.         if (Env.browser.isIE() || Env.browser.isEdge()) {
  11404.           editor.on('mousedown click', function (e) {
  11405.             var target = e.target, nodeName = target.nodeName;
  11406.             if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
  11407.               if (e.button !== 2) {
  11408.                 editor.selection.select(target, nodeName === 'TABLE');
  11409.               }
  11410.               if (e.type === 'mousedown') {
  11411.                 editor.nodeChanged();
  11412.               }
  11413.             }
  11414.           });
  11415.           var handleMSControlSelect_1 = function (e) {
  11416.             var delayedSelect = function (node) {
  11417.               Delay.setEditorTimeout(editor, function () {
  11418.                 return editor.selection.select(node);
  11419.               });
  11420.             };
  11421.             if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
  11422.               e.preventDefault();
  11423.               delayedSelect(e.target);
  11424.               return;
  11425.             }
  11426.             if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  11427.               e.preventDefault();
  11428.               if (e.target.tagName === 'IMG') {
  11429.                 delayedSelect(e.target);
  11430.               }
  11431.             }
  11432.           };
  11433.           dom.bind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11434.           editor.on('remove', function () {
  11435.             return dom.unbind(rootElement, 'mscontrolselect', handleMSControlSelect_1);
  11436.           });
  11437.         }
  11438.         var throttledUpdateResizeRect = Delay.throttle(function (e) {
  11439.           if (!editor.composing) {
  11440.             updateResizeRect(e);
  11441.           }
  11442.         });
  11443.         editor.on('NodeChange ResizeEditor ResizeWindow ResizeContent drop', throttledUpdateResizeRect);
  11444.         editor.on('keyup compositionend', function (e) {
  11445.           if (selectedElm && selectedElm.nodeName === 'TABLE') {
  11446.             throttledUpdateResizeRect(e);
  11447.           }
  11448.         });
  11449.         editor.on('hide blur', hideResizeRect);
  11450.         editor.on('contextmenu longpress', contextMenuSelectImage, true);
  11451.       });
  11452.       editor.on('remove', unbindResizeHandleEvents);
  11453.       var destroy = function () {
  11454.         selectedElm = selectedElmGhost = resizeBackdrop = null;
  11455.       };
  11456.       return {
  11457.         isResizable: isResizable,
  11458.         showResizeRect: showResizeRect,
  11459.         hideResizeRect: hideResizeRect,
  11460.         updateResizeRect: updateResizeRect,
  11461.         destroy: destroy
  11462.       };
  11463.     };
  11464.  
  11465.     var hasCeProperty = function (node) {
  11466.       return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
  11467.     };
  11468.     var findParent$1 = function (node, rootNode, predicate) {
  11469.       while (node && node !== rootNode) {
  11470.         if (predicate(node)) {
  11471.           return node;
  11472.         }
  11473.         node = node.parentNode;
  11474.       }
  11475.       return null;
  11476.     };
  11477.     var findClosestIeRange = function (clientX, clientY, doc) {
  11478.       var rects;
  11479.       var element = doc.elementFromPoint(clientX, clientY);
  11480.       var rng = doc.body.createTextRange();
  11481.       if (!element || element.tagName === 'HTML') {
  11482.         element = doc.body;
  11483.       }
  11484.       rng.moveToElementText(element);
  11485.       rects = Tools.toArray(rng.getClientRects());
  11486.       rects = rects.sort(function (a, b) {
  11487.         a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
  11488.         b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
  11489.         return a - b;
  11490.       });
  11491.       if (rects.length > 0) {
  11492.         clientY = (rects[0].bottom + rects[0].top) / 2;
  11493.         try {
  11494.           rng.moveToPoint(clientX, clientY);
  11495.           rng.collapse(true);
  11496.           return rng;
  11497.         } catch (ex) {
  11498.         }
  11499.       }
  11500.       return null;
  11501.     };
  11502.     var moveOutOfContentEditableFalse = function (rng, rootNode) {
  11503.       var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
  11504.       return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
  11505.     };
  11506.     var fromPoint = function (clientX, clientY, doc) {
  11507.       var rng, point;
  11508.       var pointDoc = doc;
  11509.       if (pointDoc.caretPositionFromPoint) {
  11510.         point = pointDoc.caretPositionFromPoint(clientX, clientY);
  11511.         if (point) {
  11512.           rng = doc.createRange();
  11513.           rng.setStart(point.offsetNode, point.offset);
  11514.           rng.collapse(true);
  11515.         }
  11516.       } else if (pointDoc.caretRangeFromPoint) {
  11517.         rng = pointDoc.caretRangeFromPoint(clientX, clientY);
  11518.       } else if (pointDoc.body.createTextRange) {
  11519.         rng = pointDoc.body.createTextRange();
  11520.         try {
  11521.           rng.moveToPoint(clientX, clientY);
  11522.           rng.collapse(true);
  11523.         } catch (ex) {
  11524.           rng = findClosestIeRange(clientX, clientY, doc);
  11525.         }
  11526.         return moveOutOfContentEditableFalse(rng, doc.body);
  11527.       }
  11528.       return rng;
  11529.     };
  11530.  
  11531.     var isEq$4 = function (rng1, rng2) {
  11532.       return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
  11533.     };
  11534.  
  11535.     var findParent = function (node, rootNode, predicate) {
  11536.       while (node && node !== rootNode) {
  11537.         if (predicate(node)) {
  11538.           return node;
  11539.         }
  11540.         node = node.parentNode;
  11541.       }
  11542.       return null;
  11543.     };
  11544.     var hasParent$1 = function (node, rootNode, predicate) {
  11545.       return findParent(node, rootNode, predicate) !== null;
  11546.     };
  11547.     var hasParentWithName = function (node, rootNode, name) {
  11548.       return hasParent$1(node, rootNode, function (node) {
  11549.         return node.nodeName === name;
  11550.       });
  11551.     };
  11552.     var isTable = function (node) {
  11553.       return node && node.nodeName === 'TABLE';
  11554.     };
  11555.     var isTableCell$2 = function (node) {
  11556.       return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  11557.     };
  11558.     var isCeFalseCaretContainer = function (node, rootNode) {
  11559.       return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
  11560.     };
  11561.     var hasBrBeforeAfter = function (dom, node, left) {
  11562.       var walker = new DomTreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || dom.getRoot());
  11563.       while (node = walker[left ? 'prev' : 'next']()) {
  11564.         if (isBr$5(node)) {
  11565.           return true;
  11566.         }
  11567.       }
  11568.     };
  11569.     var isPrevNode = function (node, name) {
  11570.       return node.previousSibling && node.previousSibling.nodeName === name;
  11571.     };
  11572.     var hasContentEditableFalseParent = function (body, node) {
  11573.       while (node && node !== body) {
  11574.         if (isContentEditableFalse$b(node)) {
  11575.           return true;
  11576.         }
  11577.         node = node.parentNode;
  11578.       }
  11579.       return false;
  11580.     };
  11581.     var findTextNodeRelative = function (dom, isAfterNode, collapsed, left, startNode) {
  11582.       var lastInlineElement;
  11583.       var body = dom.getRoot();
  11584.       var node;
  11585.       var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11586.       var parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  11587.       if (left && isBr$5(startNode) && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  11588.         return Optional.some(CaretPosition(startNode.parentNode, dom.nodeIndex(startNode)));
  11589.       }
  11590.       var walker = new DomTreeWalker(startNode, parentBlockContainer);
  11591.       while (node = walker[left ? 'prev' : 'next']()) {
  11592.         if (dom.getContentEditableParent(node) === 'false' || isCeFalseCaretContainer(node, body)) {
  11593.           return Optional.none();
  11594.         }
  11595.         if (isText$7(node) && node.nodeValue.length > 0) {
  11596.           if (hasParentWithName(node, body, 'A') === false) {
  11597.             return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
  11598.           }
  11599.           return Optional.none();
  11600.         }
  11601.         if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  11602.           return Optional.none();
  11603.         }
  11604.         lastInlineElement = node;
  11605.       }
  11606.       if (collapsed && lastInlineElement) {
  11607.         return Optional.some(CaretPosition(lastInlineElement, 0));
  11608.       }
  11609.       return Optional.none();
  11610.     };
  11611.     var normalizeEndPoint = function (dom, collapsed, start, rng) {
  11612.       var container, offset;
  11613.       var body = dom.getRoot();
  11614.       var node;
  11615.       var directionLeft, normalized = false;
  11616.       container = rng[(start ? 'start' : 'end') + 'Container'];
  11617.       offset = rng[(start ? 'start' : 'end') + 'Offset'];
  11618.       var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
  11619.       var nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  11620.       directionLeft = start;
  11621.       if (isCaretContainer$2(container)) {
  11622.         return Optional.none();
  11623.       }
  11624.       if (isElement$5(container) && offset > container.childNodes.length - 1) {
  11625.         directionLeft = false;
  11626.       }
  11627.       if (isDocument$1(container)) {
  11628.         container = body;
  11629.         offset = 0;
  11630.       }
  11631.       if (container === body) {
  11632.         if (directionLeft) {
  11633.           node = container.childNodes[offset > 0 ? offset - 1 : 0];
  11634.           if (node) {
  11635.             if (isCaretContainer$2(node)) {
  11636.               return Optional.none();
  11637.             }
  11638.             if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
  11639.               return Optional.none();
  11640.             }
  11641.           }
  11642.         }
  11643.         if (container.hasChildNodes()) {
  11644.           offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  11645.           container = container.childNodes[offset];
  11646.           offset = isText$7(container) && isAfterNode ? container.data.length : 0;
  11647.           if (!collapsed && container === body.lastChild && isTable(container)) {
  11648.             return Optional.none();
  11649.           }
  11650.           if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
  11651.             return Optional.none();
  11652.           }
  11653.           if (container.hasChildNodes() && isTable(container) === false) {
  11654.             node = container;
  11655.             var walker = new DomTreeWalker(container, body);
  11656.             do {
  11657.               if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
  11658.                 normalized = false;
  11659.                 break;
  11660.               }
  11661.               if (isText$7(node) && node.nodeValue.length > 0) {
  11662.                 offset = directionLeft ? 0 : node.nodeValue.length;
  11663.                 container = node;
  11664.                 normalized = true;
  11665.                 break;
  11666.               }
  11667.               if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
  11668.                 offset = dom.nodeIndex(node);
  11669.                 container = node.parentNode;
  11670.                 if (!directionLeft) {
  11671.                   offset++;
  11672.                 }
  11673.                 normalized = true;
  11674.                 break;
  11675.               }
  11676.             } while (node = directionLeft ? walker.next() : walker.prev());
  11677.           }
  11678.         }
  11679.       }
  11680.       if (collapsed) {
  11681.         if (isText$7(container) && offset === 0) {
  11682.           findTextNodeRelative(dom, isAfterNode, collapsed, true, container).each(function (pos) {
  11683.             container = pos.container();
  11684.             offset = pos.offset();
  11685.             normalized = true;
  11686.           });
  11687.         }
  11688.         if (isElement$5(container)) {
  11689.           node = container.childNodes[offset];
  11690.           if (!node) {
  11691.             node = container.childNodes[offset - 1];
  11692.           }
  11693.           if (node && isBr$5(node) && !isPrevNode(node, 'A') && !hasBrBeforeAfter(dom, node, false) && !hasBrBeforeAfter(dom, node, true)) {
  11694.             findTextNodeRelative(dom, isAfterNode, collapsed, true, node).each(function (pos) {
  11695.               container = pos.container();
  11696.               offset = pos.offset();
  11697.               normalized = true;
  11698.             });
  11699.           }
  11700.         }
  11701.       }
  11702.       if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
  11703.         findTextNodeRelative(dom, isAfterNode, collapsed, false, container).each(function (pos) {
  11704.           container = pos.container();
  11705.           offset = pos.offset();
  11706.           normalized = true;
  11707.         });
  11708.       }
  11709.       return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
  11710.     };
  11711.     var normalize$2 = function (dom, rng) {
  11712.       var collapsed = rng.collapsed, normRng = rng.cloneRange();
  11713.       var startPos = CaretPosition.fromRangeStart(rng);
  11714.       normalizeEndPoint(dom, collapsed, true, normRng).each(function (pos) {
  11715.         if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
  11716.           normRng.setStart(pos.container(), pos.offset());
  11717.         }
  11718.       });
  11719.       if (!collapsed) {
  11720.         normalizeEndPoint(dom, collapsed, false, normRng).each(function (pos) {
  11721.           normRng.setEnd(pos.container(), pos.offset());
  11722.         });
  11723.       }
  11724.       if (collapsed) {
  11725.         normRng.collapse(true);
  11726.       }
  11727.       return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
  11728.     };
  11729.  
  11730.     var splitText = function (node, offset) {
  11731.       return node.splitText(offset);
  11732.     };
  11733.     var split = function (rng) {
  11734.       var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
  11735.       if (startContainer === endContainer && isText$7(startContainer)) {
  11736.         if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11737.           endContainer = splitText(startContainer, startOffset);
  11738.           startContainer = endContainer.previousSibling;
  11739.           if (endOffset > startOffset) {
  11740.             endOffset = endOffset - startOffset;
  11741.             startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  11742.             endOffset = endContainer.nodeValue.length;
  11743.             startOffset = 0;
  11744.           } else {
  11745.             endOffset = 0;
  11746.           }
  11747.         }
  11748.       } else {
  11749.         if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  11750.           startContainer = splitText(startContainer, startOffset);
  11751.           startOffset = 0;
  11752.         }
  11753.         if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  11754.           endContainer = splitText(endContainer, endOffset).previousSibling;
  11755.           endOffset = endContainer.nodeValue.length;
  11756.         }
  11757.       }
  11758.       return {
  11759.         startContainer: startContainer,
  11760.         startOffset: startOffset,
  11761.         endContainer: endContainer,
  11762.         endOffset: endOffset
  11763.       };
  11764.     };
  11765.  
  11766.     var RangeUtils = function (dom) {
  11767.       var walk = function (rng, callback) {
  11768.         return walk$2(dom, rng, callback);
  11769.       };
  11770.       var split$1 = split;
  11771.       var normalize = function (rng) {
  11772.         return normalize$2(dom, rng).fold(never, function (normalizedRng) {
  11773.           rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
  11774.           rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
  11775.           return true;
  11776.         });
  11777.       };
  11778.       return {
  11779.         walk: walk,
  11780.         split: split$1,
  11781.         normalize: normalize
  11782.       };
  11783.     };
  11784.     RangeUtils.compareRanges = isEq$4;
  11785.     RangeUtils.getCaretRangeFromPoint = fromPoint;
  11786.     RangeUtils.getSelectedNode = getSelectedNode;
  11787.     RangeUtils.getNode = getNode$1;
  11788.  
  11789.     var Dimension = function (name, getOffset) {
  11790.       var set = function (element, h) {
  11791.         if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  11792.           throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  11793.         }
  11794.         var dom = element.dom;
  11795.         if (isSupported(dom)) {
  11796.           dom.style[name] = h + 'px';
  11797.         }
  11798.       };
  11799.       var get = function (element) {
  11800.         var r = getOffset(element);
  11801.         if (r <= 0 || r === null) {
  11802.           var css = get$5(element, name);
  11803.           return parseFloat(css) || 0;
  11804.         }
  11805.         return r;
  11806.       };
  11807.       var getOuter = get;
  11808.       var aggregate = function (element, properties) {
  11809.         return foldl(properties, function (acc, property) {
  11810.           var val = get$5(element, property);
  11811.           var value = val === undefined ? 0 : parseInt(val, 10);
  11812.           return isNaN(value) ? acc : acc + value;
  11813.         }, 0);
  11814.       };
  11815.       var max = function (element, value, properties) {
  11816.         var cumulativeInclusions = aggregate(element, properties);
  11817.         var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  11818.         return absoluteMax;
  11819.       };
  11820.       return {
  11821.         set: set,
  11822.         get: get,
  11823.         getOuter: getOuter,
  11824.         aggregate: aggregate,
  11825.         max: max
  11826.       };
  11827.     };
  11828.  
  11829.     var api = Dimension('height', function (element) {
  11830.       var dom = element.dom;
  11831.       return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  11832.     });
  11833.     var get$1 = function (element) {
  11834.       return api.get(element);
  11835.     };
  11836.  
  11837.     var walkUp = function (navigation, doc) {
  11838.       var frame = navigation.view(doc);
  11839.       return frame.fold(constant([]), function (f) {
  11840.         var parent = navigation.owner(f);
  11841.         var rest = walkUp(navigation, parent);
  11842.         return [f].concat(rest);
  11843.       });
  11844.     };
  11845.     var pathTo = function (element, navigation) {
  11846.       var d = navigation.owner(element);
  11847.       return walkUp(navigation, d);
  11848.     };
  11849.  
  11850.     var view = function (doc) {
  11851.       var _a;
  11852.       var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  11853.       return element.map(SugarElement.fromDom);
  11854.     };
  11855.     var owner = function (element) {
  11856.       return documentOrOwner(element);
  11857.     };
  11858.  
  11859.     var Navigation = /*#__PURE__*/Object.freeze({
  11860.         __proto__: null,
  11861.         view: view,
  11862.         owner: owner
  11863.     });
  11864.  
  11865.     var find$1 = function (element) {
  11866.       var doc = SugarElement.fromDom(document);
  11867.       var scroll = get$8(doc);
  11868.       var frames = pathTo(element, Navigation);
  11869.       var offset = viewport(element);
  11870.       var r = foldr(frames, function (b, a) {
  11871.         var loc = viewport(a);
  11872.         return {
  11873.           left: b.left + loc.left,
  11874.           top: b.top + loc.top
  11875.         };
  11876.       }, {
  11877.         left: 0,
  11878.         top: 0
  11879.       });
  11880.       return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  11881.     };
  11882.  
  11883.     var excludeFromDescend = function (element) {
  11884.       return name(element) === 'textarea';
  11885.     };
  11886.     var fireScrollIntoViewEvent = function (editor, data) {
  11887.       var scrollEvent = editor.fire('ScrollIntoView', data);
  11888.       return scrollEvent.isDefaultPrevented();
  11889.     };
  11890.     var fireAfterScrollIntoViewEvent = function (editor, data) {
  11891.       editor.fire('AfterScrollIntoView', data);
  11892.     };
  11893.     var descend = function (element, offset) {
  11894.       var children$1 = children(element);
  11895.       if (children$1.length === 0 || excludeFromDescend(element)) {
  11896.         return {
  11897.           element: element,
  11898.           offset: offset
  11899.         };
  11900.       } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
  11901.         return {
  11902.           element: children$1[offset],
  11903.           offset: 0
  11904.         };
  11905.       } else {
  11906.         var last = children$1[children$1.length - 1];
  11907.         if (excludeFromDescend(last)) {
  11908.           return {
  11909.             element: element,
  11910.             offset: offset
  11911.           };
  11912.         } else {
  11913.           if (name(last) === 'img') {
  11914.             return {
  11915.               element: last,
  11916.               offset: 1
  11917.             };
  11918.           } else if (isText$8(last)) {
  11919.             return {
  11920.               element: last,
  11921.               offset: get$2(last).length
  11922.             };
  11923.           } else {
  11924.             return {
  11925.               element: last,
  11926.               offset: children(last).length
  11927.             };
  11928.           }
  11929.         }
  11930.       }
  11931.     };
  11932.     var markerInfo = function (element, cleanupFun) {
  11933.       var pos = absolute(element);
  11934.       var height = get$1(element);
  11935.       return {
  11936.         element: element,
  11937.         bottom: pos.top + height,
  11938.         height: height,
  11939.         pos: pos,
  11940.         cleanup: cleanupFun
  11941.       };
  11942.     };
  11943.     var createMarker = function (element, offset) {
  11944.       var startPoint = descend(element, offset);
  11945.       var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + '</span>');
  11946.       before$4(startPoint.element, span);
  11947.       return markerInfo(span, function () {
  11948.         return remove$7(span);
  11949.       });
  11950.     };
  11951.     var elementMarker = function (element) {
  11952.       return markerInfo(SugarElement.fromDom(element), noop);
  11953.     };
  11954.     var withMarker = function (editor, f, rng, alignToTop) {
  11955.       preserveWith(editor, function (_s, _e) {
  11956.         return applyWithMarker(editor, f, rng, alignToTop);
  11957.       }, rng);
  11958.     };
  11959.     var withScrollEvents = function (editor, doc, f, marker, alignToTop) {
  11960.       var data = {
  11961.         elm: marker.element.dom,
  11962.         alignToTop: alignToTop
  11963.       };
  11964.       if (fireScrollIntoViewEvent(editor, data)) {
  11965.         return;
  11966.       }
  11967.       var scrollTop = get$8(doc).top;
  11968.       f(doc, scrollTop, marker, alignToTop);
  11969.       fireAfterScrollIntoViewEvent(editor, data);
  11970.     };
  11971.     var applyWithMarker = function (editor, f, rng, alignToTop) {
  11972.       var body = SugarElement.fromDom(editor.getBody());
  11973.       var doc = SugarElement.fromDom(editor.getDoc());
  11974.       reflow(body);
  11975.       var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  11976.       withScrollEvents(editor, doc, f, marker, alignToTop);
  11977.       marker.cleanup();
  11978.     };
  11979.     var withElement = function (editor, element, f, alignToTop) {
  11980.       var doc = SugarElement.fromDom(editor.getDoc());
  11981.       withScrollEvents(editor, doc, f, elementMarker(element), alignToTop);
  11982.     };
  11983.     var preserveWith = function (editor, f, rng) {
  11984.       var startElement = rng.startContainer;
  11985.       var startOffset = rng.startOffset;
  11986.       var endElement = rng.endContainer;
  11987.       var endOffset = rng.endOffset;
  11988.       f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
  11989.       var newRng = editor.dom.createRng();
  11990.       newRng.setStart(startElement, startOffset);
  11991.       newRng.setEnd(endElement, endOffset);
  11992.       editor.selection.setRng(rng);
  11993.     };
  11994.     var scrollToMarker = function (marker, viewHeight, alignToTop, doc) {
  11995.       var pos = marker.pos;
  11996.       if (alignToTop) {
  11997.         to(pos.left, pos.top, doc);
  11998.       } else {
  11999.         var y = pos.top - viewHeight + marker.height;
  12000.         to(pos.left, y, doc);
  12001.       }
  12002.     };
  12003.     var intoWindowIfNeeded = function (doc, scrollTop, viewHeight, marker, alignToTop) {
  12004.       var viewportBottom = viewHeight + scrollTop;
  12005.       var markerTop = marker.pos.top;
  12006.       var markerBottom = marker.bottom;
  12007.       var largerThanViewport = markerBottom - markerTop >= viewHeight;
  12008.       if (markerTop < scrollTop) {
  12009.         scrollToMarker(marker, viewHeight, alignToTop !== false, doc);
  12010.       } else if (markerTop > viewportBottom) {
  12011.         var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
  12012.         scrollToMarker(marker, viewHeight, align, doc);
  12013.       } else if (markerBottom > viewportBottom && !largerThanViewport) {
  12014.         scrollToMarker(marker, viewHeight, alignToTop === true, doc);
  12015.       }
  12016.     };
  12017.     var intoWindow = function (doc, scrollTop, marker, alignToTop) {
  12018.       var viewHeight = doc.dom.defaultView.innerHeight;
  12019.       intoWindowIfNeeded(doc, scrollTop, viewHeight, marker, alignToTop);
  12020.     };
  12021.     var intoFrame = function (doc, scrollTop, marker, alignToTop) {
  12022.       var frameViewHeight = doc.dom.defaultView.innerHeight;
  12023.       intoWindowIfNeeded(doc, scrollTop, frameViewHeight, marker, alignToTop);
  12024.       var op = find$1(marker.element);
  12025.       var viewportBounds = getBounds(window);
  12026.       if (op.top < viewportBounds.y) {
  12027.         intoView(marker.element, alignToTop !== false);
  12028.       } else if (op.top > viewportBounds.bottom) {
  12029.         intoView(marker.element, alignToTop === true);
  12030.       }
  12031.     };
  12032.     var rangeIntoWindow = function (editor, rng, alignToTop) {
  12033.       return withMarker(editor, intoWindow, rng, alignToTop);
  12034.     };
  12035.     var elementIntoWindow = function (editor, element, alignToTop) {
  12036.       return withElement(editor, element, intoWindow, alignToTop);
  12037.     };
  12038.     var rangeIntoFrame = function (editor, rng, alignToTop) {
  12039.       return withMarker(editor, intoFrame, rng, alignToTop);
  12040.     };
  12041.     var elementIntoFrame = function (editor, element, alignToTop) {
  12042.       return withElement(editor, element, intoFrame, alignToTop);
  12043.     };
  12044.     var scrollElementIntoView = function (editor, element, alignToTop) {
  12045.       var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
  12046.       scroller(editor, element, alignToTop);
  12047.     };
  12048.     var scrollRangeIntoView = function (editor, rng, alignToTop) {
  12049.       var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
  12050.       scroller(editor, rng, alignToTop);
  12051.     };
  12052.  
  12053.     var getDocument = function () {
  12054.       return SugarElement.fromDom(document);
  12055.     };
  12056.  
  12057.     var focus$1 = function (element) {
  12058.       return element.dom.focus();
  12059.     };
  12060.     var hasFocus$1 = function (element) {
  12061.       var root = getRootNode(element).dom;
  12062.       return element.dom === root.activeElement;
  12063.     };
  12064.     var active = function (root) {
  12065.       if (root === void 0) {
  12066.         root = getDocument();
  12067.       }
  12068.       return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  12069.     };
  12070.     var search = function (element) {
  12071.       return active(getRootNode(element)).filter(function (e) {
  12072.         return element.dom.contains(e.dom);
  12073.       });
  12074.     };
  12075.  
  12076.     var create$5 = function (start, soffset, finish, foffset) {
  12077.       return {
  12078.         start: start,
  12079.         soffset: soffset,
  12080.         finish: finish,
  12081.         foffset: foffset
  12082.       };
  12083.     };
  12084.     var SimRange = { create: create$5 };
  12085.  
  12086.     var adt$1 = Adt.generate([
  12087.       { before: ['element'] },
  12088.       {
  12089.         on: [
  12090.           'element',
  12091.           'offset'
  12092.         ]
  12093.       },
  12094.       { after: ['element'] }
  12095.     ]);
  12096.     var cata = function (subject, onBefore, onOn, onAfter) {
  12097.       return subject.fold(onBefore, onOn, onAfter);
  12098.     };
  12099.     var getStart$2 = function (situ) {
  12100.       return situ.fold(identity, identity, identity);
  12101.     };
  12102.     var before$1 = adt$1.before;
  12103.     var on = adt$1.on;
  12104.     var after$1 = adt$1.after;
  12105.     var Situ = {
  12106.       before: before$1,
  12107.       on: on,
  12108.       after: after$1,
  12109.       cata: cata,
  12110.       getStart: getStart$2
  12111.     };
  12112.  
  12113.     var adt = Adt.generate([
  12114.       { domRange: ['rng'] },
  12115.       {
  12116.         relative: [
  12117.           'startSitu',
  12118.           'finishSitu'
  12119.         ]
  12120.       },
  12121.       {
  12122.         exact: [
  12123.           'start',
  12124.           'soffset',
  12125.           'finish',
  12126.           'foffset'
  12127.         ]
  12128.       }
  12129.     ]);
  12130.     var exactFromRange = function (simRange) {
  12131.       return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  12132.     };
  12133.     var getStart$1 = function (selection) {
  12134.       return selection.match({
  12135.         domRange: function (rng) {
  12136.           return SugarElement.fromDom(rng.startContainer);
  12137.         },
  12138.         relative: function (startSitu, _finishSitu) {
  12139.           return Situ.getStart(startSitu);
  12140.         },
  12141.         exact: function (start, _soffset, _finish, _foffset) {
  12142.           return start;
  12143.         }
  12144.       });
  12145.     };
  12146.     var domRange = adt.domRange;
  12147.     var relative = adt.relative;
  12148.     var exact = adt.exact;
  12149.     var getWin = function (selection) {
  12150.       var start = getStart$1(selection);
  12151.       return defaultView(start);
  12152.     };
  12153.     var range = SimRange.create;
  12154.     var SimSelection = {
  12155.       domRange: domRange,
  12156.       relative: relative,
  12157.       exact: exact,
  12158.       exactFromRange: exactFromRange,
  12159.       getWin: getWin,
  12160.       range: range
  12161.     };
  12162.  
  12163.     var browser$1 = detect().browser;
  12164.     var clamp$1 = function (offset, element) {
  12165.       var max = isText$8(element) ? get$2(element).length : children(element).length + 1;
  12166.       if (offset > max) {
  12167.         return max;
  12168.       } else if (offset < 0) {
  12169.         return 0;
  12170.       }
  12171.       return offset;
  12172.     };
  12173.     var normalizeRng = function (rng) {
  12174.       return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
  12175.     };
  12176.     var isOrContains = function (root, elm) {
  12177.       return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
  12178.     };
  12179.     var isRngInRoot = function (root) {
  12180.       return function (rng) {
  12181.         return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
  12182.       };
  12183.     };
  12184.     var shouldStore = function (editor) {
  12185.       return editor.inline === true || browser$1.isIE();
  12186.     };
  12187.     var nativeRangeToSelectionRange = function (r) {
  12188.       return SimSelection.range(SugarElement.fromDom(r.startContainer), r.startOffset, SugarElement.fromDom(r.endContainer), r.endOffset);
  12189.     };
  12190.     var readRange = function (win) {
  12191.       var selection = win.getSelection();
  12192.       var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
  12193.       return rng.map(nativeRangeToSelectionRange);
  12194.     };
  12195.     var getBookmark = function (root) {
  12196.       var win = defaultView(root);
  12197.       return readRange(win.dom).filter(isRngInRoot(root));
  12198.     };
  12199.     var validate = function (root, bookmark) {
  12200.       return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
  12201.     };
  12202.     var bookmarkToNativeRng = function (bookmark) {
  12203.       var rng = document.createRange();
  12204.       try {
  12205.         rng.setStart(bookmark.start.dom, bookmark.soffset);
  12206.         rng.setEnd(bookmark.finish.dom, bookmark.foffset);
  12207.         return Optional.some(rng);
  12208.       } catch (_) {
  12209.         return Optional.none();
  12210.       }
  12211.     };
  12212.     var store = function (editor) {
  12213.       var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
  12214.       editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12215.     };
  12216.     var storeNative = function (editor, rng) {
  12217.       var root = SugarElement.fromDom(editor.getBody());
  12218.       var range = shouldStore(editor) ? Optional.from(rng) : Optional.none();
  12219.       var newBookmark = range.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
  12220.       editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
  12221.     };
  12222.     var getRng = function (editor) {
  12223.       var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
  12224.       return bookmark.bind(function (x) {
  12225.         return validate(SugarElement.fromDom(editor.getBody()), x);
  12226.       }).bind(bookmarkToNativeRng);
  12227.     };
  12228.     var restore = function (editor) {
  12229.       getRng(editor).each(function (rng) {
  12230.         return editor.selection.setRng(rng);
  12231.       });
  12232.     };
  12233.  
  12234.     var isEditorUIElement$1 = function (elm) {
  12235.       var className = elm.className.toString();
  12236.       return className.indexOf('tox-') !== -1 || className.indexOf('mce-') !== -1;
  12237.     };
  12238.     var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
  12239.  
  12240.     var isManualNodeChange = function (e) {
  12241.       return e.type === 'nodechange' && e.selectionChange;
  12242.     };
  12243.     var registerPageMouseUp = function (editor, throttledStore) {
  12244.       var mouseUpPage = function () {
  12245.         throttledStore.throttle();
  12246.       };
  12247.       DOMUtils.DOM.bind(document, 'mouseup', mouseUpPage);
  12248.       editor.on('remove', function () {
  12249.         DOMUtils.DOM.unbind(document, 'mouseup', mouseUpPage);
  12250.       });
  12251.     };
  12252.     var registerFocusOut = function (editor) {
  12253.       editor.on('focusout', function () {
  12254.         store(editor);
  12255.       });
  12256.     };
  12257.     var registerMouseUp = function (editor, throttledStore) {
  12258.       editor.on('mouseup touchend', function (_e) {
  12259.         throttledStore.throttle();
  12260.       });
  12261.     };
  12262.     var registerEditorEvents = function (editor, throttledStore) {
  12263.       var browser = detect().browser;
  12264.       if (browser.isIE()) {
  12265.         registerFocusOut(editor);
  12266.       } else {
  12267.         registerMouseUp(editor, throttledStore);
  12268.       }
  12269.       editor.on('keyup NodeChange', function (e) {
  12270.         if (!isManualNodeChange(e)) {
  12271.           store(editor);
  12272.         }
  12273.       });
  12274.     };
  12275.     var register$3 = function (editor) {
  12276.       var throttledStore = first(function () {
  12277.         store(editor);
  12278.       }, 0);
  12279.       editor.on('init', function () {
  12280.         if (editor.inline) {
  12281.           registerPageMouseUp(editor, throttledStore);
  12282.         }
  12283.         registerEditorEvents(editor, throttledStore);
  12284.       });
  12285.       editor.on('remove', function () {
  12286.         throttledStore.cancel();
  12287.       });
  12288.     };
  12289.  
  12290.     var documentFocusInHandler;
  12291.     var DOM$8 = DOMUtils.DOM;
  12292.     var isEditorUIElement = function (elm) {
  12293.       return FocusManager.isEditorUIElement(elm);
  12294.     };
  12295.     var isEditorContentAreaElement = function (elm) {
  12296.       var classList = elm.classList;
  12297.       if (classList !== undefined) {
  12298.         return classList.contains('tox-edit-area') || classList.contains('tox-edit-area__iframe') || classList.contains('mce-content-body');
  12299.       } else {
  12300.         return false;
  12301.       }
  12302.     };
  12303.     var isUIElement = function (editor, elm) {
  12304.       var customSelector = getCustomUiSelector(editor);
  12305.       var parent = DOM$8.getParent(elm, function (elm) {
  12306.         return isEditorUIElement(elm) || (customSelector ? editor.dom.is(elm, customSelector) : false);
  12307.       });
  12308.       return parent !== null;
  12309.     };
  12310.     var getActiveElement = function (editor) {
  12311.       try {
  12312.         var root = getRootNode(SugarElement.fromDom(editor.getElement()));
  12313.         return active(root).fold(function () {
  12314.           return document.body;
  12315.         }, function (x) {
  12316.           return x.dom;
  12317.         });
  12318.       } catch (ex) {
  12319.         return document.body;
  12320.       }
  12321.     };
  12322.     var registerEvents$1 = function (editorManager, e) {
  12323.       var editor = e.editor;
  12324.       register$3(editor);
  12325.       editor.on('focusin', function () {
  12326.         var focusedEditor = editorManager.focusedEditor;
  12327.         if (focusedEditor !== editor) {
  12328.           if (focusedEditor) {
  12329.             focusedEditor.fire('blur', { focusedEditor: editor });
  12330.           }
  12331.           editorManager.setActive(editor);
  12332.           editorManager.focusedEditor = editor;
  12333.           editor.fire('focus', { blurredEditor: focusedEditor });
  12334.           editor.focus(true);
  12335.         }
  12336.       });
  12337.       editor.on('focusout', function () {
  12338.         Delay.setEditorTimeout(editor, function () {
  12339.           var focusedEditor = editorManager.focusedEditor;
  12340.           if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
  12341.             editor.fire('blur', { focusedEditor: null });
  12342.             editorManager.focusedEditor = null;
  12343.           }
  12344.         });
  12345.       });
  12346.       if (!documentFocusInHandler) {
  12347.         documentFocusInHandler = function (e) {
  12348.           var activeEditor = editorManager.activeEditor;
  12349.           if (activeEditor) {
  12350.             getOriginalEventTarget(e).each(function (target) {
  12351.               if (target.ownerDocument === document) {
  12352.                 if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
  12353.                   activeEditor.fire('blur', { focusedEditor: null });
  12354.                   editorManager.focusedEditor = null;
  12355.                 }
  12356.               }
  12357.             });
  12358.           }
  12359.         };
  12360.         DOM$8.bind(document, 'focusin', documentFocusInHandler);
  12361.       }
  12362.     };
  12363.     var unregisterDocumentEvents = function (editorManager, e) {
  12364.       if (editorManager.focusedEditor === e.editor) {
  12365.         editorManager.focusedEditor = null;
  12366.       }
  12367.       if (!editorManager.activeEditor) {
  12368.         DOM$8.unbind(document, 'focusin', documentFocusInHandler);
  12369.         documentFocusInHandler = null;
  12370.       }
  12371.     };
  12372.     var setup$l = function (editorManager) {
  12373.       editorManager.on('AddEditor', curry(registerEvents$1, editorManager));
  12374.       editorManager.on('RemoveEditor', curry(unregisterDocumentEvents, editorManager));
  12375.     };
  12376.  
  12377.     var getContentEditableHost = function (editor, node) {
  12378.       return editor.dom.getParent(node, function (node) {
  12379.         return editor.dom.getContentEditable(node) === 'true';
  12380.       });
  12381.     };
  12382.     var getCollapsedNode = function (rng) {
  12383.       return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
  12384.     };
  12385.     var getFocusInElement = function (root, rng) {
  12386.       return getCollapsedNode(rng).bind(function (node) {
  12387.         if (isTableSection(node)) {
  12388.           return Optional.some(node);
  12389.         } else if (contains$1(root, node) === false) {
  12390.           return Optional.some(root);
  12391.         } else {
  12392.           return Optional.none();
  12393.         }
  12394.       });
  12395.     };
  12396.     var normalizeSelection$1 = function (editor, rng) {
  12397.       getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function (elm) {
  12398.         return firstPositionIn(elm.dom);
  12399.       }).fold(function () {
  12400.         editor.selection.normalize();
  12401.         return;
  12402.       }, function (caretPos) {
  12403.         return editor.selection.setRng(caretPos.toRange());
  12404.       });
  12405.     };
  12406.     var focusBody = function (body) {
  12407.       if (body.setActive) {
  12408.         try {
  12409.           body.setActive();
  12410.         } catch (ex) {
  12411.           body.focus();
  12412.         }
  12413.       } else {
  12414.         body.focus();
  12415.       }
  12416.     };
  12417.     var hasElementFocus = function (elm) {
  12418.       return hasFocus$1(elm) || search(elm).isSome();
  12419.     };
  12420.     var hasIframeFocus = function (editor) {
  12421.       return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
  12422.     };
  12423.     var hasInlineFocus = function (editor) {
  12424.       var rawBody = editor.getBody();
  12425.       return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
  12426.     };
  12427.     var hasUiFocus = function (editor) {
  12428.       var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
  12429.       return active(dos).filter(function (elem) {
  12430.         return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
  12431.       }).isSome();
  12432.     };
  12433.     var hasFocus = function (editor) {
  12434.       return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
  12435.     };
  12436.     var hasEditorOrUiFocus = function (editor) {
  12437.       return hasFocus(editor) || hasUiFocus(editor);
  12438.     };
  12439.     var focusEditor = function (editor) {
  12440.       var selection = editor.selection;
  12441.       var body = editor.getBody();
  12442.       var rng = selection.getRng();
  12443.       editor.quirks.refreshContentEditable();
  12444.       if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  12445.         getRng(editor).each(function (bookmarkRng) {
  12446.           editor.selection.setRng(bookmarkRng);
  12447.           rng = bookmarkRng;
  12448.         });
  12449.       }
  12450.       var contentEditableHost = getContentEditableHost(editor, selection.getNode());
  12451.       if (editor.$.contains(body, contentEditableHost)) {
  12452.         focusBody(contentEditableHost);
  12453.         normalizeSelection$1(editor, rng);
  12454.         activateEditor(editor);
  12455.         return;
  12456.       }
  12457.       if (!editor.inline) {
  12458.         if (!Env.opera) {
  12459.           focusBody(body);
  12460.         }
  12461.         editor.getWin().focus();
  12462.       }
  12463.       if (Env.gecko || editor.inline) {
  12464.         focusBody(body);
  12465.         normalizeSelection$1(editor, rng);
  12466.       }
  12467.       activateEditor(editor);
  12468.     };
  12469.     var activateEditor = function (editor) {
  12470.       return editor.editorManager.setActive(editor);
  12471.     };
  12472.     var focus = function (editor, skipFocus) {
  12473.       if (editor.removed) {
  12474.         return;
  12475.       }
  12476.       if (skipFocus) {
  12477.         activateEditor(editor);
  12478.       } else {
  12479.         focusEditor(editor);
  12480.       }
  12481.     };
  12482.  
  12483.     var getEndpointElement = function (root, rng, start, real, resolve) {
  12484.       var container = start ? rng.startContainer : rng.endContainer;
  12485.       var offset = start ? rng.startOffset : rng.endOffset;
  12486.       return Optional.from(container).map(SugarElement.fromDom).map(function (elm) {
  12487.         return !real || !rng.collapsed ? child$1(elm, resolve(elm, offset)).getOr(elm) : elm;
  12488.       }).bind(function (elm) {
  12489.         return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
  12490.       }).map(function (elm) {
  12491.         return elm.dom;
  12492.       }).getOr(root);
  12493.     };
  12494.     var getStart = function (root, rng, real) {
  12495.       return getEndpointElement(root, rng, true, real, function (elm, offset) {
  12496.         return Math.min(childNodesCount(elm), offset);
  12497.       });
  12498.     };
  12499.     var getEnd = function (root, rng, real) {
  12500.       return getEndpointElement(root, rng, false, real, function (elm, offset) {
  12501.         return offset > 0 ? offset - 1 : offset;
  12502.       });
  12503.     };
  12504.     var skipEmptyTextNodes = function (node, forwards) {
  12505.       var orig = node;
  12506.       while (node && isText$7(node) && node.length === 0) {
  12507.         node = forwards ? node.nextSibling : node.previousSibling;
  12508.       }
  12509.       return node || orig;
  12510.     };
  12511.     var getNode = function (root, rng) {
  12512.       var elm, startContainer, endContainer;
  12513.       if (!rng) {
  12514.         return root;
  12515.       }
  12516.       startContainer = rng.startContainer;
  12517.       endContainer = rng.endContainer;
  12518.       var startOffset = rng.startOffset;
  12519.       var endOffset = rng.endOffset;
  12520.       elm = rng.commonAncestorContainer;
  12521.       if (!rng.collapsed) {
  12522.         if (startContainer === endContainer) {
  12523.           if (endOffset - startOffset < 2) {
  12524.             if (startContainer.hasChildNodes()) {
  12525.               elm = startContainer.childNodes[startOffset];
  12526.             }
  12527.           }
  12528.         }
  12529.         if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  12530.           if (startContainer.length === startOffset) {
  12531.             startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  12532.           } else {
  12533.             startContainer = startContainer.parentNode;
  12534.           }
  12535.           if (endOffset === 0) {
  12536.             endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  12537.           } else {
  12538.             endContainer = endContainer.parentNode;
  12539.           }
  12540.           if (startContainer && startContainer === endContainer) {
  12541.             return startContainer;
  12542.           }
  12543.         }
  12544.       }
  12545.       if (elm && elm.nodeType === 3) {
  12546.         return elm.parentNode;
  12547.       }
  12548.       return elm;
  12549.     };
  12550.     var getSelectedBlocks = function (dom, rng, startElm, endElm) {
  12551.       var node;
  12552.       var selectedBlocks = [];
  12553.       var root = dom.getRoot();
  12554.       startElm = dom.getParent(startElm || getStart(root, rng, rng.collapsed), dom.isBlock);
  12555.       endElm = dom.getParent(endElm || getEnd(root, rng, rng.collapsed), dom.isBlock);
  12556.       if (startElm && startElm !== root) {
  12557.         selectedBlocks.push(startElm);
  12558.       }
  12559.       if (startElm && endElm && startElm !== endElm) {
  12560.         node = startElm;
  12561.         var walker = new DomTreeWalker(startElm, root);
  12562.         while ((node = walker.next()) && node !== endElm) {
  12563.           if (dom.isBlock(node)) {
  12564.             selectedBlocks.push(node);
  12565.           }
  12566.         }
  12567.       }
  12568.       if (endElm && startElm !== endElm && endElm !== root) {
  12569.         selectedBlocks.push(endElm);
  12570.       }
  12571.       return selectedBlocks;
  12572.     };
  12573.     var select = function (dom, node, content) {
  12574.       return Optional.from(node).map(function (node) {
  12575.         var idx = dom.nodeIndex(node);
  12576.         var rng = dom.createRng();
  12577.         rng.setStart(node.parentNode, idx);
  12578.         rng.setEnd(node.parentNode, idx + 1);
  12579.         if (content) {
  12580.           moveEndPoint(dom, rng, node, true);
  12581.           moveEndPoint(dom, rng, node, false);
  12582.         }
  12583.         return rng;
  12584.       });
  12585.     };
  12586.  
  12587.     var processRanges = function (editor, ranges) {
  12588.       return map$3(ranges, function (range) {
  12589.         var evt = editor.fire('GetSelectionRange', { range: range });
  12590.         return evt.range !== range ? evt.range : range;
  12591.       });
  12592.     };
  12593.  
  12594.     var typeLookup = {
  12595.       '#text': 3,
  12596.       '#comment': 8,
  12597.       '#cdata': 4,
  12598.       '#pi': 7,
  12599.       '#doctype': 10,
  12600.       '#document-fragment': 11
  12601.     };
  12602.     var walk$1 = function (node, root, prev) {
  12603.       var startName = prev ? 'lastChild' : 'firstChild';
  12604.       var siblingName = prev ? 'prev' : 'next';
  12605.       if (node[startName]) {
  12606.         return node[startName];
  12607.       }
  12608.       if (node !== root) {
  12609.         var sibling = node[siblingName];
  12610.         if (sibling) {
  12611.           return sibling;
  12612.         }
  12613.         for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
  12614.           sibling = parent_1[siblingName];
  12615.           if (sibling) {
  12616.             return sibling;
  12617.           }
  12618.         }
  12619.       }
  12620.     };
  12621.     var isEmptyTextNode = function (node) {
  12622.       if (!isWhitespaceText(node.value)) {
  12623.         return false;
  12624.       }
  12625.       var parentNode = node.parent;
  12626.       if (parentNode && (parentNode.name !== 'span' || parentNode.attr('style')) && /^[ ]+$/.test(node.value)) {
  12627.         return false;
  12628.       }
  12629.       return true;
  12630.     };
  12631.     var isNonEmptyElement = function (node) {
  12632.       var isNamedAnchor = node.name === 'a' && !node.attr('href') && node.attr('id');
  12633.       return node.attr('name') || node.attr('id') && !node.firstChild || node.attr('data-mce-bookmark') || isNamedAnchor;
  12634.     };
  12635.     var AstNode = function () {
  12636.       function AstNode(name, type) {
  12637.         this.name = name;
  12638.         this.type = type;
  12639.         if (type === 1) {
  12640.           this.attributes = [];
  12641.           this.attributes.map = {};
  12642.         }
  12643.       }
  12644.       AstNode.create = function (name, attrs) {
  12645.         var node = new AstNode(name, typeLookup[name] || 1);
  12646.         if (attrs) {
  12647.           each$j(attrs, function (value, attrName) {
  12648.             node.attr(attrName, value);
  12649.           });
  12650.         }
  12651.         return node;
  12652.       };
  12653.       AstNode.prototype.replace = function (node) {
  12654.         var self = this;
  12655.         if (node.parent) {
  12656.           node.remove();
  12657.         }
  12658.         self.insert(node, self);
  12659.         self.remove();
  12660.         return self;
  12661.       };
  12662.       AstNode.prototype.attr = function (name, value) {
  12663.         var self = this;
  12664.         var attrs;
  12665.         if (typeof name !== 'string') {
  12666.           if (name !== undefined && name !== null) {
  12667.             each$j(name, function (value, key) {
  12668.               self.attr(key, value);
  12669.             });
  12670.           }
  12671.           return self;
  12672.         }
  12673.         if (attrs = self.attributes) {
  12674.           if (value !== undefined) {
  12675.             if (value === null) {
  12676.               if (name in attrs.map) {
  12677.                 delete attrs.map[name];
  12678.                 var i = attrs.length;
  12679.                 while (i--) {
  12680.                   if (attrs[i].name === name) {
  12681.                     attrs.splice(i, 1);
  12682.                     return self;
  12683.                   }
  12684.                 }
  12685.               }
  12686.               return self;
  12687.             }
  12688.             if (name in attrs.map) {
  12689.               var i = attrs.length;
  12690.               while (i--) {
  12691.                 if (attrs[i].name === name) {
  12692.                   attrs[i].value = value;
  12693.                   break;
  12694.                 }
  12695.               }
  12696.             } else {
  12697.               attrs.push({
  12698.                 name: name,
  12699.                 value: value
  12700.               });
  12701.             }
  12702.             attrs.map[name] = value;
  12703.             return self;
  12704.           }
  12705.           return attrs.map[name];
  12706.         }
  12707.       };
  12708.       AstNode.prototype.clone = function () {
  12709.         var self = this;
  12710.         var clone = new AstNode(self.name, self.type);
  12711.         var selfAttrs;
  12712.         if (selfAttrs = self.attributes) {
  12713.           var cloneAttrs = [];
  12714.           cloneAttrs.map = {};
  12715.           for (var i = 0, l = selfAttrs.length; i < l; i++) {
  12716.             var selfAttr = selfAttrs[i];
  12717.             if (selfAttr.name !== 'id') {
  12718.               cloneAttrs[cloneAttrs.length] = {
  12719.                 name: selfAttr.name,
  12720.                 value: selfAttr.value
  12721.               };
  12722.               cloneAttrs.map[selfAttr.name] = selfAttr.value;
  12723.             }
  12724.           }
  12725.           clone.attributes = cloneAttrs;
  12726.         }
  12727.         clone.value = self.value;
  12728.         clone.shortEnded = self.shortEnded;
  12729.         return clone;
  12730.       };
  12731.       AstNode.prototype.wrap = function (wrapper) {
  12732.         var self = this;
  12733.         self.parent.insert(wrapper, self);
  12734.         wrapper.append(self);
  12735.         return self;
  12736.       };
  12737.       AstNode.prototype.unwrap = function () {
  12738.         var self = this;
  12739.         for (var node = self.firstChild; node;) {
  12740.           var next = node.next;
  12741.           self.insert(node, self, true);
  12742.           node = next;
  12743.         }
  12744.         self.remove();
  12745.       };
  12746.       AstNode.prototype.remove = function () {
  12747.         var self = this, parent = self.parent, next = self.next, prev = self.prev;
  12748.         if (parent) {
  12749.           if (parent.firstChild === self) {
  12750.             parent.firstChild = next;
  12751.             if (next) {
  12752.               next.prev = null;
  12753.             }
  12754.           } else {
  12755.             prev.next = next;
  12756.           }
  12757.           if (parent.lastChild === self) {
  12758.             parent.lastChild = prev;
  12759.             if (prev) {
  12760.               prev.next = null;
  12761.             }
  12762.           } else {
  12763.             next.prev = prev;
  12764.           }
  12765.           self.parent = self.next = self.prev = null;
  12766.         }
  12767.         return self;
  12768.       };
  12769.       AstNode.prototype.append = function (node) {
  12770.         var self = this;
  12771.         if (node.parent) {
  12772.           node.remove();
  12773.         }
  12774.         var last = self.lastChild;
  12775.         if (last) {
  12776.           last.next = node;
  12777.           node.prev = last;
  12778.           self.lastChild = node;
  12779.         } else {
  12780.           self.lastChild = self.firstChild = node;
  12781.         }
  12782.         node.parent = self;
  12783.         return node;
  12784.       };
  12785.       AstNode.prototype.insert = function (node, refNode, before) {
  12786.         if (node.parent) {
  12787.           node.remove();
  12788.         }
  12789.         var parent = refNode.parent || this;
  12790.         if (before) {
  12791.           if (refNode === parent.firstChild) {
  12792.             parent.firstChild = node;
  12793.           } else {
  12794.             refNode.prev.next = node;
  12795.           }
  12796.           node.prev = refNode.prev;
  12797.           node.next = refNode;
  12798.           refNode.prev = node;
  12799.         } else {
  12800.           if (refNode === parent.lastChild) {
  12801.             parent.lastChild = node;
  12802.           } else {
  12803.             refNode.next.prev = node;
  12804.           }
  12805.           node.next = refNode.next;
  12806.           node.prev = refNode;
  12807.           refNode.next = node;
  12808.         }
  12809.         node.parent = parent;
  12810.         return node;
  12811.       };
  12812.       AstNode.prototype.getAll = function (name) {
  12813.         var self = this;
  12814.         var collection = [];
  12815.         for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12816.           if (node.name === name) {
  12817.             collection.push(node);
  12818.           }
  12819.         }
  12820.         return collection;
  12821.       };
  12822.       AstNode.prototype.children = function () {
  12823.         var self = this;
  12824.         var collection = [];
  12825.         for (var node = self.firstChild; node; node = node.next) {
  12826.           collection.push(node);
  12827.         }
  12828.         return collection;
  12829.       };
  12830.       AstNode.prototype.empty = function () {
  12831.         var self = this;
  12832.         if (self.firstChild) {
  12833.           var nodes = [];
  12834.           for (var node = self.firstChild; node; node = walk$1(node, self)) {
  12835.             nodes.push(node);
  12836.           }
  12837.           var i = nodes.length;
  12838.           while (i--) {
  12839.             var node = nodes[i];
  12840.             node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  12841.           }
  12842.         }
  12843.         self.firstChild = self.lastChild = null;
  12844.         return self;
  12845.       };
  12846.       AstNode.prototype.isEmpty = function (elements, whitespace, predicate) {
  12847.         if (whitespace === void 0) {
  12848.           whitespace = {};
  12849.         }
  12850.         var self = this;
  12851.         var node = self.firstChild;
  12852.         if (isNonEmptyElement(self)) {
  12853.           return false;
  12854.         }
  12855.         if (node) {
  12856.           do {
  12857.             if (node.type === 1) {
  12858.               if (node.attr('data-mce-bogus')) {
  12859.                 continue;
  12860.               }
  12861.               if (elements[node.name]) {
  12862.                 return false;
  12863.               }
  12864.               if (isNonEmptyElement(node)) {
  12865.                 return false;
  12866.               }
  12867.             }
  12868.             if (node.type === 8) {
  12869.               return false;
  12870.             }
  12871.             if (node.type === 3 && !isEmptyTextNode(node)) {
  12872.               return false;
  12873.             }
  12874.             if (node.type === 3 && node.parent && whitespace[node.parent.name] && isWhitespaceText(node.value)) {
  12875.               return false;
  12876.             }
  12877.             if (predicate && predicate(node)) {
  12878.               return false;
  12879.             }
  12880.           } while (node = walk$1(node, self));
  12881.         }
  12882.         return true;
  12883.       };
  12884.       AstNode.prototype.walk = function (prev) {
  12885.         return walk$1(this, null, prev);
  12886.       };
  12887.       return AstNode;
  12888.     }();
  12889.  
  12890.     var getTemporaryNodeSelector = function (tempAttrs) {
  12891.       return (tempAttrs.length === 0 ? '' : map$3(tempAttrs, function (attr) {
  12892.         return '[' + attr + ']';
  12893.       }).join(',') + ',') + '[data-mce-bogus="all"]';
  12894.     };
  12895.     var getTemporaryNodes = function (body, tempAttrs) {
  12896.       return body.querySelectorAll(getTemporaryNodeSelector(tempAttrs));
  12897.     };
  12898.     var createCommentWalker = function (body) {
  12899.       return document.createTreeWalker(body, NodeFilter.SHOW_COMMENT, null, false);
  12900.     };
  12901.     var hasComments = function (body) {
  12902.       return createCommentWalker(body).nextNode() !== null;
  12903.     };
  12904.     var hasTemporaryNodes = function (body, tempAttrs) {
  12905.       return body.querySelector(getTemporaryNodeSelector(tempAttrs)) !== null;
  12906.     };
  12907.     var trimTemporaryNodes = function (body, tempAttrs) {
  12908.       each$k(getTemporaryNodes(body, tempAttrs), function (elm) {
  12909.         var element = SugarElement.fromDom(elm);
  12910.         if (get$6(element, 'data-mce-bogus') === 'all') {
  12911.           remove$7(element);
  12912.         } else {
  12913.           each$k(tempAttrs, function (attr) {
  12914.             if (has$1(element, attr)) {
  12915.               remove$6(element, attr);
  12916.             }
  12917.           });
  12918.         }
  12919.       });
  12920.     };
  12921.     var removeCommentsContainingZwsp = function (body) {
  12922.       var walker = createCommentWalker(body);
  12923.       var nextNode = walker.nextNode();
  12924.       while (nextNode !== null) {
  12925.         var comment = walker.currentNode;
  12926.         nextNode = walker.nextNode();
  12927.         if (isString$1(comment.nodeValue) && comment.nodeValue.indexOf(ZWSP$1) !== -1) {
  12928.           remove$7(SugarElement.fromDom(comment));
  12929.         }
  12930.       }
  12931.     };
  12932.     var deepClone = function (body) {
  12933.       return body.cloneNode(true);
  12934.     };
  12935.     var trim$1 = function (body, tempAttrs) {
  12936.       var trimmed = body;
  12937.       if (hasComments(body)) {
  12938.         trimmed = deepClone(body);
  12939.         removeCommentsContainingZwsp(trimmed);
  12940.         if (hasTemporaryNodes(trimmed, tempAttrs)) {
  12941.           trimTemporaryNodes(trimmed, tempAttrs);
  12942.         }
  12943.       } else if (hasTemporaryNodes(body, tempAttrs)) {
  12944.         trimmed = deepClone(body);
  12945.         trimTemporaryNodes(trimmed, tempAttrs);
  12946.       }
  12947.       return trimmed;
  12948.     };
  12949.  
  12950.     var trimEmptyContents = function (editor, html) {
  12951.       var blockName = getForcedRootBlock(editor);
  12952.       var emptyRegExp = new RegExp('^(<' + blockName + '[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/' + blockName + '>[\r\n]*|<br \\/>[\r\n]*)$');
  12953.       return html.replace(emptyRegExp, '');
  12954.     };
  12955.     var setupArgs$3 = function (args, format) {
  12956.       return __assign(__assign({}, args), {
  12957.         format: format,
  12958.         get: true,
  12959.         getInner: true
  12960.       });
  12961.     };
  12962.     var getContentFromBody = function (editor, args, format, body) {
  12963.       var defaultedArgs = setupArgs$3(args, format);
  12964.       var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeGetContent', defaultedArgs);
  12965.       var content;
  12966.       if (updatedArgs.format === 'raw') {
  12967.         content = Tools.trim(trim$3(trim$1(body, editor.serializer.getTempAttrs()).innerHTML));
  12968.       } else if (updatedArgs.format === 'text') {
  12969.         content = editor.dom.isEmpty(body) ? '' : trim$3(body.innerText || body.textContent);
  12970.       } else if (updatedArgs.format === 'tree') {
  12971.         content = editor.serializer.serialize(body, updatedArgs);
  12972.       } else {
  12973.         content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
  12974.       }
  12975.       if (!contains$3([
  12976.           'text',
  12977.           'tree'
  12978.         ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
  12979.         updatedArgs.content = Tools.trim(content);
  12980.       } else {
  12981.         updatedArgs.content = content;
  12982.       }
  12983.       if (updatedArgs.no_events) {
  12984.         return updatedArgs.content;
  12985.       } else {
  12986.         return editor.fire('GetContent', updatedArgs).content;
  12987.       }
  12988.     };
  12989.     var getContentInternal = function (editor, args, format) {
  12990.       return Optional.from(editor.getBody()).fold(constant(args.format === 'tree' ? new AstNode('body', 11) : ''), function (body) {
  12991.         return getContentFromBody(editor, args, format, body);
  12992.       });
  12993.     };
  12994.  
  12995.     var each$d = Tools.each;
  12996.     var ElementUtils = function (dom) {
  12997.       var compare = function (node1, node2) {
  12998.         if (node1.nodeName !== node2.nodeName) {
  12999.           return false;
  13000.         }
  13001.         var getAttribs = function (node) {
  13002.           var attribs = {};
  13003.           each$d(dom.getAttribs(node), function (attr) {
  13004.             var name = attr.nodeName.toLowerCase();
  13005.             if (name.indexOf('_') !== 0 && name !== 'style' && name.indexOf('data-') !== 0) {
  13006.               attribs[name] = dom.getAttrib(node, name);
  13007.             }
  13008.           });
  13009.           return attribs;
  13010.         };
  13011.         var compareObjects = function (obj1, obj2) {
  13012.           var value, name;
  13013.           for (name in obj1) {
  13014.             if (has$2(obj1, name)) {
  13015.               value = obj2[name];
  13016.               if (typeof value === 'undefined') {
  13017.                 return false;
  13018.               }
  13019.               if (obj1[name] !== value) {
  13020.                 return false;
  13021.               }
  13022.               delete obj2[name];
  13023.             }
  13024.           }
  13025.           for (name in obj2) {
  13026.             if (has$2(obj2, name)) {
  13027.               return false;
  13028.             }
  13029.           }
  13030.           return true;
  13031.         };
  13032.         if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  13033.           return false;
  13034.         }
  13035.         if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  13036.           return false;
  13037.         }
  13038.         return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
  13039.       };
  13040.       return { compare: compare };
  13041.     };
  13042.  
  13043.     var makeMap$1 = Tools.makeMap;
  13044.     var Writer = function (settings) {
  13045.       var html = [];
  13046.       settings = settings || {};
  13047.       var indent = settings.indent;
  13048.       var indentBefore = makeMap$1(settings.indent_before || '');
  13049.       var indentAfter = makeMap$1(settings.indent_after || '');
  13050.       var encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  13051.       var htmlOutput = settings.element_format === 'html';
  13052.       return {
  13053.         start: function (name, attrs, empty) {
  13054.           var i, l, attr, value;
  13055.           if (indent && indentBefore[name] && html.length > 0) {
  13056.             value = html[html.length - 1];
  13057.             if (value.length > 0 && value !== '\n') {
  13058.               html.push('\n');
  13059.             }
  13060.           }
  13061.           html.push('<', name);
  13062.           if (attrs) {
  13063.             for (i = 0, l = attrs.length; i < l; i++) {
  13064.               attr = attrs[i];
  13065.               html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  13066.             }
  13067.           }
  13068.           if (!empty || htmlOutput) {
  13069.             html[html.length] = '>';
  13070.           } else {
  13071.             html[html.length] = ' />';
  13072.           }
  13073.           if (empty && indent && indentAfter[name] && html.length > 0) {
  13074.             value = html[html.length - 1];
  13075.             if (value.length > 0 && value !== '\n') {
  13076.               html.push('\n');
  13077.             }
  13078.           }
  13079.         },
  13080.         end: function (name) {
  13081.           var value;
  13082.           html.push('</', name, '>');
  13083.           if (indent && indentAfter[name] && html.length > 0) {
  13084.             value = html[html.length - 1];
  13085.             if (value.length > 0 && value !== '\n') {
  13086.               html.push('\n');
  13087.             }
  13088.           }
  13089.         },
  13090.         text: function (text, raw) {
  13091.           if (text.length > 0) {
  13092.             html[html.length] = raw ? text : encode(text);
  13093.           }
  13094.         },
  13095.         cdata: function (text) {
  13096.           html.push('<![CDATA[', text, ']]>');
  13097.         },
  13098.         comment: function (text) {
  13099.           html.push('<!--', text, '-->');
  13100.         },
  13101.         pi: function (name, text) {
  13102.           if (text) {
  13103.             html.push('<?', name, ' ', encode(text), '?>');
  13104.           } else {
  13105.             html.push('<?', name, '?>');
  13106.           }
  13107.           if (indent) {
  13108.             html.push('\n');
  13109.           }
  13110.         },
  13111.         doctype: function (text) {
  13112.           html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  13113.         },
  13114.         reset: function () {
  13115.           html.length = 0;
  13116.         },
  13117.         getContent: function () {
  13118.           return html.join('').replace(/\n$/, '');
  13119.         }
  13120.       };
  13121.     };
  13122.  
  13123.     var HtmlSerializer = function (settings, schema) {
  13124.       if (schema === void 0) {
  13125.         schema = Schema();
  13126.       }
  13127.       var writer = Writer(settings);
  13128.       settings = settings || {};
  13129.       settings.validate = 'validate' in settings ? settings.validate : true;
  13130.       var serialize = function (node) {
  13131.         var validate = settings.validate;
  13132.         var handlers = {
  13133.           3: function (node) {
  13134.             writer.text(node.value, node.raw);
  13135.           },
  13136.           8: function (node) {
  13137.             writer.comment(node.value);
  13138.           },
  13139.           7: function (node) {
  13140.             writer.pi(node.name, node.value);
  13141.           },
  13142.           10: function (node) {
  13143.             writer.doctype(node.value);
  13144.           },
  13145.           4: function (node) {
  13146.             writer.cdata(node.value);
  13147.           },
  13148.           11: function (node) {
  13149.             if (node = node.firstChild) {
  13150.               do {
  13151.                 walk(node);
  13152.               } while (node = node.next);
  13153.             }
  13154.           }
  13155.         };
  13156.         writer.reset();
  13157.         var walk = function (node) {
  13158.           var handler = handlers[node.type];
  13159.           if (!handler) {
  13160.             var name_1 = node.name;
  13161.             var isEmpty = node.shortEnded;
  13162.             var attrs = node.attributes;
  13163.             if (validate && attrs && attrs.length > 1) {
  13164.               var sortedAttrs = [];
  13165.               sortedAttrs.map = {};
  13166.               var elementRule = schema.getElementRule(node.name);
  13167.               if (elementRule) {
  13168.                 for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  13169.                   var attrName = elementRule.attributesOrder[i];
  13170.                   if (attrName in attrs.map) {
  13171.                     var attrValue = attrs.map[attrName];
  13172.                     sortedAttrs.map[attrName] = attrValue;
  13173.                     sortedAttrs.push({
  13174.                       name: attrName,
  13175.                       value: attrValue
  13176.                     });
  13177.                   }
  13178.                 }
  13179.                 for (var i = 0, l = attrs.length; i < l; i++) {
  13180.                   var attrName = attrs[i].name;
  13181.                   if (!(attrName in sortedAttrs.map)) {
  13182.                     var attrValue = attrs.map[attrName];
  13183.                     sortedAttrs.map[attrName] = attrValue;
  13184.                     sortedAttrs.push({
  13185.                       name: attrName,
  13186.                       value: attrValue
  13187.                     });
  13188.                   }
  13189.                 }
  13190.                 attrs = sortedAttrs;
  13191.               }
  13192.             }
  13193.             writer.start(node.name, attrs, isEmpty);
  13194.             if (!isEmpty) {
  13195.               if (node = node.firstChild) {
  13196.                 do {
  13197.                   walk(node);
  13198.                 } while (node = node.next);
  13199.               }
  13200.               writer.end(name_1);
  13201.             }
  13202.           } else {
  13203.             handler(node);
  13204.           }
  13205.         };
  13206.         if (node.type === 1 && !settings.inner) {
  13207.           walk(node);
  13208.         } else {
  13209.           handlers[11](node);
  13210.         }
  13211.         return writer.getContent();
  13212.       };
  13213.       return { serialize: serialize };
  13214.     };
  13215.  
  13216.     var nonInheritableStyles = new Set();
  13217.     (function () {
  13218.       var nonInheritableStylesArr = [
  13219.         'margin',
  13220.         'margin-left',
  13221.         'margin-right',
  13222.         'margin-top',
  13223.         'margin-bottom',
  13224.         'padding',
  13225.         'padding-left',
  13226.         'padding-right',
  13227.         'padding-top',
  13228.         'padding-bottom',
  13229.         'border',
  13230.         'border-width',
  13231.         'border-style',
  13232.         'border-color',
  13233.         'background',
  13234.         'background-attachment',
  13235.         'background-clip',
  13236.         'background-color',
  13237.         'background-image',
  13238.         'background-origin',
  13239.         'background-position',
  13240.         'background-repeat',
  13241.         'background-size',
  13242.         'float',
  13243.         'position',
  13244.         'left',
  13245.         'right',
  13246.         'top',
  13247.         'bottom',
  13248.         'z-index',
  13249.         'display',
  13250.         'transform',
  13251.         'width',
  13252.         'max-width',
  13253.         'min-width',
  13254.         'height',
  13255.         'max-height',
  13256.         'min-height',
  13257.         'overflow',
  13258.         'overflow-x',
  13259.         'overflow-y',
  13260.         'text-overflow',
  13261.         'vertical-align',
  13262.         'transition',
  13263.         'transition-delay',
  13264.         'transition-duration',
  13265.         'transition-property',
  13266.         'transition-timing-function'
  13267.       ];
  13268.       each$k(nonInheritableStylesArr, function (style) {
  13269.         nonInheritableStyles.add(style);
  13270.       });
  13271.     }());
  13272.     var shorthandStyleProps = [
  13273.       'font',
  13274.       'text-decoration',
  13275.       'text-emphasis'
  13276.     ];
  13277.     var getStyleProps = function (dom, node) {
  13278.       return keys(dom.parseStyle(dom.getAttrib(node, 'style')));
  13279.     };
  13280.     var isNonInheritableStyle = function (style) {
  13281.       return nonInheritableStyles.has(style);
  13282.     };
  13283.     var hasInheritableStyles = function (dom, node) {
  13284.       return forall(getStyleProps(dom, node), function (style) {
  13285.         return !isNonInheritableStyle(style);
  13286.       });
  13287.     };
  13288.     var getLonghandStyleProps = function (styles) {
  13289.       return filter$4(styles, function (style) {
  13290.         return exists(shorthandStyleProps, function (prop) {
  13291.           return startsWith(style, prop);
  13292.         });
  13293.       });
  13294.     };
  13295.     var hasStyleConflict = function (dom, node, parentNode) {
  13296.       var nodeStyleProps = getStyleProps(dom, node);
  13297.       var parentNodeStyleProps = getStyleProps(dom, parentNode);
  13298.       var valueMismatch = function (prop) {
  13299.         var nodeValue = dom.getStyle(node, prop);
  13300.         var parentValue = dom.getStyle(parentNode, prop);
  13301.         return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
  13302.       };
  13303.       return exists(nodeStyleProps, function (nodeStyleProp) {
  13304.         var propExists = function (props) {
  13305.           return exists(props, function (prop) {
  13306.             return prop === nodeStyleProp;
  13307.           });
  13308.         };
  13309.         if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
  13310.           var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
  13311.           return exists(longhandProps, valueMismatch);
  13312.         } else {
  13313.           return valueMismatch(nodeStyleProp);
  13314.         }
  13315.       });
  13316.     };
  13317.  
  13318.     var isChar = function (forward, predicate, pos) {
  13319.       return Optional.from(pos.container()).filter(isText$7).exists(function (text) {
  13320.         var delta = forward ? 0 : -1;
  13321.         return predicate(text.data.charAt(pos.offset() + delta));
  13322.       });
  13323.     };
  13324.     var isBeforeSpace = curry(isChar, true, isWhiteSpace);
  13325.     var isAfterSpace = curry(isChar, false, isWhiteSpace);
  13326.     var isEmptyText = function (pos) {
  13327.       var container = pos.container();
  13328.       return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
  13329.     };
  13330.     var matchesElementPosition = function (before, predicate) {
  13331.       return function (pos) {
  13332.         return Optional.from(getChildNodeAtRelativeOffset(before ? 0 : -1, pos)).filter(predicate).isSome();
  13333.       };
  13334.     };
  13335.     var isImageBlock = function (node) {
  13336.       return isImg(node) && get$5(SugarElement.fromDom(node), 'display') === 'block';
  13337.     };
  13338.     var isCefNode = function (node) {
  13339.       return isContentEditableFalse$b(node) && !isBogusAll$1(node);
  13340.     };
  13341.     var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
  13342.     var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
  13343.     var isBeforeMedia = matchesElementPosition(true, isMedia$2);
  13344.     var isAfterMedia = matchesElementPosition(false, isMedia$2);
  13345.     var isBeforeTable = matchesElementPosition(true, isTable$3);
  13346.     var isAfterTable = matchesElementPosition(false, isTable$3);
  13347.     var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
  13348.     var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
  13349.  
  13350.     var getLastChildren = function (elm) {
  13351.       var children = [];
  13352.       var rawNode = elm.dom;
  13353.       while (rawNode) {
  13354.         children.push(SugarElement.fromDom(rawNode));
  13355.         rawNode = rawNode.lastChild;
  13356.       }
  13357.       return children;
  13358.     };
  13359.     var removeTrailingBr = function (elm) {
  13360.       var allBrs = descendants(elm, 'br');
  13361.       var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
  13362.       if (allBrs.length === brs.length) {
  13363.         each$k(brs, remove$7);
  13364.       }
  13365.     };
  13366.     var fillWithPaddingBr = function (elm) {
  13367.       empty(elm);
  13368.       append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
  13369.     };
  13370.     var trimBlockTrailingBr = function (elm) {
  13371.       lastChild(elm).each(function (lastChild) {
  13372.         prevSibling(lastChild).each(function (lastChildPrevSibling) {
  13373.           if (isBlock$2(elm) && isBr$4(lastChild) && isBlock$2(lastChildPrevSibling)) {
  13374.             remove$7(lastChild);
  13375.           }
  13376.         });
  13377.       });
  13378.     };
  13379.  
  13380.     var dropLast = function (xs) {
  13381.       return xs.slice(0, -1);
  13382.     };
  13383.     var parentsUntil = function (start, root, predicate) {
  13384.       if (contains$1(root, start)) {
  13385.         return dropLast(parents$1(start, function (elm) {
  13386.           return predicate(elm) || eq(elm, root);
  13387.         }));
  13388.       } else {
  13389.         return [];
  13390.       }
  13391.     };
  13392.     var parents = function (start, root) {
  13393.       return parentsUntil(start, root, never);
  13394.     };
  13395.     var parentsAndSelf = function (start, root) {
  13396.       return [start].concat(parents(start, root));
  13397.     };
  13398.  
  13399.     var navigateIgnoreEmptyTextNodes = function (forward, root, from) {
  13400.       return navigateIgnore(forward, root, from, isEmptyText);
  13401.     };
  13402.     var getClosestBlock$1 = function (root, pos) {
  13403.       return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13404.     };
  13405.     var isAtBeforeAfterBlockBoundary = function (forward, root, pos) {
  13406.       return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13407.         return getClosestBlock$1(root, pos).fold(function () {
  13408.           return isInSameBlock(newPos, pos, root.dom) === false;
  13409.         }, function (fromBlock) {
  13410.           return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
  13411.         });
  13412.       });
  13413.     };
  13414.     var isAtBlockBoundary = function (forward, root, pos) {
  13415.       return getClosestBlock$1(root, pos).fold(function () {
  13416.         return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function (newPos) {
  13417.           return isInSameBlock(newPos, pos, root.dom) === false;
  13418.         });
  13419.       }, function (parent) {
  13420.         return navigateIgnoreEmptyTextNodes(forward, parent.dom, pos).isNone();
  13421.       });
  13422.     };
  13423.     var isAtStartOfBlock = curry(isAtBlockBoundary, false);
  13424.     var isAtEndOfBlock = curry(isAtBlockBoundary, true);
  13425.     var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
  13426.     var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
  13427.  
  13428.     var isBr = function (pos) {
  13429.       return getElementFromPosition(pos).exists(isBr$4);
  13430.     };
  13431.     var findBr = function (forward, root, pos) {
  13432.       var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13433.       var scope = head(parentBlocks).getOr(root);
  13434.       return fromPosition(forward, scope.dom, pos).filter(isBr);
  13435.     };
  13436.     var isBeforeBr$1 = function (root, pos) {
  13437.       return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
  13438.     };
  13439.     var isAfterBr = function (root, pos) {
  13440.       return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
  13441.     };
  13442.     var findPreviousBr = curry(findBr, false);
  13443.     var findNextBr = curry(findBr, true);
  13444.  
  13445.     var isInMiddleOfText = function (pos) {
  13446.       return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
  13447.     };
  13448.     var getClosestBlock = function (root, pos) {
  13449.       var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
  13450.       return head(parentBlocks).getOr(root);
  13451.     };
  13452.     var hasSpaceBefore = function (root, pos) {
  13453.       if (isInMiddleOfText(pos)) {
  13454.         return isAfterSpace(pos);
  13455.       } else {
  13456.         return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
  13457.       }
  13458.     };
  13459.     var hasSpaceAfter = function (root, pos) {
  13460.       if (isInMiddleOfText(pos)) {
  13461.         return isBeforeSpace(pos);
  13462.       } else {
  13463.         return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
  13464.       }
  13465.     };
  13466.     var isPreValue = function (value) {
  13467.       return contains$3([
  13468.         'pre',
  13469.         'pre-wrap'
  13470.       ], value);
  13471.     };
  13472.     var isInPre = function (pos) {
  13473.       return getElementFromPosition(pos).bind(function (elm) {
  13474.         return closest$3(elm, isElement$6);
  13475.       }).exists(function (elm) {
  13476.         return isPreValue(get$5(elm, 'white-space'));
  13477.       });
  13478.     };
  13479.     var isAtBeginningOfBody = function (root, pos) {
  13480.       return prevPosition(root.dom, pos).isNone();
  13481.     };
  13482.     var isAtEndOfBody = function (root, pos) {
  13483.       return nextPosition(root.dom, pos).isNone();
  13484.     };
  13485.     var isAtLineBoundary = function (root, pos) {
  13486.       return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
  13487.     };
  13488.     var needsToHaveNbsp = function (root, pos) {
  13489.       if (isInPre(pos)) {
  13490.         return false;
  13491.       } else {
  13492.         return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
  13493.       }
  13494.     };
  13495.     var needsToBeNbspLeft = function (root, pos) {
  13496.       if (isInPre(pos)) {
  13497.         return false;
  13498.       } else {
  13499.         return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
  13500.       }
  13501.     };
  13502.     var leanRight = function (pos) {
  13503.       var container = pos.container();
  13504.       var offset = pos.offset();
  13505.       if (isText$7(container) && offset < container.data.length) {
  13506.         return CaretPosition(container, offset + 1);
  13507.       } else {
  13508.         return pos;
  13509.       }
  13510.     };
  13511.     var needsToBeNbspRight = function (root, pos) {
  13512.       if (isInPre(pos)) {
  13513.         return false;
  13514.       } else {
  13515.         return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
  13516.       }
  13517.     };
  13518.     var needsToBeNbsp = function (root, pos) {
  13519.       return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
  13520.     };
  13521.     var isNbspAt = function (text, offset) {
  13522.       return isNbsp(text.charAt(offset));
  13523.     };
  13524.     var hasNbsp = function (pos) {
  13525.       var container = pos.container();
  13526.       return isText$7(container) && contains$2(container.data, nbsp);
  13527.     };
  13528.     var normalizeNbspMiddle = function (text) {
  13529.       var chars = text.split('');
  13530.       return map$3(chars, function (chr, i) {
  13531.         if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
  13532.           return ' ';
  13533.         } else {
  13534.           return chr;
  13535.         }
  13536.       }).join('');
  13537.     };
  13538.     var normalizeNbspAtStart = function (root, node) {
  13539.       var text = node.data;
  13540.       var firstPos = CaretPosition(node, 0);
  13541.       if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
  13542.         node.data = ' ' + text.slice(1);
  13543.         return true;
  13544.       } else {
  13545.         return false;
  13546.       }
  13547.     };
  13548.     var normalizeNbspInMiddleOfTextNode = function (node) {
  13549.       var text = node.data;
  13550.       var newText = normalizeNbspMiddle(text);
  13551.       if (newText !== text) {
  13552.         node.data = newText;
  13553.         return true;
  13554.       } else {
  13555.         return false;
  13556.       }
  13557.     };
  13558.     var normalizeNbspAtEnd = function (root, node) {
  13559.       var text = node.data;
  13560.       var lastPos = CaretPosition(node, text.length - 1);
  13561.       if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
  13562.         node.data = text.slice(0, -1) + ' ';
  13563.         return true;
  13564.       } else {
  13565.         return false;
  13566.       }
  13567.     };
  13568.     var normalizeNbsps = function (root, pos) {
  13569.       return Optional.some(pos).filter(hasNbsp).bind(function (pos) {
  13570.         var container = pos.container();
  13571.         var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
  13572.         return normalized ? Optional.some(pos) : Optional.none();
  13573.       });
  13574.     };
  13575.     var normalizeNbspsInEditor = function (editor) {
  13576.       var root = SugarElement.fromDom(editor.getBody());
  13577.       if (editor.selection.isCollapsed()) {
  13578.         normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function (pos) {
  13579.           editor.selection.setRng(pos.toRange());
  13580.         });
  13581.       }
  13582.     };
  13583.  
  13584.     var normalizeContent = function (content, isStartOfContent, isEndOfContent) {
  13585.       var result = foldl(content, function (acc, c) {
  13586.         if (isWhiteSpace(c) || isNbsp(c)) {
  13587.           if (acc.previousCharIsSpace || acc.str === '' && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
  13588.             return {
  13589.               previousCharIsSpace: false,
  13590.               str: acc.str + nbsp
  13591.             };
  13592.           } else {
  13593.             return {
  13594.               previousCharIsSpace: true,
  13595.               str: acc.str + ' '
  13596.             };
  13597.           }
  13598.         } else {
  13599.           return {
  13600.             previousCharIsSpace: false,
  13601.             str: acc.str + c
  13602.           };
  13603.         }
  13604.       }, {
  13605.         previousCharIsSpace: false,
  13606.         str: ''
  13607.       });
  13608.       return result.str;
  13609.     };
  13610.     var normalize$1 = function (node, offset, count) {
  13611.       if (count === 0) {
  13612.         return;
  13613.       }
  13614.       var elm = SugarElement.fromDom(node);
  13615.       var root = ancestor$3(elm, isBlock$2).getOr(elm);
  13616.       var whitespace = node.data.slice(offset, offset + count);
  13617.       var isEndOfContent = offset + count >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
  13618.       var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
  13619.       node.replaceData(offset, count, normalizeContent(whitespace, isStartOfContent, isEndOfContent));
  13620.     };
  13621.     var normalizeWhitespaceAfter = function (node, offset) {
  13622.       var content = node.data.slice(offset);
  13623.       var whitespaceCount = content.length - lTrim(content).length;
  13624.       normalize$1(node, offset, whitespaceCount);
  13625.     };
  13626.     var normalizeWhitespaceBefore = function (node, offset) {
  13627.       var content = node.data.slice(0, offset);
  13628.       var whitespaceCount = content.length - rTrim(content).length;
  13629.       normalize$1(node, offset - whitespaceCount, whitespaceCount);
  13630.     };
  13631.     var mergeTextNodes = function (prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
  13632.       if (mergeToPrev === void 0) {
  13633.         mergeToPrev = true;
  13634.       }
  13635.       var whitespaceOffset = rTrim(prevNode.data).length;
  13636.       var newNode = mergeToPrev ? prevNode : nextNode;
  13637.       var removeNode = mergeToPrev ? nextNode : prevNode;
  13638.       if (mergeToPrev) {
  13639.         newNode.appendData(removeNode.data);
  13640.       } else {
  13641.         newNode.insertData(0, removeNode.data);
  13642.       }
  13643.       remove$7(SugarElement.fromDom(removeNode));
  13644.       if (normalizeWhitespace) {
  13645.         normalizeWhitespaceAfter(newNode, whitespaceOffset);
  13646.       }
  13647.       return newNode;
  13648.     };
  13649.  
  13650.     var needsReposition = function (pos, elm) {
  13651.       var container = pos.container();
  13652.       var offset = pos.offset();
  13653.       return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
  13654.     };
  13655.     var reposition = function (elm, pos) {
  13656.       return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
  13657.     };
  13658.     var beforeOrStartOf = function (node) {
  13659.       return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
  13660.     };
  13661.     var afterOrEndOf = function (node) {
  13662.       return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
  13663.     };
  13664.     var getPreviousSiblingCaretPosition = function (elm) {
  13665.       if (isCaretCandidate$3(elm.previousSibling)) {
  13666.         return Optional.some(afterOrEndOf(elm.previousSibling));
  13667.       } else {
  13668.         return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
  13669.       }
  13670.     };
  13671.     var getNextSiblingCaretPosition = function (elm) {
  13672.       if (isCaretCandidate$3(elm.nextSibling)) {
  13673.         return Optional.some(beforeOrStartOf(elm.nextSibling));
  13674.       } else {
  13675.         return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
  13676.       }
  13677.     };
  13678.     var findCaretPositionBackwardsFromElm = function (rootElement, elm) {
  13679.       var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
  13680.       return prevPosition(rootElement, startPosition).fold(function () {
  13681.         return nextPosition(rootElement, CaretPosition.after(elm));
  13682.       }, Optional.some);
  13683.     };
  13684.     var findCaretPositionForwardsFromElm = function (rootElement, elm) {
  13685.       return nextPosition(rootElement, CaretPosition.after(elm)).fold(function () {
  13686.         return prevPosition(rootElement, CaretPosition.before(elm));
  13687.       }, Optional.some);
  13688.     };
  13689.     var findCaretPositionBackwards = function (rootElement, elm) {
  13690.       return getPreviousSiblingCaretPosition(elm).orThunk(function () {
  13691.         return getNextSiblingCaretPosition(elm);
  13692.       }).orThunk(function () {
  13693.         return findCaretPositionBackwardsFromElm(rootElement, elm);
  13694.       });
  13695.     };
  13696.     var findCaretPositionForward = function (rootElement, elm) {
  13697.       return getNextSiblingCaretPosition(elm).orThunk(function () {
  13698.         return getPreviousSiblingCaretPosition(elm);
  13699.       }).orThunk(function () {
  13700.         return findCaretPositionForwardsFromElm(rootElement, elm);
  13701.       });
  13702.     };
  13703.     var findCaretPosition = function (forward, rootElement, elm) {
  13704.       return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
  13705.     };
  13706.     var findCaretPosOutsideElmAfterDelete = function (forward, rootElement, elm) {
  13707.       return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
  13708.     };
  13709.     var setSelection$1 = function (editor, forward, pos) {
  13710.       pos.fold(function () {
  13711.         editor.focus();
  13712.       }, function (pos) {
  13713.         editor.selection.setRng(pos.toRange(), forward);
  13714.       });
  13715.     };
  13716.     var eqRawNode = function (rawNode) {
  13717.       return function (elm) {
  13718.         return elm.dom === rawNode;
  13719.       };
  13720.     };
  13721.     var isBlock = function (editor, elm) {
  13722.       return elm && has$2(editor.schema.getBlockElements(), name(elm));
  13723.     };
  13724.     var paddEmptyBlock = function (elm) {
  13725.       if (isEmpty$2(elm)) {
  13726.         var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
  13727.         empty(elm);
  13728.         append$1(elm, br);
  13729.         return Optional.some(CaretPosition.before(br.dom));
  13730.       } else {
  13731.         return Optional.none();
  13732.       }
  13733.     };
  13734.     var deleteNormalized = function (elm, afterDeletePosOpt, normalizeWhitespace) {
  13735.       var prevTextOpt = prevSibling(elm).filter(isText$8);
  13736.       var nextTextOpt = nextSibling(elm).filter(isText$8);
  13737.       remove$7(elm);
  13738.       return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function (prev, next, pos) {
  13739.         var prevNode = prev.dom, nextNode = next.dom;
  13740.         var offset = prevNode.data.length;
  13741.         mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
  13742.         return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
  13743.       }).orThunk(function () {
  13744.         if (normalizeWhitespace) {
  13745.           prevTextOpt.each(function (elm) {
  13746.             return normalizeWhitespaceBefore(elm.dom, elm.dom.length);
  13747.           });
  13748.           nextTextOpt.each(function (elm) {
  13749.             return normalizeWhitespaceAfter(elm.dom, 0);
  13750.           });
  13751.         }
  13752.         return afterDeletePosOpt;
  13753.       });
  13754.     };
  13755.     var isInlineElement = function (editor, element) {
  13756.       return has$2(editor.schema.getTextInlineElements(), name(element));
  13757.     };
  13758.     var deleteElement$2 = function (editor, forward, elm, moveCaret) {
  13759.       if (moveCaret === void 0) {
  13760.         moveCaret = true;
  13761.       }
  13762.       var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
  13763.       var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
  13764.       var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
  13765.       if (editor.dom.isEmpty(editor.getBody())) {
  13766.         editor.setContent('');
  13767.         editor.selection.setCursorLocation();
  13768.       } else {
  13769.         parentBlock.bind(paddEmptyBlock).fold(function () {
  13770.           if (moveCaret) {
  13771.             setSelection$1(editor, forward, normalizedAfterDeletePos);
  13772.           }
  13773.         }, function (paddPos) {
  13774.           if (moveCaret) {
  13775.             setSelection$1(editor, forward, Optional.some(paddPos));
  13776.           }
  13777.         });
  13778.       }
  13779.     };
  13780.  
  13781.     var isRootFromElement = function (root) {
  13782.       return function (cur) {
  13783.         return eq(root, cur);
  13784.       };
  13785.     };
  13786.     var getTableCells = function (table) {
  13787.       return descendants(table, 'td,th');
  13788.     };
  13789.     var getTableDetailsFromRange = function (rng, isRoot) {
  13790.       var getTable = function (node) {
  13791.         return getClosestTable(SugarElement.fromDom(node), isRoot);
  13792.       };
  13793.       var startTable = getTable(rng.startContainer);
  13794.       var endTable = getTable(rng.endContainer);
  13795.       var isStartInTable = startTable.isSome();
  13796.       var isEndInTable = endTable.isSome();
  13797.       var isSameTable = lift2(startTable, endTable, eq).getOr(false);
  13798.       var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
  13799.       return {
  13800.         startTable: startTable,
  13801.         endTable: endTable,
  13802.         isStartInTable: isStartInTable,
  13803.         isEndInTable: isEndInTable,
  13804.         isSameTable: isSameTable,
  13805.         isMultiTable: isMultiTable
  13806.       };
  13807.     };
  13808.  
  13809.     var tableCellRng = function (start, end) {
  13810.       return {
  13811.         start: start,
  13812.         end: end
  13813.       };
  13814.     };
  13815.     var tableSelection = function (rng, table, cells) {
  13816.       return {
  13817.         rng: rng,
  13818.         table: table,
  13819.         cells: cells
  13820.       };
  13821.     };
  13822.     var deleteAction = Adt.generate([
  13823.       {
  13824.         singleCellTable: [
  13825.           'rng',
  13826.           'cell'
  13827.         ]
  13828.       },
  13829.       { fullTable: ['table'] },
  13830.       {
  13831.         partialTable: [
  13832.           'cells',
  13833.           'outsideDetails'
  13834.         ]
  13835.       },
  13836.       {
  13837.         multiTable: [
  13838.           'startTableCells',
  13839.           'endTableCells',
  13840.           'betweenRng'
  13841.         ]
  13842.       }
  13843.     ]);
  13844.     var getClosestCell$1 = function (container, isRoot) {
  13845.       return closest$2(SugarElement.fromDom(container), 'td,th', isRoot);
  13846.     };
  13847.     var isExpandedCellRng = function (cellRng) {
  13848.       return !eq(cellRng.start, cellRng.end);
  13849.     };
  13850.     var getTableFromCellRng = function (cellRng, isRoot) {
  13851.       return getClosestTable(cellRng.start, isRoot).bind(function (startParentTable) {
  13852.         return getClosestTable(cellRng.end, isRoot).bind(function (endParentTable) {
  13853.           return someIf(eq(startParentTable, endParentTable), startParentTable);
  13854.         });
  13855.       });
  13856.     };
  13857.     var isSingleCellTable = function (cellRng, isRoot) {
  13858.       return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function (table) {
  13859.         var rows = table.dom.rows;
  13860.         return rows.length === 1 && rows[0].cells.length === 1;
  13861.       });
  13862.     };
  13863.     var getCellRng = function (rng, isRoot) {
  13864.       var startCell = getClosestCell$1(rng.startContainer, isRoot);
  13865.       var endCell = getClosestCell$1(rng.endContainer, isRoot);
  13866.       return lift2(startCell, endCell, tableCellRng);
  13867.     };
  13868.     var getCellRangeFromStartTable = function (isRoot) {
  13869.       return function (startCell) {
  13870.         return getClosestTable(startCell, isRoot).bind(function (table) {
  13871.           return last$2(getTableCells(table)).map(function (endCell) {
  13872.             return tableCellRng(startCell, endCell);
  13873.           });
  13874.         });
  13875.       };
  13876.     };
  13877.     var getCellRangeFromEndTable = function (isRoot) {
  13878.       return function (endCell) {
  13879.         return getClosestTable(endCell, isRoot).bind(function (table) {
  13880.           return head(getTableCells(table)).map(function (startCell) {
  13881.             return tableCellRng(startCell, endCell);
  13882.           });
  13883.         });
  13884.       };
  13885.     };
  13886.     var getTableSelectionFromCellRng = function (isRoot) {
  13887.       return function (cellRng) {
  13888.         return getTableFromCellRng(cellRng, isRoot).map(function (table) {
  13889.           return tableSelection(cellRng, table, getTableCells(table));
  13890.         });
  13891.       };
  13892.     };
  13893.     var getTableSelections = function (cellRng, selectionDetails, rng, isRoot) {
  13894.       if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
  13895.         return Optional.none();
  13896.       } else if (selectionDetails.isSameTable) {
  13897.         var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
  13898.         return Optional.some({
  13899.           start: sameTableSelection,
  13900.           end: sameTableSelection
  13901.         });
  13902.       } else {
  13903.         var startCell = getClosestCell$1(rng.startContainer, isRoot);
  13904.         var endCell = getClosestCell$1(rng.endContainer, isRoot);
  13905.         var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  13906.         var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
  13907.         return Optional.some({
  13908.           start: startTableSelection,
  13909.           end: endTableSelection
  13910.         });
  13911.       }
  13912.     };
  13913.     var getCellIndex = function (cells, cell) {
  13914.       return findIndex$2(cells, function (x) {
  13915.         return eq(x, cell);
  13916.       });
  13917.     };
  13918.     var getSelectedCells = function (tableSelection) {
  13919.       return lift2(getCellIndex(tableSelection.cells, tableSelection.rng.start), getCellIndex(tableSelection.cells, tableSelection.rng.end), function (startIndex, endIndex) {
  13920.         return tableSelection.cells.slice(startIndex, endIndex + 1);
  13921.       });
  13922.     };
  13923.     var isSingleCellTableContentSelected = function (optCellRng, rng, isRoot) {
  13924.       return optCellRng.exists(function (cellRng) {
  13925.         return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
  13926.       });
  13927.     };
  13928.     var unselectCells = function (rng, selectionDetails) {
  13929.       var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
  13930.       var otherContentRng = rng.cloneRange();
  13931.       startTable.each(function (table) {
  13932.         return otherContentRng.setStartAfter(table.dom);
  13933.       });
  13934.       endTable.each(function (table) {
  13935.         return otherContentRng.setEndBefore(table.dom);
  13936.       });
  13937.       return otherContentRng;
  13938.     };
  13939.     var handleSingleTable = function (cellRng, selectionDetails, rng, isRoot) {
  13940.       return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  13941.         var start = _a.start, end = _a.end;
  13942.         return start.or(end);
  13943.       }).bind(function (tableSelection) {
  13944.         var isSameTable = selectionDetails.isSameTable;
  13945.         var selectedCells = getSelectedCells(tableSelection).getOr([]);
  13946.         if (isSameTable && tableSelection.cells.length === selectedCells.length) {
  13947.           return Optional.some(deleteAction.fullTable(tableSelection.table));
  13948.         } else if (selectedCells.length > 0) {
  13949.           if (isSameTable) {
  13950.             return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
  13951.           } else {
  13952.             var otherContentRng = unselectCells(rng, selectionDetails);
  13953.             return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
  13954.           }
  13955.         } else {
  13956.           return Optional.none();
  13957.         }
  13958.       });
  13959.     };
  13960.     var handleMultiTable = function (cellRng, selectionDetails, rng, isRoot) {
  13961.       return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function (_a) {
  13962.         var start = _a.start, end = _a.end;
  13963.         var startTableSelectedCells = start.bind(getSelectedCells).getOr([]);
  13964.         var endTableSelectedCells = end.bind(getSelectedCells).getOr([]);
  13965.         if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
  13966.           var otherContentRng = unselectCells(rng, selectionDetails);
  13967.           return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
  13968.         } else {
  13969.           return Optional.none();
  13970.         }
  13971.       });
  13972.     };
  13973.     var getActionFromRange = function (root, rng) {
  13974.       var isRoot = isRootFromElement(root);
  13975.       var optCellRng = getCellRng(rng, isRoot);
  13976.       var selectionDetails = getTableDetailsFromRange(rng, isRoot);
  13977.       if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
  13978.         return optCellRng.map(function (cellRng) {
  13979.           return deleteAction.singleCellTable(rng, cellRng.start);
  13980.         });
  13981.       } else if (selectionDetails.isMultiTable) {
  13982.         return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
  13983.       } else {
  13984.         return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
  13985.       }
  13986.     };
  13987.  
  13988.     var freefallRtl = function (root) {
  13989.       var child = isComment$1(root) ? prevSibling(root) : lastChild(root);
  13990.       return child.bind(freefallRtl).orThunk(function () {
  13991.         return Optional.some(root);
  13992.       });
  13993.     };
  13994.     var cleanCells = function (cells) {
  13995.       return each$k(cells, function (cell) {
  13996.         remove$6(cell, 'contenteditable');
  13997.         fillWithPaddingBr(cell);
  13998.       });
  13999.     };
  14000.     var getOutsideBlock = function (editor, container) {
  14001.       return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
  14002.     };
  14003.     var handleEmptyBlock = function (editor, startInTable, emptyBlock) {
  14004.       emptyBlock.each(function (block) {
  14005.         if (startInTable) {
  14006.           remove$7(block);
  14007.         } else {
  14008.           fillWithPaddingBr(block);
  14009.           editor.selection.setCursorLocation(block.dom, 0);
  14010.         }
  14011.       });
  14012.     };
  14013.     var deleteContentInsideCell = function (editor, cell, rng, isFirstCellInSelection) {
  14014.       var insideTableRng = rng.cloneRange();
  14015.       if (isFirstCellInSelection) {
  14016.         insideTableRng.setStart(rng.startContainer, rng.startOffset);
  14017.         insideTableRng.setEndAfter(cell.dom.lastChild);
  14018.       } else {
  14019.         insideTableRng.setStartBefore(cell.dom.firstChild);
  14020.         insideTableRng.setEnd(rng.endContainer, rng.endOffset);
  14021.       }
  14022.       deleteCellContents(editor, insideTableRng, cell, false);
  14023.     };
  14024.     var collapseAndRestoreCellSelection = function (editor) {
  14025.       var selectedCells = getCellsFromEditor(editor);
  14026.       var selectedNode = SugarElement.fromDom(editor.selection.getNode());
  14027.       if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
  14028.         editor.selection.setCursorLocation(selectedNode.dom, 0);
  14029.       } else {
  14030.         editor.selection.collapse(true);
  14031.       }
  14032.       if (selectedCells.length > 1 && exists(selectedCells, function (cell) {
  14033.           return eq(cell, selectedNode);
  14034.         })) {
  14035.         set$1(selectedNode, 'data-mce-selected', '1');
  14036.       }
  14037.     };
  14038.     var emptySingleTableCells = function (editor, cells, outsideDetails) {
  14039.       var editorRng = editor.selection.getRng();
  14040.       var cellsToClean = outsideDetails.bind(function (_a) {
  14041.         var rng = _a.rng, isStartInTable = _a.isStartInTable;
  14042.         var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
  14043.         rng.deleteContents();
  14044.         handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
  14045.         var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
  14046.         deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
  14047.         if (!isEmpty$2(endPointCell)) {
  14048.           return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
  14049.         } else {
  14050.           return Optional.none();
  14051.         }
  14052.       }).getOr(cells);
  14053.       cleanCells(cellsToClean);
  14054.       collapseAndRestoreCellSelection(editor);
  14055.       return true;
  14056.     };
  14057.     var emptyMultiTableCells = function (editor, startTableCells, endTableCells, betweenRng) {
  14058.       var rng = editor.selection.getRng();
  14059.       var startCell = startTableCells[0];
  14060.       var endCell = endTableCells[endTableCells.length - 1];
  14061.       deleteContentInsideCell(editor, startCell, rng, true);
  14062.       deleteContentInsideCell(editor, endCell, rng, false);
  14063.       var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
  14064.       var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
  14065.       cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
  14066.       betweenRng.deleteContents();
  14067.       collapseAndRestoreCellSelection(editor);
  14068.       return true;
  14069.     };
  14070.     var deleteCellContents = function (editor, rng, cell, moveSelection) {
  14071.       if (moveSelection === void 0) {
  14072.         moveSelection = true;
  14073.       }
  14074.       rng.deleteContents();
  14075.       var lastNode = freefallRtl(cell).getOr(cell);
  14076.       var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
  14077.       if (isEmpty$2(lastBlock)) {
  14078.         fillWithPaddingBr(lastBlock);
  14079.         if (moveSelection) {
  14080.           editor.selection.setCursorLocation(lastBlock.dom, 0);
  14081.         }
  14082.       }
  14083.       if (!eq(cell, lastBlock)) {
  14084.         var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
  14085.         each$k(additionalCleanupNodes.concat(children(cell)), function (node) {
  14086.           if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
  14087.             remove$7(node);
  14088.           }
  14089.         });
  14090.       }
  14091.       return true;
  14092.     };
  14093.     var deleteTableElement = function (editor, table) {
  14094.       deleteElement$2(editor, false, table);
  14095.       return true;
  14096.     };
  14097.     var deleteCellRange = function (editor, rootElm, rng) {
  14098.       return getActionFromRange(rootElm, rng).map(function (action) {
  14099.         return action.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
  14100.       });
  14101.     };
  14102.     var deleteCaptionRange = function (editor, caption) {
  14103.       return emptyElement(editor, caption);
  14104.     };
  14105.     var deleteTableRange = function (editor, rootElm, rng, startElm) {
  14106.       return getParentCaption(rootElm, startElm).fold(function () {
  14107.         return deleteCellRange(editor, rootElm, rng);
  14108.       }, function (caption) {
  14109.         return deleteCaptionRange(editor, caption);
  14110.       }).getOr(false);
  14111.     };
  14112.     var deleteRange$2 = function (editor, startElm, selectedCells) {
  14113.       var rootNode = SugarElement.fromDom(editor.getBody());
  14114.       var rng = editor.selection.getRng();
  14115.       return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
  14116.     };
  14117.     var getParentCell = function (rootElm, elm) {
  14118.       return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
  14119.     };
  14120.     var getParentCaption = function (rootElm, elm) {
  14121.       return find$3(parentsAndSelf(elm, rootElm), isTag('caption'));
  14122.     };
  14123.     var deleteBetweenCells = function (editor, rootElm, forward, fromCell, from) {
  14124.       return navigate(forward, editor.getBody(), from).bind(function (to) {
  14125.         return getParentCell(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCell) {
  14126.           return eq(toCell, fromCell) === false;
  14127.         });
  14128.       });
  14129.     };
  14130.     var emptyElement = function (editor, elm) {
  14131.       fillWithPaddingBr(elm);
  14132.       editor.selection.setCursorLocation(elm.dom, 0);
  14133.       return Optional.some(true);
  14134.     };
  14135.     var isDeleteOfLastCharPos = function (fromCaption, forward, from, to) {
  14136.       return firstPositionIn(fromCaption.dom).bind(function (first) {
  14137.         return lastPositionIn(fromCaption.dom).map(function (last) {
  14138.           return forward ? from.isEqual(first) && to.isEqual(last) : from.isEqual(last) && to.isEqual(first);
  14139.         });
  14140.       }).getOr(true);
  14141.     };
  14142.     var emptyCaretCaption = function (editor, elm) {
  14143.       return emptyElement(editor, elm);
  14144.     };
  14145.     var validateCaretCaption = function (rootElm, fromCaption, to) {
  14146.       return getParentCaption(rootElm, SugarElement.fromDom(to.getNode())).map(function (toCaption) {
  14147.         return eq(toCaption, fromCaption) === false;
  14148.       });
  14149.     };
  14150.     var deleteCaretInsideCaption = function (editor, rootElm, forward, fromCaption, from) {
  14151.       return navigate(forward, editor.getBody(), from).bind(function (to) {
  14152.         return isDeleteOfLastCharPos(fromCaption, forward, from, to) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to);
  14153.       }).or(Optional.some(true));
  14154.     };
  14155.     var deleteCaretCells = function (editor, forward, rootElm, startElm) {
  14156.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14157.       return getParentCell(rootElm, startElm).bind(function (fromCell) {
  14158.         return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from);
  14159.       }).getOr(false);
  14160.     };
  14161.     var deleteCaretCaption = function (editor, forward, rootElm, fromCaption) {
  14162.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  14163.       return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from);
  14164.     };
  14165.     var isNearTable = function (forward, pos) {
  14166.       return forward ? isBeforeTable(pos) : isAfterTable(pos);
  14167.     };
  14168.     var isBeforeOrAfterTable = function (editor, forward) {
  14169.       var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  14170.       return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function (pos) {
  14171.         return isNearTable(forward, pos);
  14172.       });
  14173.     };
  14174.     var deleteCaret$3 = function (editor, forward, startElm) {
  14175.       var rootElm = SugarElement.fromDom(editor.getBody());
  14176.       return getParentCaption(rootElm, startElm).fold(function () {
  14177.         return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
  14178.       }, function (fromCaption) {
  14179.         return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
  14180.       });
  14181.     };
  14182.     var backspaceDelete$9 = function (editor, forward) {
  14183.       var startElm = SugarElement.fromDom(editor.selection.getStart(true));
  14184.       var cells = getCellsFromEditor(editor);
  14185.       return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
  14186.     };
  14187.  
  14188.     var createRange = function (sc, so, ec, eo) {
  14189.       var rng = document.createRange();
  14190.       rng.setStart(sc, so);
  14191.       rng.setEnd(ec, eo);
  14192.       return rng;
  14193.     };
  14194.     var normalizeBlockSelectionRange = function (rng) {
  14195.       var startPos = CaretPosition.fromRangeStart(rng);
  14196.       var endPos = CaretPosition.fromRangeEnd(rng);
  14197.       var rootNode = rng.commonAncestorContainer;
  14198.       return fromPosition(false, rootNode, endPos).map(function (newEndPos) {
  14199.         if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
  14200.           return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
  14201.         } else {
  14202.           return rng;
  14203.         }
  14204.       }).getOr(rng);
  14205.     };
  14206.     var normalize = function (rng) {
  14207.       return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
  14208.     };
  14209.  
  14210.     var hasOnlyOneChild$1 = function (node) {
  14211.       return node.firstChild && node.firstChild === node.lastChild;
  14212.     };
  14213.     var isPaddingNode = function (node) {
  14214.       return node.name === 'br' || node.value === nbsp;
  14215.     };
  14216.     var isPaddedEmptyBlock = function (schema, node) {
  14217.       var blockElements = schema.getBlockElements();
  14218.       return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
  14219.     };
  14220.     var isEmptyFragmentElement = function (schema, node) {
  14221.       var nonEmptyElements = schema.getNonEmptyElements();
  14222.       return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
  14223.     };
  14224.     var isListFragment = function (schema, fragment) {
  14225.       var firstChild = fragment.firstChild;
  14226.       var lastChild = fragment.lastChild;
  14227.       if (firstChild && firstChild.name === 'meta') {
  14228.         firstChild = firstChild.next;
  14229.       }
  14230.       if (lastChild && lastChild.attr('id') === 'mce_marker') {
  14231.         lastChild = lastChild.prev;
  14232.       }
  14233.       if (isEmptyFragmentElement(schema, lastChild)) {
  14234.         lastChild = lastChild.prev;
  14235.       }
  14236.       if (!firstChild || firstChild !== lastChild) {
  14237.         return false;
  14238.       }
  14239.       return firstChild.name === 'ul' || firstChild.name === 'ol';
  14240.     };
  14241.     var cleanupDomFragment = function (domFragment) {
  14242.       var firstChild = domFragment.firstChild;
  14243.       var lastChild = domFragment.lastChild;
  14244.       if (firstChild && firstChild.nodeName === 'META') {
  14245.         firstChild.parentNode.removeChild(firstChild);
  14246.       }
  14247.       if (lastChild && lastChild.id === 'mce_marker') {
  14248.         lastChild.parentNode.removeChild(lastChild);
  14249.       }
  14250.       return domFragment;
  14251.     };
  14252.     var toDomFragment = function (dom, serializer, fragment) {
  14253.       var html = serializer.serialize(fragment);
  14254.       var domFragment = dom.createFragment(html);
  14255.       return cleanupDomFragment(domFragment);
  14256.     };
  14257.     var listItems = function (elm) {
  14258.       return filter$4(elm.childNodes, function (child) {
  14259.         return child.nodeName === 'LI';
  14260.       });
  14261.     };
  14262.     var isPadding = function (node) {
  14263.       return node.data === nbsp || isBr$5(node);
  14264.     };
  14265.     var isListItemPadded = function (node) {
  14266.       return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
  14267.     };
  14268.     var isEmptyOrPadded = function (elm) {
  14269.       return !elm.firstChild || isListItemPadded(elm);
  14270.     };
  14271.     var trimListItems = function (elms) {
  14272.       return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
  14273.     };
  14274.     var getParentLi = function (dom, node) {
  14275.       var parentBlock = dom.getParent(node, dom.isBlock);
  14276.       return parentBlock && parentBlock.nodeName === 'LI' ? parentBlock : null;
  14277.     };
  14278.     var isParentBlockLi = function (dom, node) {
  14279.       return !!getParentLi(dom, node);
  14280.     };
  14281.     var getSplit = function (parentNode, rng) {
  14282.       var beforeRng = rng.cloneRange();
  14283.       var afterRng = rng.cloneRange();
  14284.       beforeRng.setStartBefore(parentNode);
  14285.       afterRng.setEndAfter(parentNode);
  14286.       return [
  14287.         beforeRng.cloneContents(),
  14288.         afterRng.cloneContents()
  14289.       ];
  14290.     };
  14291.     var findFirstIn = function (node, rootNode) {
  14292.       var caretPos = CaretPosition.before(node);
  14293.       var caretWalker = CaretWalker(rootNode);
  14294.       var newCaretPos = caretWalker.next(caretPos);
  14295.       return newCaretPos ? newCaretPos.toRange() : null;
  14296.     };
  14297.     var findLastOf = function (node, rootNode) {
  14298.       var caretPos = CaretPosition.after(node);
  14299.       var caretWalker = CaretWalker(rootNode);
  14300.       var newCaretPos = caretWalker.prev(caretPos);
  14301.       return newCaretPos ? newCaretPos.toRange() : null;
  14302.     };
  14303.     var insertMiddle = function (target, elms, rootNode, rng) {
  14304.       var parts = getSplit(target, rng);
  14305.       var parentElm = target.parentNode;
  14306.       parentElm.insertBefore(parts[0], target);
  14307.       Tools.each(elms, function (li) {
  14308.         parentElm.insertBefore(li, target);
  14309.       });
  14310.       parentElm.insertBefore(parts[1], target);
  14311.       parentElm.removeChild(target);
  14312.       return findLastOf(elms[elms.length - 1], rootNode);
  14313.     };
  14314.     var insertBefore$1 = function (target, elms, rootNode) {
  14315.       var parentElm = target.parentNode;
  14316.       Tools.each(elms, function (elm) {
  14317.         parentElm.insertBefore(elm, target);
  14318.       });
  14319.       return findFirstIn(target, rootNode);
  14320.     };
  14321.     var insertAfter$1 = function (target, elms, rootNode, dom) {
  14322.       dom.insertAfter(elms.reverse(), target);
  14323.       return findLastOf(elms[0], rootNode);
  14324.     };
  14325.     var insertAtCaret$1 = function (serializer, dom, rng, fragment) {
  14326.       var domFragment = toDomFragment(dom, serializer, fragment);
  14327.       var liTarget = getParentLi(dom, rng.startContainer);
  14328.       var liElms = trimListItems(listItems(domFragment.firstChild));
  14329.       var BEGINNING = 1, END = 2;
  14330.       var rootNode = dom.getRoot();
  14331.       var isAt = function (location) {
  14332.         var caretPos = CaretPosition.fromRangeStart(rng);
  14333.         var caretWalker = CaretWalker(dom.getRoot());
  14334.         var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
  14335.         return newPos ? getParentLi(dom, newPos.getNode()) !== liTarget : true;
  14336.       };
  14337.       if (isAt(BEGINNING)) {
  14338.         return insertBefore$1(liTarget, liElms, rootNode);
  14339.       } else if (isAt(END)) {
  14340.         return insertAfter$1(liTarget, liElms, rootNode, dom);
  14341.       }
  14342.       return insertMiddle(liTarget, liElms, rootNode, rng);
  14343.     };
  14344.  
  14345.     var trimOrPadLeftRight = function (dom, rng, html) {
  14346.       var root = SugarElement.fromDom(dom.getRoot());
  14347.       if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
  14348.         html = html.replace(/^ /, '&nbsp;');
  14349.       } else {
  14350.         html = html.replace(/^&nbsp;/, ' ');
  14351.       }
  14352.       if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
  14353.         html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, '&nbsp;');
  14354.       } else {
  14355.         html = html.replace(/&nbsp;(<br( \/)?>)?$/, ' ');
  14356.       }
  14357.       return html;
  14358.     };
  14359.  
  14360.     var isTableCell$1 = isTableCell$5;
  14361.     var isTableCellContentSelected = function (dom, rng, cell) {
  14362.       if (cell !== null) {
  14363.         var endCell = dom.getParent(rng.endContainer, isTableCell$1);
  14364.         return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
  14365.       } else {
  14366.         return false;
  14367.       }
  14368.     };
  14369.     var validInsertion = function (editor, value, parentNode) {
  14370.       if (parentNode.getAttribute('data-mce-bogus') === 'all') {
  14371.         parentNode.parentNode.insertBefore(editor.dom.createFragment(value), parentNode);
  14372.       } else {
  14373.         var node = parentNode.firstChild;
  14374.         var node2 = parentNode.lastChild;
  14375.         if (!node || node === node2 && node.nodeName === 'BR') {
  14376.           editor.dom.setHTML(parentNode, value);
  14377.         } else {
  14378.           editor.selection.setContent(value);
  14379.         }
  14380.       }
  14381.     };
  14382.     var trimBrsFromTableCell = function (dom, elm) {
  14383.       Optional.from(dom.getParent(elm, 'td,th')).map(SugarElement.fromDom).each(trimBlockTrailingBr);
  14384.     };
  14385.     var reduceInlineTextElements = function (editor, merge) {
  14386.       var textInlineElements = editor.schema.getTextInlineElements();
  14387.       var dom = editor.dom;
  14388.       if (merge) {
  14389.         var root_1 = editor.getBody();
  14390.         var elementUtils_1 = ElementUtils(dom);
  14391.         Tools.each(dom.select('*[data-mce-fragment]'), function (node) {
  14392.           var isInline = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
  14393.           if (isInline && hasInheritableStyles(dom, node)) {
  14394.             for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
  14395.               var styleConflict = hasStyleConflict(dom, node, parentNode);
  14396.               if (styleConflict) {
  14397.                 break;
  14398.               }
  14399.               if (elementUtils_1.compare(parentNode, node)) {
  14400.                 dom.remove(node, true);
  14401.                 break;
  14402.               }
  14403.             }
  14404.           }
  14405.         });
  14406.       }
  14407.     };
  14408.     var markFragmentElements = function (fragment) {
  14409.       var node = fragment;
  14410.       while (node = node.walk()) {
  14411.         if (node.type === 1) {
  14412.           node.attr('data-mce-fragment', '1');
  14413.         }
  14414.       }
  14415.     };
  14416.     var unmarkFragmentElements = function (elm) {
  14417.       Tools.each(elm.getElementsByTagName('*'), function (elm) {
  14418.         elm.removeAttribute('data-mce-fragment');
  14419.       });
  14420.     };
  14421.     var isPartOfFragment = function (node) {
  14422.       return !!node.getAttribute('data-mce-fragment');
  14423.     };
  14424.     var canHaveChildren = function (editor, node) {
  14425.       return node && !editor.schema.getShortEndedElements()[node.nodeName];
  14426.     };
  14427.     var moveSelectionToMarker = function (editor, marker) {
  14428.       var nextRng;
  14429.       var dom = editor.dom;
  14430.       var selection = editor.selection;
  14431.       if (!marker) {
  14432.         return;
  14433.       }
  14434.       selection.scrollIntoView(marker);
  14435.       var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
  14436.       if (dom.getContentEditable(parentEditableElm) === 'false') {
  14437.         dom.remove(marker);
  14438.         selection.select(parentEditableElm);
  14439.         return;
  14440.       }
  14441.       var rng = dom.createRng();
  14442.       var node = marker.previousSibling;
  14443.       if (isText$7(node)) {
  14444.         rng.setStart(node, node.nodeValue.length);
  14445.         if (!Env.ie) {
  14446.           var node2 = marker.nextSibling;
  14447.           if (isText$7(node2)) {
  14448.             node.appendData(node2.data);
  14449.             node2.parentNode.removeChild(node2);
  14450.           }
  14451.         }
  14452.       } else {
  14453.         rng.setStartBefore(marker);
  14454.         rng.setEndBefore(marker);
  14455.       }
  14456.       var findNextCaretRng = function (rng) {
  14457.         var caretPos = CaretPosition.fromRangeStart(rng);
  14458.         var caretWalker = CaretWalker(editor.getBody());
  14459.         caretPos = caretWalker.next(caretPos);
  14460.         if (caretPos) {
  14461.           return caretPos.toRange();
  14462.         }
  14463.       };
  14464.       var parentBlock = dom.getParent(marker, dom.isBlock);
  14465.       dom.remove(marker);
  14466.       if (parentBlock && dom.isEmpty(parentBlock)) {
  14467.         editor.$(parentBlock).empty();
  14468.         rng.setStart(parentBlock, 0);
  14469.         rng.setEnd(parentBlock, 0);
  14470.         if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
  14471.           rng = nextRng;
  14472.           dom.remove(parentBlock);
  14473.         } else {
  14474.           dom.add(parentBlock, dom.create('br', { 'data-mce-bogus': '1' }));
  14475.         }
  14476.       }
  14477.       selection.setRng(rng);
  14478.     };
  14479.     var deleteSelectedContent = function (editor) {
  14480.       var dom = editor.dom;
  14481.       var rng = normalize(editor.selection.getRng());
  14482.       editor.selection.setRng(rng);
  14483.       var startCell = dom.getParent(rng.startContainer, isTableCell$1);
  14484.       if (isTableCellContentSelected(dom, rng, startCell)) {
  14485.         deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
  14486.       } else {
  14487.         editor.getDoc().execCommand('Delete', false, null);
  14488.       }
  14489.     };
  14490.     var insertHtmlAtCaret = function (editor, value, details) {
  14491.       var parentNode;
  14492.       var rng, node;
  14493.       var selection = editor.selection;
  14494.       var dom = editor.dom;
  14495.       if (/^ | $/.test(value)) {
  14496.         value = trimOrPadLeftRight(dom, selection.getRng(), value);
  14497.       }
  14498.       var parser = editor.parser;
  14499.       var merge = details.merge;
  14500.       var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
  14501.       var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
  14502.       var args = editor.fire('BeforeSetContent', {
  14503.         content: value,
  14504.         format: 'html',
  14505.         selection: true,
  14506.         paste: details.paste
  14507.       });
  14508.       if (args.isDefaultPrevented()) {
  14509.         editor.fire('SetContent', {
  14510.           content: args.content,
  14511.           format: 'html',
  14512.           selection: true,
  14513.           paste: details.paste
  14514.         });
  14515.         return;
  14516.       }
  14517.       value = args.content;
  14518.       if (value.indexOf('{$caret}') === -1) {
  14519.         value += '{$caret}';
  14520.       }
  14521.       value = value.replace(/\{\$caret\}/, bookmarkHtml);
  14522.       rng = selection.getRng();
  14523.       var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  14524.       var body = editor.getBody();
  14525.       if (caretElement === body && selection.isCollapsed()) {
  14526.         if (dom.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom.isEmpty(body.firstChild)) {
  14527.           rng = dom.createRng();
  14528.           rng.setStart(body.firstChild, 0);
  14529.           rng.setEnd(body.firstChild, 0);
  14530.           selection.setRng(rng);
  14531.         }
  14532.       }
  14533.       if (!selection.isCollapsed()) {
  14534.         deleteSelectedContent(editor);
  14535.       }
  14536.       parentNode = selection.getNode();
  14537.       var parserArgs = {
  14538.         context: parentNode.nodeName.toLowerCase(),
  14539.         data: details.data,
  14540.         insert: true
  14541.       };
  14542.       var fragment = parser.parse(value, parserArgs);
  14543.       if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom, parentNode)) {
  14544.         rng = insertAtCaret$1(serializer, dom, selection.getRng(), fragment);
  14545.         selection.setRng(rng);
  14546.         editor.fire('SetContent', args);
  14547.         return;
  14548.       }
  14549.       markFragmentElements(fragment);
  14550.       node = fragment.lastChild;
  14551.       if (node.attr('id') === 'mce_marker') {
  14552.         var marker = node;
  14553.         for (node = node.prev; node; node = node.walk(true)) {
  14554.           if (node.type === 3 || !dom.isBlock(node.name)) {
  14555.             if (editor.schema.isValidChild(node.parent.name, 'span')) {
  14556.               node.parent.insert(marker, node, node.name === 'br');
  14557.             }
  14558.             break;
  14559.           }
  14560.         }
  14561.       }
  14562.       editor._selectionOverrides.showBlockCaretContainer(parentNode);
  14563.       if (!parserArgs.invalid) {
  14564.         value = serializer.serialize(fragment);
  14565.         validInsertion(editor, value, parentNode);
  14566.       } else {
  14567.         editor.selection.setContent(bookmarkHtml);
  14568.         parentNode = selection.getNode();
  14569.         var rootNode = editor.getBody();
  14570.         if (parentNode.nodeType === 9) {
  14571.           parentNode = node = rootNode;
  14572.         } else {
  14573.           node = parentNode;
  14574.         }
  14575.         while (node !== rootNode) {
  14576.           parentNode = node;
  14577.           node = node.parentNode;
  14578.         }
  14579.         value = parentNode === rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  14580.         value = serializer.serialize(parser.parse(value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function () {
  14581.           return serializer.serialize(fragment);
  14582.         })));
  14583.         if (parentNode === rootNode) {
  14584.           dom.setHTML(rootNode, value);
  14585.         } else {
  14586.           dom.setOuterHTML(parentNode, value);
  14587.         }
  14588.       }
  14589.       reduceInlineTextElements(editor, merge);
  14590.       moveSelectionToMarker(editor, dom.get('mce_marker'));
  14591.       unmarkFragmentElements(editor.getBody());
  14592.       trimBrsFromTableCell(dom, selection.getStart());
  14593.       editor.fire('SetContent', args);
  14594.       editor.addVisual();
  14595.     };
  14596.  
  14597.     var traverse = function (node, fn) {
  14598.       fn(node);
  14599.       if (node.firstChild) {
  14600.         traverse(node.firstChild, fn);
  14601.       }
  14602.       if (node.next) {
  14603.         traverse(node.next, fn);
  14604.       }
  14605.     };
  14606.     var findMatchingNodes = function (nodeFilters, attributeFilters, node) {
  14607.       var nodeMatches = {};
  14608.       var attrMatches = {};
  14609.       var matches = [];
  14610.       if (node.firstChild) {
  14611.         traverse(node.firstChild, function (node) {
  14612.           each$k(nodeFilters, function (filter) {
  14613.             if (filter.name === node.name) {
  14614.               if (nodeMatches[filter.name]) {
  14615.                 nodeMatches[filter.name].nodes.push(node);
  14616.               } else {
  14617.                 nodeMatches[filter.name] = {
  14618.                   filter: filter,
  14619.                   nodes: [node]
  14620.                 };
  14621.               }
  14622.             }
  14623.           });
  14624.           each$k(attributeFilters, function (filter) {
  14625.             if (typeof node.attr(filter.name) === 'string') {
  14626.               if (attrMatches[filter.name]) {
  14627.                 attrMatches[filter.name].nodes.push(node);
  14628.               } else {
  14629.                 attrMatches[filter.name] = {
  14630.                   filter: filter,
  14631.                   nodes: [node]
  14632.                 };
  14633.               }
  14634.             }
  14635.           });
  14636.         });
  14637.       }
  14638.       for (var name_1 in nodeMatches) {
  14639.         if (has$2(nodeMatches, name_1)) {
  14640.           matches.push(nodeMatches[name_1]);
  14641.         }
  14642.       }
  14643.       for (var name_2 in attrMatches) {
  14644.         if (has$2(attrMatches, name_2)) {
  14645.           matches.push(attrMatches[name_2]);
  14646.         }
  14647.       }
  14648.       return matches;
  14649.     };
  14650.     var filter$1 = function (nodeFilters, attributeFilters, node) {
  14651.       var matches = findMatchingNodes(nodeFilters, attributeFilters, node);
  14652.       each$k(matches, function (match) {
  14653.         each$k(match.filter.callbacks, function (callback) {
  14654.           callback(match.nodes, match.filter.name, {});
  14655.         });
  14656.       });
  14657.     };
  14658.  
  14659.     var defaultFormat$1 = 'html';
  14660.     var isTreeNode = function (content) {
  14661.       return content instanceof AstNode;
  14662.     };
  14663.     var moveSelection = function (editor) {
  14664.       if (hasFocus(editor)) {
  14665.         firstPositionIn(editor.getBody()).each(function (pos) {
  14666.           var node = pos.getNode();
  14667.           var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  14668.           editor.selection.setRng(caretPos.toRange());
  14669.         });
  14670.       }
  14671.     };
  14672.     var setEditorHtml = function (editor, html, noSelection) {
  14673.       editor.dom.setHTML(editor.getBody(), html);
  14674.       if (noSelection !== true) {
  14675.         moveSelection(editor);
  14676.       }
  14677.     };
  14678.     var setContentString = function (editor, body, content, args) {
  14679.       if (content.length === 0 || /^\s+$/.test(content)) {
  14680.         var padd = '<br data-mce-bogus="1">';
  14681.         if (body.nodeName === 'TABLE') {
  14682.           content = '<tr><td>' + padd + '</td></tr>';
  14683.         } else if (/^(UL|OL)$/.test(body.nodeName)) {
  14684.           content = '<li>' + padd + '</li>';
  14685.         }
  14686.         var forcedRootBlockName = getForcedRootBlock(editor);
  14687.         if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  14688.           content = padd;
  14689.           content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
  14690.         } else if (!content) {
  14691.           content = '<br data-mce-bogus="1">';
  14692.         }
  14693.         setEditorHtml(editor, content, args.no_selection);
  14694.         editor.fire('SetContent', args);
  14695.       } else {
  14696.         if (args.format !== 'raw') {
  14697.           content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
  14698.             isRootContent: true,
  14699.             insert: true
  14700.           }));
  14701.         }
  14702.         args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
  14703.         setEditorHtml(editor, args.content, args.no_selection);
  14704.         if (!args.no_events) {
  14705.           editor.fire('SetContent', args);
  14706.         }
  14707.       }
  14708.       return args.content;
  14709.     };
  14710.     var setContentTree = function (editor, body, content, args) {
  14711.       filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
  14712.       var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
  14713.       args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
  14714.       setEditorHtml(editor, args.content, args.no_selection);
  14715.       if (!args.no_events) {
  14716.         editor.fire('SetContent', args);
  14717.       }
  14718.       return content;
  14719.     };
  14720.     var setupArgs$2 = function (args, content) {
  14721.       return __assign(__assign({ format: defaultFormat$1 }, args), {
  14722.         set: true,
  14723.         content: isTreeNode(content) ? '' : content
  14724.       });
  14725.     };
  14726.     var setContentInternal = function (editor, content, args) {
  14727.       var defaultedArgs = setupArgs$2(args, content);
  14728.       var updatedArgs = args.no_events ? defaultedArgs : editor.fire('BeforeSetContent', defaultedArgs);
  14729.       if (!isTreeNode(content)) {
  14730.         content = updatedArgs.content;
  14731.       }
  14732.       return Optional.from(editor.getBody()).fold(constant(content), function (body) {
  14733.         return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
  14734.       });
  14735.     };
  14736.  
  14737.     var sibling = function (scope, predicate) {
  14738.       return sibling$2(scope, predicate).isSome();
  14739.     };
  14740.  
  14741.     var ensureIsRoot = function (isRoot) {
  14742.       return isFunction(isRoot) ? isRoot : never;
  14743.     };
  14744.     var ancestor = function (scope, transform, isRoot) {
  14745.       var element = scope.dom;
  14746.       var stop = ensureIsRoot(isRoot);
  14747.       while (element.parentNode) {
  14748.         element = element.parentNode;
  14749.         var el = SugarElement.fromDom(element);
  14750.         var transformed = transform(el);
  14751.         if (transformed.isSome()) {
  14752.           return transformed;
  14753.         } else if (stop(el)) {
  14754.           break;
  14755.         }
  14756.       }
  14757.       return Optional.none();
  14758.     };
  14759.     var closest$1 = function (scope, transform, isRoot) {
  14760.       var current = transform(scope);
  14761.       var stop = ensureIsRoot(isRoot);
  14762.       return current.orThunk(function () {
  14763.         return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  14764.       });
  14765.     };
  14766.  
  14767.     var isEq$3 = isEq$5;
  14768.     var matchesUnInheritedFormatSelector = function (ed, node, name) {
  14769.       var formatList = ed.formatter.get(name);
  14770.       if (formatList) {
  14771.         for (var i = 0; i < formatList.length; i++) {
  14772.           var format = formatList[i];
  14773.           if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
  14774.             return true;
  14775.           }
  14776.         }
  14777.       }
  14778.       return false;
  14779.     };
  14780.     var matchParents = function (editor, node, name, vars, similar) {
  14781.       var root = editor.dom.getRoot();
  14782.       if (node === root) {
  14783.         return false;
  14784.       }
  14785.       node = editor.dom.getParent(node, function (node) {
  14786.         if (matchesUnInheritedFormatSelector(editor, node, name)) {
  14787.           return true;
  14788.         }
  14789.         return node.parentNode === root || !!matchNode(editor, node, name, vars, true);
  14790.       });
  14791.       return !!matchNode(editor, node, name, vars, similar);
  14792.     };
  14793.     var matchName$1 = function (dom, node, format) {
  14794.       if (isEq$3(node, format.inline)) {
  14795.         return true;
  14796.       }
  14797.       if (isEq$3(node, format.block)) {
  14798.         return true;
  14799.       }
  14800.       if (format.selector) {
  14801.         return node.nodeType === 1 && dom.is(node, format.selector);
  14802.       }
  14803.     };
  14804.     var matchItems = function (dom, node, format, itemName, similar, vars) {
  14805.       var items = format[itemName];
  14806.       if (isFunction(format.onmatch)) {
  14807.         return format.onmatch(node, format, itemName);
  14808.       }
  14809.       if (items) {
  14810.         if (isUndefined(items.length)) {
  14811.           for (var key in items) {
  14812.             if (has$2(items, key)) {
  14813.               var value = itemName === 'attributes' ? dom.getAttrib(node, key) : getStyle(dom, node, key);
  14814.               var expectedValue = replaceVars(items[key], vars);
  14815.               var isEmptyValue = isNullable(value) || isEmpty$3(value);
  14816.               if (isEmptyValue && isNullable(expectedValue)) {
  14817.                 continue;
  14818.               }
  14819.               if (similar && isEmptyValue && !format.exact) {
  14820.                 return false;
  14821.               }
  14822.               if ((!similar || format.exact) && !isEq$3(value, normalizeStyleValue(dom, expectedValue, key))) {
  14823.                 return false;
  14824.               }
  14825.             }
  14826.           }
  14827.         } else {
  14828.           for (var i = 0; i < items.length; i++) {
  14829.             if (itemName === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(dom, node, items[i])) {
  14830.               return true;
  14831.             }
  14832.           }
  14833.         }
  14834.       }
  14835.       return true;
  14836.     };
  14837.     var matchNode = function (ed, node, name, vars, similar) {
  14838.       var formatList = ed.formatter.get(name);
  14839.       var dom = ed.dom;
  14840.       if (formatList && node) {
  14841.         for (var i = 0; i < formatList.length; i++) {
  14842.           var format = formatList[i];
  14843.           if (matchName$1(ed.dom, node, format) && matchItems(dom, node, format, 'attributes', similar, vars) && matchItems(dom, node, format, 'styles', similar, vars)) {
  14844.             var classes = format.classes;
  14845.             if (classes) {
  14846.               for (var x = 0; x < classes.length; x++) {
  14847.                 if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
  14848.                   return;
  14849.                 }
  14850.               }
  14851.             }
  14852.             return format;
  14853.           }
  14854.         }
  14855.       }
  14856.     };
  14857.     var match$2 = function (editor, name, vars, node, similar) {
  14858.       if (node) {
  14859.         return matchParents(editor, node, name, vars, similar);
  14860.       }
  14861.       node = editor.selection.getNode();
  14862.       if (matchParents(editor, node, name, vars, similar)) {
  14863.         return true;
  14864.       }
  14865.       var startNode = editor.selection.getStart();
  14866.       if (startNode !== node) {
  14867.         if (matchParents(editor, startNode, name, vars, similar)) {
  14868.           return true;
  14869.         }
  14870.       }
  14871.       return false;
  14872.     };
  14873.     var matchAll = function (editor, names, vars) {
  14874.       var matchedFormatNames = [];
  14875.       var checkedMap = {};
  14876.       var startElement = editor.selection.getStart();
  14877.       editor.dom.getParent(startElement, function (node) {
  14878.         for (var i = 0; i < names.length; i++) {
  14879.           var name_1 = names[i];
  14880.           if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
  14881.             checkedMap[name_1] = true;
  14882.             matchedFormatNames.push(name_1);
  14883.           }
  14884.         }
  14885.       }, editor.dom.getRoot());
  14886.       return matchedFormatNames;
  14887.     };
  14888.     var closest = function (editor, names) {
  14889.       var isRoot = function (elm) {
  14890.         return eq(elm, SugarElement.fromDom(editor.getBody()));
  14891.       };
  14892.       var match = function (elm, name) {
  14893.         return matchNode(editor, elm.dom, name) ? Optional.some(name) : Optional.none();
  14894.       };
  14895.       return Optional.from(editor.selection.getStart(true)).bind(function (rawElm) {
  14896.         return closest$1(SugarElement.fromDom(rawElm), function (elm) {
  14897.           return findMap(names, function (name) {
  14898.             return match(elm, name);
  14899.           });
  14900.         }, isRoot);
  14901.       }).getOrNull();
  14902.     };
  14903.     var canApply = function (editor, name) {
  14904.       var formatList = editor.formatter.get(name);
  14905.       var dom = editor.dom;
  14906.       if (formatList) {
  14907.         var startNode = editor.selection.getStart();
  14908.         var parents = getParents$2(dom, startNode);
  14909.         for (var x = formatList.length - 1; x >= 0; x--) {
  14910.           var format = formatList[x];
  14911.           if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
  14912.             return true;
  14913.           }
  14914.           for (var i = parents.length - 1; i >= 0; i--) {
  14915.             if (dom.is(parents[i], format.selector)) {
  14916.               return true;
  14917.             }
  14918.           }
  14919.         }
  14920.       }
  14921.       return false;
  14922.     };
  14923.     var matchAllOnNode = function (editor, node, formatNames) {
  14924.       return foldl(formatNames, function (acc, name) {
  14925.         var matchSimilar = isVariableFormatName(editor, name);
  14926.         if (editor.formatter.matchNode(node, name, {}, matchSimilar)) {
  14927.           return acc.concat([name]);
  14928.         } else {
  14929.           return acc;
  14930.         }
  14931.       }, []);
  14932.     };
  14933.  
  14934.     var ZWSP = ZWSP$1, CARET_ID = '_mce_caret';
  14935.     var importNode = function (ownerDocument, node) {
  14936.       return ownerDocument.importNode(node, true);
  14937.     };
  14938.     var getEmptyCaretContainers = function (node) {
  14939.       var nodes = [];
  14940.       while (node) {
  14941.         if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
  14942.           return [];
  14943.         }
  14944.         if (node.nodeType === 1) {
  14945.           nodes.push(node);
  14946.         }
  14947.         node = node.firstChild;
  14948.       }
  14949.       return nodes;
  14950.     };
  14951.     var isCaretContainerEmpty = function (node) {
  14952.       return getEmptyCaretContainers(node).length > 0;
  14953.     };
  14954.     var findFirstTextNode = function (node) {
  14955.       if (node) {
  14956.         var walker = new DomTreeWalker(node, node);
  14957.         for (node = walker.current(); node; node = walker.next()) {
  14958.           if (isText$7(node)) {
  14959.             return node;
  14960.           }
  14961.         }
  14962.       }
  14963.       return null;
  14964.     };
  14965.     var createCaretContainer = function (fill) {
  14966.       var caretContainer = SugarElement.fromTag('span');
  14967.       setAll$1(caretContainer, {
  14968.         'id': CARET_ID,
  14969.         'data-mce-bogus': '1',
  14970.         'data-mce-type': 'format-caret'
  14971.       });
  14972.       if (fill) {
  14973.         append$1(caretContainer, SugarElement.fromText(ZWSP));
  14974.       }
  14975.       return caretContainer;
  14976.     };
  14977.     var trimZwspFromCaretContainer = function (caretContainerNode) {
  14978.       var textNode = findFirstTextNode(caretContainerNode);
  14979.       if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
  14980.         textNode.deleteData(0, 1);
  14981.       }
  14982.       return textNode;
  14983.     };
  14984.     var removeCaretContainerNode = function (editor, node, moveCaret) {
  14985.       if (moveCaret === void 0) {
  14986.         moveCaret = true;
  14987.       }
  14988.       var dom = editor.dom, selection = editor.selection;
  14989.       if (isCaretContainerEmpty(node)) {
  14990.         deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret);
  14991.       } else {
  14992.         var rng = selection.getRng();
  14993.         var block = dom.getParent(node, dom.isBlock);
  14994.         var startContainer = rng.startContainer;
  14995.         var startOffset = rng.startOffset;
  14996.         var endContainer = rng.endContainer;
  14997.         var endOffset = rng.endOffset;
  14998.         var textNode = trimZwspFromCaretContainer(node);
  14999.         dom.remove(node, true);
  15000.         if (startContainer === textNode && startOffset > 0) {
  15001.           rng.setStart(textNode, startOffset - 1);
  15002.         }
  15003.         if (endContainer === textNode && endOffset > 0) {
  15004.           rng.setEnd(textNode, endOffset - 1);
  15005.         }
  15006.         if (block && dom.isEmpty(block)) {
  15007.           fillWithPaddingBr(SugarElement.fromDom(block));
  15008.         }
  15009.         selection.setRng(rng);
  15010.       }
  15011.     };
  15012.     var removeCaretContainer = function (editor, node, moveCaret) {
  15013.       if (moveCaret === void 0) {
  15014.         moveCaret = true;
  15015.       }
  15016.       var dom = editor.dom, selection = editor.selection;
  15017.       if (!node) {
  15018.         node = getParentCaretContainer(editor.getBody(), selection.getStart());
  15019.         if (!node) {
  15020.           while (node = dom.get(CARET_ID)) {
  15021.             removeCaretContainerNode(editor, node, false);
  15022.           }
  15023.         }
  15024.       } else {
  15025.         removeCaretContainerNode(editor, node, moveCaret);
  15026.       }
  15027.     };
  15028.     var insertCaretContainerNode = function (editor, caretContainer, formatNode) {
  15029.       var dom = editor.dom, block = dom.getParent(formatNode, curry(isTextBlock$1, editor));
  15030.       if (block && dom.isEmpty(block)) {
  15031.         formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15032.       } else {
  15033.         removeTrailingBr(SugarElement.fromDom(formatNode));
  15034.         if (dom.isEmpty(formatNode)) {
  15035.           formatNode.parentNode.replaceChild(caretContainer, formatNode);
  15036.         } else {
  15037.           dom.insertAfter(caretContainer, formatNode);
  15038.         }
  15039.       }
  15040.     };
  15041.     var appendNode = function (parentNode, node) {
  15042.       parentNode.appendChild(node);
  15043.       return node;
  15044.     };
  15045.     var insertFormatNodesIntoCaretContainer = function (formatNodes, caretContainer) {
  15046.       var innerMostFormatNode = foldr(formatNodes, function (parentNode, formatNode) {
  15047.         return appendNode(parentNode, formatNode.cloneNode(false));
  15048.       }, caretContainer);
  15049.       return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
  15050.     };
  15051.     var cleanFormatNode = function (editor, caretContainer, formatNode, name, vars, similar) {
  15052.       var formatter = editor.formatter;
  15053.       var dom = editor.dom;
  15054.       var validFormats = filter$4(keys(formatter.get()), function (formatName) {
  15055.         return formatName !== name && !contains$2(formatName, 'removeformat');
  15056.       });
  15057.       var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
  15058.       var uniqueFormats = filter$4(matchedFormats, function (fmtName) {
  15059.         return !areSimilarFormats(editor, fmtName, name);
  15060.       });
  15061.       if (uniqueFormats.length > 0) {
  15062.         var clonedFormatNode = formatNode.cloneNode(false);
  15063.         dom.add(caretContainer, clonedFormatNode);
  15064.         formatter.remove(name, vars, clonedFormatNode, similar);
  15065.         dom.remove(clonedFormatNode);
  15066.         return Optional.some(clonedFormatNode);
  15067.       } else {
  15068.         return Optional.none();
  15069.       }
  15070.     };
  15071.     var applyCaretFormat = function (editor, name, vars) {
  15072.       var caretContainer, textNode;
  15073.       var selection = editor.selection;
  15074.       var selectionRng = selection.getRng();
  15075.       var offset = selectionRng.startOffset;
  15076.       var container = selectionRng.startContainer;
  15077.       var text = container.nodeValue;
  15078.       caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
  15079.       if (caretContainer) {
  15080.         textNode = findFirstTextNode(caretContainer);
  15081.       }
  15082.       var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
  15083.       if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
  15084.         var bookmark = selection.getBookmark();
  15085.         selectionRng.collapse(true);
  15086.         var rng = expandRng(editor, selectionRng, editor.formatter.get(name));
  15087.         rng = split(rng);
  15088.         editor.formatter.apply(name, vars, rng);
  15089.         selection.moveToBookmark(bookmark);
  15090.       } else {
  15091.         if (!caretContainer || textNode.nodeValue !== ZWSP) {
  15092.           caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
  15093.           textNode = caretContainer.firstChild;
  15094.           selectionRng.insertNode(caretContainer);
  15095.           offset = 1;
  15096.           editor.formatter.apply(name, vars, caretContainer);
  15097.         } else {
  15098.           editor.formatter.apply(name, vars, caretContainer);
  15099.         }
  15100.         selection.setCursorLocation(textNode, offset);
  15101.       }
  15102.     };
  15103.     var removeCaretFormat = function (editor, name, vars, similar) {
  15104.       var dom = editor.dom;
  15105.       var selection = editor.selection;
  15106.       var hasContentAfter, node, formatNode;
  15107.       var parents = [];
  15108.       var rng = selection.getRng();
  15109.       var container = rng.startContainer;
  15110.       var offset = rng.startOffset;
  15111.       node = container;
  15112.       if (container.nodeType === 3) {
  15113.         if (offset !== container.nodeValue.length) {
  15114.           hasContentAfter = true;
  15115.         }
  15116.         node = node.parentNode;
  15117.       }
  15118.       while (node) {
  15119.         if (matchNode(editor, node, name, vars, similar)) {
  15120.           formatNode = node;
  15121.           break;
  15122.         }
  15123.         if (node.nextSibling) {
  15124.           hasContentAfter = true;
  15125.         }
  15126.         parents.push(node);
  15127.         node = node.parentNode;
  15128.       }
  15129.       if (!formatNode) {
  15130.         return;
  15131.       }
  15132.       if (hasContentAfter) {
  15133.         var bookmark = selection.getBookmark();
  15134.         rng.collapse(true);
  15135.         var expandedRng = expandRng(editor, rng, editor.formatter.get(name), true);
  15136.         expandedRng = split(expandedRng);
  15137.         editor.formatter.remove(name, vars, expandedRng, similar);
  15138.         selection.moveToBookmark(bookmark);
  15139.       } else {
  15140.         var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
  15141.         var newCaretContainer = createCaretContainer(false).dom;
  15142.         insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
  15143.         var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name, vars, similar);
  15144.         var caretTextNode = insertFormatNodesIntoCaretContainer(parents.concat(cleanedFormatNode.toArray()), newCaretContainer);
  15145.         removeCaretContainerNode(editor, caretContainer, false);
  15146.         selection.setCursorLocation(caretTextNode, 1);
  15147.         if (dom.isEmpty(formatNode)) {
  15148.           dom.remove(formatNode);
  15149.         }
  15150.       }
  15151.     };
  15152.     var disableCaretContainer = function (editor, keyCode) {
  15153.       var selection = editor.selection, body = editor.getBody();
  15154.       removeCaretContainer(editor, null, false);
  15155.       if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
  15156.         removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15157.       }
  15158.       if (keyCode === 37 || keyCode === 39) {
  15159.         removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
  15160.       }
  15161.     };
  15162.     var setup$k = function (editor) {
  15163.       editor.on('mouseup keydown', function (e) {
  15164.         disableCaretContainer(editor, e.keyCode);
  15165.       });
  15166.     };
  15167.     var replaceWithCaretFormat = function (targetNode, formatNodes) {
  15168.       var caretContainer = createCaretContainer(false);
  15169.       var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
  15170.       before$4(SugarElement.fromDom(targetNode), caretContainer);
  15171.       remove$7(SugarElement.fromDom(targetNode));
  15172.       return CaretPosition(innerMost, 0);
  15173.     };
  15174.     var isFormatElement = function (editor, element) {
  15175.       var inlineElements = editor.schema.getTextInlineElements();
  15176.       return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
  15177.     };
  15178.     var isEmptyCaretFormatElement = function (element) {
  15179.       return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
  15180.     };
  15181.  
  15182.     var postProcessHooks = {};
  15183.     var filter = filter$2;
  15184.     var each$c = each$i;
  15185.     var addPostProcessHook = function (name, hook) {
  15186.       var hooks = postProcessHooks[name];
  15187.       if (!hooks) {
  15188.         postProcessHooks[name] = [];
  15189.       }
  15190.       postProcessHooks[name].push(hook);
  15191.     };
  15192.     var postProcess$1 = function (name, editor) {
  15193.       each$c(postProcessHooks[name], function (hook) {
  15194.         hook(editor);
  15195.       });
  15196.     };
  15197.     addPostProcessHook('pre', function (editor) {
  15198.       var rng = editor.selection.getRng();
  15199.       var blocks;
  15200.       var hasPreSibling = function (pre) {
  15201.         return isPre(pre.previousSibling) && indexOf$1(blocks, pre.previousSibling) !== -1;
  15202.       };
  15203.       var joinPre = function (pre1, pre2) {
  15204.         DomQuery(pre2).remove();
  15205.         DomQuery(pre1).append('<br><br>').append(pre2.childNodes);
  15206.       };
  15207.       var isPre = matchNodeNames(['pre']);
  15208.       if (!rng.collapsed) {
  15209.         blocks = editor.selection.getSelectedBlocks();
  15210.         each$c(filter(filter(blocks, isPre), hasPreSibling), function (pre) {
  15211.           joinPre(pre.previousSibling, pre);
  15212.         });
  15213.       }
  15214.     });
  15215.  
  15216.     var each$b = Tools.each;
  15217.     var isElementNode$1 = function (node) {
  15218.       return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15219.     };
  15220.     var findElementSibling = function (node, siblingName) {
  15221.       for (var sibling = node; sibling; sibling = sibling[siblingName]) {
  15222.         if (isText$7(sibling) && isNotEmpty(sibling.data)) {
  15223.           return node;
  15224.         }
  15225.         if (isElement$5(sibling) && !isBookmarkNode$1(sibling)) {
  15226.           return sibling;
  15227.         }
  15228.       }
  15229.       return node;
  15230.     };
  15231.     var mergeSiblingsNodes = function (dom, prev, next) {
  15232.       var elementUtils = ElementUtils(dom);
  15233.       if (prev && next) {
  15234.         prev = findElementSibling(prev, 'previousSibling');
  15235.         next = findElementSibling(next, 'nextSibling');
  15236.         if (elementUtils.compare(prev, next)) {
  15237.           for (var sibling = prev.nextSibling; sibling && sibling !== next;) {
  15238.             var tmpSibling = sibling;
  15239.             sibling = sibling.nextSibling;
  15240.             prev.appendChild(tmpSibling);
  15241.           }
  15242.           dom.remove(next);
  15243.           Tools.each(Tools.grep(next.childNodes), function (node) {
  15244.             prev.appendChild(node);
  15245.           });
  15246.           return prev;
  15247.         }
  15248.       }
  15249.       return next;
  15250.     };
  15251.     var mergeSiblings = function (dom, format, vars, node) {
  15252.       if (node && format.merge_siblings !== false) {
  15253.         var newNode = mergeSiblingsNodes(dom, getNonWhiteSpaceSibling(node), node);
  15254.         mergeSiblingsNodes(dom, newNode, getNonWhiteSpaceSibling(newNode, true));
  15255.       }
  15256.     };
  15257.     var clearChildStyles = function (dom, format, node) {
  15258.       if (format.clear_child_styles) {
  15259.         var selector = format.links ? '*:not(a)' : '*';
  15260.         each$b(dom.select(selector, node), function (node) {
  15261.           if (isElementNode$1(node)) {
  15262.             each$b(format.styles, function (value, name) {
  15263.               dom.setStyle(node, name, '');
  15264.             });
  15265.           }
  15266.         });
  15267.       }
  15268.     };
  15269.     var processChildElements = function (node, filter, process) {
  15270.       each$b(node.childNodes, function (node) {
  15271.         if (isElementNode$1(node)) {
  15272.           if (filter(node)) {
  15273.             process(node);
  15274.           }
  15275.           if (node.hasChildNodes()) {
  15276.             processChildElements(node, filter, process);
  15277.           }
  15278.         }
  15279.       });
  15280.     };
  15281.     var unwrapEmptySpan = function (dom, node) {
  15282.       if (node.nodeName === 'SPAN' && dom.getAttribs(node).length === 0) {
  15283.         dom.remove(node, true);
  15284.       }
  15285.     };
  15286.     var hasStyle = function (dom, name) {
  15287.       return function (node) {
  15288.         return !!(node && getStyle(dom, node, name));
  15289.       };
  15290.     };
  15291.     var applyStyle = function (dom, name, value) {
  15292.       return function (node) {
  15293.         dom.setStyle(node, name, value);
  15294.         if (node.getAttribute('style') === '') {
  15295.           node.removeAttribute('style');
  15296.         }
  15297.         unwrapEmptySpan(dom, node);
  15298.       };
  15299.     };
  15300.  
  15301.     var removeResult = Adt.generate([
  15302.       { keep: [] },
  15303.       { rename: ['name'] },
  15304.       { removed: [] }
  15305.     ]);
  15306.     var MCE_ATTR_RE = /^(src|href|style)$/;
  15307.     var each$a = Tools.each;
  15308.     var isEq$2 = isEq$5;
  15309.     var isTableCellOrRow = function (node) {
  15310.       return /^(TR|TH|TD)$/.test(node.nodeName);
  15311.     };
  15312.     var isChildOfInlineParent = function (dom, node, parent) {
  15313.       return dom.isChildOf(node, parent) && node !== parent && !dom.isBlock(parent);
  15314.     };
  15315.     var getContainer = function (ed, rng, start) {
  15316.       var container = rng[start ? 'startContainer' : 'endContainer'];
  15317.       var offset = rng[start ? 'startOffset' : 'endOffset'];
  15318.       if (isElement$5(container)) {
  15319.         var lastIdx = container.childNodes.length - 1;
  15320.         if (!start && offset) {
  15321.           offset--;
  15322.         }
  15323.         container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  15324.       }
  15325.       if (isText$7(container) && start && offset >= container.nodeValue.length) {
  15326.         container = new DomTreeWalker(container, ed.getBody()).next() || container;
  15327.       }
  15328.       if (isText$7(container) && !start && offset === 0) {
  15329.         container = new DomTreeWalker(container, ed.getBody()).prev() || container;
  15330.       }
  15331.       return container;
  15332.     };
  15333.     var normalizeTableSelection = function (node, start) {
  15334.       var prop = start ? 'firstChild' : 'lastChild';
  15335.       if (isTableCellOrRow(node) && node[prop]) {
  15336.         var childNode = node[prop];
  15337.         if (node.nodeName === 'TR') {
  15338.           return childNode[prop] || childNode;
  15339.         } else {
  15340.           return childNode;
  15341.         }
  15342.       }
  15343.       return node;
  15344.     };
  15345.     var wrap$1 = function (dom, node, name, attrs) {
  15346.       var wrapper = dom.create(name, attrs);
  15347.       node.parentNode.insertBefore(wrapper, node);
  15348.       wrapper.appendChild(node);
  15349.       return wrapper;
  15350.     };
  15351.     var wrapWithSiblings = function (dom, node, next, name, attrs) {
  15352.       var start = SugarElement.fromDom(node);
  15353.       var wrapper = SugarElement.fromDom(dom.create(name, attrs));
  15354.       var siblings = next ? nextSiblings(start) : prevSiblings(start);
  15355.       append(wrapper, siblings);
  15356.       if (next) {
  15357.         before$4(start, wrapper);
  15358.         prepend(wrapper, start);
  15359.       } else {
  15360.         after$3(start, wrapper);
  15361.         append$1(wrapper, start);
  15362.       }
  15363.       return wrapper.dom;
  15364.     };
  15365.     var matchName = function (dom, node, format) {
  15366.       if (isInlineFormat(format) && isEq$2(node, format.inline)) {
  15367.         return true;
  15368.       }
  15369.       if (isBlockFormat(format) && isEq$2(node, format.block)) {
  15370.         return true;
  15371.       }
  15372.       if (isSelectorFormat(format)) {
  15373.         return isElement$5(node) && dom.is(node, format.selector);
  15374.       }
  15375.     };
  15376.     var isColorFormatAndAnchor = function (node, format) {
  15377.       return format.links && node.nodeName === 'A';
  15378.     };
  15379.     var find = function (dom, node, next, inc) {
  15380.       var sibling = getNonWhiteSpaceSibling(node, next, inc);
  15381.       return isNullable(sibling) || sibling.nodeName === 'BR' || dom.isBlock(sibling);
  15382.     };
  15383.     var removeNode = function (ed, node, format) {
  15384.       var parentNode = node.parentNode;
  15385.       var rootBlockElm;
  15386.       var dom = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
  15387.       if (isBlockFormat(format)) {
  15388.         if (!forcedRootBlock) {
  15389.           if (dom.isBlock(node) && !dom.isBlock(parentNode)) {
  15390.             if (!find(dom, node, false) && !find(dom, node.firstChild, true, true)) {
  15391.               node.insertBefore(dom.create('br'), node.firstChild);
  15392.             }
  15393.             if (!find(dom, node, true) && !find(dom, node.lastChild, false, true)) {
  15394.               node.appendChild(dom.create('br'));
  15395.             }
  15396.           }
  15397.         } else {
  15398.           if (parentNode === dom.getRoot()) {
  15399.             if (!format.list_block || !isEq$2(node, format.list_block)) {
  15400.               each$k(from(node.childNodes), function (node) {
  15401.                 if (isValid(ed, forcedRootBlock, node.nodeName.toLowerCase())) {
  15402.                   if (!rootBlockElm) {
  15403.                     rootBlockElm = wrap$1(dom, node, forcedRootBlock);
  15404.                     dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  15405.                   } else {
  15406.                     rootBlockElm.appendChild(node);
  15407.                   }
  15408.                 } else {
  15409.                   rootBlockElm = null;
  15410.                 }
  15411.               });
  15412.             }
  15413.           }
  15414.         }
  15415.       }
  15416.       if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
  15417.         return;
  15418.       }
  15419.       dom.remove(node, true);
  15420.     };
  15421.     var removeFormatInternal = function (ed, format, vars, node, compareNode) {
  15422.       var stylesModified;
  15423.       var dom = ed.dom;
  15424.       if (!matchName(dom, node, format) && !isColorFormatAndAnchor(node, format)) {
  15425.         return removeResult.keep();
  15426.       }
  15427.       var elm = node;
  15428.       if (isInlineFormat(format) && format.remove === 'all' && isArray$1(format.preserve_attributes)) {
  15429.         var attrsToPreserve = filter$4(dom.getAttribs(elm), function (attr) {
  15430.           return contains$3(format.preserve_attributes, attr.name.toLowerCase());
  15431.         });
  15432.         dom.removeAllAttribs(elm);
  15433.         each$k(attrsToPreserve, function (attr) {
  15434.           return dom.setAttrib(elm, attr.name, attr.value);
  15435.         });
  15436.         if (attrsToPreserve.length > 0) {
  15437.           return removeResult.rename('span');
  15438.         }
  15439.       }
  15440.       if (format.remove !== 'all') {
  15441.         each$a(format.styles, function (value, name) {
  15442.           value = normalizeStyleValue(dom, replaceVars(value, vars), name + '');
  15443.           if (isNumber(name)) {
  15444.             name = value;
  15445.             compareNode = null;
  15446.           }
  15447.           if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom, compareNode, name), value))) {
  15448.             dom.setStyle(elm, name, '');
  15449.           }
  15450.           stylesModified = true;
  15451.         });
  15452.         if (stylesModified && dom.getAttrib(elm, 'style') === '') {
  15453.           elm.removeAttribute('style');
  15454.           elm.removeAttribute('data-mce-style');
  15455.         }
  15456.         each$a(format.attributes, function (value, name) {
  15457.           var valueOut;
  15458.           value = replaceVars(value, vars);
  15459.           if (isNumber(name)) {
  15460.             name = value;
  15461.             compareNode = null;
  15462.           }
  15463.           if (format.remove_similar || (!compareNode || isEq$2(dom.getAttrib(compareNode, name), value))) {
  15464.             if (name === 'class') {
  15465.               value = dom.getAttrib(elm, name);
  15466.               if (value) {
  15467.                 valueOut = '';
  15468.                 each$k(value.split(/\s+/), function (cls) {
  15469.                   if (/mce\-\w+/.test(cls)) {
  15470.                     valueOut += (valueOut ? ' ' : '') + cls;
  15471.                   }
  15472.                 });
  15473.                 if (valueOut) {
  15474.                   dom.setAttrib(elm, name, valueOut);
  15475.                   return;
  15476.                 }
  15477.               }
  15478.             }
  15479.             if (MCE_ATTR_RE.test(name)) {
  15480.               elm.removeAttribute('data-mce-' + name);
  15481.             }
  15482.             if (name === 'style' && matchNodeNames(['li'])(elm) && dom.getStyle(elm, 'list-style-type') === 'none') {
  15483.               elm.removeAttribute(name);
  15484.               dom.setStyle(elm, 'list-style-type', 'none');
  15485.               return;
  15486.             }
  15487.             if (name === 'class') {
  15488.               elm.removeAttribute('className');
  15489.             }
  15490.             elm.removeAttribute(name);
  15491.           }
  15492.         });
  15493.         each$a(format.classes, function (value) {
  15494.           value = replaceVars(value, vars);
  15495.           if (!compareNode || dom.hasClass(compareNode, value)) {
  15496.             dom.removeClass(elm, value);
  15497.           }
  15498.         });
  15499.         var attrs = dom.getAttribs(elm);
  15500.         for (var i = 0; i < attrs.length; i++) {
  15501.           var attrName = attrs[i].nodeName;
  15502.           if (attrName.indexOf('_') !== 0 && attrName.indexOf('data-') !== 0) {
  15503.             return removeResult.keep();
  15504.           }
  15505.         }
  15506.       }
  15507.       if (format.remove !== 'none') {
  15508.         removeNode(ed, elm, format);
  15509.         return removeResult.removed();
  15510.       }
  15511.       return removeResult.keep();
  15512.     };
  15513.     var removeFormat$1 = function (ed, format, vars, node, compareNode) {
  15514.       return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function (newName) {
  15515.         ed.dom.rename(node, newName);
  15516.         return true;
  15517.       }, always);
  15518.     };
  15519.     var findFormatRoot = function (editor, container, name, vars, similar) {
  15520.       var formatRoot;
  15521.       each$k(getParents$2(editor.dom, container.parentNode).reverse(), function (parent) {
  15522.         if (!formatRoot && parent.id !== '_start' && parent.id !== '_end') {
  15523.           var format = matchNode(editor, parent, name, vars, similar);
  15524.           if (format && format.split !== false) {
  15525.             formatRoot = parent;
  15526.           }
  15527.         }
  15528.       });
  15529.       return formatRoot;
  15530.     };
  15531.     var removeFormatFromClone = function (editor, format, vars, clone) {
  15532.       return removeFormatInternal(editor, format, vars, clone, clone).fold(constant(clone), function (newName) {
  15533.         var fragment = editor.dom.createFragment();
  15534.         fragment.appendChild(clone);
  15535.         return editor.dom.rename(clone, newName);
  15536.       }, constant(null));
  15537.     };
  15538.     var wrapAndSplit = function (editor, formatList, formatRoot, container, target, split, format, vars) {
  15539.       var clone, lastClone, firstClone;
  15540.       var dom = editor.dom;
  15541.       if (formatRoot) {
  15542.         var formatRootParent = formatRoot.parentNode;
  15543.         for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
  15544.           clone = dom.clone(parent_1, false);
  15545.           for (var i = 0; i < formatList.length; i++) {
  15546.             clone = removeFormatFromClone(editor, formatList[i], vars, clone);
  15547.             if (clone === null) {
  15548.               break;
  15549.             }
  15550.           }
  15551.           if (clone) {
  15552.             if (lastClone) {
  15553.               clone.appendChild(lastClone);
  15554.             }
  15555.             if (!firstClone) {
  15556.               firstClone = clone;
  15557.             }
  15558.             lastClone = clone;
  15559.           }
  15560.         }
  15561.         if (split && (!format.mixed || !dom.isBlock(formatRoot))) {
  15562.           container = dom.split(formatRoot, container);
  15563.         }
  15564.         if (lastClone) {
  15565.           target.parentNode.insertBefore(lastClone, target);
  15566.           firstClone.appendChild(target);
  15567.           if (isInlineFormat(format)) {
  15568.             mergeSiblings(dom, format, vars, lastClone);
  15569.           }
  15570.         }
  15571.       }
  15572.       return container;
  15573.     };
  15574.     var remove$1 = function (ed, name, vars, node, similar) {
  15575.       var formatList = ed.formatter.get(name);
  15576.       var format = formatList[0];
  15577.       var contentEditable = true;
  15578.       var dom = ed.dom;
  15579.       var selection = ed.selection;
  15580.       var splitToFormatRoot = function (container) {
  15581.         var formatRoot = findFormatRoot(ed, container, name, vars, similar);
  15582.         return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
  15583.       };
  15584.       var isRemoveBookmarkNode = function (node) {
  15585.         return isBookmarkNode$1(node) && isElement$5(node) && (node.id === '_start' || node.id === '_end');
  15586.       };
  15587.       var removeNodeFormat = function (node) {
  15588.         return exists(formatList, function (fmt) {
  15589.           return removeFormat$1(ed, fmt, vars, node, node);
  15590.         });
  15591.       };
  15592.       var process = function (node) {
  15593.         var lastContentEditable = true;
  15594.         var hasContentEditableState = false;
  15595.         if (isElement$5(node) && dom.getContentEditable(node)) {
  15596.           lastContentEditable = contentEditable;
  15597.           contentEditable = dom.getContentEditable(node) === 'true';
  15598.           hasContentEditableState = true;
  15599.         }
  15600.         var children = from(node.childNodes);
  15601.         if (contentEditable && !hasContentEditableState) {
  15602.           var removed = removeNodeFormat(node);
  15603.           var currentNodeMatches = removed || exists(formatList, function (f) {
  15604.             return matchName$1(dom, node, f);
  15605.           });
  15606.           var parentNode = node.parentNode;
  15607.           if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  15608.             removeNodeFormat(parentNode);
  15609.           }
  15610.         }
  15611.         if (format.deep) {
  15612.           if (children.length) {
  15613.             for (var i = 0; i < children.length; i++) {
  15614.               process(children[i]);
  15615.             }
  15616.             if (hasContentEditableState) {
  15617.               contentEditable = lastContentEditable;
  15618.             }
  15619.           }
  15620.         }
  15621.         var textDecorations = [
  15622.           'underline',
  15623.           'line-through',
  15624.           'overline'
  15625.         ];
  15626.         each$k(textDecorations, function (decoration) {
  15627.           if (isElement$5(node) && ed.dom.getStyle(node, 'text-decoration') === decoration && node.parentNode && getTextDecoration(dom, node.parentNode) === decoration) {
  15628.             removeFormat$1(ed, {
  15629.               deep: false,
  15630.               exact: true,
  15631.               inline: 'span',
  15632.               styles: { textDecoration: decoration }
  15633.             }, null, node);
  15634.           }
  15635.         });
  15636.       };
  15637.       var unwrap = function (start) {
  15638.         var node = dom.get(start ? '_start' : '_end');
  15639.         var out = node[start ? 'firstChild' : 'lastChild'];
  15640.         if (isRemoveBookmarkNode(out)) {
  15641.           out = out[start ? 'firstChild' : 'lastChild'];
  15642.         }
  15643.         if (isText$7(out) && out.data.length === 0) {
  15644.           out = start ? node.previousSibling || node.nextSibling : node.nextSibling || node.previousSibling;
  15645.         }
  15646.         dom.remove(node, true);
  15647.         return out;
  15648.       };
  15649.       var removeRngStyle = function (rng) {
  15650.         var startContainer, endContainer;
  15651.         var expandedRng = expandRng(ed, rng, formatList, rng.collapsed);
  15652.         if (format.split) {
  15653.           expandedRng = split(expandedRng);
  15654.           startContainer = getContainer(ed, expandedRng, true);
  15655.           endContainer = getContainer(ed, expandedRng);
  15656.           if (startContainer !== endContainer) {
  15657.             startContainer = normalizeTableSelection(startContainer, true);
  15658.             endContainer = normalizeTableSelection(endContainer, false);
  15659.             if (isChildOfInlineParent(dom, startContainer, endContainer)) {
  15660.               var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
  15661.               splitToFormatRoot(wrapWithSiblings(dom, marker, true, 'span', {
  15662.                 'id': '_start',
  15663.                 'data-mce-type': 'bookmark'
  15664.               }));
  15665.               unwrap(true);
  15666.               return;
  15667.             }
  15668.             if (isChildOfInlineParent(dom, endContainer, startContainer)) {
  15669.               var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
  15670.               splitToFormatRoot(wrapWithSiblings(dom, marker, false, 'span', {
  15671.                 'id': '_end',
  15672.                 'data-mce-type': 'bookmark'
  15673.               }));
  15674.               unwrap(false);
  15675.               return;
  15676.             }
  15677.             startContainer = wrap$1(dom, startContainer, 'span', {
  15678.               'id': '_start',
  15679.               'data-mce-type': 'bookmark'
  15680.             });
  15681.             endContainer = wrap$1(dom, endContainer, 'span', {
  15682.               'id': '_end',
  15683.               'data-mce-type': 'bookmark'
  15684.             });
  15685.             var newRng = dom.createRng();
  15686.             newRng.setStartAfter(startContainer);
  15687.             newRng.setEndBefore(endContainer);
  15688.             walk$2(dom, newRng, function (nodes) {
  15689.               each$k(nodes, function (n) {
  15690.                 if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
  15691.                   splitToFormatRoot(n);
  15692.                 }
  15693.               });
  15694.             });
  15695.             splitToFormatRoot(startContainer);
  15696.             splitToFormatRoot(endContainer);
  15697.             startContainer = unwrap(true);
  15698.             endContainer = unwrap();
  15699.           } else {
  15700.             startContainer = endContainer = splitToFormatRoot(startContainer);
  15701.           }
  15702.           expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
  15703.           expandedRng.startOffset = dom.nodeIndex(startContainer);
  15704.           expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
  15705.           expandedRng.endOffset = dom.nodeIndex(endContainer) + 1;
  15706.         }
  15707.         walk$2(dom, expandedRng, function (nodes) {
  15708.           each$k(nodes, process);
  15709.         });
  15710.       };
  15711.       if (node) {
  15712.         if (isNode(node)) {
  15713.           var rng = dom.createRng();
  15714.           rng.setStartBefore(node);
  15715.           rng.setEndAfter(node);
  15716.           removeRngStyle(rng);
  15717.         } else {
  15718.           removeRngStyle(node);
  15719.         }
  15720.         fireFormatRemove(ed, name, node, vars);
  15721.         return;
  15722.       }
  15723.       if (dom.getContentEditable(selection.getNode()) === 'false') {
  15724.         node = selection.getNode();
  15725.         for (var i = 0; i < formatList.length; i++) {
  15726.           if (formatList[i].ceFalseOverride) {
  15727.             if (removeFormat$1(ed, formatList[i], vars, node, node)) {
  15728.               break;
  15729.             }
  15730.           }
  15731.         }
  15732.         fireFormatRemove(ed, name, node, vars);
  15733.         return;
  15734.       }
  15735.       if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  15736.         preserve(selection, true, function () {
  15737.           runOnRanges(ed, removeRngStyle);
  15738.         });
  15739.         if (isInlineFormat(format) && match$2(ed, name, vars, selection.getStart())) {
  15740.           moveStart(dom, selection, selection.getRng());
  15741.         }
  15742.         ed.nodeChanged();
  15743.       } else {
  15744.         removeCaretFormat(ed, name, vars, similar);
  15745.       }
  15746.       fireFormatRemove(ed, name, node, vars);
  15747.     };
  15748.  
  15749.     var each$9 = Tools.each;
  15750.     var mergeTextDecorationsAndColor = function (dom, format, vars, node) {
  15751.       var processTextDecorationsAndColor = function (n) {
  15752.         if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
  15753.           var textDecoration = getTextDecoration(dom, n.parentNode);
  15754.           if (dom.getStyle(n, 'color') && textDecoration) {
  15755.             dom.setStyle(n, 'text-decoration', textDecoration);
  15756.           } else if (dom.getStyle(n, 'text-decoration') === textDecoration) {
  15757.             dom.setStyle(n, 'text-decoration', null);
  15758.           }
  15759.         }
  15760.       };
  15761.       if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  15762.         Tools.walk(node, processTextDecorationsAndColor, 'childNodes');
  15763.         processTextDecorationsAndColor(node);
  15764.       }
  15765.     };
  15766.     var mergeBackgroundColorAndFontSize = function (dom, format, vars, node) {
  15767.       if (format.styles && format.styles.backgroundColor) {
  15768.         processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'backgroundColor', replaceVars(format.styles.backgroundColor, vars)));
  15769.       }
  15770.     };
  15771.     var mergeSubSup = function (dom, format, vars, node) {
  15772.       if (isInlineFormat(format) && (format.inline === 'sub' || format.inline === 'sup')) {
  15773.         processChildElements(node, hasStyle(dom, 'fontSize'), applyStyle(dom, 'fontSize', ''));
  15774.         dom.remove(dom.select(format.inline === 'sup' ? 'sub' : 'sup', node), true);
  15775.       }
  15776.     };
  15777.     var mergeWithChildren = function (editor, formatList, vars, node) {
  15778.       each$9(formatList, function (format) {
  15779.         if (isInlineFormat(format)) {
  15780.           each$9(editor.dom.select(format.inline, node), function (child) {
  15781.             if (!isElementNode$1(child)) {
  15782.               return;
  15783.             }
  15784.             removeFormat$1(editor, format, vars, child, format.exact ? child : null);
  15785.           });
  15786.         }
  15787.         clearChildStyles(editor.dom, format, node);
  15788.       });
  15789.     };
  15790.     var mergeWithParents = function (editor, format, name, vars, node) {
  15791.       if (matchNode(editor, node.parentNode, name, vars)) {
  15792.         if (removeFormat$1(editor, format, vars, node)) {
  15793.           return;
  15794.         }
  15795.       }
  15796.       if (format.merge_with_parents) {
  15797.         editor.dom.getParent(node.parentNode, function (parent) {
  15798.           if (matchNode(editor, parent, name, vars)) {
  15799.             removeFormat$1(editor, format, vars, node);
  15800.             return true;
  15801.           }
  15802.         });
  15803.       }
  15804.     };
  15805.  
  15806.     var each$8 = Tools.each;
  15807.     var isElementNode = function (node) {
  15808.       return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
  15809.     };
  15810.     var canFormatBR = function (editor, format, node, parentName) {
  15811.       if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
  15812.         var validBRParentElements = getTextRootBlockElements(editor.schema);
  15813.         var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function (sibling) {
  15814.           return isCaretNode(sibling.dom);
  15815.         });
  15816.         return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
  15817.       } else {
  15818.         return false;
  15819.       }
  15820.     };
  15821.     var applyFormat$1 = function (ed, name, vars, node) {
  15822.       var formatList = ed.formatter.get(name);
  15823.       var format = formatList[0];
  15824.       var isCollapsed = !node && ed.selection.isCollapsed();
  15825.       var dom = ed.dom;
  15826.       var selection = ed.selection;
  15827.       var setElementFormat = function (elm, fmt) {
  15828.         if (fmt === void 0) {
  15829.           fmt = format;
  15830.         }
  15831.         if (isFunction(fmt.onformat)) {
  15832.           fmt.onformat(elm, fmt, vars, node);
  15833.         }
  15834.         each$8(fmt.styles, function (value, name) {
  15835.           dom.setStyle(elm, name, replaceVars(value, vars));
  15836.         });
  15837.         if (fmt.styles) {
  15838.           var styleVal = dom.getAttrib(elm, 'style');
  15839.           if (styleVal) {
  15840.             dom.setAttrib(elm, 'data-mce-style', styleVal);
  15841.           }
  15842.         }
  15843.         each$8(fmt.attributes, function (value, name) {
  15844.           dom.setAttrib(elm, name, replaceVars(value, vars));
  15845.         });
  15846.         each$8(fmt.classes, function (value) {
  15847.           value = replaceVars(value, vars);
  15848.           if (!dom.hasClass(elm, value)) {
  15849.             dom.addClass(elm, value);
  15850.           }
  15851.         });
  15852.       };
  15853.       var applyNodeStyle = function (formatList, node) {
  15854.         var found = false;
  15855.         each$8(formatList, function (format) {
  15856.           if (!isSelectorFormat(format)) {
  15857.             return false;
  15858.           }
  15859.           if (isNonNullable(format.collapsed) && format.collapsed !== isCollapsed) {
  15860.             return;
  15861.           }
  15862.           if (dom.is(node, format.selector) && !isCaretNode(node)) {
  15863.             setElementFormat(node, format);
  15864.             found = true;
  15865.             return false;
  15866.           }
  15867.         });
  15868.         return found;
  15869.       };
  15870.       var createWrapElement = function (wrapName) {
  15871.         if (isString$1(wrapName)) {
  15872.           var wrapElm = dom.create(wrapName);
  15873.           setElementFormat(wrapElm);
  15874.           return wrapElm;
  15875.         } else {
  15876.           return null;
  15877.         }
  15878.       };
  15879.       var applyRngStyle = function (dom, rng, nodeSpecific) {
  15880.         var newWrappers = [];
  15881.         var contentEditable = true;
  15882.         var wrapName = format.inline || format.block;
  15883.         var wrapElm = createWrapElement(wrapName);
  15884.         walk$2(dom, rng, function (nodes) {
  15885.           var currentWrapElm;
  15886.           var process = function (node) {
  15887.             var hasContentEditableState = false;
  15888.             var lastContentEditable = contentEditable;
  15889.             var nodeName = node.nodeName.toLowerCase();
  15890.             var parentNode = node.parentNode;
  15891.             var parentName = parentNode.nodeName.toLowerCase();
  15892.             if (isElement$5(node) && dom.getContentEditable(node)) {
  15893.               lastContentEditable = contentEditable;
  15894.               contentEditable = dom.getContentEditable(node) === 'true';
  15895.               hasContentEditableState = true;
  15896.             }
  15897.             if (isBr$5(node) && !canFormatBR(ed, format, node, parentName)) {
  15898.               currentWrapElm = null;
  15899.               if (isBlockFormat(format)) {
  15900.                 dom.remove(node);
  15901.               }
  15902.               return;
  15903.             }
  15904.             if (isBlockFormat(format) && format.wrapper && matchNode(ed, node, name, vars)) {
  15905.               currentWrapElm = null;
  15906.               return;
  15907.             }
  15908.             if (contentEditable && !hasContentEditableState && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
  15909.               var elm = dom.rename(node, wrapName);
  15910.               setElementFormat(elm);
  15911.               newWrappers.push(elm);
  15912.               currentWrapElm = null;
  15913.               return;
  15914.             }
  15915.             if (isSelectorFormat(format)) {
  15916.               var found = applyNodeStyle(formatList, node);
  15917.               if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
  15918.                 found = applyNodeStyle(formatList, parentNode);
  15919.               }
  15920.               if (!isInlineFormat(format) || found) {
  15921.                 currentWrapElm = null;
  15922.                 return;
  15923.               }
  15924.             }
  15925.             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))) {
  15926.               if (!currentWrapElm) {
  15927.                 currentWrapElm = dom.clone(wrapElm, false);
  15928.                 node.parentNode.insertBefore(currentWrapElm, node);
  15929.                 newWrappers.push(currentWrapElm);
  15930.               }
  15931.               currentWrapElm.appendChild(node);
  15932.             } else {
  15933.               currentWrapElm = null;
  15934.               each$k(from(node.childNodes), process);
  15935.               if (hasContentEditableState) {
  15936.                 contentEditable = lastContentEditable;
  15937.               }
  15938.               currentWrapElm = null;
  15939.             }
  15940.           };
  15941.           each$k(nodes, process);
  15942.         });
  15943.         if (format.links === true) {
  15944.           each$k(newWrappers, function (node) {
  15945.             var process = function (node) {
  15946.               if (node.nodeName === 'A') {
  15947.                 setElementFormat(node, format);
  15948.               }
  15949.               each$k(from(node.childNodes), process);
  15950.             };
  15951.             process(node);
  15952.           });
  15953.         }
  15954.         each$k(newWrappers, function (node) {
  15955.           var getChildCount = function (node) {
  15956.             var count = 0;
  15957.             each$k(node.childNodes, function (node) {
  15958.               if (!isEmptyTextNode$1(node) && !isBookmarkNode$1(node)) {
  15959.                 count++;
  15960.               }
  15961.             });
  15962.             return count;
  15963.           };
  15964.           var mergeStyles = function (node) {
  15965.             var childElement = find$3(node.childNodes, isElementNode).filter(function (child) {
  15966.               return matchName$1(dom, child, format);
  15967.             });
  15968.             return childElement.map(function (child) {
  15969.               var clone = dom.clone(child, false);
  15970.               setElementFormat(clone);
  15971.               dom.replace(clone, node, true);
  15972.               dom.remove(child, true);
  15973.               return clone;
  15974.             }).getOr(node);
  15975.           };
  15976.           var childCount = getChildCount(node);
  15977.           if ((newWrappers.length > 1 || !dom.isBlock(node)) && childCount === 0) {
  15978.             dom.remove(node, true);
  15979.             return;
  15980.           }
  15981.           if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
  15982.             if (!format.exact && childCount === 1) {
  15983.               node = mergeStyles(node);
  15984.             }
  15985.             mergeWithChildren(ed, formatList, vars, node);
  15986.             mergeWithParents(ed, format, name, vars, node);
  15987.             mergeBackgroundColorAndFontSize(dom, format, vars, node);
  15988.             mergeTextDecorationsAndColor(dom, format, vars, node);
  15989.             mergeSubSup(dom, format, vars, node);
  15990.             mergeSiblings(dom, format, vars, node);
  15991.           }
  15992.         });
  15993.       };
  15994.       if (dom.getContentEditable(selection.getNode()) === 'false') {
  15995.         node = selection.getNode();
  15996.         for (var i = 0, l = formatList.length; i < l; i++) {
  15997.           var formatItem = formatList[i];
  15998.           if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom.is(node, formatItem.selector)) {
  15999.             setElementFormat(node, formatItem);
  16000.             break;
  16001.           }
  16002.         }
  16003.         fireFormatApply(ed, name, node, vars);
  16004.         return;
  16005.       }
  16006.       if (format) {
  16007.         if (node) {
  16008.           if (isNode(node)) {
  16009.             if (!applyNodeStyle(formatList, node)) {
  16010.               var rng = dom.createRng();
  16011.               rng.setStartBefore(node);
  16012.               rng.setEndAfter(node);
  16013.               applyRngStyle(dom, expandRng(ed, rng, formatList), true);
  16014.             }
  16015.           } else {
  16016.             applyRngStyle(dom, node, true);
  16017.           }
  16018.         } else {
  16019.           if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
  16020.             var curSelNode = selection.getNode();
  16021.             var firstFormat = formatList[0];
  16022.             if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  16023.               applyFormat$1(ed, firstFormat.defaultBlock);
  16024.             }
  16025.             selection.setRng(normalize(selection.getRng()));
  16026.             preserve(selection, true, function () {
  16027.               runOnRanges(ed, function (selectionRng, fake) {
  16028.                 var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
  16029.                 applyRngStyle(dom, expandedRng, false);
  16030.               });
  16031.             });
  16032.             moveStart(dom, selection, selection.getRng());
  16033.             ed.nodeChanged();
  16034.           } else {
  16035.             applyCaretFormat(ed, name, vars);
  16036.           }
  16037.         }
  16038.         postProcess$1(name, ed);
  16039.       }
  16040.       fireFormatApply(ed, name, node, vars);
  16041.     };
  16042.  
  16043.     var hasVars = function (value) {
  16044.       return has$2(value, 'vars');
  16045.     };
  16046.     var setup$j = function (registeredFormatListeners, editor) {
  16047.       registeredFormatListeners.set({});
  16048.       editor.on('NodeChange', function (e) {
  16049.         updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
  16050.       });
  16051.       editor.on('FormatApply FormatRemove', function (e) {
  16052.         var element = Optional.from(e.node).map(function (nodeOrRange) {
  16053.           return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
  16054.         }).bind(function (node) {
  16055.           return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
  16056.         }).getOrThunk(function () {
  16057.           return fallbackElement(editor);
  16058.         });
  16059.         updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
  16060.       });
  16061.     };
  16062.     var fallbackElement = function (editor) {
  16063.       return editor.selection.getStart();
  16064.     };
  16065.     var matchingNode = function (editor, parents, format, similar, vars) {
  16066.       var isMatchingNode = function (node) {
  16067.         var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
  16068.         return !isUndefined(matchingFormat);
  16069.       };
  16070.       var isUnableToMatch = function (node) {
  16071.         if (matchesUnInheritedFormatSelector(editor, node, format)) {
  16072.           return true;
  16073.         } else {
  16074.           if (!similar) {
  16075.             return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
  16076.           } else {
  16077.             return false;
  16078.           }
  16079.         }
  16080.       };
  16081.       return findUntil$1(parents, isMatchingNode, isUnableToMatch);
  16082.     };
  16083.     var getParents = function (editor, elm) {
  16084.       var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
  16085.       return filter$4(getParents$2(editor.dom, element), function (node) {
  16086.         return isElement$5(node) && !isBogus$2(node);
  16087.       });
  16088.     };
  16089.     var updateAndFireChangeCallbacks = function (editor, elm, registeredCallbacks) {
  16090.       var parents = getParents(editor, elm);
  16091.       each$j(registeredCallbacks, function (data, format) {
  16092.         var runIfChanged = function (spec) {
  16093.           var match = matchingNode(editor, parents, format, spec.similar, hasVars(spec) ? spec.vars : undefined);
  16094.           var isSet = match.isSome();
  16095.           if (spec.state.get() !== isSet) {
  16096.             spec.state.set(isSet);
  16097.             var node_1 = match.getOr(elm);
  16098.             if (hasVars(spec)) {
  16099.               spec.callback(isSet, {
  16100.                 node: node_1,
  16101.                 format: format,
  16102.                 parents: parents
  16103.               });
  16104.             } else {
  16105.               each$k(spec.callbacks, function (callback) {
  16106.                 return callback(isSet, {
  16107.                   node: node_1,
  16108.                   format: format,
  16109.                   parents: parents
  16110.                 });
  16111.               });
  16112.             }
  16113.           }
  16114.         };
  16115.         each$k([
  16116.           data.withSimilar,
  16117.           data.withoutSimilar
  16118.         ], runIfChanged);
  16119.         each$k(data.withVars, runIfChanged);
  16120.       });
  16121.     };
  16122.     var addListeners = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16123.       var formatChangeItems = registeredFormatListeners.get();
  16124.       each$k(formats.split(','), function (format) {
  16125.         var group = get$9(formatChangeItems, format).getOrThunk(function () {
  16126.           var base = {
  16127.             withSimilar: {
  16128.               state: Cell(false),
  16129.               similar: true,
  16130.               callbacks: []
  16131.             },
  16132.             withoutSimilar: {
  16133.               state: Cell(false),
  16134.               similar: false,
  16135.               callbacks: []
  16136.             },
  16137.             withVars: []
  16138.           };
  16139.           formatChangeItems[format] = base;
  16140.           return base;
  16141.         });
  16142.         var getCurrent = function () {
  16143.           var parents = getParents(editor);
  16144.           return matchingNode(editor, parents, format, similar, vars).isSome();
  16145.         };
  16146.         if (isUndefined(vars)) {
  16147.           var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
  16148.           toAppendTo.callbacks.push(callback);
  16149.           if (toAppendTo.callbacks.length === 1) {
  16150.             toAppendTo.state.set(getCurrent());
  16151.           }
  16152.         } else {
  16153.           group.withVars.push({
  16154.             state: Cell(getCurrent()),
  16155.             similar: similar,
  16156.             vars: vars,
  16157.             callback: callback
  16158.           });
  16159.         }
  16160.       });
  16161.       registeredFormatListeners.set(formatChangeItems);
  16162.     };
  16163.     var removeListeners = function (registeredFormatListeners, formats, callback) {
  16164.       var formatChangeItems = registeredFormatListeners.get();
  16165.       each$k(formats.split(','), function (format) {
  16166.         return get$9(formatChangeItems, format).each(function (group) {
  16167.           formatChangeItems[format] = {
  16168.             withSimilar: __assign(__assign({}, group.withSimilar), {
  16169.               callbacks: filter$4(group.withSimilar.callbacks, function (cb) {
  16170.                 return cb !== callback;
  16171.               })
  16172.             }),
  16173.             withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
  16174.               callbacks: filter$4(group.withoutSimilar.callbacks, function (cb) {
  16175.                 return cb !== callback;
  16176.               })
  16177.             }),
  16178.             withVars: filter$4(group.withVars, function (item) {
  16179.               return item.callback !== callback;
  16180.             })
  16181.           };
  16182.         });
  16183.       });
  16184.       registeredFormatListeners.set(formatChangeItems);
  16185.     };
  16186.     var formatChangedInternal = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  16187.       if (registeredFormatListeners.get() === null) {
  16188.         setup$j(registeredFormatListeners, editor);
  16189.       }
  16190.       addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
  16191.       return {
  16192.         unbind: function () {
  16193.           return removeListeners(registeredFormatListeners, formats, callback);
  16194.         }
  16195.       };
  16196.     };
  16197.  
  16198.     var toggle = function (editor, name, vars, node) {
  16199.       var fmt = editor.formatter.get(name);
  16200.       if (match$2(editor, name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  16201.         remove$1(editor, name, vars, node);
  16202.       } else {
  16203.         applyFormat$1(editor, name, vars, node);
  16204.       }
  16205.     };
  16206.  
  16207.     var fromElements = function (elements, scope) {
  16208.       var doc = scope || document;
  16209.       var fragment = doc.createDocumentFragment();
  16210.       each$k(elements, function (element) {
  16211.         fragment.appendChild(element.dom);
  16212.       });
  16213.       return SugarElement.fromDom(fragment);
  16214.     };
  16215.  
  16216.     var tableModel = function (element, width, rows) {
  16217.       return {
  16218.         element: element,
  16219.         width: width,
  16220.         rows: rows
  16221.       };
  16222.     };
  16223.     var tableRow = function (element, cells) {
  16224.       return {
  16225.         element: element,
  16226.         cells: cells
  16227.       };
  16228.     };
  16229.     var cellPosition = function (x, y) {
  16230.       return {
  16231.         x: x,
  16232.         y: y
  16233.       };
  16234.     };
  16235.     var getSpan = function (td, key) {
  16236.       var value = parseInt(get$6(td, key), 10);
  16237.       return isNaN(value) ? 1 : value;
  16238.     };
  16239.     var fillout = function (table, x, y, tr, td) {
  16240.       var rowspan = getSpan(td, 'rowspan');
  16241.       var colspan = getSpan(td, 'colspan');
  16242.       var rows = table.rows;
  16243.       for (var y2 = y; y2 < y + rowspan; y2++) {
  16244.         if (!rows[y2]) {
  16245.           rows[y2] = tableRow(deep$1(tr), []);
  16246.         }
  16247.         for (var x2 = x; x2 < x + colspan; x2++) {
  16248.           var cells = rows[y2].cells;
  16249.           cells[x2] = y2 === y && x2 === x ? td : shallow(td);
  16250.         }
  16251.       }
  16252.     };
  16253.     var cellExists = function (table, x, y) {
  16254.       var rows = table.rows;
  16255.       var cells = rows[y] ? rows[y].cells : [];
  16256.       return !!cells[x];
  16257.     };
  16258.     var skipCellsX = function (table, x, y) {
  16259.       while (cellExists(table, x, y)) {
  16260.         x++;
  16261.       }
  16262.       return x;
  16263.     };
  16264.     var getWidth = function (rows) {
  16265.       return foldl(rows, function (acc, row) {
  16266.         return row.cells.length > acc ? row.cells.length : acc;
  16267.       }, 0);
  16268.     };
  16269.     var findElementPos = function (table, element) {
  16270.       var rows = table.rows;
  16271.       for (var y = 0; y < rows.length; y++) {
  16272.         var cells = rows[y].cells;
  16273.         for (var x = 0; x < cells.length; x++) {
  16274.           if (eq(cells[x], element)) {
  16275.             return Optional.some(cellPosition(x, y));
  16276.           }
  16277.         }
  16278.       }
  16279.       return Optional.none();
  16280.     };
  16281.     var extractRows = function (table, sx, sy, ex, ey) {
  16282.       var newRows = [];
  16283.       var rows = table.rows;
  16284.       for (var y = sy; y <= ey; y++) {
  16285.         var cells = rows[y].cells;
  16286.         var slice = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
  16287.         newRows.push(tableRow(rows[y].element, slice));
  16288.       }
  16289.       return newRows;
  16290.     };
  16291.     var subTable = function (table, startPos, endPos) {
  16292.       var sx = startPos.x, sy = startPos.y;
  16293.       var ex = endPos.x, ey = endPos.y;
  16294.       var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
  16295.       return tableModel(table.element, getWidth(newRows), newRows);
  16296.     };
  16297.     var createDomTable = function (table, rows) {
  16298.       var tableElement = shallow(table.element);
  16299.       var tableBody = SugarElement.fromTag('tbody');
  16300.       append(tableBody, rows);
  16301.       append$1(tableElement, tableBody);
  16302.       return tableElement;
  16303.     };
  16304.     var modelRowsToDomRows = function (table) {
  16305.       return map$3(table.rows, function (row) {
  16306.         var cells = map$3(row.cells, function (cell) {
  16307.           var td = deep$1(cell);
  16308.           remove$6(td, 'colspan');
  16309.           remove$6(td, 'rowspan');
  16310.           return td;
  16311.         });
  16312.         var tr = shallow(row.element);
  16313.         append(tr, cells);
  16314.         return tr;
  16315.       });
  16316.     };
  16317.     var fromDom = function (tableElm) {
  16318.       var table = tableModel(shallow(tableElm), 0, []);
  16319.       each$k(descendants(tableElm, 'tr'), function (tr, y) {
  16320.         each$k(descendants(tr, 'td,th'), function (td, x) {
  16321.           fillout(table, skipCellsX(table, x, y), y, tr, td);
  16322.         });
  16323.       });
  16324.       return tableModel(table.element, getWidth(table.rows), table.rows);
  16325.     };
  16326.     var toDom = function (table) {
  16327.       return createDomTable(table, modelRowsToDomRows(table));
  16328.     };
  16329.     var subsection = function (table, startElement, endElement) {
  16330.       return findElementPos(table, startElement).bind(function (startPos) {
  16331.         return findElementPos(table, endElement).map(function (endPos) {
  16332.           return subTable(table, startPos, endPos);
  16333.         });
  16334.       });
  16335.     };
  16336.  
  16337.     var findParentListContainer = function (parents) {
  16338.       return find$3(parents, function (elm) {
  16339.         return name(elm) === 'ul' || name(elm) === 'ol';
  16340.       });
  16341.     };
  16342.     var getFullySelectedListWrappers = function (parents, rng) {
  16343.       return find$3(parents, function (elm) {
  16344.         return name(elm) === 'li' && hasAllContentsSelected(elm, rng);
  16345.       }).fold(constant([]), function (_li) {
  16346.         return findParentListContainer(parents).map(function (listCont) {
  16347.           var listElm = SugarElement.fromTag(name(listCont));
  16348.           var listStyles = filter$3(getAllRaw(listCont), function (_style, name) {
  16349.             return startsWith(name, 'list-style');
  16350.           });
  16351.           setAll(listElm, listStyles);
  16352.           return [
  16353.             SugarElement.fromTag('li'),
  16354.             listElm
  16355.           ];
  16356.         }).getOr([]);
  16357.       });
  16358.     };
  16359.     var wrap = function (innerElm, elms) {
  16360.       var wrapped = foldl(elms, function (acc, elm) {
  16361.         append$1(elm, acc);
  16362.         return elm;
  16363.       }, innerElm);
  16364.       return elms.length > 0 ? fromElements([wrapped]) : wrapped;
  16365.     };
  16366.     var directListWrappers = function (commonAnchorContainer) {
  16367.       if (isListItem(commonAnchorContainer)) {
  16368.         return parent(commonAnchorContainer).filter(isList).fold(constant([]), function (listElm) {
  16369.           return [
  16370.             commonAnchorContainer,
  16371.             listElm
  16372.           ];
  16373.         });
  16374.       } else {
  16375.         return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
  16376.       }
  16377.     };
  16378.     var getWrapElements = function (rootNode, rng) {
  16379.       var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
  16380.       var parents = parentsAndSelf(commonAnchorContainer, rootNode);
  16381.       var wrapElements = filter$4(parents, function (elm) {
  16382.         return isInline$1(elm) || isHeading(elm);
  16383.       });
  16384.       var listWrappers = getFullySelectedListWrappers(parents, rng);
  16385.       var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
  16386.       return map$3(allWrappers, shallow);
  16387.     };
  16388.     var emptyFragment = function () {
  16389.       return fromElements([]);
  16390.     };
  16391.     var getFragmentFromRange = function (rootNode, rng) {
  16392.       return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
  16393.     };
  16394.     var getParentTable = function (rootElm, cell) {
  16395.       return ancestor$2(cell, 'table', curry(eq, rootElm));
  16396.     };
  16397.     var getTableFragment = function (rootNode, selectedTableCells) {
  16398.       return getParentTable(rootNode, selectedTableCells[0]).bind(function (tableElm) {
  16399.         var firstCell = selectedTableCells[0];
  16400.         var lastCell = selectedTableCells[selectedTableCells.length - 1];
  16401.         var fullTableModel = fromDom(tableElm);
  16402.         return subsection(fullTableModel, firstCell, lastCell).map(function (sectionedTableModel) {
  16403.           return fromElements([toDom(sectionedTableModel)]);
  16404.         });
  16405.       }).getOrThunk(emptyFragment);
  16406.     };
  16407.     var getSelectionFragment = function (rootNode, ranges) {
  16408.       return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
  16409.     };
  16410.     var read$3 = function (rootNode, ranges) {
  16411.       var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
  16412.       return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
  16413.     };
  16414.  
  16415.     var trimLeadingCollapsibleText = function (text) {
  16416.       return text.replace(/^[ \f\n\r\t\v]+/, '');
  16417.     };
  16418.     var isCollapsibleWhitespace = function (text, index) {
  16419.       return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
  16420.     };
  16421.     var getInnerText = function (bin, shouldTrim) {
  16422.       var text = trim$3(bin.innerText);
  16423.       return shouldTrim ? trimLeadingCollapsibleText(text) : text;
  16424.     };
  16425.     var getContextNodeName = function (parentBlockOpt) {
  16426.       return parentBlockOpt.map(function (block) {
  16427.         return block.nodeName;
  16428.       }).getOr('div').toLowerCase();
  16429.     };
  16430.     var getTextContent = function (editor) {
  16431.       return Optional.from(editor.selection.getRng()).map(function (rng) {
  16432.         var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
  16433.         var body = editor.getBody();
  16434.         var contextNodeName = getContextNodeName(parentBlockOpt);
  16435.         var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== 'pre';
  16436.         var bin = editor.dom.add(body, contextNodeName, {
  16437.           'data-mce-bogus': 'all',
  16438.           'style': 'overflow: hidden; opacity: 0;'
  16439.         }, rng.cloneContents());
  16440.         var text = getInnerText(bin, shouldTrimSpaces);
  16441.         var nonRenderedText = trim$3(bin.textContent);
  16442.         editor.dom.remove(bin);
  16443.         if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
  16444.           var parentBlock = parentBlockOpt.getOr(body);
  16445.           var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
  16446.           var textIndex = parentBlockText.indexOf(text);
  16447.           if (textIndex === -1) {
  16448.             return text;
  16449.           } else {
  16450.             var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
  16451.             var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
  16452.             return (hasProceedingSpace ? ' ' : '') + text + (hasTrailingSpace ? ' ' : '');
  16453.           }
  16454.         } else {
  16455.           return text;
  16456.         }
  16457.       }).getOr('');
  16458.     };
  16459.     var getSerializedContent = function (editor, args) {
  16460.       var rng = editor.selection.getRng(), tmpElm = editor.dom.create('body');
  16461.       var sel = editor.selection.getSel();
  16462.       var ranges = processRanges(editor, getRanges(sel));
  16463.       var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
  16464.       if (fragment) {
  16465.         tmpElm.appendChild(fragment);
  16466.       }
  16467.       return editor.selection.serializer.serialize(tmpElm, args);
  16468.     };
  16469.     var setupArgs$1 = function (args, format) {
  16470.       return __assign(__assign({}, args), {
  16471.         format: format,
  16472.         get: true,
  16473.         selection: true
  16474.       });
  16475.     };
  16476.     var getSelectedContentInternal = function (editor, format, args) {
  16477.       if (args === void 0) {
  16478.         args = {};
  16479.       }
  16480.       var defaultedArgs = setupArgs$1(args, format);
  16481.       var updatedArgs = editor.fire('BeforeGetContent', defaultedArgs);
  16482.       if (updatedArgs.isDefaultPrevented()) {
  16483.         editor.fire('GetContent', updatedArgs);
  16484.         return updatedArgs.content;
  16485.       }
  16486.       if (updatedArgs.format === 'text') {
  16487.         return getTextContent(editor);
  16488.       } else {
  16489.         updatedArgs.getInner = true;
  16490.         var content = getSerializedContent(editor, updatedArgs);
  16491.         if (updatedArgs.format === 'tree') {
  16492.           return content;
  16493.         } else {
  16494.           updatedArgs.content = editor.selection.isCollapsed() ? '' : content;
  16495.           editor.fire('GetContent', updatedArgs);
  16496.           return updatedArgs.content;
  16497.         }
  16498.       }
  16499.     };
  16500.  
  16501.     var KEEP = 0, INSERT = 1, DELETE = 2;
  16502.     var diff = function (left, right) {
  16503.       var size = left.length + right.length + 2;
  16504.       var vDown = new Array(size);
  16505.       var vUp = new Array(size);
  16506.       var snake = function (start, end, diag) {
  16507.         return {
  16508.           start: start,
  16509.           end: end,
  16510.           diag: diag
  16511.         };
  16512.       };
  16513.       var buildScript = function (start1, end1, start2, end2, script) {
  16514.         var middle = getMiddleSnake(start1, end1, start2, end2);
  16515.         if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
  16516.           var i = start1;
  16517.           var j = start2;
  16518.           while (i < end1 || j < end2) {
  16519.             if (i < end1 && j < end2 && left[i] === right[j]) {
  16520.               script.push([
  16521.                 KEEP,
  16522.                 left[i]
  16523.               ]);
  16524.               ++i;
  16525.               ++j;
  16526.             } else {
  16527.               if (end1 - start1 > end2 - start2) {
  16528.                 script.push([
  16529.                   DELETE,
  16530.                   left[i]
  16531.                 ]);
  16532.                 ++i;
  16533.               } else {
  16534.                 script.push([
  16535.                   INSERT,
  16536.                   right[j]
  16537.                 ]);
  16538.                 ++j;
  16539.               }
  16540.             }
  16541.           }
  16542.         } else {
  16543.           buildScript(start1, middle.start, start2, middle.start - middle.diag, script);
  16544.           for (var i2 = middle.start; i2 < middle.end; ++i2) {
  16545.             script.push([
  16546.               KEEP,
  16547.               left[i2]
  16548.             ]);
  16549.           }
  16550.           buildScript(middle.end, end1, middle.end - middle.diag, end2, script);
  16551.         }
  16552.       };
  16553.       var buildSnake = function (start, diag, end1, end2) {
  16554.         var end = start;
  16555.         while (end - diag < end2 && end < end1 && left[end] === right[end - diag]) {
  16556.           ++end;
  16557.         }
  16558.         return snake(start, end, diag);
  16559.       };
  16560.       var getMiddleSnake = function (start1, end1, start2, end2) {
  16561.         var m = end1 - start1;
  16562.         var n = end2 - start2;
  16563.         if (m === 0 || n === 0) {
  16564.           return null;
  16565.         }
  16566.         var delta = m - n;
  16567.         var sum = n + m;
  16568.         var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
  16569.         vDown[1 + offset] = start1;
  16570.         vUp[1 + offset] = end1 + 1;
  16571.         var d, k, i, x, y;
  16572.         for (d = 0; d <= offset; ++d) {
  16573.           for (k = -d; k <= d; k += 2) {
  16574.             i = k + offset;
  16575.             if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
  16576.               vDown[i] = vDown[i + 1];
  16577.             } else {
  16578.               vDown[i] = vDown[i - 1] + 1;
  16579.             }
  16580.             x = vDown[i];
  16581.             y = x - start1 + start2 - k;
  16582.             while (x < end1 && y < end2 && left[x] === right[y]) {
  16583.               vDown[i] = ++x;
  16584.               ++y;
  16585.             }
  16586.             if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
  16587.               if (vUp[i - delta] <= vDown[i]) {
  16588.                 return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
  16589.               }
  16590.             }
  16591.           }
  16592.           for (k = delta - d; k <= delta + d; k += 2) {
  16593.             i = k + offset - delta;
  16594.             if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
  16595.               vUp[i] = vUp[i + 1] - 1;
  16596.             } else {
  16597.               vUp[i] = vUp[i - 1];
  16598.             }
  16599.             x = vUp[i] - 1;
  16600.             y = x - start1 + start2 - k;
  16601.             while (x >= start1 && y >= start2 && left[x] === right[y]) {
  16602.               vUp[i] = x--;
  16603.               y--;
  16604.             }
  16605.             if (delta % 2 === 0 && -d <= k && k <= d) {
  16606.               if (vUp[i] <= vDown[i + delta]) {
  16607.                 return buildSnake(vUp[i], k + start1 - start2, end1, end2);
  16608.               }
  16609.             }
  16610.           }
  16611.         }
  16612.       };
  16613.       var script = [];
  16614.       buildScript(0, left.length, 0, right.length, script);
  16615.       return script;
  16616.     };
  16617.  
  16618.     var getOuterHtml = function (elm) {
  16619.       if (isElement$5(elm)) {
  16620.         return elm.outerHTML;
  16621.       } else if (isText$7(elm)) {
  16622.         return Entities.encodeRaw(elm.data, false);
  16623.       } else if (isComment(elm)) {
  16624.         return '<!--' + elm.data + '-->';
  16625.       }
  16626.       return '';
  16627.     };
  16628.     var createFragment = function (html) {
  16629.       var node;
  16630.       var container = document.createElement('div');
  16631.       var frag = document.createDocumentFragment();
  16632.       if (html) {
  16633.         container.innerHTML = html;
  16634.       }
  16635.       while (node = container.firstChild) {
  16636.         frag.appendChild(node);
  16637.       }
  16638.       return frag;
  16639.     };
  16640.     var insertAt = function (elm, html, index) {
  16641.       var fragment = createFragment(html);
  16642.       if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16643.         var target = elm.childNodes[index];
  16644.         target.parentNode.insertBefore(fragment, target);
  16645.       } else {
  16646.         elm.appendChild(fragment);
  16647.       }
  16648.     };
  16649.     var removeAt = function (elm, index) {
  16650.       if (elm.hasChildNodes() && index < elm.childNodes.length) {
  16651.         var target = elm.childNodes[index];
  16652.         target.parentNode.removeChild(target);
  16653.       }
  16654.     };
  16655.     var applyDiff = function (diff, elm) {
  16656.       var index = 0;
  16657.       each$k(diff, function (action) {
  16658.         if (action[0] === KEEP) {
  16659.           index++;
  16660.         } else if (action[0] === INSERT) {
  16661.           insertAt(elm, action[1], index);
  16662.           index++;
  16663.         } else if (action[0] === DELETE) {
  16664.           removeAt(elm, index);
  16665.         }
  16666.       });
  16667.     };
  16668.     var read$2 = function (elm, trimZwsp) {
  16669.       return filter$4(map$3(from(elm.childNodes), trimZwsp ? compose(trim$3, getOuterHtml) : getOuterHtml), function (item) {
  16670.         return item.length > 0;
  16671.       });
  16672.     };
  16673.     var write = function (fragments, elm) {
  16674.       var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
  16675.       applyDiff(diff(currentFragments, fragments), elm);
  16676.       return elm;
  16677.     };
  16678.  
  16679.     var lazyTempDocument$1 = cached(function () {
  16680.       return document.implementation.createHTMLDocument('undo');
  16681.     });
  16682.     var hasIframes = function (body) {
  16683.       return body.querySelector('iframe') !== null;
  16684.     };
  16685.     var createFragmentedLevel = function (fragments) {
  16686.       return {
  16687.         type: 'fragmented',
  16688.         fragments: fragments,
  16689.         content: '',
  16690.         bookmark: null,
  16691.         beforeBookmark: null
  16692.       };
  16693.     };
  16694.     var createCompleteLevel = function (content) {
  16695.       return {
  16696.         type: 'complete',
  16697.         fragments: null,
  16698.         content: content,
  16699.         bookmark: null,
  16700.         beforeBookmark: null
  16701.       };
  16702.     };
  16703.     var createFromEditor = function (editor) {
  16704.       var tempAttrs = editor.serializer.getTempAttrs();
  16705.       var body = trim$1(editor.getBody(), tempAttrs);
  16706.       return hasIframes(body) ? createFragmentedLevel(read$2(body, true)) : createCompleteLevel(trim$3(body.innerHTML));
  16707.     };
  16708.     var applyToEditor = function (editor, level, before) {
  16709.       var bookmark = before ? level.beforeBookmark : level.bookmark;
  16710.       if (level.type === 'fragmented') {
  16711.         write(level.fragments, editor.getBody());
  16712.       } else {
  16713.         editor.setContent(level.content, {
  16714.           format: 'raw',
  16715.           no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
  16716.         });
  16717.       }
  16718.       editor.selection.moveToBookmark(bookmark);
  16719.     };
  16720.     var getLevelContent = function (level) {
  16721.       return level.type === 'fragmented' ? level.fragments.join('') : level.content;
  16722.     };
  16723.     var getCleanLevelContent = function (level) {
  16724.       var elm = SugarElement.fromTag('body', lazyTempDocument$1());
  16725.       set(elm, getLevelContent(level));
  16726.       each$k(descendants(elm, '*[data-mce-bogus]'), unwrap);
  16727.       return get$3(elm);
  16728.     };
  16729.     var hasEqualContent = function (level1, level2) {
  16730.       return getLevelContent(level1) === getLevelContent(level2);
  16731.     };
  16732.     var hasEqualCleanedContent = function (level1, level2) {
  16733.       return getCleanLevelContent(level1) === getCleanLevelContent(level2);
  16734.     };
  16735.     var isEq$1 = function (level1, level2) {
  16736.       if (!level1 || !level2) {
  16737.         return false;
  16738.       } else if (hasEqualContent(level1, level2)) {
  16739.         return true;
  16740.       } else {
  16741.         return hasEqualCleanedContent(level1, level2);
  16742.       }
  16743.     };
  16744.  
  16745.     var isUnlocked = function (locks) {
  16746.       return locks.get() === 0;
  16747.     };
  16748.  
  16749.     var setTyping = function (undoManager, typing, locks) {
  16750.       if (isUnlocked(locks)) {
  16751.         undoManager.typing = typing;
  16752.       }
  16753.     };
  16754.     var endTyping = function (undoManager, locks) {
  16755.       if (undoManager.typing) {
  16756.         setTyping(undoManager, false, locks);
  16757.         undoManager.add();
  16758.       }
  16759.     };
  16760.     var endTypingLevelIgnoreLocks = function (undoManager) {
  16761.       if (undoManager.typing) {
  16762.         undoManager.typing = false;
  16763.         undoManager.add();
  16764.       }
  16765.     };
  16766.  
  16767.     var beforeChange$1 = function (editor, locks, beforeBookmark) {
  16768.       if (isUnlocked(locks)) {
  16769.         beforeBookmark.set(getUndoBookmark(editor.selection));
  16770.       }
  16771.     };
  16772.     var addUndoLevel$1 = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  16773.       var currentLevel = createFromEditor(editor);
  16774.       level = level || {};
  16775.       level = Tools.extend(level, currentLevel);
  16776.       if (isUnlocked(locks) === false || editor.removed) {
  16777.         return null;
  16778.       }
  16779.       var lastLevel = undoManager.data[index.get()];
  16780.       if (editor.fire('BeforeAddUndo', {
  16781.           level: level,
  16782.           lastLevel: lastLevel,
  16783.           originalEvent: event
  16784.         }).isDefaultPrevented()) {
  16785.         return null;
  16786.       }
  16787.       if (lastLevel && isEq$1(lastLevel, level)) {
  16788.         return null;
  16789.       }
  16790.       if (undoManager.data[index.get()]) {
  16791.         beforeBookmark.get().each(function (bm) {
  16792.           undoManager.data[index.get()].beforeBookmark = bm;
  16793.         });
  16794.       }
  16795.       var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
  16796.       if (customUndoRedoLevels) {
  16797.         if (undoManager.data.length > customUndoRedoLevels) {
  16798.           for (var i = 0; i < undoManager.data.length - 1; i++) {
  16799.             undoManager.data[i] = undoManager.data[i + 1];
  16800.           }
  16801.           undoManager.data.length--;
  16802.           index.set(undoManager.data.length);
  16803.         }
  16804.       }
  16805.       level.bookmark = getUndoBookmark(editor.selection);
  16806.       if (index.get() < undoManager.data.length - 1) {
  16807.         undoManager.data.length = index.get() + 1;
  16808.       }
  16809.       undoManager.data.push(level);
  16810.       index.set(undoManager.data.length - 1);
  16811.       var args = {
  16812.         level: level,
  16813.         lastLevel: lastLevel,
  16814.         originalEvent: event
  16815.       };
  16816.       if (index.get() > 0) {
  16817.         editor.setDirty(true);
  16818.         editor.fire('AddUndo', args);
  16819.         editor.fire('change', args);
  16820.       } else {
  16821.         editor.fire('AddUndo', args);
  16822.       }
  16823.       return level;
  16824.     };
  16825.     var clear$1 = function (editor, undoManager, index) {
  16826.       undoManager.data = [];
  16827.       index.set(0);
  16828.       undoManager.typing = false;
  16829.       editor.fire('ClearUndos');
  16830.     };
  16831.     var extra$1 = function (editor, undoManager, index, callback1, callback2) {
  16832.       if (undoManager.transact(callback1)) {
  16833.         var bookmark = undoManager.data[index.get()].bookmark;
  16834.         var lastLevel = undoManager.data[index.get() - 1];
  16835.         applyToEditor(editor, lastLevel, true);
  16836.         if (undoManager.transact(callback2)) {
  16837.           undoManager.data[index.get() - 1].beforeBookmark = bookmark;
  16838.         }
  16839.       }
  16840.     };
  16841.     var redo$1 = function (editor, index, data) {
  16842.       var level;
  16843.       if (index.get() < data.length - 1) {
  16844.         index.set(index.get() + 1);
  16845.         level = data[index.get()];
  16846.         applyToEditor(editor, level, false);
  16847.         editor.setDirty(true);
  16848.         editor.fire('Redo', { level: level });
  16849.       }
  16850.       return level;
  16851.     };
  16852.     var undo$1 = function (editor, undoManager, locks, index) {
  16853.       var level;
  16854.       if (undoManager.typing) {
  16855.         undoManager.add();
  16856.         undoManager.typing = false;
  16857.         setTyping(undoManager, false, locks);
  16858.       }
  16859.       if (index.get() > 0) {
  16860.         index.set(index.get() - 1);
  16861.         level = undoManager.data[index.get()];
  16862.         applyToEditor(editor, level, true);
  16863.         editor.setDirty(true);
  16864.         editor.fire('Undo', { level: level });
  16865.       }
  16866.       return level;
  16867.     };
  16868.     var reset$1 = function (undoManager) {
  16869.       undoManager.clear();
  16870.       undoManager.add();
  16871.     };
  16872.     var hasUndo$1 = function (editor, undoManager, index) {
  16873.       return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
  16874.     };
  16875.     var hasRedo$1 = function (undoManager, index) {
  16876.       return index.get() < undoManager.data.length - 1 && !undoManager.typing;
  16877.     };
  16878.     var transact$1 = function (undoManager, locks, callback) {
  16879.       endTyping(undoManager, locks);
  16880.       undoManager.beforeChange();
  16881.       undoManager.ignore(callback);
  16882.       return undoManager.add();
  16883.     };
  16884.     var ignore$1 = function (locks, callback) {
  16885.       try {
  16886.         locks.set(locks.get() + 1);
  16887.         callback();
  16888.       } finally {
  16889.         locks.set(locks.get() - 1);
  16890.       }
  16891.     };
  16892.  
  16893.     var addVisualInternal = function (editor, elm) {
  16894.       var dom = editor.dom;
  16895.       var scope = isNonNullable(elm) ? elm : editor.getBody();
  16896.       if (isUndefined(editor.hasVisual)) {
  16897.         editor.hasVisual = isVisualAidsEnabled(editor);
  16898.       }
  16899.       each$k(dom.select('table,a', scope), function (matchedElm) {
  16900.         switch (matchedElm.nodeName) {
  16901.         case 'TABLE':
  16902.           var cls = getVisualAidsTableClass(editor);
  16903.           var value = dom.getAttrib(matchedElm, 'border');
  16904.           if ((!value || value === '0') && editor.hasVisual) {
  16905.             dom.addClass(matchedElm, cls);
  16906.           } else {
  16907.             dom.removeClass(matchedElm, cls);
  16908.           }
  16909.           break;
  16910.         case 'A':
  16911.           if (!dom.getAttrib(matchedElm, 'href')) {
  16912.             var value_1 = dom.getAttrib(matchedElm, 'name') || matchedElm.id;
  16913.             var cls_1 = getVisualAidsAnchorClass(editor);
  16914.             if (value_1 && editor.hasVisual) {
  16915.               dom.addClass(matchedElm, cls_1);
  16916.             } else {
  16917.               dom.removeClass(matchedElm, cls_1);
  16918.             }
  16919.           }
  16920.           break;
  16921.         }
  16922.       });
  16923.       editor.fire('VisualAid', {
  16924.         element: elm,
  16925.         hasVisual: editor.hasVisual
  16926.       });
  16927.     };
  16928.  
  16929.     var makePlainAdaptor = function (editor) {
  16930.       return {
  16931.         undoManager: {
  16932.           beforeChange: function (locks, beforeBookmark) {
  16933.             return beforeChange$1(editor, locks, beforeBookmark);
  16934.           },
  16935.           add: function (undoManager, index, locks, beforeBookmark, level, event) {
  16936.             return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
  16937.           },
  16938.           undo: function (undoManager, locks, index) {
  16939.             return undo$1(editor, undoManager, locks, index);
  16940.           },
  16941.           redo: function (index, data) {
  16942.             return redo$1(editor, index, data);
  16943.           },
  16944.           clear: function (undoManager, index) {
  16945.             return clear$1(editor, undoManager, index);
  16946.           },
  16947.           reset: function (undoManager) {
  16948.             return reset$1(undoManager);
  16949.           },
  16950.           hasUndo: function (undoManager, index) {
  16951.             return hasUndo$1(editor, undoManager, index);
  16952.           },
  16953.           hasRedo: function (undoManager, index) {
  16954.             return hasRedo$1(undoManager, index);
  16955.           },
  16956.           transact: function (undoManager, locks, callback) {
  16957.             return transact$1(undoManager, locks, callback);
  16958.           },
  16959.           ignore: function (locks, callback) {
  16960.             return ignore$1(locks, callback);
  16961.           },
  16962.           extra: function (undoManager, index, callback1, callback2) {
  16963.             return extra$1(editor, undoManager, index, callback1, callback2);
  16964.           }
  16965.         },
  16966.         formatter: {
  16967.           match: function (name, vars, node, similar) {
  16968.             return match$2(editor, name, vars, node, similar);
  16969.           },
  16970.           matchAll: function (names, vars) {
  16971.             return matchAll(editor, names, vars);
  16972.           },
  16973.           matchNode: function (node, name, vars, similar) {
  16974.             return matchNode(editor, node, name, vars, similar);
  16975.           },
  16976.           canApply: function (name) {
  16977.             return canApply(editor, name);
  16978.           },
  16979.           closest: function (names) {
  16980.             return closest(editor, names);
  16981.           },
  16982.           apply: function (name, vars, node) {
  16983.             return applyFormat$1(editor, name, vars, node);
  16984.           },
  16985.           remove: function (name, vars, node, similar) {
  16986.             return remove$1(editor, name, vars, node, similar);
  16987.           },
  16988.           toggle: function (name, vars, node) {
  16989.             return toggle(editor, name, vars, node);
  16990.           },
  16991.           formatChanged: function (registeredFormatListeners, formats, callback, similar, vars) {
  16992.             return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
  16993.           }
  16994.         },
  16995.         editor: {
  16996.           getContent: function (args, format) {
  16997.             return getContentInternal(editor, args, format);
  16998.           },
  16999.           setContent: function (content, args) {
  17000.             return setContentInternal(editor, content, args);
  17001.           },
  17002.           insertContent: function (value, details) {
  17003.             return insertHtmlAtCaret(editor, value, details);
  17004.           },
  17005.           addVisual: function (elm) {
  17006.             return addVisualInternal(editor, elm);
  17007.           }
  17008.         },
  17009.         selection: {
  17010.           getContent: function (format, args) {
  17011.             return getSelectedContentInternal(editor, format, args);
  17012.           }
  17013.         },
  17014.         raw: {
  17015.           getModel: function () {
  17016.             return Optional.none();
  17017.           }
  17018.         }
  17019.       };
  17020.     };
  17021.     var makeRtcAdaptor = function (rtcEditor) {
  17022.       var defaultVars = function (vars) {
  17023.         return isObject(vars) ? vars : {};
  17024.       };
  17025.       var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
  17026.       return {
  17027.         undoManager: {
  17028.           beforeChange: undoManager.beforeChange,
  17029.           add: undoManager.add,
  17030.           undo: undoManager.undo,
  17031.           redo: undoManager.redo,
  17032.           clear: undoManager.clear,
  17033.           reset: undoManager.reset,
  17034.           hasUndo: undoManager.hasUndo,
  17035.           hasRedo: undoManager.hasRedo,
  17036.           transact: function (_undoManager, _locks, fn) {
  17037.             return undoManager.transact(fn);
  17038.           },
  17039.           ignore: function (_locks, callback) {
  17040.             return undoManager.ignore(callback);
  17041.           },
  17042.           extra: function (_undoManager, _index, callback1, callback2) {
  17043.             return undoManager.extra(callback1, callback2);
  17044.           }
  17045.         },
  17046.         formatter: {
  17047.           match: function (name, vars, _node, similar) {
  17048.             return formatter.match(name, defaultVars(vars), similar);
  17049.           },
  17050.           matchAll: formatter.matchAll,
  17051.           matchNode: formatter.matchNode,
  17052.           canApply: function (name) {
  17053.             return formatter.canApply(name);
  17054.           },
  17055.           closest: function (names) {
  17056.             return formatter.closest(names);
  17057.           },
  17058.           apply: function (name, vars, _node) {
  17059.             return formatter.apply(name, defaultVars(vars));
  17060.           },
  17061.           remove: function (name, vars, _node, _similar) {
  17062.             return formatter.remove(name, defaultVars(vars));
  17063.           },
  17064.           toggle: function (name, vars, _node) {
  17065.             return formatter.toggle(name, defaultVars(vars));
  17066.           },
  17067.           formatChanged: function (_rfl, formats, callback, similar, vars) {
  17068.             return formatter.formatChanged(formats, callback, similar, vars);
  17069.           }
  17070.         },
  17071.         editor: {
  17072.           getContent: function (args, _format) {
  17073.             return editor.getContent(args);
  17074.           },
  17075.           setContent: function (content, args) {
  17076.             return editor.setContent(content, args);
  17077.           },
  17078.           insertContent: function (content, _details) {
  17079.             return editor.insertContent(content);
  17080.           },
  17081.           addVisual: editor.addVisual
  17082.         },
  17083.         selection: {
  17084.           getContent: function (_format, args) {
  17085.             return selection.getContent(args);
  17086.           }
  17087.         },
  17088.         raw: {
  17089.           getModel: function () {
  17090.             return Optional.some(raw.getRawModel());
  17091.           }
  17092.         }
  17093.       };
  17094.     };
  17095.     var makeNoopAdaptor = function () {
  17096.       var nul = constant(null);
  17097.       var empty = constant('');
  17098.       return {
  17099.         undoManager: {
  17100.           beforeChange: noop,
  17101.           add: nul,
  17102.           undo: nul,
  17103.           redo: nul,
  17104.           clear: noop,
  17105.           reset: noop,
  17106.           hasUndo: never,
  17107.           hasRedo: never,
  17108.           transact: nul,
  17109.           ignore: noop,
  17110.           extra: noop
  17111.         },
  17112.         formatter: {
  17113.           match: never,
  17114.           matchAll: constant([]),
  17115.           matchNode: constant(undefined),
  17116.           canApply: never,
  17117.           closest: empty,
  17118.           apply: noop,
  17119.           remove: noop,
  17120.           toggle: noop,
  17121.           formatChanged: constant({ unbind: noop })
  17122.         },
  17123.         editor: {
  17124.           getContent: empty,
  17125.           setContent: empty,
  17126.           insertContent: noop,
  17127.           addVisual: noop
  17128.         },
  17129.         selection: { getContent: empty },
  17130.         raw: { getModel: constant(Optional.none()) }
  17131.       };
  17132.     };
  17133.     var isRtc = function (editor) {
  17134.       return has$2(editor.plugins, 'rtc');
  17135.     };
  17136.     var getRtcSetup = function (editor) {
  17137.       return get$9(editor.plugins, 'rtc').bind(function (rtcPlugin) {
  17138.         return Optional.from(rtcPlugin.setup);
  17139.       });
  17140.     };
  17141.     var setup$i = function (editor) {
  17142.       var editorCast = editor;
  17143.       return getRtcSetup(editor).fold(function () {
  17144.         editorCast.rtcInstance = makePlainAdaptor(editor);
  17145.         return Optional.none();
  17146.       }, function (setup) {
  17147.         editorCast.rtcInstance = makeNoopAdaptor();
  17148.         return Optional.some(function () {
  17149.           return setup().then(function (rtcEditor) {
  17150.             editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
  17151.             return rtcEditor.rtc.isRemote;
  17152.           });
  17153.         });
  17154.       });
  17155.     };
  17156.     var getRtcInstanceWithFallback = function (editor) {
  17157.       return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
  17158.     };
  17159.     var getRtcInstanceWithError = function (editor) {
  17160.       var rtcInstance = editor.rtcInstance;
  17161.       if (!rtcInstance) {
  17162.         throw new Error('Failed to get RTC instance not yet initialized.');
  17163.       } else {
  17164.         return rtcInstance;
  17165.       }
  17166.     };
  17167.     var beforeChange = function (editor, locks, beforeBookmark) {
  17168.       getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
  17169.     };
  17170.     var addUndoLevel = function (editor, undoManager, index, locks, beforeBookmark, level, event) {
  17171.       return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
  17172.     };
  17173.     var undo = function (editor, undoManager, locks, index) {
  17174.       return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
  17175.     };
  17176.     var redo = function (editor, index, data) {
  17177.       return getRtcInstanceWithError(editor).undoManager.redo(index, data);
  17178.     };
  17179.     var clear = function (editor, undoManager, index) {
  17180.       getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
  17181.     };
  17182.     var reset = function (editor, undoManager) {
  17183.       getRtcInstanceWithError(editor).undoManager.reset(undoManager);
  17184.     };
  17185.     var hasUndo = function (editor, undoManager, index) {
  17186.       return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
  17187.     };
  17188.     var hasRedo = function (editor, undoManager, index) {
  17189.       return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
  17190.     };
  17191.     var transact = function (editor, undoManager, locks, callback) {
  17192.       return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
  17193.     };
  17194.     var ignore = function (editor, locks, callback) {
  17195.       getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
  17196.     };
  17197.     var extra = function (editor, undoManager, index, callback1, callback2) {
  17198.       getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
  17199.     };
  17200.     var matchFormat = function (editor, name, vars, node, similar) {
  17201.       return getRtcInstanceWithError(editor).formatter.match(name, vars, node, similar);
  17202.     };
  17203.     var matchAllFormats = function (editor, names, vars) {
  17204.       return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
  17205.     };
  17206.     var matchNodeFormat = function (editor, node, name, vars, similar) {
  17207.       return getRtcInstanceWithError(editor).formatter.matchNode(node, name, vars, similar);
  17208.     };
  17209.     var canApplyFormat = function (editor, name) {
  17210.       return getRtcInstanceWithError(editor).formatter.canApply(name);
  17211.     };
  17212.     var closestFormat = function (editor, names) {
  17213.       return getRtcInstanceWithError(editor).formatter.closest(names);
  17214.     };
  17215.     var applyFormat = function (editor, name, vars, node) {
  17216.       getRtcInstanceWithError(editor).formatter.apply(name, vars, node);
  17217.     };
  17218.     var removeFormat = function (editor, name, vars, node, similar) {
  17219.       getRtcInstanceWithError(editor).formatter.remove(name, vars, node, similar);
  17220.     };
  17221.     var toggleFormat = function (editor, name, vars, node) {
  17222.       getRtcInstanceWithError(editor).formatter.toggle(name, vars, node);
  17223.     };
  17224.     var formatChanged = function (editor, registeredFormatListeners, formats, callback, similar, vars) {
  17225.       return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
  17226.     };
  17227.     var getContent$2 = function (editor, args, format) {
  17228.       return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
  17229.     };
  17230.     var setContent$2 = function (editor, content, args) {
  17231.       return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
  17232.     };
  17233.     var insertContent = function (editor, value, details) {
  17234.       return getRtcInstanceWithFallback(editor).editor.insertContent(value, details);
  17235.     };
  17236.     var getSelectedContent = function (editor, format, args) {
  17237.       return getRtcInstanceWithError(editor).selection.getContent(format, args);
  17238.     };
  17239.     var addVisual$1 = function (editor, elm) {
  17240.       return getRtcInstanceWithError(editor).editor.addVisual(elm);
  17241.     };
  17242.  
  17243.     var getContent$1 = function (editor, args) {
  17244.       if (args === void 0) {
  17245.         args = {};
  17246.       }
  17247.       var format = args.format ? args.format : 'html';
  17248.       return getSelectedContent(editor, format, args);
  17249.     };
  17250.  
  17251.     var removeEmpty = function (text) {
  17252.       if (text.dom.length === 0) {
  17253.         remove$7(text);
  17254.         return Optional.none();
  17255.       } else {
  17256.         return Optional.some(text);
  17257.       }
  17258.     };
  17259.     var walkPastBookmark = function (node, start) {
  17260.       return node.filter(function (elm) {
  17261.         return BookmarkManager.isBookmarkNode(elm.dom);
  17262.       }).bind(start ? nextSibling : prevSibling);
  17263.     };
  17264.     var merge = function (outer, inner, rng, start) {
  17265.       var outerElm = outer.dom;
  17266.       var innerElm = inner.dom;
  17267.       var oldLength = start ? outerElm.length : innerElm.length;
  17268.       if (start) {
  17269.         mergeTextNodes(outerElm, innerElm, false, !start);
  17270.         rng.setStart(innerElm, oldLength);
  17271.       } else {
  17272.         mergeTextNodes(innerElm, outerElm, false, !start);
  17273.         rng.setEnd(innerElm, oldLength);
  17274.       }
  17275.     };
  17276.     var normalizeTextIfRequired = function (inner, start) {
  17277.       parent(inner).each(function (root) {
  17278.         var text = inner.dom;
  17279.         if (start && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
  17280.           normalizeWhitespaceAfter(text, 0);
  17281.         } else if (!start && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
  17282.           normalizeWhitespaceBefore(text, text.length);
  17283.         }
  17284.       });
  17285.     };
  17286.     var mergeAndNormalizeText = function (outerNode, innerNode, rng, start) {
  17287.       outerNode.bind(function (outer) {
  17288.         var normalizer = start ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
  17289.         normalizer(outer.dom, start ? outer.dom.length : 0);
  17290.         return innerNode.filter(isText$8).map(function (inner) {
  17291.           return merge(outer, inner, rng, start);
  17292.         });
  17293.       }).orThunk(function () {
  17294.         var innerTextNode = walkPastBookmark(innerNode, start).or(innerNode).filter(isText$8);
  17295.         return innerTextNode.map(function (inner) {
  17296.           return normalizeTextIfRequired(inner, start);
  17297.         });
  17298.       });
  17299.     };
  17300.     var rngSetContent = function (rng, fragment) {
  17301.       var firstChild = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
  17302.       var lastChild = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
  17303.       rng.deleteContents();
  17304.       rng.insertNode(fragment);
  17305.       var prevText = firstChild.bind(prevSibling).filter(isText$8).bind(removeEmpty);
  17306.       var nextText = lastChild.bind(nextSibling).filter(isText$8).bind(removeEmpty);
  17307.       mergeAndNormalizeText(prevText, firstChild, rng, true);
  17308.       mergeAndNormalizeText(nextText, lastChild, rng, false);
  17309.       rng.collapse(false);
  17310.     };
  17311.     var setupArgs = function (args, content) {
  17312.       return __assign(__assign({ format: 'html' }, args), {
  17313.         set: true,
  17314.         selection: true,
  17315.         content: content
  17316.       });
  17317.     };
  17318.     var cleanContent = function (editor, args) {
  17319.       if (args.format !== 'raw') {
  17320.         var rng = editor.selection.getRng();
  17321.         var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
  17322.         var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
  17323.         var node = editor.parser.parse(args.content, __assign(__assign({
  17324.           isRootContent: true,
  17325.           forced_root_block: false
  17326.         }, contextArgs), args));
  17327.         return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
  17328.       } else {
  17329.         return args.content;
  17330.       }
  17331.     };
  17332.     var setContent$1 = function (editor, content, args) {
  17333.       if (args === void 0) {
  17334.         args = {};
  17335.       }
  17336.       var defaultedArgs = setupArgs(args, content);
  17337.       var updatedArgs = defaultedArgs;
  17338.       if (!defaultedArgs.no_events) {
  17339.         var eventArgs = editor.fire('BeforeSetContent', defaultedArgs);
  17340.         if (eventArgs.isDefaultPrevented()) {
  17341.           editor.fire('SetContent', eventArgs);
  17342.           return;
  17343.         } else {
  17344.           updatedArgs = eventArgs;
  17345.         }
  17346.       }
  17347.       updatedArgs.content = cleanContent(editor, updatedArgs);
  17348.       var rng = editor.selection.getRng();
  17349.       rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
  17350.       editor.selection.setRng(rng);
  17351.       scrollRangeIntoView(editor, rng);
  17352.       if (!updatedArgs.no_events) {
  17353.         editor.fire('SetContent', updatedArgs);
  17354.       }
  17355.     };
  17356.  
  17357.     var deleteFromCallbackMap = function (callbackMap, selector, callback) {
  17358.       if (callbackMap && has$2(callbackMap, selector)) {
  17359.         var newCallbacks = filter$4(callbackMap[selector], function (cb) {
  17360.           return cb !== callback;
  17361.         });
  17362.         if (newCallbacks.length === 0) {
  17363.           delete callbackMap[selector];
  17364.         } else {
  17365.           callbackMap[selector] = newCallbacks;
  17366.         }
  17367.       }
  17368.     };
  17369.     function SelectorChanged (dom, editor) {
  17370.       var selectorChangedData;
  17371.       var currentSelectors;
  17372.       var findMatchingNode = function (selector, nodes) {
  17373.         return find$3(nodes, function (node) {
  17374.           return dom.is(node, selector);
  17375.         });
  17376.       };
  17377.       var getParents = function (elem) {
  17378.         return dom.getParents(elem, null, dom.getRoot());
  17379.       };
  17380.       return {
  17381.         selectorChangedWithUnbind: function (selector, callback) {
  17382.           if (!selectorChangedData) {
  17383.             selectorChangedData = {};
  17384.             currentSelectors = {};
  17385.             editor.on('NodeChange', function (e) {
  17386.               var node = e.element;
  17387.               var parents = getParents(node);
  17388.               var matchedSelectors = {};
  17389.               Tools.each(selectorChangedData, function (callbacks, selector) {
  17390.                 findMatchingNode(selector, parents).each(function (node) {
  17391.                   if (!currentSelectors[selector]) {
  17392.                     each$k(callbacks, function (callback) {
  17393.                       callback(true, {
  17394.                         node: node,
  17395.                         selector: selector,
  17396.                         parents: parents
  17397.                       });
  17398.                     });
  17399.                     currentSelectors[selector] = callbacks;
  17400.                   }
  17401.                   matchedSelectors[selector] = callbacks;
  17402.                 });
  17403.               });
  17404.               Tools.each(currentSelectors, function (callbacks, selector) {
  17405.                 if (!matchedSelectors[selector]) {
  17406.                   delete currentSelectors[selector];
  17407.                   Tools.each(callbacks, function (callback) {
  17408.                     callback(false, {
  17409.                       node: node,
  17410.                       selector: selector,
  17411.                       parents: parents
  17412.                     });
  17413.                   });
  17414.                 }
  17415.               });
  17416.             });
  17417.           }
  17418.           if (!selectorChangedData[selector]) {
  17419.             selectorChangedData[selector] = [];
  17420.           }
  17421.           selectorChangedData[selector].push(callback);
  17422.           findMatchingNode(selector, getParents(editor.selection.getStart())).each(function () {
  17423.             currentSelectors[selector] = selectorChangedData[selector];
  17424.           });
  17425.           return {
  17426.             unbind: function () {
  17427.               deleteFromCallbackMap(selectorChangedData, selector, callback);
  17428.               deleteFromCallbackMap(currentSelectors, selector, callback);
  17429.             }
  17430.           };
  17431.         }
  17432.       };
  17433.     }
  17434.  
  17435.     var isNativeIeSelection = function (rng) {
  17436.       return !!rng.select;
  17437.     };
  17438.     var isAttachedToDom = function (node) {
  17439.       return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
  17440.     };
  17441.     var isValidRange = function (rng) {
  17442.       if (!rng) {
  17443.         return false;
  17444.       } else if (isNativeIeSelection(rng)) {
  17445.         return true;
  17446.       } else {
  17447.         return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
  17448.       }
  17449.     };
  17450.     var EditorSelection = function (dom, win, serializer, editor) {
  17451.       var selectedRange;
  17452.       var explicitRange;
  17453.       var selectorChangedWithUnbind = SelectorChanged(dom, editor).selectorChangedWithUnbind;
  17454.       var setCursorLocation = function (node, offset) {
  17455.         var rng = dom.createRng();
  17456.         if (isNonNullable(node) && isNonNullable(offset)) {
  17457.           rng.setStart(node, offset);
  17458.           rng.setEnd(node, offset);
  17459.           setRng(rng);
  17460.           collapse(false);
  17461.         } else {
  17462.           moveEndPoint(dom, rng, editor.getBody(), true);
  17463.           setRng(rng);
  17464.         }
  17465.       };
  17466.       var getContent = function (args) {
  17467.         return getContent$1(editor, args);
  17468.       };
  17469.       var setContent = function (content, args) {
  17470.         return setContent$1(editor, content, args);
  17471.       };
  17472.       var getStart$1 = function (real) {
  17473.         return getStart(editor.getBody(), getRng$1(), real);
  17474.       };
  17475.       var getEnd$1 = function (real) {
  17476.         return getEnd(editor.getBody(), getRng$1(), real);
  17477.       };
  17478.       var getBookmark = function (type, normalized) {
  17479.         return bookmarkManager.getBookmark(type, normalized);
  17480.       };
  17481.       var moveToBookmark = function (bookmark) {
  17482.         return bookmarkManager.moveToBookmark(bookmark);
  17483.       };
  17484.       var select$1 = function (node, content) {
  17485.         select(dom, node, content).each(setRng);
  17486.         return node;
  17487.       };
  17488.       var isCollapsed = function () {
  17489.         var rng = getRng$1(), sel = getSel();
  17490.         if (!rng || rng.item) {
  17491.           return false;
  17492.         }
  17493.         if (rng.compareEndPoints) {
  17494.           return rng.compareEndPoints('StartToEnd', rng) === 0;
  17495.         }
  17496.         return !sel || rng.collapsed;
  17497.       };
  17498.       var collapse = function (toStart) {
  17499.         var rng = getRng$1();
  17500.         rng.collapse(!!toStart);
  17501.         setRng(rng);
  17502.       };
  17503.       var getSel = function () {
  17504.         return win.getSelection ? win.getSelection() : win.document.selection;
  17505.       };
  17506.       var getRng$1 = function () {
  17507.         var selection, rng, elm;
  17508.         var tryCompareBoundaryPoints = function (how, sourceRange, destinationRange) {
  17509.           try {
  17510.             return sourceRange.compareBoundaryPoints(how, destinationRange);
  17511.           } catch (ex) {
  17512.             return -1;
  17513.           }
  17514.         };
  17515.         var doc = win.document;
  17516.         if (editor.bookmark !== undefined && hasFocus(editor) === false) {
  17517.           var bookmark = getRng(editor);
  17518.           if (bookmark.isSome()) {
  17519.             return bookmark.map(function (r) {
  17520.               return processRanges(editor, [r])[0];
  17521.             }).getOr(doc.createRange());
  17522.           }
  17523.         }
  17524.         try {
  17525.           if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
  17526.             if (selection.rangeCount > 0) {
  17527.               rng = selection.getRangeAt(0);
  17528.             } else {
  17529.               rng = selection.createRange ? selection.createRange() : doc.createRange();
  17530.             }
  17531.             rng = processRanges(editor, [rng])[0];
  17532.           }
  17533.         } catch (ex) {
  17534.         }
  17535.         if (!rng) {
  17536.           rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  17537.         }
  17538.         if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  17539.           elm = dom.getRoot();
  17540.           rng.setStart(elm, 0);
  17541.           rng.setEnd(elm, 0);
  17542.         }
  17543.         if (selectedRange && explicitRange) {
  17544.           if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
  17545.             rng = explicitRange;
  17546.           } else {
  17547.             selectedRange = null;
  17548.             explicitRange = null;
  17549.           }
  17550.         }
  17551.         return rng;
  17552.       };
  17553.       var setRng = function (rng, forward) {
  17554.         var node;
  17555.         if (!isValidRange(rng)) {
  17556.           return;
  17557.         }
  17558.         var ieRange = isNativeIeSelection(rng) ? rng : null;
  17559.         if (ieRange) {
  17560.           explicitRange = null;
  17561.           try {
  17562.             ieRange.select();
  17563.           } catch (ex) {
  17564.           }
  17565.           return;
  17566.         }
  17567.         var sel = getSel();
  17568.         var evt = editor.fire('SetSelectionRange', {
  17569.           range: rng,
  17570.           forward: forward
  17571.         });
  17572.         rng = evt.range;
  17573.         if (sel) {
  17574.           explicitRange = rng;
  17575.           try {
  17576.             sel.removeAllRanges();
  17577.             sel.addRange(rng);
  17578.           } catch (ex) {
  17579.           }
  17580.           if (forward === false && sel.extend) {
  17581.             sel.collapse(rng.endContainer, rng.endOffset);
  17582.             sel.extend(rng.startContainer, rng.startOffset);
  17583.           }
  17584.           selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  17585.         }
  17586.         if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
  17587.           if (rng.endOffset - rng.startOffset < 2) {
  17588.             if (rng.startContainer.hasChildNodes()) {
  17589.               node = rng.startContainer.childNodes[rng.startOffset];
  17590.               if (node && node.tagName === 'IMG') {
  17591.                 sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
  17592.                 if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
  17593.                   sel.setBaseAndExtent(node, 0, node, 1);
  17594.                 }
  17595.               }
  17596.             }
  17597.           }
  17598.         }
  17599.         editor.fire('AfterSetSelectionRange', {
  17600.           range: rng,
  17601.           forward: forward
  17602.         });
  17603.       };
  17604.       var setNode = function (elm) {
  17605.         setContent(dom.getOuterHTML(elm));
  17606.         return elm;
  17607.       };
  17608.       var getNode$1 = function () {
  17609.         return getNode(editor.getBody(), getRng$1());
  17610.       };
  17611.       var getSelectedBlocks$1 = function (startElm, endElm) {
  17612.         return getSelectedBlocks(dom, getRng$1(), startElm, endElm);
  17613.       };
  17614.       var isForward = function () {
  17615.         var sel = getSel();
  17616.         var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
  17617.         var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
  17618.         if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
  17619.           return true;
  17620.         }
  17621.         var anchorRange = dom.createRng();
  17622.         anchorRange.setStart(anchorNode, sel.anchorOffset);
  17623.         anchorRange.collapse(true);
  17624.         var focusRange = dom.createRng();
  17625.         focusRange.setStart(focusNode, sel.focusOffset);
  17626.         focusRange.collapse(true);
  17627.         return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  17628.       };
  17629.       var normalize = function () {
  17630.         var rng = getRng$1();
  17631.         var sel = getSel();
  17632.         if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
  17633.           var normRng = normalize$2(dom, rng);
  17634.           normRng.each(function (normRng) {
  17635.             setRng(normRng, isForward());
  17636.           });
  17637.           return normRng.getOr(rng);
  17638.         }
  17639.         return rng;
  17640.       };
  17641.       var selectorChanged = function (selector, callback) {
  17642.         selectorChangedWithUnbind(selector, callback);
  17643.         return exports;
  17644.       };
  17645.       var getScrollContainer = function () {
  17646.         var scrollContainer;
  17647.         var node = dom.getRoot();
  17648.         while (node && node.nodeName !== 'BODY') {
  17649.           if (node.scrollHeight > node.clientHeight) {
  17650.             scrollContainer = node;
  17651.             break;
  17652.           }
  17653.           node = node.parentNode;
  17654.         }
  17655.         return scrollContainer;
  17656.       };
  17657.       var scrollIntoView = function (elm, alignToTop) {
  17658.         if (isNonNullable(elm)) {
  17659.           scrollElementIntoView(editor, elm, alignToTop);
  17660.         } else {
  17661.           scrollRangeIntoView(editor, getRng$1(), alignToTop);
  17662.         }
  17663.       };
  17664.       var placeCaretAt = function (clientX, clientY) {
  17665.         return setRng(fromPoint(clientX, clientY, editor.getDoc()));
  17666.       };
  17667.       var getBoundingClientRect = function () {
  17668.         var rng = getRng$1();
  17669.         return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
  17670.       };
  17671.       var destroy = function () {
  17672.         win = selectedRange = explicitRange = null;
  17673.         controlSelection.destroy();
  17674.       };
  17675.       var exports = {
  17676.         bookmarkManager: null,
  17677.         controlSelection: null,
  17678.         dom: dom,
  17679.         win: win,
  17680.         serializer: serializer,
  17681.         editor: editor,
  17682.         collapse: collapse,
  17683.         setCursorLocation: setCursorLocation,
  17684.         getContent: getContent,
  17685.         setContent: setContent,
  17686.         getBookmark: getBookmark,
  17687.         moveToBookmark: moveToBookmark,
  17688.         select: select$1,
  17689.         isCollapsed: isCollapsed,
  17690.         isForward: isForward,
  17691.         setNode: setNode,
  17692.         getNode: getNode$1,
  17693.         getSel: getSel,
  17694.         setRng: setRng,
  17695.         getRng: getRng$1,
  17696.         getStart: getStart$1,
  17697.         getEnd: getEnd$1,
  17698.         getSelectedBlocks: getSelectedBlocks$1,
  17699.         normalize: normalize,
  17700.         selectorChanged: selectorChanged,
  17701.         selectorChangedWithUnbind: selectorChangedWithUnbind,
  17702.         getScrollContainer: getScrollContainer,
  17703.         scrollIntoView: scrollIntoView,
  17704.         placeCaretAt: placeCaretAt,
  17705.         getBoundingClientRect: getBoundingClientRect,
  17706.         destroy: destroy
  17707.       };
  17708.       var bookmarkManager = BookmarkManager(exports);
  17709.       var controlSelection = ControlSelection(exports, editor);
  17710.       exports.bookmarkManager = bookmarkManager;
  17711.       exports.controlSelection = controlSelection;
  17712.       return exports;
  17713.     };
  17714.  
  17715.     var removeAttrs = function (node, names) {
  17716.       each$k(names, function (name) {
  17717.         node.attr(name, null);
  17718.       });
  17719.     };
  17720.     var addFontToSpansFilter = function (domParser, styles, fontSizes) {
  17721.       domParser.addNodeFilter('font', function (nodes) {
  17722.         each$k(nodes, function (node) {
  17723.           var props = styles.parse(node.attr('style'));
  17724.           var color = node.attr('color');
  17725.           var face = node.attr('face');
  17726.           var size = node.attr('size');
  17727.           if (color) {
  17728.             props.color = color;
  17729.           }
  17730.           if (face) {
  17731.             props['font-family'] = face;
  17732.           }
  17733.           if (size) {
  17734.             props['font-size'] = fontSizes[parseInt(node.attr('size'), 10) - 1];
  17735.           }
  17736.           node.name = 'span';
  17737.           node.attr('style', styles.serialize(props));
  17738.           removeAttrs(node, [
  17739.             'color',
  17740.             'face',
  17741.             'size'
  17742.           ]);
  17743.         });
  17744.       });
  17745.     };
  17746.     var addStrikeToSpanFilter = function (domParser, styles) {
  17747.       domParser.addNodeFilter('strike', function (nodes) {
  17748.         each$k(nodes, function (node) {
  17749.           var props = styles.parse(node.attr('style'));
  17750.           props['text-decoration'] = 'line-through';
  17751.           node.name = 'span';
  17752.           node.attr('style', styles.serialize(props));
  17753.         });
  17754.       });
  17755.     };
  17756.     var addFilters = function (domParser, settings) {
  17757.       var styles = Styles();
  17758.       if (settings.convert_fonts_to_spans) {
  17759.         addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
  17760.       }
  17761.       addStrikeToSpanFilter(domParser, styles);
  17762.     };
  17763.     var register$2 = function (domParser, settings) {
  17764.       if (settings.inline_styles) {
  17765.         addFilters(domParser, settings);
  17766.       }
  17767.     };
  17768.  
  17769.     var blobUriToBlob = function (url) {
  17770.       return new promiseObj(function (resolve, reject) {
  17771.         var rejectWithError = function () {
  17772.           reject('Cannot convert ' + url + ' to Blob. Resource might not exist or is inaccessible.');
  17773.         };
  17774.         try {
  17775.           var xhr_1 = new XMLHttpRequest();
  17776.           xhr_1.open('GET', url, true);
  17777.           xhr_1.responseType = 'blob';
  17778.           xhr_1.onload = function () {
  17779.             if (xhr_1.status === 200) {
  17780.               resolve(xhr_1.response);
  17781.             } else {
  17782.               rejectWithError();
  17783.             }
  17784.           };
  17785.           xhr_1.onerror = rejectWithError;
  17786.           xhr_1.send();
  17787.         } catch (ex) {
  17788.           rejectWithError();
  17789.         }
  17790.       });
  17791.     };
  17792.     var parseDataUri$1 = function (uri) {
  17793.       var type;
  17794.       var uriParts = decodeURIComponent(uri).split(',');
  17795.       var matches = /data:([^;]+)/.exec(uriParts[0]);
  17796.       if (matches) {
  17797.         type = matches[1];
  17798.       }
  17799.       return {
  17800.         type: type,
  17801.         data: uriParts[1]
  17802.       };
  17803.     };
  17804.     var buildBlob = function (type, data) {
  17805.       var str;
  17806.       try {
  17807.         str = atob(data);
  17808.       } catch (e) {
  17809.         return Optional.none();
  17810.       }
  17811.       var arr = new Uint8Array(str.length);
  17812.       for (var i = 0; i < arr.length; i++) {
  17813.         arr[i] = str.charCodeAt(i);
  17814.       }
  17815.       return Optional.some(new Blob([arr], { type: type }));
  17816.     };
  17817.     var dataUriToBlob = function (uri) {
  17818.       return new promiseObj(function (resolve) {
  17819.         var _a = parseDataUri$1(uri), type = _a.type, data = _a.data;
  17820.         buildBlob(type, data).fold(function () {
  17821.           return resolve(new Blob([]));
  17822.         }, resolve);
  17823.       });
  17824.     };
  17825.     var uriToBlob = function (url) {
  17826.       if (url.indexOf('blob:') === 0) {
  17827.         return blobUriToBlob(url);
  17828.       }
  17829.       if (url.indexOf('data:') === 0) {
  17830.         return dataUriToBlob(url);
  17831.       }
  17832.       return null;
  17833.     };
  17834.     var blobToDataUri = function (blob) {
  17835.       return new promiseObj(function (resolve) {
  17836.         var reader = new FileReader();
  17837.         reader.onloadend = function () {
  17838.           resolve(reader.result);
  17839.         };
  17840.         reader.readAsDataURL(blob);
  17841.       });
  17842.     };
  17843.  
  17844.     var count$1 = 0;
  17845.     var uniqueId = function (prefix) {
  17846.       return (prefix || 'blobid') + count$1++;
  17847.     };
  17848.     var imageToBlobInfo = function (blobCache, img, resolve, reject) {
  17849.       var base64, blobInfo;
  17850.       if (img.src.indexOf('blob:') === 0) {
  17851.         blobInfo = blobCache.getByUri(img.src);
  17852.         if (blobInfo) {
  17853.           resolve({
  17854.             image: img,
  17855.             blobInfo: blobInfo
  17856.           });
  17857.         } else {
  17858.           uriToBlob(img.src).then(function (blob) {
  17859.             blobToDataUri(blob).then(function (dataUri) {
  17860.               base64 = parseDataUri$1(dataUri).data;
  17861.               blobInfo = blobCache.create(uniqueId(), blob, base64);
  17862.               blobCache.add(blobInfo);
  17863.               resolve({
  17864.                 image: img,
  17865.                 blobInfo: blobInfo
  17866.               });
  17867.             });
  17868.           }, function (err) {
  17869.             reject(err);
  17870.           });
  17871.         }
  17872.         return;
  17873.       }
  17874.       var _a = parseDataUri$1(img.src), data = _a.data, type = _a.type;
  17875.       base64 = data;
  17876.       blobInfo = blobCache.getByData(base64, type);
  17877.       if (blobInfo) {
  17878.         resolve({
  17879.           image: img,
  17880.           blobInfo: blobInfo
  17881.         });
  17882.       } else {
  17883.         uriToBlob(img.src).then(function (blob) {
  17884.           blobInfo = blobCache.create(uniqueId(), blob, base64);
  17885.           blobCache.add(blobInfo);
  17886.           resolve({
  17887.             image: img,
  17888.             blobInfo: blobInfo
  17889.           });
  17890.         }, function (err) {
  17891.           reject(err);
  17892.         });
  17893.       }
  17894.     };
  17895.     var getAllImages = function (elm) {
  17896.       return elm ? from(elm.getElementsByTagName('img')) : [];
  17897.     };
  17898.     var ImageScanner = function (uploadStatus, blobCache) {
  17899.       var cachedPromises = {};
  17900.       var findAll = function (elm, predicate) {
  17901.         if (!predicate) {
  17902.           predicate = always;
  17903.         }
  17904.         var images = filter$4(getAllImages(elm), function (img) {
  17905.           var src = img.src;
  17906.           if (!Env.fileApi) {
  17907.             return false;
  17908.           }
  17909.           if (img.hasAttribute('data-mce-bogus')) {
  17910.             return false;
  17911.           }
  17912.           if (img.hasAttribute('data-mce-placeholder')) {
  17913.             return false;
  17914.           }
  17915.           if (!src || src === Env.transparentSrc) {
  17916.             return false;
  17917.           }
  17918.           if (src.indexOf('blob:') === 0) {
  17919.             return !uploadStatus.isUploaded(src) && predicate(img);
  17920.           }
  17921.           if (src.indexOf('data:') === 0) {
  17922.             return predicate(img);
  17923.           }
  17924.           return false;
  17925.         });
  17926.         var promises = map$3(images, function (img) {
  17927.           if (cachedPromises[img.src] !== undefined) {
  17928.             return new promiseObj(function (resolve) {
  17929.               cachedPromises[img.src].then(function (imageInfo) {
  17930.                 if (typeof imageInfo === 'string') {
  17931.                   return imageInfo;
  17932.                 }
  17933.                 resolve({
  17934.                   image: img,
  17935.                   blobInfo: imageInfo.blobInfo
  17936.                 });
  17937.               });
  17938.             });
  17939.           }
  17940.           var newPromise = new promiseObj(function (resolve, reject) {
  17941.             imageToBlobInfo(blobCache, img, resolve, reject);
  17942.           }).then(function (result) {
  17943.             delete cachedPromises[result.image.src];
  17944.             return result;
  17945.           }).catch(function (error) {
  17946.             delete cachedPromises[img.src];
  17947.             return error;
  17948.           });
  17949.           cachedPromises[img.src] = newPromise;
  17950.           return newPromise;
  17951.         });
  17952.         return promiseObj.all(promises);
  17953.       };
  17954.       return { findAll: findAll };
  17955.     };
  17956.  
  17957.     var extractBase64DataUris = function (html) {
  17958.       var dataImageUri = /data:[^;<"'\s]+;base64,([a-z0-9\+\/=\s]+)/gi;
  17959.       var chunks = [];
  17960.       var uris = {};
  17961.       var prefix = generate('img');
  17962.       var matches;
  17963.       var index = 0;
  17964.       var count = 0;
  17965.       while (matches = dataImageUri.exec(html)) {
  17966.         var uri = matches[0];
  17967.         var imageId = prefix + '_' + count++;
  17968.         uris[imageId] = uri;
  17969.         if (index < matches.index) {
  17970.           chunks.push(html.substr(index, matches.index - index));
  17971.         }
  17972.         chunks.push(imageId);
  17973.         index = matches.index + uri.length;
  17974.       }
  17975.       var re = new RegExp(prefix + '_[0-9]+', 'g');
  17976.       if (index === 0) {
  17977.         return {
  17978.           prefix: prefix,
  17979.           uris: uris,
  17980.           html: html,
  17981.           re: re
  17982.         };
  17983.       } else {
  17984.         if (index < html.length) {
  17985.           chunks.push(html.substr(index));
  17986.         }
  17987.         return {
  17988.           prefix: prefix,
  17989.           uris: uris,
  17990.           html: chunks.join(''),
  17991.           re: re
  17992.         };
  17993.       }
  17994.     };
  17995.     var restoreDataUris = function (html, result) {
  17996.       return html.replace(result.re, function (imageId) {
  17997.         return get$9(result.uris, imageId).getOr(imageId);
  17998.       });
  17999.     };
  18000.     var parseDataUri = function (uri) {
  18001.       var matches = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
  18002.       if (matches) {
  18003.         return Optional.some({
  18004.           type: matches[1],
  18005.           data: decodeURIComponent(matches[2])
  18006.         });
  18007.       } else {
  18008.         return Optional.none();
  18009.       }
  18010.     };
  18011.  
  18012.     var paddEmptyNode = function (settings, args, blockElements, node) {
  18013.       var brPreferred = settings.padd_empty_with_br || args.insert;
  18014.       if (brPreferred && blockElements[node.name]) {
  18015.         node.empty().append(new AstNode('br', 1)).shortEnded = true;
  18016.       } else {
  18017.         node.empty().append(new AstNode('#text', 3)).value = nbsp;
  18018.       }
  18019.     };
  18020.     var isPaddedWithNbsp = function (node) {
  18021.       return hasOnlyChild(node, '#text') && node.firstChild.value === nbsp;
  18022.     };
  18023.     var hasOnlyChild = function (node, name) {
  18024.       return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name;
  18025.     };
  18026.     var isPadded = function (schema, node) {
  18027.       var rule = schema.getElementRule(node.name);
  18028.       return rule && rule.paddEmpty;
  18029.     };
  18030.     var isEmpty = function (schema, nonEmptyElements, whitespaceElements, node) {
  18031.       return node.isEmpty(nonEmptyElements, whitespaceElements, function (node) {
  18032.         return isPadded(schema, node);
  18033.       });
  18034.     };
  18035.     var isLineBreakNode = function (node, blockElements) {
  18036.       return node && (has$2(blockElements, node.name) || node.name === 'br');
  18037.     };
  18038.  
  18039.     var isBogusImage = function (img) {
  18040.       return isNonNullable(img.attr('data-mce-bogus'));
  18041.     };
  18042.     var isInternalImageSource = function (img) {
  18043.       return img.attr('src') === Env.transparentSrc || isNonNullable(img.attr('data-mce-placeholder'));
  18044.     };
  18045.     var isValidDataImg = function (img, settings) {
  18046.       if (settings.images_dataimg_filter) {
  18047.         var imgElem_1 = new Image();
  18048.         imgElem_1.src = img.attr('src');
  18049.         each$j(img.attributes.map, function (value, key) {
  18050.           imgElem_1.setAttribute(key, value);
  18051.         });
  18052.         return settings.images_dataimg_filter(imgElem_1);
  18053.       } else {
  18054.         return true;
  18055.       }
  18056.     };
  18057.     var registerBase64ImageFilter = function (parser, settings) {
  18058.       var blobCache = settings.blob_cache;
  18059.       var processImage = function (img) {
  18060.         var inputSrc = img.attr('src');
  18061.         if (isInternalImageSource(img) || isBogusImage(img)) {
  18062.           return;
  18063.         }
  18064.         parseDataUri(inputSrc).filter(function () {
  18065.           return isValidDataImg(img, settings);
  18066.         }).bind(function (_a) {
  18067.           var type = _a.type, data = _a.data;
  18068.           return Optional.from(blobCache.getByData(data, type)).orThunk(function () {
  18069.             return buildBlob(type, data).map(function (blob) {
  18070.               var blobInfo = blobCache.create(uniqueId(), blob, data);
  18071.               blobCache.add(blobInfo);
  18072.               return blobInfo;
  18073.             });
  18074.           });
  18075.         }).each(function (blobInfo) {
  18076.           img.attr('src', blobInfo.blobUri());
  18077.         });
  18078.       };
  18079.       if (blobCache) {
  18080.         parser.addAttributeFilter('src', function (nodes) {
  18081.           return each$k(nodes, processImage);
  18082.         });
  18083.       }
  18084.     };
  18085.     var register$1 = function (parser, settings) {
  18086.       var schema = parser.schema;
  18087.       if (settings.remove_trailing_brs) {
  18088.         parser.addNodeFilter('br', function (nodes, _, args) {
  18089.           var i;
  18090.           var l = nodes.length;
  18091.           var node;
  18092.           var blockElements = Tools.extend({}, schema.getBlockElements());
  18093.           var nonEmptyElements = schema.getNonEmptyElements();
  18094.           var parent, lastParent, prev, prevName;
  18095.           var whiteSpaceElements = schema.getWhiteSpaceElements();
  18096.           var elementRule, textNode;
  18097.           blockElements.body = 1;
  18098.           for (i = 0; i < l; i++) {
  18099.             node = nodes[i];
  18100.             parent = node.parent;
  18101.             if (blockElements[node.parent.name] && node === parent.lastChild) {
  18102.               prev = node.prev;
  18103.               while (prev) {
  18104.                 prevName = prev.name;
  18105.                 if (prevName !== 'span' || prev.attr('data-mce-type') !== 'bookmark') {
  18106.                   if (prevName === 'br') {
  18107.                     node = null;
  18108.                   }
  18109.                   break;
  18110.                 }
  18111.                 prev = prev.prev;
  18112.               }
  18113.               if (node) {
  18114.                 node.remove();
  18115.                 if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent)) {
  18116.                   elementRule = schema.getElementRule(parent.name);
  18117.                   if (elementRule) {
  18118.                     if (elementRule.removeEmpty) {
  18119.                       parent.remove();
  18120.                     } else if (elementRule.paddEmpty) {
  18121.                       paddEmptyNode(settings, args, blockElements, parent);
  18122.                     }
  18123.                   }
  18124.                 }
  18125.               }
  18126.             } else {
  18127.               lastParent = node;
  18128.               while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  18129.                 lastParent = parent;
  18130.                 if (blockElements[parent.name]) {
  18131.                   break;
  18132.                 }
  18133.                 parent = parent.parent;
  18134.               }
  18135.               if (lastParent === parent && settings.padd_empty_with_br !== true) {
  18136.                 textNode = new AstNode('#text', 3);
  18137.                 textNode.value = nbsp;
  18138.                 node.replace(textNode);
  18139.               }
  18140.             }
  18141.           }
  18142.         });
  18143.       }
  18144.       parser.addAttributeFilter('href', function (nodes) {
  18145.         var i = nodes.length;
  18146.         var appendRel = function (rel) {
  18147.           var parts = rel.split(' ').filter(function (p) {
  18148.             return p.length > 0;
  18149.           });
  18150.           return parts.concat(['noopener']).sort().join(' ');
  18151.         };
  18152.         var addNoOpener = function (rel) {
  18153.           var newRel = rel ? Tools.trim(rel) : '';
  18154.           if (!/\b(noopener)\b/g.test(newRel)) {
  18155.             return appendRel(newRel);
  18156.           } else {
  18157.             return newRel;
  18158.           }
  18159.         };
  18160.         if (!settings.allow_unsafe_link_target) {
  18161.           while (i--) {
  18162.             var node = nodes[i];
  18163.             if (node.name === 'a' && node.attr('target') === '_blank') {
  18164.               node.attr('rel', addNoOpener(node.attr('rel')));
  18165.             }
  18166.           }
  18167.         }
  18168.       });
  18169.       if (!settings.allow_html_in_named_anchor) {
  18170.         parser.addAttributeFilter('id,name', function (nodes) {
  18171.           var i = nodes.length, sibling, prevSibling, parent, node;
  18172.           while (i--) {
  18173.             node = nodes[i];
  18174.             if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  18175.               parent = node.parent;
  18176.               sibling = node.lastChild;
  18177.               do {
  18178.                 prevSibling = sibling.prev;
  18179.                 parent.insert(sibling, node);
  18180.                 sibling = prevSibling;
  18181.               } while (sibling);
  18182.             }
  18183.           }
  18184.         });
  18185.       }
  18186.       if (settings.fix_list_elements) {
  18187.         parser.addNodeFilter('ul,ol', function (nodes) {
  18188.           var i = nodes.length, node, parentNode;
  18189.           while (i--) {
  18190.             node = nodes[i];
  18191.             parentNode = node.parent;
  18192.             if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  18193.               if (node.prev && node.prev.name === 'li') {
  18194.                 node.prev.append(node);
  18195.               } else {
  18196.                 var li = new AstNode('li', 1);
  18197.                 li.attr('style', 'list-style-type: none');
  18198.                 node.wrap(li);
  18199.               }
  18200.             }
  18201.           }
  18202.         });
  18203.       }
  18204.       if (settings.validate && schema.getValidClasses()) {
  18205.         parser.addAttributeFilter('class', function (nodes) {
  18206.           var validClasses = schema.getValidClasses();
  18207.           var i = nodes.length;
  18208.           while (i--) {
  18209.             var node = nodes[i];
  18210.             var classList = node.attr('class').split(' ');
  18211.             var classValue = '';
  18212.             for (var ci = 0; ci < classList.length; ci++) {
  18213.               var className = classList[ci];
  18214.               var valid = false;
  18215.               var validClassesMap = validClasses['*'];
  18216.               if (validClassesMap && validClassesMap[className]) {
  18217.                 valid = true;
  18218.               }
  18219.               validClassesMap = validClasses[node.name];
  18220.               if (!valid && validClassesMap && validClassesMap[className]) {
  18221.                 valid = true;
  18222.               }
  18223.               if (valid) {
  18224.                 if (classValue) {
  18225.                   classValue += ' ';
  18226.                 }
  18227.                 classValue += className;
  18228.               }
  18229.             }
  18230.             if (!classValue.length) {
  18231.               classValue = null;
  18232.             }
  18233.             node.attr('class', classValue);
  18234.           }
  18235.         });
  18236.       }
  18237.       registerBase64ImageFilter(parser, settings);
  18238.     };
  18239.  
  18240.     var each$7 = Tools.each, trim = Tools.trim;
  18241.     var queryParts = 'source protocol authority userInfo user password host port relative path directory file query anchor'.split(' ');
  18242.     var DEFAULT_PORTS = {
  18243.       ftp: 21,
  18244.       http: 80,
  18245.       https: 443,
  18246.       mailto: 25
  18247.     };
  18248.     var safeSvgDataUrlElements = [
  18249.       'img',
  18250.       'video'
  18251.     ];
  18252.     var blockSvgDataUris = function (allowSvgDataUrls, tagName) {
  18253.       if (isNonNullable(allowSvgDataUrls)) {
  18254.         return !allowSvgDataUrls;
  18255.       } else {
  18256.         return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
  18257.       }
  18258.     };
  18259.     var isInvalidUri = function (settings, uri, tagName) {
  18260.       if (settings.allow_html_data_urls) {
  18261.         return false;
  18262.       } else if (/^data:image\//i.test(uri)) {
  18263.         return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
  18264.       } else {
  18265.         return /^data:/i.test(uri);
  18266.       }
  18267.     };
  18268.     var URI = function () {
  18269.       function URI(url, settings) {
  18270.         url = trim(url);
  18271.         this.settings = settings || {};
  18272.         var baseUri = this.settings.base_uri;
  18273.         var self = this;
  18274.         if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  18275.           self.source = url;
  18276.           return;
  18277.         }
  18278.         var isProtocolRelative = url.indexOf('//') === 0;
  18279.         if (url.indexOf('/') === 0 && !isProtocolRelative) {
  18280.           url = (baseUri ? baseUri.protocol || 'http' : 'http') + '://mce_host' + url;
  18281.         }
  18282.         if (!/^[\w\-]*:?\/\//.test(url)) {
  18283.           var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI(document.location.href).directory;
  18284.           if (this.settings.base_uri && this.settings.base_uri.protocol == '') {
  18285.             url = '//mce_host' + self.toAbsPath(baseUrl, url);
  18286.           } else {
  18287.             var match = /([^#?]*)([#?]?.*)/.exec(url);
  18288.             url = (baseUri && baseUri.protocol || 'http') + '://mce_host' + self.toAbsPath(baseUrl, match[1]) + match[2];
  18289.           }
  18290.         }
  18291.         url = url.replace(/@@/g, '(mce_at)');
  18292.         var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  18293.         each$7(queryParts, function (v, i) {
  18294.           var part = urlMatch[i];
  18295.           if (part) {
  18296.             part = part.replace(/\(mce_at\)/g, '@@');
  18297.           }
  18298.           self[v] = part;
  18299.         });
  18300.         if (baseUri) {
  18301.           if (!self.protocol) {
  18302.             self.protocol = baseUri.protocol;
  18303.           }
  18304.           if (!self.userInfo) {
  18305.             self.userInfo = baseUri.userInfo;
  18306.           }
  18307.           if (!self.port && self.host === 'mce_host') {
  18308.             self.port = baseUri.port;
  18309.           }
  18310.           if (!self.host || self.host === 'mce_host') {
  18311.             self.host = baseUri.host;
  18312.           }
  18313.           self.source = '';
  18314.         }
  18315.         if (isProtocolRelative) {
  18316.           self.protocol = '';
  18317.         }
  18318.       }
  18319.       URI.parseDataUri = function (uri) {
  18320.         var type;
  18321.         var uriComponents = decodeURIComponent(uri).split(',');
  18322.         var matches = /data:([^;]+)/.exec(uriComponents[0]);
  18323.         if (matches) {
  18324.           type = matches[1];
  18325.         }
  18326.         return {
  18327.           type: type,
  18328.           data: uriComponents[1]
  18329.         };
  18330.       };
  18331.       URI.isDomSafe = function (uri, context, options) {
  18332.         if (options === void 0) {
  18333.           options = {};
  18334.         }
  18335.         if (options.allow_script_urls) {
  18336.           return true;
  18337.         } else {
  18338.           var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, '');
  18339.           try {
  18340.             decodedUri = decodeURIComponent(decodedUri);
  18341.           } catch (ex) {
  18342.             decodedUri = unescape(decodedUri);
  18343.           }
  18344.           if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
  18345.             return false;
  18346.           }
  18347.           return !isInvalidUri(options, decodedUri, context);
  18348.         }
  18349.       };
  18350.       URI.getDocumentBaseUrl = function (loc) {
  18351.         var baseUrl;
  18352.         if (loc.protocol.indexOf('http') !== 0 && loc.protocol !== 'file:') {
  18353.           baseUrl = loc.href;
  18354.         } else {
  18355.           baseUrl = loc.protocol + '//' + loc.host + loc.pathname;
  18356.         }
  18357.         if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
  18358.           baseUrl = baseUrl.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  18359.           if (!/[\/\\]$/.test(baseUrl)) {
  18360.             baseUrl += '/';
  18361.           }
  18362.         }
  18363.         return baseUrl;
  18364.       };
  18365.       URI.prototype.setPath = function (path) {
  18366.         var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
  18367.         this.path = pathMatch[0];
  18368.         this.directory = pathMatch[1];
  18369.         this.file = pathMatch[2];
  18370.         this.source = '';
  18371.         this.getURI();
  18372.       };
  18373.       URI.prototype.toRelative = function (uri) {
  18374.         var output;
  18375.         if (uri === './') {
  18376.           return uri;
  18377.         }
  18378.         var relativeUri = new URI(uri, { base_uri: this });
  18379.         if (relativeUri.host !== 'mce_host' && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== '') {
  18380.           return relativeUri.getURI();
  18381.         }
  18382.         var tu = this.getURI(), uu = relativeUri.getURI();
  18383.         if (tu === uu || tu.charAt(tu.length - 1) === '/' && tu.substr(0, tu.length - 1) === uu) {
  18384.           return tu;
  18385.         }
  18386.         output = this.toRelPath(this.path, relativeUri.path);
  18387.         if (relativeUri.query) {
  18388.           output += '?' + relativeUri.query;
  18389.         }
  18390.         if (relativeUri.anchor) {
  18391.           output += '#' + relativeUri.anchor;
  18392.         }
  18393.         return output;
  18394.       };
  18395.       URI.prototype.toAbsolute = function (uri, noHost) {
  18396.         var absoluteUri = new URI(uri, { base_uri: this });
  18397.         return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
  18398.       };
  18399.       URI.prototype.isSameOrigin = function (uri) {
  18400.         if (this.host == uri.host && this.protocol == uri.protocol) {
  18401.           if (this.port == uri.port) {
  18402.             return true;
  18403.           }
  18404.           var defaultPort = DEFAULT_PORTS[this.protocol];
  18405.           if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
  18406.             return true;
  18407.           }
  18408.         }
  18409.         return false;
  18410.       };
  18411.       URI.prototype.toRelPath = function (base, path) {
  18412.         var breakPoint = 0, out = '', i, l;
  18413.         var normalizedBase = base.substring(0, base.lastIndexOf('/')).split('/');
  18414.         var items = path.split('/');
  18415.         if (normalizedBase.length >= items.length) {
  18416.           for (i = 0, l = normalizedBase.length; i < l; i++) {
  18417.             if (i >= items.length || normalizedBase[i] !== items[i]) {
  18418.               breakPoint = i + 1;
  18419.               break;
  18420.             }
  18421.           }
  18422.         }
  18423.         if (normalizedBase.length < items.length) {
  18424.           for (i = 0, l = items.length; i < l; i++) {
  18425.             if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
  18426.               breakPoint = i + 1;
  18427.               break;
  18428.             }
  18429.           }
  18430.         }
  18431.         if (breakPoint === 1) {
  18432.           return path;
  18433.         }
  18434.         for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
  18435.           out += '../';
  18436.         }
  18437.         for (i = breakPoint - 1, l = items.length; i < l; i++) {
  18438.           if (i !== breakPoint - 1) {
  18439.             out += '/' + items[i];
  18440.           } else {
  18441.             out += items[i];
  18442.           }
  18443.         }
  18444.         return out;
  18445.       };
  18446.       URI.prototype.toAbsPath = function (base, path) {
  18447.         var i, nb = 0, o = [], outPath;
  18448.         var tr = /\/$/.test(path) ? '/' : '';
  18449.         var normalizedBase = base.split('/');
  18450.         var normalizedPath = path.split('/');
  18451.         each$7(normalizedBase, function (k) {
  18452.           if (k) {
  18453.             o.push(k);
  18454.           }
  18455.         });
  18456.         normalizedBase = o;
  18457.         for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
  18458.           if (normalizedPath[i].length === 0 || normalizedPath[i] === '.') {
  18459.             continue;
  18460.           }
  18461.           if (normalizedPath[i] === '..') {
  18462.             nb++;
  18463.             continue;
  18464.           }
  18465.           if (nb > 0) {
  18466.             nb--;
  18467.             continue;
  18468.           }
  18469.           o.push(normalizedPath[i]);
  18470.         }
  18471.         i = normalizedBase.length - nb;
  18472.         if (i <= 0) {
  18473.           outPath = reverse(o).join('/');
  18474.         } else {
  18475.           outPath = normalizedBase.slice(0, i).join('/') + '/' + reverse(o).join('/');
  18476.         }
  18477.         if (outPath.indexOf('/') !== 0) {
  18478.           outPath = '/' + outPath;
  18479.         }
  18480.         if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  18481.           outPath += tr;
  18482.         }
  18483.         return outPath;
  18484.       };
  18485.       URI.prototype.getURI = function (noProtoHost) {
  18486.         if (noProtoHost === void 0) {
  18487.           noProtoHost = false;
  18488.         }
  18489.         var s;
  18490.         if (!this.source || noProtoHost) {
  18491.           s = '';
  18492.           if (!noProtoHost) {
  18493.             if (this.protocol) {
  18494.               s += this.protocol + '://';
  18495.             } else {
  18496.               s += '//';
  18497.             }
  18498.             if (this.userInfo) {
  18499.               s += this.userInfo + '@';
  18500.             }
  18501.             if (this.host) {
  18502.               s += this.host;
  18503.             }
  18504.             if (this.port) {
  18505.               s += ':' + this.port;
  18506.             }
  18507.           }
  18508.           if (this.path) {
  18509.             s += this.path;
  18510.           }
  18511.           if (this.query) {
  18512.             s += '?' + this.query;
  18513.           }
  18514.           if (this.anchor) {
  18515.             s += '#' + this.anchor;
  18516.           }
  18517.           this.source = s;
  18518.         }
  18519.         return this.source;
  18520.       };
  18521.       return URI;
  18522.     }();
  18523.  
  18524.     var filteredClobberElements = Tools.makeMap('button,fieldset,form,iframe,img,image,input,object,output,select,textarea');
  18525.     var isValidPrefixAttrName = function (name) {
  18526.       return name.indexOf('data-') === 0 || name.indexOf('aria-') === 0;
  18527.     };
  18528.     var lazyTempDocument = cached(function () {
  18529.       return document.implementation.createHTMLDocument('parser');
  18530.     });
  18531.     var findMatchingEndTagIndex = function (schema, html, startIndex) {
  18532.       var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
  18533.       var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
  18534.       var shortEndedElements = schema.getShortEndedElements();
  18535.       var count = 1, index = startIndex;
  18536.       while (count !== 0) {
  18537.         startTagRegExp.lastIndex = index;
  18538.         while (true) {
  18539.           var startMatch = startTagRegExp.exec(html);
  18540.           if (startMatch === null) {
  18541.             return index;
  18542.           } else if (startMatch[1] === '!') {
  18543.             if (startsWith(startMatch[2], '--')) {
  18544.               index = findCommentEndIndex(html, false, startMatch.index + '!--'.length);
  18545.             } else {
  18546.               index = findCommentEndIndex(html, true, startMatch.index + 1);
  18547.             }
  18548.             break;
  18549.           } else {
  18550.             endTagRegExp.lastIndex = startTagRegExp.lastIndex;
  18551.             var endMatch = endTagRegExp.exec(html);
  18552.             if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
  18553.               continue;
  18554.             }
  18555.             if (startMatch[1] === '/') {
  18556.               count -= 1;
  18557.             } else if (!has$2(shortEndedElements, startMatch[2])) {
  18558.               count += 1;
  18559.             }
  18560.             index = startTagRegExp.lastIndex + endMatch[0].length;
  18561.             break;
  18562.           }
  18563.         }
  18564.       }
  18565.       return index;
  18566.     };
  18567.     var isConditionalComment = function (html, startIndex) {
  18568.       return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
  18569.     };
  18570.     var findCommentEndIndex = function (html, isBogus, startIndex) {
  18571.       if (startIndex === void 0) {
  18572.         startIndex = 0;
  18573.       }
  18574.       var lcHtml = html.toLowerCase();
  18575.       if (lcHtml.indexOf('[if ', startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
  18576.         var endIfIndex = lcHtml.indexOf('[endif]', startIndex);
  18577.         return lcHtml.indexOf('>', endIfIndex);
  18578.       } else {
  18579.         if (isBogus) {
  18580.           var endIndex = lcHtml.indexOf('>', startIndex);
  18581.           return endIndex !== -1 ? endIndex : lcHtml.length;
  18582.         } else {
  18583.           var endCommentRegexp = /--!?>/g;
  18584.           endCommentRegexp.lastIndex = startIndex;
  18585.           var match = endCommentRegexp.exec(html);
  18586.           return match ? match.index + match[0].length : lcHtml.length;
  18587.         }
  18588.       }
  18589.     };
  18590.     var checkBogusAttribute = function (regExp, attrString) {
  18591.       var matches = regExp.exec(attrString);
  18592.       if (matches) {
  18593.         var name_1 = matches[1];
  18594.         var value = matches[2];
  18595.         return typeof name_1 === 'string' && name_1.toLowerCase() === 'data-mce-bogus' ? value : null;
  18596.       } else {
  18597.         return null;
  18598.       }
  18599.     };
  18600.     var SaxParser = function (settings, schema) {
  18601.       if (schema === void 0) {
  18602.         schema = Schema();
  18603.       }
  18604.       settings = settings || {};
  18605.       var doc = lazyTempDocument();
  18606.       var form = doc.createElement('form');
  18607.       if (settings.fix_self_closing !== false) {
  18608.         settings.fix_self_closing = true;
  18609.       }
  18610.       var comment = settings.comment ? settings.comment : noop;
  18611.       var cdata = settings.cdata ? settings.cdata : noop;
  18612.       var text = settings.text ? settings.text : noop;
  18613.       var start = settings.start ? settings.start : noop;
  18614.       var end = settings.end ? settings.end : noop;
  18615.       var pi = settings.pi ? settings.pi : noop;
  18616.       var doctype = settings.doctype ? settings.doctype : noop;
  18617.       var parseInternal = function (base64Extract, format) {
  18618.         if (format === void 0) {
  18619.           format = 'html';
  18620.         }
  18621.         var html = base64Extract.html;
  18622.         var matches, index = 0, value, endRegExp;
  18623.         var stack = [];
  18624.         var attrList, i, textData, name;
  18625.         var isInternalElement, isShortEnded;
  18626.         var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  18627.         var attributesRequired, attributesDefault, attributesForced;
  18628.         var anyAttributesRequired, attrValue, idCount = 0;
  18629.         var decode = Entities.decode;
  18630.         var filteredUrlAttrs = Tools.makeMap('src,href,data,background,action,formaction,poster,xlink:href');
  18631.         var parsingMode = format === 'html' ? 0 : 1;
  18632.         var processEndTag = function (name) {
  18633.           var pos, i;
  18634.           pos = stack.length;
  18635.           while (pos--) {
  18636.             if (stack[pos].name === name) {
  18637.               break;
  18638.             }
  18639.           }
  18640.           if (pos >= 0) {
  18641.             for (i = stack.length - 1; i >= pos; i--) {
  18642.               name = stack[i];
  18643.               if (name.valid) {
  18644.                 end(name.name);
  18645.               }
  18646.             }
  18647.             stack.length = pos;
  18648.           }
  18649.         };
  18650.         var processText = function (value, raw) {
  18651.           return text(restoreDataUris(value, base64Extract), raw);
  18652.         };
  18653.         var processComment = function (value) {
  18654.           if (value === '') {
  18655.             return;
  18656.           }
  18657.           if (value.charAt(0) === '>') {
  18658.             value = ' ' + value;
  18659.           }
  18660.           if (!settings.allow_conditional_comments && value.substr(0, 3).toLowerCase() === '[if') {
  18661.             value = ' ' + value;
  18662.           }
  18663.           comment(restoreDataUris(value, base64Extract));
  18664.         };
  18665.         var processAttr = function (value) {
  18666.           return restoreDataUris(value, base64Extract);
  18667.         };
  18668.         var processMalformedComment = function (value, startIndex) {
  18669.           var startTag = value || '';
  18670.           var isBogus = !startsWith(startTag, '--');
  18671.           var endIndex = findCommentEndIndex(html, isBogus, startIndex);
  18672.           value = html.substr(startIndex, endIndex - startIndex);
  18673.           processComment(isBogus ? startTag + value : value);
  18674.           return endIndex + 1;
  18675.         };
  18676.         var parseAttribute = function (tagName, name, value, val2, val3) {
  18677.           name = name.toLowerCase();
  18678.           value = processAttr(name in fillAttrsMap ? name : decode(value || val2 || val3 || ''));
  18679.           if (validate && !isInternalElement && isValidPrefixAttrName(name) === false) {
  18680.             var attrRule = validAttributesMap[name];
  18681.             if (!attrRule && validAttributePatterns) {
  18682.               var i_1 = validAttributePatterns.length;
  18683.               while (i_1--) {
  18684.                 attrRule = validAttributePatterns[i_1];
  18685.                 if (attrRule.pattern.test(name)) {
  18686.                   break;
  18687.                 }
  18688.               }
  18689.               if (i_1 === -1) {
  18690.                 attrRule = null;
  18691.               }
  18692.             }
  18693.             if (!attrRule) {
  18694.               return;
  18695.             }
  18696.             if (attrRule.validValues && !(value in attrRule.validValues)) {
  18697.               return;
  18698.             }
  18699.           }
  18700.           var isNameOrId = name === 'name' || name === 'id';
  18701.           if (isNameOrId && tagName in filteredClobberElements && (value in doc || value in form)) {
  18702.             return;
  18703.           }
  18704.           if (filteredUrlAttrs[name] && !URI.isDomSafe(value, tagName, settings)) {
  18705.             return;
  18706.           }
  18707.           if (isInternalElement && (name in filteredUrlAttrs || name.indexOf('on') === 0)) {
  18708.             return;
  18709.           }
  18710.           attrList.map[name] = value;
  18711.           attrList.push({
  18712.             name: name,
  18713.             value: value
  18714.           });
  18715.         };
  18716.         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');
  18717.         var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  18718.         var shortEndedElements = schema.getShortEndedElements();
  18719.         var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  18720.         var fillAttrsMap = schema.getBoolAttrs();
  18721.         var validate = settings.validate;
  18722.         var removeInternalElements = settings.remove_internals;
  18723.         var fixSelfClosing = settings.fix_self_closing;
  18724.         var specialElements = schema.getSpecialElements();
  18725.         var processHtml = html + '>';
  18726.         while (matches = tokenRegExp.exec(processHtml)) {
  18727.           var matchText = matches[0];
  18728.           if (index < matches.index) {
  18729.             processText(decode(html.substr(index, matches.index - index)));
  18730.           }
  18731.           if (value = matches[7]) {
  18732.             value = value.toLowerCase();
  18733.             if (value.charAt(0) === ':') {
  18734.               value = value.substr(1);
  18735.             }
  18736.             processEndTag(value);
  18737.           } else if (value = matches[8]) {
  18738.             if (matches.index + matchText.length > html.length) {
  18739.               processText(decode(html.substr(matches.index)));
  18740.               index = matches.index + matchText.length;
  18741.               continue;
  18742.             }
  18743.             value = value.toLowerCase();
  18744.             if (value.charAt(0) === ':') {
  18745.               value = value.substr(1);
  18746.             }
  18747.             isShortEnded = value in shortEndedElements;
  18748.             if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  18749.               processEndTag(value);
  18750.             }
  18751.             var bogusValue = checkBogusAttribute(attrRegExp, matches[9]);
  18752.             if (bogusValue !== null) {
  18753.               if (bogusValue === 'all') {
  18754.                 index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  18755.                 tokenRegExp.lastIndex = index;
  18756.                 continue;
  18757.               }
  18758.               isValidElement = false;
  18759.             }
  18760.             if (!validate || (elementRule = schema.getElementRule(value))) {
  18761.               isValidElement = true;
  18762.               if (validate) {
  18763.                 validAttributesMap = elementRule.attributes;
  18764.                 validAttributePatterns = elementRule.attributePatterns;
  18765.               }
  18766.               if (attribsValue = matches[9]) {
  18767.                 isInternalElement = attribsValue.indexOf('data-mce-type') !== -1;
  18768.                 if (isInternalElement && removeInternalElements) {
  18769.                   isValidElement = false;
  18770.                 }
  18771.                 attrList = [];
  18772.                 attrList.map = {};
  18773.                 attribsValue.replace(attrRegExp, function (match, name, val, val2, val3) {
  18774.                   parseAttribute(value, name, val, val2, val3);
  18775.                   return '';
  18776.                 });
  18777.               } else {
  18778.                 attrList = [];
  18779.                 attrList.map = {};
  18780.               }
  18781.               if (validate && !isInternalElement) {
  18782.                 attributesRequired = elementRule.attributesRequired;
  18783.                 attributesDefault = elementRule.attributesDefault;
  18784.                 attributesForced = elementRule.attributesForced;
  18785.                 anyAttributesRequired = elementRule.removeEmptyAttrs;
  18786.                 if (anyAttributesRequired && !attrList.length) {
  18787.                   isValidElement = false;
  18788.                 }
  18789.                 if (attributesForced) {
  18790.                   i = attributesForced.length;
  18791.                   while (i--) {
  18792.                     attr = attributesForced[i];
  18793.                     name = attr.name;
  18794.                     attrValue = attr.value;
  18795.                     if (attrValue === '{$uid}') {
  18796.                       attrValue = 'mce_' + idCount++;
  18797.                     }
  18798.                     attrList.map[name] = attrValue;
  18799.                     attrList.push({
  18800.                       name: name,
  18801.                       value: attrValue
  18802.                     });
  18803.                   }
  18804.                 }
  18805.                 if (attributesDefault) {
  18806.                   i = attributesDefault.length;
  18807.                   while (i--) {
  18808.                     attr = attributesDefault[i];
  18809.                     name = attr.name;
  18810.                     if (!(name in attrList.map)) {
  18811.                       attrValue = attr.value;
  18812.                       if (attrValue === '{$uid}') {
  18813.                         attrValue = 'mce_' + idCount++;
  18814.                       }
  18815.                       attrList.map[name] = attrValue;
  18816.                       attrList.push({
  18817.                         name: name,
  18818.                         value: attrValue
  18819.                       });
  18820.                     }
  18821.                   }
  18822.                 }
  18823.                 if (attributesRequired) {
  18824.                   i = attributesRequired.length;
  18825.                   while (i--) {
  18826.                     if (attributesRequired[i] in attrList.map) {
  18827.                       break;
  18828.                     }
  18829.                   }
  18830.                   if (i === -1) {
  18831.                     isValidElement = false;
  18832.                   }
  18833.                 }
  18834.                 if (attr = attrList.map['data-mce-bogus']) {
  18835.                   if (attr === 'all') {
  18836.                     index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
  18837.                     tokenRegExp.lastIndex = index;
  18838.                     continue;
  18839.                   }
  18840.                   isValidElement = false;
  18841.                 }
  18842.               }
  18843.               if (isValidElement) {
  18844.                 start(value, attrList, isShortEnded);
  18845.               }
  18846.             } else {
  18847.               isValidElement = false;
  18848.             }
  18849.             if (endRegExp = specialElements[value]) {
  18850.               endRegExp.lastIndex = index = matches.index + matchText.length;
  18851.               if (matches = endRegExp.exec(html)) {
  18852.                 if (isValidElement) {
  18853.                   textData = html.substr(index, matches.index - index);
  18854.                 }
  18855.                 index = matches.index + matches[0].length;
  18856.               } else {
  18857.                 textData = html.substr(index);
  18858.                 index = html.length;
  18859.               }
  18860.               if (isValidElement) {
  18861.                 if (textData.length > 0) {
  18862.                   processText(textData, true);
  18863.                 }
  18864.                 end(value);
  18865.               }
  18866.               tokenRegExp.lastIndex = index;
  18867.               continue;
  18868.             }
  18869.             if (!isShortEnded) {
  18870.               if (!attribsValue || attribsValue.indexOf('/') !== attribsValue.length - 1) {
  18871.                 stack.push({
  18872.                   name: value,
  18873.                   valid: isValidElement
  18874.                 });
  18875.               } else if (isValidElement) {
  18876.                 end(value);
  18877.               }
  18878.             }
  18879.           } else if (value = matches[1]) {
  18880.             processComment(value);
  18881.           } else if (value = matches[2]) {
  18882.             var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, '#cdata');
  18883.             if (isValidCdataSection) {
  18884.               cdata(value);
  18885.             } else {
  18886.               index = processMalformedComment('', matches.index + 2);
  18887.               tokenRegExp.lastIndex = index;
  18888.               continue;
  18889.             }
  18890.           } else if (value = matches[3]) {
  18891.             doctype(value);
  18892.           } else if ((value = matches[4]) || matchText === '<!') {
  18893.             index = processMalformedComment(value, matches.index + matchText.length);
  18894.             tokenRegExp.lastIndex = index;
  18895.             continue;
  18896.           } else if (value = matches[5]) {
  18897.             if (parsingMode === 1) {
  18898.               pi(value, matches[6]);
  18899.             } else {
  18900.               index = processMalformedComment('?', matches.index + 2);
  18901.               tokenRegExp.lastIndex = index;
  18902.               continue;
  18903.             }
  18904.           }
  18905.           index = matches.index + matchText.length;
  18906.         }
  18907.         if (index < html.length) {
  18908.           processText(decode(html.substr(index)));
  18909.         }
  18910.         for (i = stack.length - 1; i >= 0; i--) {
  18911.           value = stack[i];
  18912.           if (value.valid) {
  18913.             end(value.name);
  18914.           }
  18915.         }
  18916.       };
  18917.       var parse = function (html, format) {
  18918.         if (format === void 0) {
  18919.           format = 'html';
  18920.         }
  18921.         parseInternal(extractBase64DataUris(html), format);
  18922.       };
  18923.       return { parse: parse };
  18924.     };
  18925.     SaxParser.findEndTag = findMatchingEndTagIndex;
  18926.  
  18927.     var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
  18928.     var DomParser = function (settings, schema) {
  18929.       if (schema === void 0) {
  18930.         schema = Schema();
  18931.       }
  18932.       var nodeFilters = {};
  18933.       var attributeFilters = [];
  18934.       var matchedNodes = {};
  18935.       var matchedAttributes = {};
  18936.       settings = settings || {};
  18937.       settings.validate = 'validate' in settings ? settings.validate : true;
  18938.       settings.root_name = settings.root_name || 'body';
  18939.       var fixInvalidChildren = function (nodes) {
  18940.         var nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  18941.         var nonEmptyElements = schema.getNonEmptyElements();
  18942.         var whitespaceElements = schema.getWhiteSpaceElements();
  18943.         var textBlockElements = schema.getTextBlockElements();
  18944.         var specialElements = schema.getSpecialElements();
  18945.         var removeOrUnwrapInvalidNode = function (node, originalNodeParent) {
  18946.           if (originalNodeParent === void 0) {
  18947.             originalNodeParent = node.parent;
  18948.           }
  18949.           if (specialElements[node.name]) {
  18950.             node.empty().remove();
  18951.           } else {
  18952.             var children = node.children();
  18953.             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18954.               var childNode = children_1[_i];
  18955.               if (!schema.isValidChild(originalNodeParent.name, childNode.name)) {
  18956.                 removeOrUnwrapInvalidNode(childNode, originalNodeParent);
  18957.               }
  18958.             }
  18959.             node.unwrap();
  18960.           }
  18961.         };
  18962.         for (var ni = 0; ni < nodes.length; ni++) {
  18963.           var node = nodes[ni];
  18964.           var parent_1 = void 0, newParent = void 0, tempNode = void 0;
  18965.           if (!node.parent || node.fixed) {
  18966.             continue;
  18967.           }
  18968.           if (textBlockElements[node.name] && node.parent.name === 'li') {
  18969.             var sibling = node.next;
  18970.             while (sibling) {
  18971.               if (textBlockElements[sibling.name]) {
  18972.                 sibling.name = 'li';
  18973.                 sibling.fixed = true;
  18974.                 node.parent.insert(sibling, node.parent);
  18975.               } else {
  18976.                 break;
  18977.               }
  18978.               sibling = sibling.next;
  18979.             }
  18980.             node.unwrap();
  18981.             continue;
  18982.           }
  18983.           var parents = [node];
  18984.           for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
  18985.             parents.push(parent_1);
  18986.           }
  18987.           if (parent_1 && parents.length > 1) {
  18988.             if (schema.isValidChild(parent_1.name, node.name)) {
  18989.               parents.reverse();
  18990.               newParent = filterNode(parents[0].clone());
  18991.               var currentNode = newParent;
  18992.               for (var i = 0; i < parents.length - 1; i++) {
  18993.                 if (schema.isValidChild(currentNode.name, parents[i].name)) {
  18994.                   tempNode = filterNode(parents[i].clone());
  18995.                   currentNode.append(tempNode);
  18996.                 } else {
  18997.                   tempNode = currentNode;
  18998.                 }
  18999.                 for (var childNode = parents[i].firstChild; childNode && childNode !== parents[i + 1];) {
  19000.                   var nextNode = childNode.next;
  19001.                   tempNode.append(childNode);
  19002.                   childNode = nextNode;
  19003.                 }
  19004.                 currentNode = tempNode;
  19005.               }
  19006.               if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
  19007.                 parent_1.insert(newParent, parents[0], true);
  19008.                 parent_1.insert(node, newParent);
  19009.               } else {
  19010.                 parent_1.insert(node, parents[0], true);
  19011.               }
  19012.               parent_1 = parents[0];
  19013.               if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, 'br')) {
  19014.                 parent_1.empty().remove();
  19015.               }
  19016.             } else {
  19017.               removeOrUnwrapInvalidNode(node);
  19018.             }
  19019.           } else if (node.parent) {
  19020.             if (node.name === 'li') {
  19021.               var sibling = node.prev;
  19022.               if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  19023.                 sibling.append(node);
  19024.                 continue;
  19025.               }
  19026.               sibling = node.next;
  19027.               if (sibling && (sibling.name === 'ul' || sibling.name === 'ol')) {
  19028.                 sibling.insert(node, sibling.firstChild, true);
  19029.                 continue;
  19030.               }
  19031.               node.wrap(filterNode(new AstNode('ul', 1)));
  19032.               continue;
  19033.             }
  19034.             if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  19035.               node.wrap(filterNode(new AstNode('div', 1)));
  19036.             } else {
  19037.               removeOrUnwrapInvalidNode(node);
  19038.             }
  19039.           }
  19040.         }
  19041.       };
  19042.       var filterNode = function (node) {
  19043.         var name = node.name;
  19044.         if (name in nodeFilters) {
  19045.           var list = matchedNodes[name];
  19046.           if (list) {
  19047.             list.push(node);
  19048.           } else {
  19049.             matchedNodes[name] = [node];
  19050.           }
  19051.         }
  19052.         var i = attributeFilters.length;
  19053.         while (i--) {
  19054.           var attrName = attributeFilters[i].name;
  19055.           if (attrName in node.attributes.map) {
  19056.             var list = matchedAttributes[attrName];
  19057.             if (list) {
  19058.               list.push(node);
  19059.             } else {
  19060.               matchedAttributes[attrName] = [node];
  19061.             }
  19062.           }
  19063.         }
  19064.         return node;
  19065.       };
  19066.       var addNodeFilter = function (name, callback) {
  19067.         each$6(explode$2(name), function (name) {
  19068.           var list = nodeFilters[name];
  19069.           if (!list) {
  19070.             nodeFilters[name] = list = [];
  19071.           }
  19072.           list.push(callback);
  19073.         });
  19074.       };
  19075.       var getNodeFilters = function () {
  19076.         var out = [];
  19077.         for (var name_1 in nodeFilters) {
  19078.           if (has$2(nodeFilters, name_1)) {
  19079.             out.push({
  19080.               name: name_1,
  19081.               callbacks: nodeFilters[name_1]
  19082.             });
  19083.           }
  19084.         }
  19085.         return out;
  19086.       };
  19087.       var addAttributeFilter = function (name, callback) {
  19088.         each$6(explode$2(name), function (name) {
  19089.           var i;
  19090.           for (i = 0; i < attributeFilters.length; i++) {
  19091.             if (attributeFilters[i].name === name) {
  19092.               attributeFilters[i].callbacks.push(callback);
  19093.               return;
  19094.             }
  19095.           }
  19096.           attributeFilters.push({
  19097.             name: name,
  19098.             callbacks: [callback]
  19099.           });
  19100.         });
  19101.       };
  19102.       var getAttributeFilters = function () {
  19103.         return [].concat(attributeFilters);
  19104.       };
  19105.       var parse = function (html, args) {
  19106.         var nodes, i, l, fi, fl, list, name;
  19107.         var invalidChildren = [];
  19108.         var node;
  19109.         var getRootBlockName = function (name) {
  19110.           if (name === false) {
  19111.             return '';
  19112.           } else if (name === true) {
  19113.             return 'p';
  19114.           } else {
  19115.             return name;
  19116.           }
  19117.         };
  19118.         args = args || {};
  19119.         matchedNodes = {};
  19120.         matchedAttributes = {};
  19121.         var blockElements = extend$4(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  19122.         var textRootBlockElements = getTextRootBlockElements(schema);
  19123.         var nonEmptyElements = schema.getNonEmptyElements();
  19124.         var children = schema.children;
  19125.         var validate = settings.validate;
  19126.         var forcedRootBlockName = 'forced_root_block' in args ? args.forced_root_block : settings.forced_root_block;
  19127.         var rootBlockName = getRootBlockName(forcedRootBlockName);
  19128.         var whiteSpaceElements = schema.getWhiteSpaceElements();
  19129.         var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  19130.         var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  19131.         var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  19132.         var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  19133.         var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
  19134.         var addRootBlocks = function () {
  19135.           var node = rootNode.firstChild, rootBlockNode = null;
  19136.           var trim = function (rootBlock) {
  19137.             if (rootBlock) {
  19138.               node = rootBlock.firstChild;
  19139.               if (node && node.type === 3) {
  19140.                 node.value = node.value.replace(startWhiteSpaceRegExp, '');
  19141.               }
  19142.               node = rootBlock.lastChild;
  19143.               if (node && node.type === 3) {
  19144.                 node.value = node.value.replace(endWhiteSpaceRegExp, '');
  19145.               }
  19146.             }
  19147.           };
  19148.           if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  19149.             return;
  19150.           }
  19151.           while (node) {
  19152.             var next = node.next;
  19153.             if (node.type === 3 || node.type === 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type')) {
  19154.               if (!rootBlockNode) {
  19155.                 rootBlockNode = createNode(rootBlockName, 1);
  19156.                 rootBlockNode.attr(settings.forced_root_block_attrs);
  19157.                 rootNode.insert(rootBlockNode, node);
  19158.                 rootBlockNode.append(node);
  19159.               } else {
  19160.                 rootBlockNode.append(node);
  19161.               }
  19162.             } else {
  19163.               trim(rootBlockNode);
  19164.               rootBlockNode = null;
  19165.             }
  19166.             node = next;
  19167.           }
  19168.           trim(rootBlockNode);
  19169.         };
  19170.         var createNode = function (name, type) {
  19171.           var node = new AstNode(name, type);
  19172.           var list;
  19173.           if (name in nodeFilters) {
  19174.             list = matchedNodes[name];
  19175.             if (list) {
  19176.               list.push(node);
  19177.             } else {
  19178.               matchedNodes[name] = [node];
  19179.             }
  19180.           }
  19181.           return node;
  19182.         };
  19183.         var removeWhitespaceBefore = function (node) {
  19184.           var blockElements = schema.getBlockElements();
  19185.           for (var textNode = node.prev; textNode && textNode.type === 3;) {
  19186.             var textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  19187.             if (textVal.length > 0) {
  19188.               textNode.value = textVal;
  19189.               return;
  19190.             }
  19191.             var textNodeNext = textNode.next;
  19192.             if (textNodeNext) {
  19193.               if (textNodeNext.type === 3 && textNodeNext.value.length) {
  19194.                 textNode = textNode.prev;
  19195.                 continue;
  19196.               }
  19197.               if (!blockElements[textNodeNext.name] && textNodeNext.name !== 'script' && textNodeNext.name !== 'style') {
  19198.                 textNode = textNode.prev;
  19199.                 continue;
  19200.               }
  19201.             }
  19202.             var sibling = textNode.prev;
  19203.             textNode.remove();
  19204.             textNode = sibling;
  19205.           }
  19206.         };
  19207.         var cloneAndExcludeBlocks = function (input) {
  19208.           var output = {};
  19209.           for (var name_2 in input) {
  19210.             if (name_2 !== 'li' && name_2 !== 'p') {
  19211.               output[name_2] = input[name_2];
  19212.             }
  19213.           }
  19214.           return output;
  19215.         };
  19216.         var isTextRootBlockEmpty = function (node) {
  19217.           var tempNode = node;
  19218.           while (isNonNullable(tempNode)) {
  19219.             if (tempNode.name in textRootBlockElements) {
  19220.               return isEmpty(schema, nonEmptyElements, whiteSpaceElements, tempNode);
  19221.             } else {
  19222.               tempNode = tempNode.parent;
  19223.             }
  19224.           }
  19225.           return false;
  19226.         };
  19227.         var parser = SaxParser({
  19228.           validate: validate,
  19229.           document: settings.document,
  19230.           allow_html_data_urls: settings.allow_html_data_urls,
  19231.           allow_svg_data_urls: settings.allow_svg_data_urls,
  19232.           allow_script_urls: settings.allow_script_urls,
  19233.           allow_conditional_comments: settings.allow_conditional_comments,
  19234.           preserve_cdata: settings.preserve_cdata,
  19235.           self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  19236.           cdata: function (text) {
  19237.             node.append(createNode('#cdata', 4)).value = text;
  19238.           },
  19239.           text: function (text, raw) {
  19240.             var textNode;
  19241.             if (!isInWhiteSpacePreservedElement) {
  19242.               text = text.replace(allWhiteSpaceRegExp, ' ');
  19243.               if (isLineBreakNode(node.lastChild, blockElements)) {
  19244.                 text = text.replace(startWhiteSpaceRegExp, '');
  19245.               }
  19246.             }
  19247.             if (text.length !== 0) {
  19248.               textNode = createNode('#text', 3);
  19249.               textNode.raw = !!raw;
  19250.               node.append(textNode).value = text;
  19251.             }
  19252.           },
  19253.           comment: function (text) {
  19254.             node.append(createNode('#comment', 8)).value = text;
  19255.           },
  19256.           pi: function (name, text) {
  19257.             node.append(createNode(name, 7)).value = text;
  19258.             removeWhitespaceBefore(node);
  19259.           },
  19260.           doctype: function (text) {
  19261.             var newNode = node.append(createNode('#doctype', 10));
  19262.             newNode.value = text;
  19263.             removeWhitespaceBefore(node);
  19264.           },
  19265.           start: function (name, attrs, empty) {
  19266.             var elementRule = validate ? schema.getElementRule(name) : {};
  19267.             if (elementRule) {
  19268.               var newNode = createNode(elementRule.outputName || name, 1);
  19269.               newNode.attributes = attrs;
  19270.               newNode.shortEnded = empty;
  19271.               node.append(newNode);
  19272.               var parent_2 = children[node.name];
  19273.               if (parent_2 && children[newNode.name] && !parent_2[newNode.name]) {
  19274.                 invalidChildren.push(newNode);
  19275.               }
  19276.               var attrFiltersLen = attributeFilters.length;
  19277.               while (attrFiltersLen--) {
  19278.                 var attrName = attributeFilters[attrFiltersLen].name;
  19279.                 if (attrName in attrs.map) {
  19280.                   list = matchedAttributes[attrName];
  19281.                   if (list) {
  19282.                     list.push(newNode);
  19283.                   } else {
  19284.                     matchedAttributes[attrName] = [newNode];
  19285.                   }
  19286.                 }
  19287.               }
  19288.               if (blockElements[name]) {
  19289.                 removeWhitespaceBefore(newNode);
  19290.               }
  19291.               if (!empty) {
  19292.                 node = newNode;
  19293.               }
  19294.               if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19295.                 isInWhiteSpacePreservedElement = true;
  19296.               }
  19297.             }
  19298.           },
  19299.           end: function (name) {
  19300.             var textNode, text, sibling;
  19301.             var elementRule = validate ? schema.getElementRule(name) : {};
  19302.             if (elementRule) {
  19303.               if (blockElements[name]) {
  19304.                 if (!isInWhiteSpacePreservedElement) {
  19305.                   textNode = node.firstChild;
  19306.                   if (textNode && textNode.type === 3) {
  19307.                     text = textNode.value.replace(startWhiteSpaceRegExp, '');
  19308.                     if (text.length > 0) {
  19309.                       textNode.value = text;
  19310.                       textNode = textNode.next;
  19311.                     } else {
  19312.                       sibling = textNode.next;
  19313.                       textNode.remove();
  19314.                       textNode = sibling;
  19315.                       while (textNode && textNode.type === 3) {
  19316.                         text = textNode.value;
  19317.                         sibling = textNode.next;
  19318.                         if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19319.                           textNode.remove();
  19320.                           textNode = sibling;
  19321.                         }
  19322.                         textNode = sibling;
  19323.                       }
  19324.                     }
  19325.                   }
  19326.                   textNode = node.lastChild;
  19327.                   if (textNode && textNode.type === 3) {
  19328.                     text = textNode.value.replace(endWhiteSpaceRegExp, '');
  19329.                     if (text.length > 0) {
  19330.                       textNode.value = text;
  19331.                       textNode = textNode.prev;
  19332.                     } else {
  19333.                       sibling = textNode.prev;
  19334.                       textNode.remove();
  19335.                       textNode = sibling;
  19336.                       while (textNode && textNode.type === 3) {
  19337.                         text = textNode.value;
  19338.                         sibling = textNode.prev;
  19339.                         if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  19340.                           textNode.remove();
  19341.                           textNode = sibling;
  19342.                         }
  19343.                         textNode = sibling;
  19344.                       }
  19345.                     }
  19346.                   }
  19347.                 }
  19348.               }
  19349.               if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  19350.                 isInWhiteSpacePreservedElement = false;
  19351.               }
  19352.               var isNodeEmpty = isEmpty(schema, nonEmptyElements, whiteSpaceElements, node);
  19353.               var parentNode = node.parent;
  19354.               if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
  19355.                 paddEmptyNode(settings, args, blockElements, node);
  19356.               } else if (elementRule.removeEmpty && isNodeEmpty) {
  19357.                 if (blockElements[node.name]) {
  19358.                   node.empty().remove();
  19359.                 } else {
  19360.                   node.unwrap();
  19361.                 }
  19362.               } else if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isNodeEmpty)) {
  19363.                 paddEmptyNode(settings, args, blockElements, node);
  19364.               }
  19365.               node = parentNode;
  19366.             }
  19367.           }
  19368.         }, schema);
  19369.         var rootNode = node = new AstNode(args.context || settings.root_name, 11);
  19370.         parser.parse(html, args.format);
  19371.         if (validate && invalidChildren.length) {
  19372.           if (!args.context) {
  19373.             fixInvalidChildren(invalidChildren);
  19374.           } else {
  19375.             args.invalid = true;
  19376.           }
  19377.         }
  19378.         if (rootBlockName && (rootNode.name === 'body' || args.isRootContent)) {
  19379.           addRootBlocks();
  19380.         }
  19381.         if (!args.invalid) {
  19382.           for (name in matchedNodes) {
  19383.             if (!has$2(matchedNodes, name)) {
  19384.               continue;
  19385.             }
  19386.             list = nodeFilters[name];
  19387.             nodes = matchedNodes[name];
  19388.             fi = nodes.length;
  19389.             while (fi--) {
  19390.               if (!nodes[fi].parent) {
  19391.                 nodes.splice(fi, 1);
  19392.               }
  19393.             }
  19394.             for (i = 0, l = list.length; i < l; i++) {
  19395.               list[i](nodes, name, args);
  19396.             }
  19397.           }
  19398.           for (i = 0, l = attributeFilters.length; i < l; i++) {
  19399.             list = attributeFilters[i];
  19400.             if (list.name in matchedAttributes) {
  19401.               nodes = matchedAttributes[list.name];
  19402.               fi = nodes.length;
  19403.               while (fi--) {
  19404.                 if (!nodes[fi].parent) {
  19405.                   nodes.splice(fi, 1);
  19406.                 }
  19407.               }
  19408.               for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  19409.                 list.callbacks[fi](nodes, list.name, args);
  19410.               }
  19411.             }
  19412.           }
  19413.         }
  19414.         return rootNode;
  19415.       };
  19416.       var exports = {
  19417.         schema: schema,
  19418.         addAttributeFilter: addAttributeFilter,
  19419.         getAttributeFilters: getAttributeFilters,
  19420.         addNodeFilter: addNodeFilter,
  19421.         getNodeFilters: getNodeFilters,
  19422.         filterNode: filterNode,
  19423.         parse: parse
  19424.       };
  19425.       register$1(exports, settings);
  19426.       register$2(exports, settings);
  19427.       return exports;
  19428.     };
  19429.  
  19430.     var register = function (htmlParser, settings, dom) {
  19431.       htmlParser.addAttributeFilter('data-mce-tabindex', function (nodes, name) {
  19432.         var i = nodes.length;
  19433.         while (i--) {
  19434.           var node = nodes[i];
  19435.           node.attr('tabindex', node.attr('data-mce-tabindex'));
  19436.           node.attr(name, null);
  19437.         }
  19438.       });
  19439.       htmlParser.addAttributeFilter('src,href,style', function (nodes, name) {
  19440.         var internalName = 'data-mce-' + name;
  19441.         var urlConverter = settings.url_converter;
  19442.         var urlConverterScope = settings.url_converter_scope;
  19443.         var i = nodes.length;
  19444.         while (i--) {
  19445.           var node = nodes[i];
  19446.           var value = node.attr(internalName);
  19447.           if (value !== undefined) {
  19448.             node.attr(name, value.length > 0 ? value : null);
  19449.             node.attr(internalName, null);
  19450.           } else {
  19451.             value = node.attr(name);
  19452.             if (name === 'style') {
  19453.               value = dom.serializeStyle(dom.parseStyle(value), node.name);
  19454.             } else if (urlConverter) {
  19455.               value = urlConverter.call(urlConverterScope, value, name, node.name);
  19456.             }
  19457.             node.attr(name, value.length > 0 ? value : null);
  19458.           }
  19459.         }
  19460.       });
  19461.       htmlParser.addAttributeFilter('class', function (nodes) {
  19462.         var i = nodes.length;
  19463.         while (i--) {
  19464.           var node = nodes[i];
  19465.           var value = node.attr('class');
  19466.           if (value) {
  19467.             value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  19468.             node.attr('class', value.length > 0 ? value : null);
  19469.           }
  19470.         }
  19471.       });
  19472.       htmlParser.addAttributeFilter('data-mce-type', function (nodes, name, args) {
  19473.         var i = nodes.length;
  19474.         while (i--) {
  19475.           var node = nodes[i];
  19476.           if (node.attr('data-mce-type') === 'bookmark' && !args.cleanup) {
  19477.             var hasChildren = Optional.from(node.firstChild).exists(function (firstChild) {
  19478.               return !isZwsp(firstChild.value);
  19479.             });
  19480.             if (hasChildren) {
  19481.               node.unwrap();
  19482.             } else {
  19483.               node.remove();
  19484.             }
  19485.           }
  19486.         }
  19487.       });
  19488.       htmlParser.addNodeFilter('noscript', function (nodes) {
  19489.         var i = nodes.length;
  19490.         while (i--) {
  19491.           var node = nodes[i].firstChild;
  19492.           if (node) {
  19493.             node.value = Entities.decode(node.value);
  19494.           }
  19495.         }
  19496.       });
  19497.       htmlParser.addNodeFilter('script,style', function (nodes, name) {
  19498.         var trim = function (value) {
  19499.           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, '');
  19500.         };
  19501.         var i = nodes.length;
  19502.         while (i--) {
  19503.           var node = nodes[i];
  19504.           var value = node.firstChild ? node.firstChild.value : '';
  19505.           if (name === 'script') {
  19506.             var type = node.attr('type');
  19507.             if (type) {
  19508.               node.attr('type', type === 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
  19509.             }
  19510.             if (settings.element_format === 'xhtml' && value.length > 0) {
  19511.               node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  19512.             }
  19513.           } else {
  19514.             if (settings.element_format === 'xhtml' && value.length > 0) {
  19515.               node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  19516.             }
  19517.           }
  19518.         }
  19519.       });
  19520.       htmlParser.addNodeFilter('#comment', function (nodes) {
  19521.         var i = nodes.length;
  19522.         while (i--) {
  19523.           var node = nodes[i];
  19524.           if (settings.preserve_cdata && node.value.indexOf('[CDATA[') === 0) {
  19525.             node.name = '#cdata';
  19526.             node.type = 4;
  19527.             node.value = dom.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ''));
  19528.           } else if (node.value.indexOf('mce:protected ') === 0) {
  19529.             node.name = '#text';
  19530.             node.type = 3;
  19531.             node.raw = true;
  19532.             node.value = unescape(node.value).substr(14);
  19533.           }
  19534.         }
  19535.       });
  19536.       htmlParser.addNodeFilter('xml:namespace,input', function (nodes, name) {
  19537.         var i = nodes.length;
  19538.         while (i--) {
  19539.           var node = nodes[i];
  19540.           if (node.type === 7) {
  19541.             node.remove();
  19542.           } else if (node.type === 1) {
  19543.             if (name === 'input' && !node.attr('type')) {
  19544.               node.attr('type', 'text');
  19545.             }
  19546.           }
  19547.         }
  19548.       });
  19549.       htmlParser.addAttributeFilter('data-mce-type', function (nodes) {
  19550.         each$k(nodes, function (node) {
  19551.           if (node.attr('data-mce-type') === 'format-caret') {
  19552.             if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
  19553.               node.remove();
  19554.             } else {
  19555.               node.unwrap();
  19556.             }
  19557.           }
  19558.         });
  19559.       });
  19560.       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) {
  19561.         var i = nodes.length;
  19562.         while (i--) {
  19563.           nodes[i].attr(name, null);
  19564.         }
  19565.       });
  19566.     };
  19567.     var trimTrailingBr = function (rootNode) {
  19568.       var isBr = function (node) {
  19569.         return node && node.name === 'br';
  19570.       };
  19571.       var brNode1 = rootNode.lastChild;
  19572.       if (isBr(brNode1)) {
  19573.         var brNode2 = brNode1.prev;
  19574.         if (isBr(brNode2)) {
  19575.           brNode1.remove();
  19576.           brNode2.remove();
  19577.         }
  19578.       }
  19579.     };
  19580.  
  19581.     var preProcess = function (editor, node, args) {
  19582.       var oldDoc;
  19583.       var dom = editor.dom;
  19584.       var clonedNode = node.cloneNode(true);
  19585.       var impl = document.implementation;
  19586.       if (impl.createHTMLDocument) {
  19587.         var doc_1 = impl.createHTMLDocument('');
  19588.         Tools.each(clonedNode.nodeName === 'BODY' ? clonedNode.childNodes : [clonedNode], function (node) {
  19589.           doc_1.body.appendChild(doc_1.importNode(node, true));
  19590.         });
  19591.         if (clonedNode.nodeName !== 'BODY') {
  19592.           clonedNode = doc_1.body.firstChild;
  19593.         } else {
  19594.           clonedNode = doc_1.body;
  19595.         }
  19596.         oldDoc = dom.doc;
  19597.         dom.doc = doc_1;
  19598.       }
  19599.       firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
  19600.       if (oldDoc) {
  19601.         dom.doc = oldDoc;
  19602.       }
  19603.       return clonedNode;
  19604.     };
  19605.     var shouldFireEvent = function (editor, args) {
  19606.       return editor && editor.hasEventListeners('PreProcess') && !args.no_events;
  19607.     };
  19608.     var process = function (editor, node, args) {
  19609.       return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
  19610.     };
  19611.  
  19612.     var addTempAttr = function (htmlParser, tempAttrs, name) {
  19613.       if (Tools.inArray(tempAttrs, name) === -1) {
  19614.         htmlParser.addAttributeFilter(name, function (nodes, name) {
  19615.           var i = nodes.length;
  19616.           while (i--) {
  19617.             nodes[i].attr(name, null);
  19618.           }
  19619.         });
  19620.         tempAttrs.push(name);
  19621.       }
  19622.     };
  19623.     var postProcess = function (editor, args, content) {
  19624.       if (!args.no_events && editor) {
  19625.         var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content: content }));
  19626.         return outArgs.content;
  19627.       } else {
  19628.         return content;
  19629.       }
  19630.     };
  19631.     var getHtmlFromNode = function (dom, node, args) {
  19632.       var html = trim$3(args.getInner ? node.innerHTML : dom.getOuterHTML(node));
  19633.       return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
  19634.     };
  19635.     var parseHtml = function (htmlParser, html, args) {
  19636.       var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
  19637.       var rootNode = htmlParser.parse(html, parserArgs);
  19638.       trimTrailingBr(rootNode);
  19639.       return rootNode;
  19640.     };
  19641.     var serializeNode = function (settings, schema, node) {
  19642.       var htmlSerializer = HtmlSerializer(settings, schema);
  19643.       return htmlSerializer.serialize(node);
  19644.     };
  19645.     var toHtml = function (editor, settings, schema, rootNode, args) {
  19646.       var content = serializeNode(settings, schema, rootNode);
  19647.       return postProcess(editor, args, content);
  19648.     };
  19649.     var DomSerializerImpl = function (settings, editor) {
  19650.       var tempAttrs = ['data-mce-selected'];
  19651.       var dom = editor && editor.dom ? editor.dom : DOMUtils.DOM;
  19652.       var schema = editor && editor.schema ? editor.schema : Schema(settings);
  19653.       settings.entity_encoding = settings.entity_encoding || 'named';
  19654.       settings.remove_trailing_brs = 'remove_trailing_brs' in settings ? settings.remove_trailing_brs : true;
  19655.       var htmlParser = DomParser(settings, schema);
  19656.       register(htmlParser, settings, dom);
  19657.       var serialize = function (node, parserArgs) {
  19658.         if (parserArgs === void 0) {
  19659.           parserArgs = {};
  19660.         }
  19661.         var args = __assign({ format: 'html' }, parserArgs);
  19662.         var targetNode = process(editor, node, args);
  19663.         var html = getHtmlFromNode(dom, targetNode, args);
  19664.         var rootNode = parseHtml(htmlParser, html, args);
  19665.         return args.format === 'tree' ? rootNode : toHtml(editor, settings, schema, rootNode, args);
  19666.       };
  19667.       return {
  19668.         schema: schema,
  19669.         addNodeFilter: htmlParser.addNodeFilter,
  19670.         addAttributeFilter: htmlParser.addAttributeFilter,
  19671.         serialize: serialize,
  19672.         addRules: schema.addValidElements,
  19673.         setRules: schema.setValidElements,
  19674.         addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
  19675.         getTempAttrs: constant(tempAttrs),
  19676.         getNodeFilters: htmlParser.getNodeFilters,
  19677.         getAttributeFilters: htmlParser.getAttributeFilters
  19678.       };
  19679.     };
  19680.  
  19681.     var DomSerializer = function (settings, editor) {
  19682.       var domSerializer = DomSerializerImpl(settings, editor);
  19683.       return {
  19684.         schema: domSerializer.schema,
  19685.         addNodeFilter: domSerializer.addNodeFilter,
  19686.         addAttributeFilter: domSerializer.addAttributeFilter,
  19687.         serialize: domSerializer.serialize,
  19688.         addRules: domSerializer.addRules,
  19689.         setRules: domSerializer.setRules,
  19690.         addTempAttr: domSerializer.addTempAttr,
  19691.         getTempAttrs: domSerializer.getTempAttrs,
  19692.         getNodeFilters: domSerializer.getNodeFilters,
  19693.         getAttributeFilters: domSerializer.getAttributeFilters
  19694.       };
  19695.     };
  19696.  
  19697.     var defaultFormat = 'html';
  19698.     var getContent = function (editor, args) {
  19699.       if (args === void 0) {
  19700.         args = {};
  19701.       }
  19702.       var format = args.format ? args.format : defaultFormat;
  19703.       return getContent$2(editor, args, format);
  19704.     };
  19705.  
  19706.     var setContent = function (editor, content, args) {
  19707.       if (args === void 0) {
  19708.         args = {};
  19709.       }
  19710.       return setContent$2(editor, content, args);
  19711.     };
  19712.  
  19713.     var DOM$7 = DOMUtils.DOM;
  19714.     var restoreOriginalStyles = function (editor) {
  19715.       DOM$7.setStyle(editor.id, 'display', editor.orgDisplay);
  19716.     };
  19717.     var safeDestroy = function (x) {
  19718.       return Optional.from(x).each(function (x) {
  19719.         return x.destroy();
  19720.       });
  19721.     };
  19722.     var clearDomReferences = function (editor) {
  19723.       editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
  19724.       editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
  19725.       editor.iframeElement = editor.targetElm = null;
  19726.       if (editor.selection) {
  19727.         editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
  19728.       }
  19729.     };
  19730.     var restoreForm = function (editor) {
  19731.       var form = editor.formElement;
  19732.       if (form) {
  19733.         if (form._mceOldSubmit) {
  19734.           form.submit = form._mceOldSubmit;
  19735.           form._mceOldSubmit = null;
  19736.         }
  19737.         DOM$7.unbind(form, 'submit reset', editor.formEventDelegate);
  19738.       }
  19739.     };
  19740.     var remove = function (editor) {
  19741.       if (!editor.removed) {
  19742.         var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
  19743.         var body = editor.getBody();
  19744.         var element = editor.getElement();
  19745.         if (body) {
  19746.           editor.save({ is_removing: true });
  19747.         }
  19748.         editor.removed = true;
  19749.         editor.unbindAllNativeEvents();
  19750.         if (editor.hasHiddenInput && element) {
  19751.           DOM$7.remove(element.nextSibling);
  19752.         }
  19753.         fireRemove(editor);
  19754.         editor.editorManager.remove(editor);
  19755.         if (!editor.inline && body) {
  19756.           restoreOriginalStyles(editor);
  19757.         }
  19758.         fireDetach(editor);
  19759.         DOM$7.remove(editor.getContainer());
  19760.         safeDestroy(_selectionOverrides);
  19761.         safeDestroy(editorUpload);
  19762.         editor.destroy();
  19763.       }
  19764.     };
  19765.     var destroy = function (editor, automatic) {
  19766.       var selection = editor.selection, dom = editor.dom;
  19767.       if (editor.destroyed) {
  19768.         return;
  19769.       }
  19770.       if (!automatic && !editor.removed) {
  19771.         editor.remove();
  19772.         return;
  19773.       }
  19774.       if (!automatic) {
  19775.         editor.editorManager.off('beforeunload', editor._beforeUnload);
  19776.         if (editor.theme && editor.theme.destroy) {
  19777.           editor.theme.destroy();
  19778.         }
  19779.         safeDestroy(selection);
  19780.         safeDestroy(dom);
  19781.       }
  19782.       restoreForm(editor);
  19783.       clearDomReferences(editor);
  19784.       editor.destroyed = true;
  19785.     };
  19786.  
  19787.     var deep = function (old, nu) {
  19788.       var bothObjects = isObject(old) && isObject(nu);
  19789.       return bothObjects ? deepMerge(old, nu) : nu;
  19790.     };
  19791.     var baseMerge = function (merger) {
  19792.       return function () {
  19793.         var objects = [];
  19794.         for (var _i = 0; _i < arguments.length; _i++) {
  19795.           objects[_i] = arguments[_i];
  19796.         }
  19797.         if (objects.length === 0) {
  19798.           throw new Error('Can\'t merge zero objects');
  19799.         }
  19800.         var ret = {};
  19801.         for (var j = 0; j < objects.length; j++) {
  19802.           var curObject = objects[j];
  19803.           for (var key in curObject) {
  19804.             if (has$2(curObject, key)) {
  19805.               ret[key] = merger(ret[key], curObject[key]);
  19806.             }
  19807.           }
  19808.         }
  19809.         return ret;
  19810.       };
  19811.     };
  19812.     var deepMerge = baseMerge(deep);
  19813.  
  19814.     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(',');
  19815.     var deprecatedPlugins = 'bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor'.split(',');
  19816.     var movedToPremiumPlugins = 'imagetools,toc'.split(',');
  19817.     var getDeprecatedSettings = function (settings) {
  19818.       var settingNames = filter$4(deprecatedSettings, function (setting) {
  19819.         return has$2(settings, setting);
  19820.       });
  19821.       var forcedRootBlock = settings.forced_root_block;
  19822.       if (forcedRootBlock === false || forcedRootBlock === '') {
  19823.         settingNames.push('forced_root_block (false only)');
  19824.       }
  19825.       return sort(settingNames);
  19826.     };
  19827.     var getDeprecatedPlugins = function (settings) {
  19828.       var plugins = Tools.makeMap(settings.plugins, ' ');
  19829.       var hasPlugin = function (plugin) {
  19830.         return has$2(plugins, plugin);
  19831.       };
  19832.       var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function (plugin) {
  19833.         return hasPlugin(plugin) ? [plugin + ' (moving to premium)'] : [];
  19834.       }), true);
  19835.       return sort(pluginNames);
  19836.     };
  19837.     var logDeprecationsWarning = function (rawSettings, finalSettings) {
  19838.       var deprecatedSettings = getDeprecatedSettings(rawSettings);
  19839.       var deprecatedPlugins = getDeprecatedPlugins(finalSettings);
  19840.       var hasDeprecatedPlugins = deprecatedPlugins.length > 0;
  19841.       var hasDeprecatedSettings = deprecatedSettings.length > 0;
  19842.       var isLegacyMobileTheme = finalSettings.theme === 'mobile';
  19843.       if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
  19844.         var listJoiner = '\n- ';
  19845.         var themesMessage = isLegacyMobileTheme ? '\n\nThemes:' + listJoiner + 'mobile' : '';
  19846.         var pluginsMessage = hasDeprecatedPlugins ? '\n\nPlugins:' + listJoiner + deprecatedPlugins.join(listJoiner) : '';
  19847.         var settingsMessage = hasDeprecatedSettings ? '\n\nSettings:' + listJoiner + deprecatedSettings.join(listJoiner) : '';
  19848.         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);
  19849.       }
  19850.     };
  19851.  
  19852.     var sectionResult = function (sections, settings) {
  19853.       return {
  19854.         sections: constant(sections),
  19855.         settings: constant(settings)
  19856.       };
  19857.     };
  19858.     var deviceDetection = detect().deviceType;
  19859.     var isTouch = deviceDetection.isTouch();
  19860.     var isPhone = deviceDetection.isPhone();
  19861.     var isTablet = deviceDetection.isTablet();
  19862.     var legacyMobilePlugins = [
  19863.       'lists',
  19864.       'autolink',
  19865.       'autosave'
  19866.     ];
  19867.     var defaultTouchSettings = {
  19868.       table_grid: false,
  19869.       object_resizing: false,
  19870.       resize: false
  19871.     };
  19872.     var normalizePlugins = function (plugins) {
  19873.       var pluginNames = isArray$1(plugins) ? plugins.join(' ') : plugins;
  19874.       var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(' ') : [], trim$5);
  19875.       return filter$4(trimmedPlugins, function (item) {
  19876.         return item.length > 0;
  19877.       });
  19878.     };
  19879.     var filterLegacyMobilePlugins = function (plugins) {
  19880.       return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
  19881.     };
  19882.     var extractSections = function (keys, settings) {
  19883.       var result = bifilter(settings, function (value, key) {
  19884.         return contains$3(keys, key);
  19885.       });
  19886.       return sectionResult(result.t, result.f);
  19887.     };
  19888.     var getSection = function (sectionResult, name, defaults) {
  19889.       if (defaults === void 0) {
  19890.         defaults = {};
  19891.       }
  19892.       var sections = sectionResult.sections();
  19893.       var sectionSettings = get$9(sections, name).getOr({});
  19894.       return Tools.extend({}, defaults, sectionSettings);
  19895.     };
  19896.     var hasSection = function (sectionResult, name) {
  19897.       return has$2(sectionResult.sections(), name);
  19898.     };
  19899.     var isSectionTheme = function (sectionResult, name, theme) {
  19900.       var section = sectionResult.sections();
  19901.       return hasSection(sectionResult, name) && section[name].theme === theme;
  19902.     };
  19903.     var getSectionConfig = function (sectionResult, name) {
  19904.       return hasSection(sectionResult, name) ? sectionResult.sections()[name] : {};
  19905.     };
  19906.     var getToolbarMode = function (settings, defaultVal) {
  19907.       return get$9(settings, 'toolbar_mode').orThunk(function () {
  19908.         return get$9(settings, 'toolbar_drawer').map(function (val) {
  19909.           return val === false ? 'wrap' : val;
  19910.         });
  19911.       }).getOr(defaultVal);
  19912.     };
  19913.     var getDefaultSettings = function (settings, id, documentBaseUrl, isTouch, editor) {
  19914.       var baseDefaults = {
  19915.         id: id,
  19916.         theme: 'silver',
  19917.         toolbar_mode: getToolbarMode(settings, 'floating'),
  19918.         plugins: '',
  19919.         document_base_url: documentBaseUrl,
  19920.         add_form_submit_trigger: true,
  19921.         submit_patch: true,
  19922.         add_unload_trigger: true,
  19923.         convert_urls: true,
  19924.         relative_urls: true,
  19925.         remove_script_host: true,
  19926.         object_resizing: true,
  19927.         doctype: '<!DOCTYPE html>',
  19928.         visual: true,
  19929.         font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  19930.         forced_root_block: 'p',
  19931.         hidden_input: true,
  19932.         inline_styles: true,
  19933.         convert_fonts_to_spans: true,
  19934.         indent: true,
  19935.         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',
  19936.         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',
  19937.         entity_encoding: 'named',
  19938.         url_converter: editor.convertURL,
  19939.         url_converter_scope: editor
  19940.       };
  19941.       return __assign(__assign({}, baseDefaults), isTouch ? defaultTouchSettings : {});
  19942.     };
  19943.     var getDefaultMobileSettings = function (mobileSettings, isPhone) {
  19944.       var defaultMobileSettings = {
  19945.         resize: false,
  19946.         toolbar_mode: getToolbarMode(mobileSettings, 'scrolling'),
  19947.         toolbar_sticky: false
  19948.       };
  19949.       var defaultPhoneSettings = { menubar: false };
  19950.       return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone ? defaultPhoneSettings : {});
  19951.     };
  19952.     var getExternalPlugins = function (overrideSettings, settings) {
  19953.       var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
  19954.       if (overrideSettings && overrideSettings.external_plugins) {
  19955.         return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
  19956.       } else {
  19957.         return userDefinedExternalPlugins;
  19958.       }
  19959.     };
  19960.     var combinePlugins = function (forcedPlugins, plugins) {
  19961.       return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
  19962.     };
  19963.     var getPlatformPlugins = function (isMobileDevice, sectionResult, desktopPlugins, mobilePlugins) {
  19964.       if (isMobileDevice && isSectionTheme(sectionResult, 'mobile', 'mobile')) {
  19965.         return filterLegacyMobilePlugins(mobilePlugins);
  19966.       } else if (isMobileDevice && hasSection(sectionResult, 'mobile')) {
  19967.         return mobilePlugins;
  19968.       } else {
  19969.         return desktopPlugins;
  19970.       }
  19971.     };
  19972.     var processPlugins = function (isMobileDevice, sectionResult, defaultOverrideSettings, settings) {
  19973.       var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
  19974.       var desktopPlugins = normalizePlugins(settings.plugins);
  19975.       var mobileConfig = getSectionConfig(sectionResult, 'mobile');
  19976.       var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
  19977.       var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult, desktopPlugins, mobilePlugins);
  19978.       var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
  19979.       if (Env.browser.isIE() && contains$3(combinedPlugins, 'rtc')) {
  19980.         throw new Error('RTC plugin is not supported on IE 11.');
  19981.       }
  19982.       return Tools.extend(settings, { plugins: combinedPlugins.join(' ') });
  19983.     };
  19984.     var isOnMobile = function (isMobileDevice, sectionResult) {
  19985.       return isMobileDevice && hasSection(sectionResult, 'mobile');
  19986.     };
  19987.     var combineSettings = function (isMobileDevice, isPhone, defaultSettings, defaultOverrideSettings, settings) {
  19988.       var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone) } : {};
  19989.       var sectionResult = extractSections(['mobile'], deepMerge(defaultDeviceSettings, settings));
  19990.       var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult.settings(), isOnMobile(isMobileDevice, sectionResult) ? getSection(sectionResult, 'mobile') : {}, {
  19991.         validate: true,
  19992.         external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult.settings())
  19993.       });
  19994.       return processPlugins(isMobileDevice, sectionResult, defaultOverrideSettings, extendedSettings);
  19995.     };
  19996.     var getEditorSettings = function (editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
  19997.       var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
  19998.       var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
  19999.       if (finalSettings.deprecation_warnings !== false) {
  20000.         logDeprecationsWarning(settings, finalSettings);
  20001.       }
  20002.       return finalSettings;
  20003.     };
  20004.     var getFiltered = function (predicate, editor, name) {
  20005.       return Optional.from(editor.settings[name]).filter(predicate);
  20006.     };
  20007.     var getParamObject = function (value) {
  20008.       var output = {};
  20009.       if (typeof value === 'string') {
  20010.         each$k(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function (val) {
  20011.           var arr = val.split('=');
  20012.           if (arr.length > 1) {
  20013.             output[Tools.trim(arr[0])] = Tools.trim(arr[1]);
  20014.           } else {
  20015.             output[Tools.trim(arr[0])] = Tools.trim(arr[0]);
  20016.           }
  20017.         });
  20018.       } else {
  20019.         output = value;
  20020.       }
  20021.       return output;
  20022.     };
  20023.     var isArrayOf = function (p) {
  20024.       return function (a) {
  20025.         return isArray$1(a) && forall(a, p);
  20026.       };
  20027.     };
  20028.     var getParam = function (editor, name, defaultVal, type) {
  20029.       var value = name in editor.settings ? editor.settings[name] : defaultVal;
  20030.       if (type === 'hash') {
  20031.         return getParamObject(value);
  20032.       } else if (type === 'string') {
  20033.         return getFiltered(isString$1, editor, name).getOr(defaultVal);
  20034.       } else if (type === 'number') {
  20035.         return getFiltered(isNumber, editor, name).getOr(defaultVal);
  20036.       } else if (type === 'boolean') {
  20037.         return getFiltered(isBoolean, editor, name).getOr(defaultVal);
  20038.       } else if (type === 'object') {
  20039.         return getFiltered(isObject, editor, name).getOr(defaultVal);
  20040.       } else if (type === 'array') {
  20041.         return getFiltered(isArray$1, editor, name).getOr(defaultVal);
  20042.       } else if (type === 'string[]') {
  20043.         return getFiltered(isArrayOf(isString$1), editor, name).getOr(defaultVal);
  20044.       } else if (type === 'function') {
  20045.         return getFiltered(isFunction, editor, name).getOr(defaultVal);
  20046.       } else {
  20047.         return value;
  20048.       }
  20049.     };
  20050.  
  20051.     var CreateIconManager = function () {
  20052.       var lookup = {};
  20053.       var add = function (id, iconPack) {
  20054.         lookup[id] = iconPack;
  20055.       };
  20056.       var get = function (id) {
  20057.         if (lookup[id]) {
  20058.           return lookup[id];
  20059.         }
  20060.         return { icons: {} };
  20061.       };
  20062.       var has = function (id) {
  20063.         return has$2(lookup, id);
  20064.       };
  20065.       return {
  20066.         add: add,
  20067.         get: get,
  20068.         has: has
  20069.       };
  20070.     };
  20071.     var IconManager = CreateIconManager();
  20072.  
  20073.     var getProp = function (propName, elm) {
  20074.       var rawElm = elm.dom;
  20075.       return rawElm[propName];
  20076.     };
  20077.     var getComputedSizeProp = function (propName, elm) {
  20078.       return parseInt(get$5(elm, propName), 10);
  20079.     };
  20080.     var getClientWidth = curry(getProp, 'clientWidth');
  20081.     var getClientHeight = curry(getProp, 'clientHeight');
  20082.     var getMarginTop = curry(getComputedSizeProp, 'margin-top');
  20083.     var getMarginLeft = curry(getComputedSizeProp, 'margin-left');
  20084.     var getBoundingClientRect = function (elm) {
  20085.       return elm.dom.getBoundingClientRect();
  20086.     };
  20087.     var isInsideElementContentArea = function (bodyElm, clientX, clientY) {
  20088.       var clientWidth = getClientWidth(bodyElm);
  20089.       var clientHeight = getClientHeight(bodyElm);
  20090.       return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
  20091.     };
  20092.     var transpose = function (inline, elm, clientX, clientY) {
  20093.       var clientRect = getBoundingClientRect(elm);
  20094.       var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
  20095.       var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
  20096.       var x = clientX - deltaX;
  20097.       var y = clientY - deltaY;
  20098.       return {
  20099.         x: x,
  20100.         y: y
  20101.       };
  20102.     };
  20103.     var isXYInContentArea = function (editor, clientX, clientY) {
  20104.       var bodyElm = SugarElement.fromDom(editor.getBody());
  20105.       var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
  20106.       var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
  20107.       return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
  20108.     };
  20109.     var fromDomSafe = function (node) {
  20110.       return Optional.from(node).map(SugarElement.fromDom);
  20111.     };
  20112.     var isEditorAttachedToDom = function (editor) {
  20113.       var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
  20114.       return fromDomSafe(rawContainer).map(inBody).getOr(false);
  20115.     };
  20116.  
  20117.     var NotificationManagerImpl = function () {
  20118.       var unimplemented = function () {
  20119.         throw new Error('Theme did not provide a NotificationManager implementation.');
  20120.       };
  20121.       return {
  20122.         open: unimplemented,
  20123.         close: unimplemented,
  20124.         reposition: unimplemented,
  20125.         getArgs: unimplemented
  20126.       };
  20127.     };
  20128.  
  20129.     var NotificationManager = function (editor) {
  20130.       var notifications = [];
  20131.       var getImplementation = function () {
  20132.         var theme = editor.theme;
  20133.         return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
  20134.       };
  20135.       var getTopNotification = function () {
  20136.         return Optional.from(notifications[0]);
  20137.       };
  20138.       var isEqual = function (a, b) {
  20139.         return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
  20140.       };
  20141.       var reposition = function () {
  20142.         if (notifications.length > 0) {
  20143.           getImplementation().reposition(notifications);
  20144.         }
  20145.       };
  20146.       var addNotification = function (notification) {
  20147.         notifications.push(notification);
  20148.       };
  20149.       var closeNotification = function (notification) {
  20150.         findIndex$2(notifications, function (otherNotification) {
  20151.           return otherNotification === notification;
  20152.         }).each(function (index) {
  20153.           notifications.splice(index, 1);
  20154.         });
  20155.       };
  20156.       var open = function (spec, fireEvent) {
  20157.         if (fireEvent === void 0) {
  20158.           fireEvent = true;
  20159.         }
  20160.         if (editor.removed || !isEditorAttachedToDom(editor)) {
  20161.           return;
  20162.         }
  20163.         if (fireEvent) {
  20164.           editor.fire('BeforeOpenNotification', { notification: spec });
  20165.         }
  20166.         return find$3(notifications, function (notification) {
  20167.           return isEqual(getImplementation().getArgs(notification), spec);
  20168.         }).getOrThunk(function () {
  20169.           editor.editorManager.setActive(editor);
  20170.           var notification = getImplementation().open(spec, function () {
  20171.             closeNotification(notification);
  20172.             reposition();
  20173.             getTopNotification().fold(function () {
  20174.               return editor.focus();
  20175.             }, function (top) {
  20176.               return focus$1(SugarElement.fromDom(top.getEl()));
  20177.             });
  20178.           });
  20179.           addNotification(notification);
  20180.           reposition();
  20181.           editor.fire('OpenNotification', { notification: __assign({}, notification) });
  20182.           return notification;
  20183.         });
  20184.       };
  20185.       var close = function () {
  20186.         getTopNotification().each(function (notification) {
  20187.           getImplementation().close(notification);
  20188.           closeNotification(notification);
  20189.           reposition();
  20190.         });
  20191.       };
  20192.       var getNotifications = constant(notifications);
  20193.       var registerEvents = function (editor) {
  20194.         editor.on('SkinLoaded', function () {
  20195.           var serviceMessage = getServiceMessage(editor);
  20196.           if (serviceMessage) {
  20197.             open({
  20198.               text: serviceMessage,
  20199.               type: 'warning',
  20200.               timeout: 0
  20201.             }, false);
  20202.           }
  20203.           reposition();
  20204.         });
  20205.         editor.on('show ResizeEditor ResizeWindow NodeChange', function () {
  20206.           Delay.requestAnimationFrame(reposition);
  20207.         });
  20208.         editor.on('remove', function () {
  20209.           each$k(notifications.slice(), function (notification) {
  20210.             getImplementation().close(notification);
  20211.           });
  20212.         });
  20213.       };
  20214.       registerEvents(editor);
  20215.       return {
  20216.         open: open,
  20217.         close: close,
  20218.         getNotifications: getNotifications
  20219.       };
  20220.     };
  20221.  
  20222.     var PluginManager = AddOnManager.PluginManager;
  20223.  
  20224.     var ThemeManager = AddOnManager.ThemeManager;
  20225.  
  20226.     function WindowManagerImpl () {
  20227.       var unimplemented = function () {
  20228.         throw new Error('Theme did not provide a WindowManager implementation.');
  20229.       };
  20230.       return {
  20231.         open: unimplemented,
  20232.         openUrl: unimplemented,
  20233.         alert: unimplemented,
  20234.         confirm: unimplemented,
  20235.         close: unimplemented,
  20236.         getParams: unimplemented,
  20237.         setParams: unimplemented
  20238.       };
  20239.     }
  20240.  
  20241.     var WindowManager = function (editor) {
  20242.       var dialogs = [];
  20243.       var getImplementation = function () {
  20244.         var theme = editor.theme;
  20245.         return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
  20246.       };
  20247.       var funcBind = function (scope, f) {
  20248.         return function () {
  20249.           var args = [];
  20250.           for (var _i = 0; _i < arguments.length; _i++) {
  20251.             args[_i] = arguments[_i];
  20252.           }
  20253.           return f ? f.apply(scope, args) : undefined;
  20254.         };
  20255.       };
  20256.       var fireOpenEvent = function (dialog) {
  20257.         editor.fire('OpenWindow', { dialog: dialog });
  20258.       };
  20259.       var fireCloseEvent = function (dialog) {
  20260.         editor.fire('CloseWindow', { dialog: dialog });
  20261.       };
  20262.       var addDialog = function (dialog) {
  20263.         dialogs.push(dialog);
  20264.         fireOpenEvent(dialog);
  20265.       };
  20266.       var closeDialog = function (dialog) {
  20267.         fireCloseEvent(dialog);
  20268.         dialogs = filter$4(dialogs, function (otherDialog) {
  20269.           return otherDialog !== dialog;
  20270.         });
  20271.         if (dialogs.length === 0) {
  20272.           editor.focus();
  20273.         }
  20274.       };
  20275.       var getTopDialog = function () {
  20276.         return Optional.from(dialogs[dialogs.length - 1]);
  20277.       };
  20278.       var storeSelectionAndOpenDialog = function (openDialog) {
  20279.         editor.editorManager.setActive(editor);
  20280.         store(editor);
  20281.         var dialog = openDialog();
  20282.         addDialog(dialog);
  20283.         return dialog;
  20284.       };
  20285.       var open = function (args, params) {
  20286.         return storeSelectionAndOpenDialog(function () {
  20287.           return getImplementation().open(args, params, closeDialog);
  20288.         });
  20289.       };
  20290.       var openUrl = function (args) {
  20291.         return storeSelectionAndOpenDialog(function () {
  20292.           return getImplementation().openUrl(args, closeDialog);
  20293.         });
  20294.       };
  20295.       var alert = function (message, callback, scope) {
  20296.         var windowManagerImpl = getImplementation();
  20297.         windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20298.       };
  20299.       var confirm = function (message, callback, scope) {
  20300.         var windowManagerImpl = getImplementation();
  20301.         windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
  20302.       };
  20303.       var close = function () {
  20304.         getTopDialog().each(function (dialog) {
  20305.           getImplementation().close(dialog);
  20306.           closeDialog(dialog);
  20307.         });
  20308.       };
  20309.       editor.on('remove', function () {
  20310.         each$k(dialogs, function (dialog) {
  20311.           getImplementation().close(dialog);
  20312.         });
  20313.       });
  20314.       return {
  20315.         open: open,
  20316.         openUrl: openUrl,
  20317.         alert: alert,
  20318.         confirm: confirm,
  20319.         close: close
  20320.       };
  20321.     };
  20322.  
  20323.     var displayNotification = function (editor, message) {
  20324.       editor.notificationManager.open({
  20325.         type: 'error',
  20326.         text: message
  20327.       });
  20328.     };
  20329.     var displayError = function (editor, message) {
  20330.       if (editor._skinLoaded) {
  20331.         displayNotification(editor, message);
  20332.       } else {
  20333.         editor.on('SkinLoaded', function () {
  20334.           displayNotification(editor, message);
  20335.         });
  20336.       }
  20337.     };
  20338.     var uploadError = function (editor, message) {
  20339.       displayError(editor, I18n.translate([
  20340.         'Failed to upload image: {0}',
  20341.         message
  20342.       ]));
  20343.     };
  20344.     var logError = function (editor, errorType, msg) {
  20345.       fireError(editor, errorType, { message: msg });
  20346.       console.error(msg);
  20347.     };
  20348.     var createLoadError = function (type, url, name) {
  20349.       return name ? 'Failed to load ' + type + ': ' + name + ' from url ' + url : 'Failed to load ' + type + ' url: ' + url;
  20350.     };
  20351.     var pluginLoadError = function (editor, url, name) {
  20352.       logError(editor, 'PluginLoadError', createLoadError('plugin', url, name));
  20353.     };
  20354.     var iconsLoadError = function (editor, url, name) {
  20355.       logError(editor, 'IconsLoadError', createLoadError('icons', url, name));
  20356.     };
  20357.     var languageLoadError = function (editor, url, name) {
  20358.       logError(editor, 'LanguageLoadError', createLoadError('language', url, name));
  20359.     };
  20360.     var pluginInitError = function (editor, name, err) {
  20361.       var message = I18n.translate([
  20362.         'Failed to initialize plugin: {0}',
  20363.         name
  20364.       ]);
  20365.       fireError(editor, 'PluginLoadError', { message: message });
  20366.       initError(message, err);
  20367.       displayError(editor, message);
  20368.     };
  20369.     var initError = function (message) {
  20370.       var x = [];
  20371.       for (var _i = 1; _i < arguments.length; _i++) {
  20372.         x[_i - 1] = arguments[_i];
  20373.       }
  20374.       var console = window.console;
  20375.       if (console) {
  20376.         if (console.error) {
  20377.           console.error.apply(console, __spreadArray([message], x, false));
  20378.         } else {
  20379.           console.log.apply(console, __spreadArray([message], x, false));
  20380.         }
  20381.       }
  20382.     };
  20383.  
  20384.     var isContentCssSkinName = function (url) {
  20385.       return /^[a-z0-9\-]+$/i.test(url);
  20386.     };
  20387.     var getContentCssUrls = function (editor) {
  20388.       return transformToUrls(editor, getContentCss(editor));
  20389.     };
  20390.     var getFontCssUrls = function (editor) {
  20391.       return transformToUrls(editor, getFontCss(editor));
  20392.     };
  20393.     var transformToUrls = function (editor, cssLinks) {
  20394.       var skinUrl = editor.editorManager.baseURL + '/skins/content';
  20395.       var suffix = editor.editorManager.suffix;
  20396.       var contentCssFile = 'content' + suffix + '.css';
  20397.       var inline = editor.inline === true;
  20398.       return map$3(cssLinks, function (url) {
  20399.         if (isContentCssSkinName(url) && !inline) {
  20400.           return skinUrl + '/' + url + '/' + contentCssFile;
  20401.         } else {
  20402.           return editor.documentBaseURI.toAbsolute(url);
  20403.         }
  20404.       });
  20405.     };
  20406.     var appendContentCssFromSettings = function (editor) {
  20407.       editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
  20408.     };
  20409.  
  20410.     var UploadStatus = function () {
  20411.       var PENDING = 1, UPLOADED = 2;
  20412.       var blobUriStatuses = {};
  20413.       var createStatus = function (status, resultUri) {
  20414.         return {
  20415.           status: status,
  20416.           resultUri: resultUri
  20417.         };
  20418.       };
  20419.       var hasBlobUri = function (blobUri) {
  20420.         return blobUri in blobUriStatuses;
  20421.       };
  20422.       var getResultUri = function (blobUri) {
  20423.         var result = blobUriStatuses[blobUri];
  20424.         return result ? result.resultUri : null;
  20425.       };
  20426.       var isPending = function (blobUri) {
  20427.         return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
  20428.       };
  20429.       var isUploaded = function (blobUri) {
  20430.         return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
  20431.       };
  20432.       var markPending = function (blobUri) {
  20433.         blobUriStatuses[blobUri] = createStatus(PENDING, null);
  20434.       };
  20435.       var markUploaded = function (blobUri, resultUri) {
  20436.         blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
  20437.       };
  20438.       var removeFailed = function (blobUri) {
  20439.         delete blobUriStatuses[blobUri];
  20440.       };
  20441.       var destroy = function () {
  20442.         blobUriStatuses = {};
  20443.       };
  20444.       return {
  20445.         hasBlobUri: hasBlobUri,
  20446.         getResultUri: getResultUri,
  20447.         isPending: isPending,
  20448.         isUploaded: isUploaded,
  20449.         markPending: markPending,
  20450.         markUploaded: markUploaded,
  20451.         removeFailed: removeFailed,
  20452.         destroy: destroy
  20453.       };
  20454.     };
  20455.  
  20456.     var count = 0;
  20457.     var seed = function () {
  20458.       var rnd = function () {
  20459.         return Math.round(Math.random() * 4294967295).toString(36);
  20460.       };
  20461.       var now = new Date().getTime();
  20462.       return 's' + now.toString(36) + rnd() + rnd() + rnd();
  20463.     };
  20464.     var uuid = function (prefix) {
  20465.       return prefix + count++ + seed();
  20466.     };
  20467.  
  20468.     var BlobCache = function () {
  20469.       var cache = [];
  20470.       var mimeToExt = function (mime) {
  20471.         var mimes = {
  20472.           'image/jpeg': 'jpg',
  20473.           'image/jpg': 'jpg',
  20474.           'image/gif': 'gif',
  20475.           'image/png': 'png',
  20476.           'image/apng': 'apng',
  20477.           'image/avif': 'avif',
  20478.           'image/svg+xml': 'svg',
  20479.           'image/webp': 'webp',
  20480.           'image/bmp': 'bmp',
  20481.           'image/tiff': 'tiff'
  20482.         };
  20483.         return mimes[mime.toLowerCase()] || 'dat';
  20484.       };
  20485.       var create = function (o, blob, base64, name, filename) {
  20486.         if (isString$1(o)) {
  20487.           var id = o;
  20488.           return toBlobInfo({
  20489.             id: id,
  20490.             name: name,
  20491.             filename: filename,
  20492.             blob: blob,
  20493.             base64: base64
  20494.           });
  20495.         } else if (isObject(o)) {
  20496.           return toBlobInfo(o);
  20497.         } else {
  20498.           throw new Error('Unknown input type');
  20499.         }
  20500.       };
  20501.       var toBlobInfo = function (o) {
  20502.         if (!o.blob || !o.base64) {
  20503.           throw new Error('blob and base64 representations of the image are required for BlobInfo to be created');
  20504.         }
  20505.         var id = o.id || uuid('blobid');
  20506.         var name = o.name || id;
  20507.         var blob = o.blob;
  20508.         return {
  20509.           id: constant(id),
  20510.           name: constant(name),
  20511.           filename: constant(o.filename || name + '.' + mimeToExt(blob.type)),
  20512.           blob: constant(blob),
  20513.           base64: constant(o.base64),
  20514.           blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
  20515.           uri: constant(o.uri)
  20516.         };
  20517.       };
  20518.       var add = function (blobInfo) {
  20519.         if (!get(blobInfo.id())) {
  20520.           cache.push(blobInfo);
  20521.         }
  20522.       };
  20523.       var findFirst = function (predicate) {
  20524.         return find$3(cache, predicate).getOrUndefined();
  20525.       };
  20526.       var get = function (id) {
  20527.         return findFirst(function (cachedBlobInfo) {
  20528.           return cachedBlobInfo.id() === id;
  20529.         });
  20530.       };
  20531.       var getByUri = function (blobUri) {
  20532.         return findFirst(function (blobInfo) {
  20533.           return blobInfo.blobUri() === blobUri;
  20534.         });
  20535.       };
  20536.       var getByData = function (base64, type) {
  20537.         return findFirst(function (blobInfo) {
  20538.           return blobInfo.base64() === base64 && blobInfo.blob().type === type;
  20539.         });
  20540.       };
  20541.       var removeByUri = function (blobUri) {
  20542.         cache = filter$4(cache, function (blobInfo) {
  20543.           if (blobInfo.blobUri() === blobUri) {
  20544.             URL.revokeObjectURL(blobInfo.blobUri());
  20545.             return false;
  20546.           }
  20547.           return true;
  20548.         });
  20549.       };
  20550.       var destroy = function () {
  20551.         each$k(cache, function (cachedBlobInfo) {
  20552.           URL.revokeObjectURL(cachedBlobInfo.blobUri());
  20553.         });
  20554.         cache = [];
  20555.       };
  20556.       return {
  20557.         create: create,
  20558.         add: add,
  20559.         get: get,
  20560.         getByUri: getByUri,
  20561.         getByData: getByData,
  20562.         findFirst: findFirst,
  20563.         removeByUri: removeByUri,
  20564.         destroy: destroy
  20565.       };
  20566.     };
  20567.  
  20568.     var Uploader = function (uploadStatus, settings) {
  20569.       var pendingPromises = {};
  20570.       var pathJoin = function (path1, path2) {
  20571.         if (path1) {
  20572.           return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
  20573.         }
  20574.         return path2;
  20575.       };
  20576.       var defaultHandler = function (blobInfo, success, failure, progress) {
  20577.         var xhr = new XMLHttpRequest();
  20578.         xhr.open('POST', settings.url);
  20579.         xhr.withCredentials = settings.credentials;
  20580.         xhr.upload.onprogress = function (e) {
  20581.           progress(e.loaded / e.total * 100);
  20582.         };
  20583.         xhr.onerror = function () {
  20584.           failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  20585.         };
  20586.         xhr.onload = function () {
  20587.           if (xhr.status < 200 || xhr.status >= 300) {
  20588.             failure('HTTP Error: ' + xhr.status);
  20589.             return;
  20590.           }
  20591.           var json = JSON.parse(xhr.responseText);
  20592.           if (!json || typeof json.location !== 'string') {
  20593.             failure('Invalid JSON: ' + xhr.responseText);
  20594.             return;
  20595.           }
  20596.           success(pathJoin(settings.basePath, json.location));
  20597.         };
  20598.         var formData = new FormData();
  20599.         formData.append('file', blobInfo.blob(), blobInfo.filename());
  20600.         xhr.send(formData);
  20601.       };
  20602.       var noUpload = function () {
  20603.         return new promiseObj(function (resolve) {
  20604.           resolve([]);
  20605.         });
  20606.       };
  20607.       var handlerSuccess = function (blobInfo, url) {
  20608.         return {
  20609.           url: url,
  20610.           blobInfo: blobInfo,
  20611.           status: true
  20612.         };
  20613.       };
  20614.       var handlerFailure = function (blobInfo, message, options) {
  20615.         return {
  20616.           url: '',
  20617.           blobInfo: blobInfo,
  20618.           status: false,
  20619.           error: {
  20620.             message: message,
  20621.             options: options
  20622.           }
  20623.         };
  20624.       };
  20625.       var resolvePending = function (blobUri, result) {
  20626.         Tools.each(pendingPromises[blobUri], function (resolve) {
  20627.           resolve(result);
  20628.         });
  20629.         delete pendingPromises[blobUri];
  20630.       };
  20631.       var uploadBlobInfo = function (blobInfo, handler, openNotification) {
  20632.         uploadStatus.markPending(blobInfo.blobUri());
  20633.         return new promiseObj(function (resolve) {
  20634.           var notification, progress;
  20635.           try {
  20636.             var closeNotification_1 = function () {
  20637.               if (notification) {
  20638.                 notification.close();
  20639.                 progress = noop;
  20640.               }
  20641.             };
  20642.             var success = function (url) {
  20643.               closeNotification_1();
  20644.               uploadStatus.markUploaded(blobInfo.blobUri(), url);
  20645.               resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
  20646.               resolve(handlerSuccess(blobInfo, url));
  20647.             };
  20648.             var failure = function (error, options) {
  20649.               var failureOptions = options ? options : {};
  20650.               closeNotification_1();
  20651.               uploadStatus.removeFailed(blobInfo.blobUri());
  20652.               resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error, failureOptions));
  20653.               resolve(handlerFailure(blobInfo, error, failureOptions));
  20654.             };
  20655.             progress = function (percent) {
  20656.               if (percent < 0 || percent > 100) {
  20657.                 return;
  20658.               }
  20659.               Optional.from(notification).orThunk(function () {
  20660.                 return Optional.from(openNotification).map(apply);
  20661.               }).each(function (n) {
  20662.                 notification = n;
  20663.                 n.progressBar.value(percent);
  20664.               });
  20665.             };
  20666.             handler(blobInfo, success, failure, progress);
  20667.           } catch (ex) {
  20668.             resolve(handlerFailure(blobInfo, ex.message, {}));
  20669.           }
  20670.         });
  20671.       };
  20672.       var isDefaultHandler = function (handler) {
  20673.         return handler === defaultHandler;
  20674.       };
  20675.       var pendingUploadBlobInfo = function (blobInfo) {
  20676.         var blobUri = blobInfo.blobUri();
  20677.         return new promiseObj(function (resolve) {
  20678.           pendingPromises[blobUri] = pendingPromises[blobUri] || [];
  20679.           pendingPromises[blobUri].push(resolve);
  20680.         });
  20681.       };
  20682.       var uploadBlobs = function (blobInfos, openNotification) {
  20683.         blobInfos = Tools.grep(blobInfos, function (blobInfo) {
  20684.           return !uploadStatus.isUploaded(blobInfo.blobUri());
  20685.         });
  20686.         return promiseObj.all(Tools.map(blobInfos, function (blobInfo) {
  20687.           return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification);
  20688.         }));
  20689.       };
  20690.       var upload = function (blobInfos, openNotification) {
  20691.         return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification);
  20692.       };
  20693.       if (isFunction(settings.handler) === false) {
  20694.         settings.handler = defaultHandler;
  20695.       }
  20696.       return { upload: upload };
  20697.     };
  20698.  
  20699.     var openNotification = function (editor) {
  20700.       return function () {
  20701.         return editor.notificationManager.open({
  20702.           text: editor.translate('Image uploading...'),
  20703.           type: 'info',
  20704.           timeout: -1,
  20705.           progressBar: true
  20706.         });
  20707.       };
  20708.     };
  20709.     var createUploader = function (editor, uploadStatus) {
  20710.       return Uploader(uploadStatus, {
  20711.         url: getImageUploadUrl(editor),
  20712.         basePath: getImageUploadBasePath(editor),
  20713.         credentials: getImagesUploadCredentials(editor),
  20714.         handler: getImagesUploadHandler(editor)
  20715.       });
  20716.     };
  20717.     var ImageUploader = function (editor) {
  20718.       var uploadStatus = UploadStatus();
  20719.       var uploader = createUploader(editor, uploadStatus);
  20720.       return {
  20721.         upload: function (blobInfos, showNotification) {
  20722.           if (showNotification === void 0) {
  20723.             showNotification = true;
  20724.           }
  20725.           return uploader.upload(blobInfos, showNotification ? openNotification(editor) : undefined);
  20726.         }
  20727.       };
  20728.     };
  20729.  
  20730.     var UploadChangeHandler = function (editor) {
  20731.       var lastChangedLevel = Cell(null);
  20732.       editor.on('change AddUndo', function (e) {
  20733.         lastChangedLevel.set(__assign({}, e.level));
  20734.       });
  20735.       var fireIfChanged = function () {
  20736.         var data = editor.undoManager.data;
  20737.         last$2(data).filter(function (level) {
  20738.           return !isEq$1(lastChangedLevel.get(), level);
  20739.         }).each(function (level) {
  20740.           editor.setDirty(true);
  20741.           editor.fire('change', {
  20742.             level: level,
  20743.             lastLevel: get$a(data, data.length - 2).getOrNull()
  20744.           });
  20745.         });
  20746.       };
  20747.       return { fireIfChanged: fireIfChanged };
  20748.     };
  20749.     var EditorUpload = function (editor) {
  20750.       var blobCache = BlobCache();
  20751.       var uploader, imageScanner;
  20752.       var uploadStatus = UploadStatus();
  20753.       var urlFilters = [];
  20754.       var changeHandler = UploadChangeHandler(editor);
  20755.       var aliveGuard = function (callback) {
  20756.         return function (result) {
  20757.           if (editor.selection) {
  20758.             return callback(result);
  20759.           }
  20760.           return [];
  20761.         };
  20762.       };
  20763.       var cacheInvalidator = function (url) {
  20764.         return url + (url.indexOf('?') === -1 ? '?' : '&') + new Date().getTime();
  20765.       };
  20766.       var replaceString = function (content, search, replace) {
  20767.         var index = 0;
  20768.         do {
  20769.           index = content.indexOf(search, index);
  20770.           if (index !== -1) {
  20771.             content = content.substring(0, index) + replace + content.substr(index + search.length);
  20772.             index += replace.length - search.length + 1;
  20773.           }
  20774.         } while (index !== -1);
  20775.         return content;
  20776.       };
  20777.       var replaceImageUrl = function (content, targetUrl, replacementUrl) {
  20778.         var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : '');
  20779.         content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
  20780.         content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
  20781.         return content;
  20782.       };
  20783.       var replaceUrlInUndoStack = function (targetUrl, replacementUrl) {
  20784.         each$k(editor.undoManager.data, function (level) {
  20785.           if (level.type === 'fragmented') {
  20786.             level.fragments = map$3(level.fragments, function (fragment) {
  20787.               return replaceImageUrl(fragment, targetUrl, replacementUrl);
  20788.             });
  20789.           } else {
  20790.             level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
  20791.           }
  20792.         });
  20793.       };
  20794.       var replaceImageUriInView = function (image, resultUri) {
  20795.         var src = editor.convertURL(resultUri, 'src');
  20796.         replaceUrlInUndoStack(image.src, resultUri);
  20797.         editor.$(image).attr({
  20798.           'src': shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
  20799.           'data-mce-src': src
  20800.         });
  20801.       };
  20802.       var uploadImages = function (callback) {
  20803.         if (!uploader) {
  20804.           uploader = createUploader(editor, uploadStatus);
  20805.         }
  20806.         return scanForImages().then(aliveGuard(function (imageInfos) {
  20807.           var blobInfos = map$3(imageInfos, function (imageInfo) {
  20808.             return imageInfo.blobInfo;
  20809.           });
  20810.           return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function (result) {
  20811.             var imagesToRemove = [];
  20812.             var filteredResult = map$3(result, function (uploadInfo, index) {
  20813.               var blobInfo = imageInfos[index].blobInfo;
  20814.               var image = imageInfos[index].image;
  20815.               if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
  20816.                 blobCache.removeByUri(image.src);
  20817.                 if (isRtc(editor)) ; else {
  20818.                   replaceImageUriInView(image, uploadInfo.url);
  20819.                 }
  20820.               } else if (uploadInfo.error) {
  20821.                 if (uploadInfo.error.options.remove) {
  20822.                   replaceUrlInUndoStack(image.getAttribute('src'), Env.transparentSrc);
  20823.                   imagesToRemove.push(image);
  20824.                 }
  20825.                 uploadError(editor, uploadInfo.error.message);
  20826.               }
  20827.               return {
  20828.                 element: image,
  20829.                 status: uploadInfo.status,
  20830.                 uploadUri: uploadInfo.url,
  20831.                 blobInfo: blobInfo
  20832.               };
  20833.             });
  20834.             if (filteredResult.length > 0) {
  20835.               changeHandler.fireIfChanged();
  20836.             }
  20837.             if (imagesToRemove.length > 0) {
  20838.               if (isRtc(editor)) {
  20839.                 console.error('Removing images on failed uploads is currently unsupported for RTC');
  20840.               } else {
  20841.                 editor.undoManager.transact(function () {
  20842.                   each$k(imagesToRemove, function (element) {
  20843.                     editor.dom.remove(element);
  20844.                     blobCache.removeByUri(element.src);
  20845.                   });
  20846.                 });
  20847.               }
  20848.             }
  20849.             if (callback) {
  20850.               callback(filteredResult);
  20851.             }
  20852.             return filteredResult;
  20853.           }));
  20854.         }));
  20855.       };
  20856.       var uploadImagesAuto = function (callback) {
  20857.         if (isAutomaticUploadsEnabled(editor)) {
  20858.           return uploadImages(callback);
  20859.         }
  20860.       };
  20861.       var isValidDataUriImage = function (imgElm) {
  20862.         if (forall(urlFilters, function (filter) {
  20863.             return filter(imgElm);
  20864.           }) === false) {
  20865.           return false;
  20866.         }
  20867.         if (imgElm.getAttribute('src').indexOf('data:') === 0) {
  20868.           var dataImgFilter = getImagesDataImgFilter(editor);
  20869.           return dataImgFilter(imgElm);
  20870.         }
  20871.         return true;
  20872.       };
  20873.       var addFilter = function (filter) {
  20874.         urlFilters.push(filter);
  20875.       };
  20876.       var scanForImages = function () {
  20877.         if (!imageScanner) {
  20878.           imageScanner = ImageScanner(uploadStatus, blobCache);
  20879.         }
  20880.         return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function (result) {
  20881.           result = filter$4(result, function (resultItem) {
  20882.             if (typeof resultItem === 'string') {
  20883.               displayError(editor, resultItem);
  20884.               return false;
  20885.             }
  20886.             return true;
  20887.           });
  20888.           if (isRtc(editor)) ; else {
  20889.             each$k(result, function (resultItem) {
  20890.               replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
  20891.               resultItem.image.src = resultItem.blobInfo.blobUri();
  20892.               resultItem.image.removeAttribute('data-mce-src');
  20893.             });
  20894.           }
  20895.           return result;
  20896.         }));
  20897.       };
  20898.       var destroy = function () {
  20899.         blobCache.destroy();
  20900.         uploadStatus.destroy();
  20901.         imageScanner = uploader = null;
  20902.       };
  20903.       var replaceBlobUris = function (content) {
  20904.         return content.replace(/src="(blob:[^"]+)"/g, function (match, blobUri) {
  20905.           var resultUri = uploadStatus.getResultUri(blobUri);
  20906.           if (resultUri) {
  20907.             return 'src="' + resultUri + '"';
  20908.           }
  20909.           var blobInfo = blobCache.getByUri(blobUri);
  20910.           if (!blobInfo) {
  20911.             blobInfo = foldl(editor.editorManager.get(), function (result, editor) {
  20912.               return result || editor.editorUpload && editor.editorUpload.blobCache.getByUri(blobUri);
  20913.             }, null);
  20914.           }
  20915.           if (blobInfo) {
  20916.             var blob = blobInfo.blob();
  20917.             return 'src="data:' + blob.type + ';base64,' + blobInfo.base64() + '"';
  20918.           }
  20919.           return match;
  20920.         });
  20921.       };
  20922.       editor.on('SetContent', function () {
  20923.         if (isAutomaticUploadsEnabled(editor)) {
  20924.           uploadImagesAuto();
  20925.         } else {
  20926.           scanForImages();
  20927.         }
  20928.       });
  20929.       editor.on('RawSaveContent', function (e) {
  20930.         e.content = replaceBlobUris(e.content);
  20931.       });
  20932.       editor.on('GetContent', function (e) {
  20933.         if (e.source_view || e.format === 'raw' || e.format === 'tree') {
  20934.           return;
  20935.         }
  20936.         e.content = replaceBlobUris(e.content);
  20937.       });
  20938.       editor.on('PostRender', function () {
  20939.         editor.parser.addNodeFilter('img', function (images) {
  20940.           each$k(images, function (img) {
  20941.             var src = img.attr('src');
  20942.             if (blobCache.getByUri(src)) {
  20943.               return;
  20944.             }
  20945.             var resultUri = uploadStatus.getResultUri(src);
  20946.             if (resultUri) {
  20947.               img.attr('src', resultUri);
  20948.             }
  20949.           });
  20950.         });
  20951.       });
  20952.       return {
  20953.         blobCache: blobCache,
  20954.         addFilter: addFilter,
  20955.         uploadImages: uploadImages,
  20956.         uploadImagesAuto: uploadImagesAuto,
  20957.         scanForImages: scanForImages,
  20958.         destroy: destroy
  20959.       };
  20960.     };
  20961.  
  20962.     var get = function (dom) {
  20963.       var formats = {
  20964.         valigntop: [{
  20965.             selector: 'td,th',
  20966.             styles: { verticalAlign: 'top' }
  20967.           }],
  20968.         valignmiddle: [{
  20969.             selector: 'td,th',
  20970.             styles: { verticalAlign: 'middle' }
  20971.           }],
  20972.         valignbottom: [{
  20973.             selector: 'td,th',
  20974.             styles: { verticalAlign: 'bottom' }
  20975.           }],
  20976.         alignleft: [
  20977.           {
  20978.             selector: 'figure.image',
  20979.             collapsed: false,
  20980.             classes: 'align-left',
  20981.             ceFalseOverride: true,
  20982.             preview: 'font-family font-size'
  20983.           },
  20984.           {
  20985.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  20986.             styles: { textAlign: 'left' },
  20987.             inherit: false,
  20988.             preview: false,
  20989.             defaultBlock: 'div'
  20990.           },
  20991.           {
  20992.             selector: 'img,table,audio,video',
  20993.             collapsed: false,
  20994.             styles: { float: 'left' },
  20995.             preview: 'font-family font-size'
  20996.           }
  20997.         ],
  20998.         aligncenter: [
  20999.           {
  21000.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  21001.             styles: { textAlign: 'center' },
  21002.             inherit: false,
  21003.             preview: 'font-family font-size',
  21004.             defaultBlock: 'div'
  21005.           },
  21006.           {
  21007.             selector: 'figure.image',
  21008.             collapsed: false,
  21009.             classes: 'align-center',
  21010.             ceFalseOverride: true,
  21011.             preview: 'font-family font-size'
  21012.           },
  21013.           {
  21014.             selector: 'img,audio,video',
  21015.             collapsed: false,
  21016.             styles: {
  21017.               display: 'block',
  21018.               marginLeft: 'auto',
  21019.               marginRight: 'auto'
  21020.             },
  21021.             preview: false
  21022.           },
  21023.           {
  21024.             selector: 'table',
  21025.             collapsed: false,
  21026.             styles: {
  21027.               marginLeft: 'auto',
  21028.               marginRight: 'auto'
  21029.             },
  21030.             preview: 'font-family font-size'
  21031.           }
  21032.         ],
  21033.         alignright: [
  21034.           {
  21035.             selector: 'figure.image',
  21036.             collapsed: false,
  21037.             classes: 'align-right',
  21038.             ceFalseOverride: true,
  21039.             preview: 'font-family font-size'
  21040.           },
  21041.           {
  21042.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  21043.             styles: { textAlign: 'right' },
  21044.             inherit: false,
  21045.             preview: 'font-family font-size',
  21046.             defaultBlock: 'div'
  21047.           },
  21048.           {
  21049.             selector: 'img,table,audio,video',
  21050.             collapsed: false,
  21051.             styles: { float: 'right' },
  21052.             preview: 'font-family font-size'
  21053.           }
  21054.         ],
  21055.         alignjustify: [{
  21056.             selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li',
  21057.             styles: { textAlign: 'justify' },
  21058.             inherit: false,
  21059.             defaultBlock: 'div',
  21060.             preview: 'font-family font-size'
  21061.           }],
  21062.         bold: [
  21063.           {
  21064.             inline: 'strong',
  21065.             remove: 'all',
  21066.             preserve_attributes: [
  21067.               'class',
  21068.               'style'
  21069.             ]
  21070.           },
  21071.           {
  21072.             inline: 'span',
  21073.             styles: { fontWeight: 'bold' }
  21074.           },
  21075.           {
  21076.             inline: 'b',
  21077.             remove: 'all',
  21078.             preserve_attributes: [
  21079.               'class',
  21080.               'style'
  21081.             ]
  21082.           }
  21083.         ],
  21084.         italic: [
  21085.           {
  21086.             inline: 'em',
  21087.             remove: 'all',
  21088.             preserve_attributes: [
  21089.               'class',
  21090.               'style'
  21091.             ]
  21092.           },
  21093.           {
  21094.             inline: 'span',
  21095.             styles: { fontStyle: 'italic' }
  21096.           },
  21097.           {
  21098.             inline: 'i',
  21099.             remove: 'all',
  21100.             preserve_attributes: [
  21101.               'class',
  21102.               'style'
  21103.             ]
  21104.           }
  21105.         ],
  21106.         underline: [
  21107.           {
  21108.             inline: 'span',
  21109.             styles: { textDecoration: 'underline' },
  21110.             exact: true
  21111.           },
  21112.           {
  21113.             inline: 'u',
  21114.             remove: 'all',
  21115.             preserve_attributes: [
  21116.               'class',
  21117.               'style'
  21118.             ]
  21119.           }
  21120.         ],
  21121.         strikethrough: [
  21122.           {
  21123.             inline: 'span',
  21124.             styles: { textDecoration: 'line-through' },
  21125.             exact: true
  21126.           },
  21127.           {
  21128.             inline: 'strike',
  21129.             remove: 'all',
  21130.             preserve_attributes: [
  21131.               'class',
  21132.               'style'
  21133.             ]
  21134.           },
  21135.           {
  21136.             inline: 's',
  21137.             remove: 'all',
  21138.             preserve_attributes: [
  21139.               'class',
  21140.               'style'
  21141.             ]
  21142.           }
  21143.         ],
  21144.         forecolor: {
  21145.           inline: 'span',
  21146.           styles: { color: '%value' },
  21147.           links: true,
  21148.           remove_similar: true,
  21149.           clear_child_styles: true
  21150.         },
  21151.         hilitecolor: {
  21152.           inline: 'span',
  21153.           styles: { backgroundColor: '%value' },
  21154.           links: true,
  21155.           remove_similar: true,
  21156.           clear_child_styles: true
  21157.         },
  21158.         fontname: {
  21159.           inline: 'span',
  21160.           toggle: false,
  21161.           styles: { fontFamily: '%value' },
  21162.           clear_child_styles: true
  21163.         },
  21164.         fontsize: {
  21165.           inline: 'span',
  21166.           toggle: false,
  21167.           styles: { fontSize: '%value' },
  21168.           clear_child_styles: true
  21169.         },
  21170.         lineheight: {
  21171.           selector: 'h1,h2,h3,h4,h5,h6,p,li,td,th,div',
  21172.           defaultBlock: 'p',
  21173.           styles: { lineHeight: '%value' }
  21174.         },
  21175.         fontsize_class: {
  21176.           inline: 'span',
  21177.           attributes: { class: '%value' }
  21178.         },
  21179.         blockquote: {
  21180.           block: 'blockquote',
  21181.           wrapper: true,
  21182.           remove: 'all'
  21183.         },
  21184.         subscript: { inline: 'sub' },
  21185.         superscript: { inline: 'sup' },
  21186.         code: { inline: 'code' },
  21187.         link: {
  21188.           inline: 'a',
  21189.           selector: 'a',
  21190.           remove: 'all',
  21191.           split: true,
  21192.           deep: true,
  21193.           onmatch: function (node, _fmt, _itemName) {
  21194.             return isElement$5(node) && node.hasAttribute('href');
  21195.           },
  21196.           onformat: function (elm, _fmt, vars) {
  21197.             Tools.each(vars, function (value, key) {
  21198.               dom.setAttrib(elm, key, value);
  21199.             });
  21200.           }
  21201.         },
  21202.         lang: {
  21203.           inline: 'span',
  21204.           clear_child_styles: true,
  21205.           remove_similar: true,
  21206.           attributes: {
  21207.             'lang': '%value',
  21208.             'data-mce-lang': function (vars) {
  21209.               var _a;
  21210.               return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
  21211.             }
  21212.           }
  21213.         },
  21214.         removeformat: [
  21215.           {
  21216.             selector: 'b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small',
  21217.             remove: 'all',
  21218.             split: true,
  21219.             expand: false,
  21220.             block_expand: true,
  21221.             deep: true
  21222.           },
  21223.           {
  21224.             selector: 'span',
  21225.             attributes: [
  21226.               'style',
  21227.               'class'
  21228.             ],
  21229.             remove: 'empty',
  21230.             split: true,
  21231.             expand: false,
  21232.             deep: true
  21233.           },
  21234.           {
  21235.             selector: '*',
  21236.             attributes: [
  21237.               'style',
  21238.               'class'
  21239.             ],
  21240.             split: false,
  21241.             expand: false,
  21242.             deep: true
  21243.           }
  21244.         ]
  21245.       };
  21246.       Tools.each('p h1 h2 h3 h4 h5 h6 div address pre dt dd samp'.split(/\s/), function (name) {
  21247.         formats[name] = {
  21248.           block: name,
  21249.           remove: 'all'
  21250.         };
  21251.       });
  21252.       return formats;
  21253.     };
  21254.  
  21255.     var FormatRegistry = function (editor) {
  21256.       var formats = {};
  21257.       var get$1 = function (name) {
  21258.         return isNonNullable(name) ? formats[name] : formats;
  21259.       };
  21260.       var has = function (name) {
  21261.         return has$2(formats, name);
  21262.       };
  21263.       var register = function (name, format) {
  21264.         if (name) {
  21265.           if (!isString$1(name)) {
  21266.             each$j(name, function (format, name) {
  21267.               register(name, format);
  21268.             });
  21269.           } else {
  21270.             if (!isArray$1(format)) {
  21271.               format = [format];
  21272.             }
  21273.             each$k(format, function (format) {
  21274.               if (isUndefined(format.deep)) {
  21275.                 format.deep = !isSelectorFormat(format);
  21276.               }
  21277.               if (isUndefined(format.split)) {
  21278.                 format.split = !isSelectorFormat(format) || isInlineFormat(format);
  21279.               }
  21280.               if (isUndefined(format.remove) && isSelectorFormat(format) && !isInlineFormat(format)) {
  21281.                 format.remove = 'none';
  21282.               }
  21283.               if (isSelectorFormat(format) && isInlineFormat(format)) {
  21284.                 format.mixed = true;
  21285.                 format.block_expand = true;
  21286.               }
  21287.               if (isString$1(format.classes)) {
  21288.                 format.classes = format.classes.split(/\s+/);
  21289.               }
  21290.             });
  21291.             formats[name] = format;
  21292.           }
  21293.         }
  21294.       };
  21295.       var unregister = function (name) {
  21296.         if (name && formats[name]) {
  21297.           delete formats[name];
  21298.         }
  21299.         return formats;
  21300.       };
  21301.       register(get(editor.dom));
  21302.       register(getFormats(editor));
  21303.       return {
  21304.         get: get$1,
  21305.         has: has,
  21306.         register: register,
  21307.         unregister: unregister
  21308.       };
  21309.     };
  21310.  
  21311.     var each$5 = Tools.each;
  21312.     var dom = DOMUtils.DOM;
  21313.     var parsedSelectorToHtml = function (ancestry, editor) {
  21314.       var elm, item, fragment;
  21315.       var schema = editor && editor.schema || Schema({});
  21316.       var decorate = function (elm, item) {
  21317.         if (item.classes.length) {
  21318.           dom.addClass(elm, item.classes.join(' '));
  21319.         }
  21320.         dom.setAttribs(elm, item.attrs);
  21321.       };
  21322.       var createElement = function (sItem) {
  21323.         item = typeof sItem === 'string' ? {
  21324.           name: sItem,
  21325.           classes: [],
  21326.           attrs: {}
  21327.         } : sItem;
  21328.         var elm = dom.create(item.name);
  21329.         decorate(elm, item);
  21330.         return elm;
  21331.       };
  21332.       var getRequiredParent = function (elm, candidate) {
  21333.         var name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm;
  21334.         var elmRule = schema.getElementRule(name);
  21335.         var parentsRequired = elmRule && elmRule.parentsRequired;
  21336.         if (parentsRequired && parentsRequired.length) {
  21337.           return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
  21338.         } else {
  21339.           return false;
  21340.         }
  21341.       };
  21342.       var wrapInHtml = function (elm, ancestry, siblings) {
  21343.         var parent, parentCandidate;
  21344.         var ancestor = ancestry.length > 0 && ancestry[0];
  21345.         var ancestorName = ancestor && ancestor.name;
  21346.         var parentRequired = getRequiredParent(elm, ancestorName);
  21347.         if (parentRequired) {
  21348.           if (ancestorName === parentRequired) {
  21349.             parentCandidate = ancestry[0];
  21350.             ancestry = ancestry.slice(1);
  21351.           } else {
  21352.             parentCandidate = parentRequired;
  21353.           }
  21354.         } else if (ancestor) {
  21355.           parentCandidate = ancestry[0];
  21356.           ancestry = ancestry.slice(1);
  21357.         } else if (!siblings) {
  21358.           return elm;
  21359.         }
  21360.         if (parentCandidate) {
  21361.           parent = createElement(parentCandidate);
  21362.           parent.appendChild(elm);
  21363.         }
  21364.         if (siblings) {
  21365.           if (!parent) {
  21366.             parent = dom.create('div');
  21367.             parent.appendChild(elm);
  21368.           }
  21369.           Tools.each(siblings, function (sibling) {
  21370.             var siblingElm = createElement(sibling);
  21371.             parent.insertBefore(siblingElm, elm);
  21372.           });
  21373.         }
  21374.         return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings);
  21375.       };
  21376.       if (ancestry && ancestry.length) {
  21377.         item = ancestry[0];
  21378.         elm = createElement(item);
  21379.         fragment = dom.create('div');
  21380.         fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
  21381.         return fragment;
  21382.       } else {
  21383.         return '';
  21384.       }
  21385.     };
  21386.     var parseSelectorItem = function (item) {
  21387.       var tagName;
  21388.       var obj = {
  21389.         classes: [],
  21390.         attrs: {}
  21391.       };
  21392.       item = obj.selector = Tools.trim(item);
  21393.       if (item !== '*') {
  21394.         tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) {
  21395.           switch ($1) {
  21396.           case '#':
  21397.             obj.attrs.id = $2;
  21398.             break;
  21399.           case '.':
  21400.             obj.classes.push($2);
  21401.             break;
  21402.           case ':':
  21403.             if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) {
  21404.               obj.attrs[$2] = $2;
  21405.             }
  21406.             break;
  21407.           }
  21408.           if ($3 === '[') {
  21409.             var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
  21410.             if (m) {
  21411.               obj.attrs[m[1]] = m[2];
  21412.             }
  21413.           }
  21414.           return '';
  21415.         });
  21416.       }
  21417.       obj.name = tagName || 'div';
  21418.       return obj;
  21419.     };
  21420.     var parseSelector = function (selector) {
  21421.       if (!selector || typeof selector !== 'string') {
  21422.         return [];
  21423.       }
  21424.       selector = selector.split(/\s*,\s*/)[0];
  21425.       selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1');
  21426.       return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) {
  21427.         var siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
  21428.         var obj = siblings.pop();
  21429.         if (siblings.length) {
  21430.           obj.siblings = siblings;
  21431.         }
  21432.         return obj;
  21433.       }).reverse();
  21434.     };
  21435.     var getCssText = function (editor, format) {
  21436.       var name, previewFrag;
  21437.       var previewCss = '', parentFontSize;
  21438.       var previewStyles = getPreviewStyles(editor);
  21439.       if (previewStyles === '') {
  21440.         return '';
  21441.       }
  21442.       var removeVars = function (val) {
  21443.         return val.replace(/%(\w+)/g, '');
  21444.       };
  21445.       if (typeof format === 'string') {
  21446.         format = editor.formatter.get(format);
  21447.         if (!format) {
  21448.           return;
  21449.         }
  21450.         format = format[0];
  21451.       }
  21452.       if ('preview' in format) {
  21453.         var previewOpt = get$9(format, 'preview');
  21454.         if (is$1(previewOpt, false)) {
  21455.           return '';
  21456.         } else {
  21457.           previewStyles = previewOpt.getOr(previewStyles);
  21458.         }
  21459.       }
  21460.       name = format.block || format.inline || 'span';
  21461.       var items = parseSelector(format.selector);
  21462.       if (items.length) {
  21463.         if (!items[0].name) {
  21464.           items[0].name = name;
  21465.         }
  21466.         name = format.selector;
  21467.         previewFrag = parsedSelectorToHtml(items, editor);
  21468.       } else {
  21469.         previewFrag = parsedSelectorToHtml([name], editor);
  21470.       }
  21471.       var previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild;
  21472.       each$5(format.styles, function (value, name) {
  21473.         var newValue = removeVars(value);
  21474.         if (newValue) {
  21475.           dom.setStyle(previewElm, name, newValue);
  21476.         }
  21477.       });
  21478.       each$5(format.attributes, function (value, name) {
  21479.         var newValue = removeVars(value);
  21480.         if (newValue) {
  21481.           dom.setAttrib(previewElm, name, newValue);
  21482.         }
  21483.       });
  21484.       each$5(format.classes, function (value) {
  21485.         var newValue = removeVars(value);
  21486.         if (!dom.hasClass(previewElm, newValue)) {
  21487.           dom.addClass(previewElm, newValue);
  21488.         }
  21489.       });
  21490.       editor.fire('PreviewFormats');
  21491.       dom.setStyles(previewFrag, {
  21492.         position: 'absolute',
  21493.         left: -65535
  21494.       });
  21495.       editor.getBody().appendChild(previewFrag);
  21496.       parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  21497.       parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  21498.       each$5(previewStyles.split(' '), function (name) {
  21499.         var value = dom.getStyle(previewElm, name, true);
  21500.         if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  21501.           value = dom.getStyle(editor.getBody(), name, true);
  21502.           if (dom.toHex(value).toLowerCase() === '#ffffff') {
  21503.             return;
  21504.           }
  21505.         }
  21506.         if (name === 'color') {
  21507.           if (dom.toHex(value).toLowerCase() === '#000000') {
  21508.             return;
  21509.           }
  21510.         }
  21511.         if (name === 'font-size') {
  21512.           if (/em|%$/.test(value)) {
  21513.             if (parentFontSize === 0) {
  21514.               return;
  21515.             }
  21516.             var numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1);
  21517.             value = numValue * parentFontSize + 'px';
  21518.           }
  21519.         }
  21520.         if (name === 'border' && value) {
  21521.           previewCss += 'padding:0 2px;';
  21522.         }
  21523.         previewCss += name + ':' + value + ';';
  21524.       });
  21525.       editor.fire('AfterPreviewFormats');
  21526.       dom.remove(previewFrag);
  21527.       return previewCss;
  21528.     };
  21529.  
  21530.     var setup$h = function (editor) {
  21531.       editor.addShortcut('meta+b', '', 'Bold');
  21532.       editor.addShortcut('meta+i', '', 'Italic');
  21533.       editor.addShortcut('meta+u', '', 'Underline');
  21534.       for (var i = 1; i <= 6; i++) {
  21535.         editor.addShortcut('access+' + i, '', [
  21536.           'FormatBlock',
  21537.           false,
  21538.           'h' + i
  21539.         ]);
  21540.       }
  21541.       editor.addShortcut('access+7', '', [
  21542.         'FormatBlock',
  21543.         false,
  21544.         'p'
  21545.       ]);
  21546.       editor.addShortcut('access+8', '', [
  21547.         'FormatBlock',
  21548.         false,
  21549.         'div'
  21550.       ]);
  21551.       editor.addShortcut('access+9', '', [
  21552.         'FormatBlock',
  21553.         false,
  21554.         'address'
  21555.       ]);
  21556.     };
  21557.  
  21558.     var Formatter = function (editor) {
  21559.       var formats = FormatRegistry(editor);
  21560.       var formatChangeState = Cell(null);
  21561.       setup$h(editor);
  21562.       setup$k(editor);
  21563.       return {
  21564.         get: formats.get,
  21565.         has: formats.has,
  21566.         register: formats.register,
  21567.         unregister: formats.unregister,
  21568.         apply: function (name, vars, node) {
  21569.           applyFormat(editor, name, vars, node);
  21570.         },
  21571.         remove: function (name, vars, node, similar) {
  21572.           removeFormat(editor, name, vars, node, similar);
  21573.         },
  21574.         toggle: function (name, vars, node) {
  21575.           toggleFormat(editor, name, vars, node);
  21576.         },
  21577.         match: function (name, vars, node, similar) {
  21578.           return matchFormat(editor, name, vars, node, similar);
  21579.         },
  21580.         closest: function (names) {
  21581.           return closestFormat(editor, names);
  21582.         },
  21583.         matchAll: function (names, vars) {
  21584.           return matchAllFormats(editor, names, vars);
  21585.         },
  21586.         matchNode: function (node, name, vars, similar) {
  21587.           return matchNodeFormat(editor, node, name, vars, similar);
  21588.         },
  21589.         canApply: function (name) {
  21590.           return canApplyFormat(editor, name);
  21591.         },
  21592.         formatChanged: function (formats, callback, similar, vars) {
  21593.           return formatChanged(editor, formatChangeState, formats, callback, similar, vars);
  21594.         },
  21595.         getCssText: curry(getCssText, editor)
  21596.       };
  21597.     };
  21598.  
  21599.     var shouldIgnoreCommand = function (cmd) {
  21600.       switch (cmd.toLowerCase()) {
  21601.       case 'undo':
  21602.       case 'redo':
  21603.       case 'mcerepaint':
  21604.       case 'mcefocus':
  21605.         return true;
  21606.       default:
  21607.         return false;
  21608.       }
  21609.     };
  21610.     var registerEvents = function (editor, undoManager, locks) {
  21611.       var isFirstTypedCharacter = Cell(false);
  21612.       var addNonTypingUndoLevel = function (e) {
  21613.         setTyping(undoManager, false, locks);
  21614.         undoManager.add({}, e);
  21615.       };
  21616.       editor.on('init', function () {
  21617.         undoManager.add();
  21618.       });
  21619.       editor.on('BeforeExecCommand', function (e) {
  21620.         var cmd = e.command;
  21621.         if (!shouldIgnoreCommand(cmd)) {
  21622.           endTyping(undoManager, locks);
  21623.           undoManager.beforeChange();
  21624.         }
  21625.       });
  21626.       editor.on('ExecCommand', function (e) {
  21627.         var cmd = e.command;
  21628.         if (!shouldIgnoreCommand(cmd)) {
  21629.           addNonTypingUndoLevel(e);
  21630.         }
  21631.       });
  21632.       editor.on('ObjectResizeStart cut', function () {
  21633.         undoManager.beforeChange();
  21634.       });
  21635.       editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  21636.       editor.on('dragend', addNonTypingUndoLevel);
  21637.       editor.on('keyup', function (e) {
  21638.         var keyCode = e.keyCode;
  21639.         if (e.isDefaultPrevented()) {
  21640.           return;
  21641.         }
  21642.         if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
  21643.           addNonTypingUndoLevel();
  21644.           editor.nodeChanged();
  21645.         }
  21646.         if (keyCode === 46 || keyCode === 8) {
  21647.           editor.nodeChanged();
  21648.         }
  21649.         if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
  21650.           if (editor.isDirty() === false) {
  21651.             editor.setDirty(true);
  21652.             editor.fire('change', {
  21653.               level: undoManager.data[0],
  21654.               lastLevel: null
  21655.             });
  21656.           }
  21657.           editor.fire('TypingUndo');
  21658.           isFirstTypedCharacter.set(false);
  21659.           editor.nodeChanged();
  21660.         }
  21661.       });
  21662.       editor.on('keydown', function (e) {
  21663.         var keyCode = e.keyCode;
  21664.         if (e.isDefaultPrevented()) {
  21665.           return;
  21666.         }
  21667.         if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
  21668.           if (undoManager.typing) {
  21669.             addNonTypingUndoLevel(e);
  21670.           }
  21671.           return;
  21672.         }
  21673.         var modKey = e.ctrlKey && !e.altKey || e.metaKey;
  21674.         if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
  21675.           undoManager.beforeChange();
  21676.           setTyping(undoManager, true, locks);
  21677.           undoManager.add({}, e);
  21678.           isFirstTypedCharacter.set(true);
  21679.         }
  21680.       });
  21681.       editor.on('mousedown', function (e) {
  21682.         if (undoManager.typing) {
  21683.           addNonTypingUndoLevel(e);
  21684.         }
  21685.       });
  21686.       var isInsertReplacementText = function (event) {
  21687.         return event.inputType === 'insertReplacementText';
  21688.       };
  21689.       var isInsertTextDataNull = function (event) {
  21690.         return event.inputType === 'insertText' && event.data === null;
  21691.       };
  21692.       var isInsertFromPasteOrDrop = function (event) {
  21693.         return event.inputType === 'insertFromPaste' || event.inputType === 'insertFromDrop';
  21694.       };
  21695.       editor.on('input', function (e) {
  21696.         if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
  21697.           addNonTypingUndoLevel(e);
  21698.         }
  21699.       });
  21700.       editor.on('AddUndo Undo Redo ClearUndos', function (e) {
  21701.         if (!e.isDefaultPrevented()) {
  21702.           editor.nodeChanged();
  21703.         }
  21704.       });
  21705.     };
  21706.     var addKeyboardShortcuts = function (editor) {
  21707.       editor.addShortcut('meta+z', '', 'Undo');
  21708.       editor.addShortcut('meta+y,meta+shift+z', '', 'Redo');
  21709.     };
  21710.  
  21711.     var UndoManager = function (editor) {
  21712.       var beforeBookmark = value();
  21713.       var locks = Cell(0);
  21714.       var index = Cell(0);
  21715.       var undoManager = {
  21716.         data: [],
  21717.         typing: false,
  21718.         beforeChange: function () {
  21719.           beforeChange(editor, locks, beforeBookmark);
  21720.         },
  21721.         add: function (level, event) {
  21722.           return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
  21723.         },
  21724.         undo: function () {
  21725.           return undo(editor, undoManager, locks, index);
  21726.         },
  21727.         redo: function () {
  21728.           return redo(editor, index, undoManager.data);
  21729.         },
  21730.         clear: function () {
  21731.           clear(editor, undoManager, index);
  21732.         },
  21733.         reset: function () {
  21734.           reset(editor, undoManager);
  21735.         },
  21736.         hasUndo: function () {
  21737.           return hasUndo(editor, undoManager, index);
  21738.         },
  21739.         hasRedo: function () {
  21740.           return hasRedo(editor, undoManager, index);
  21741.         },
  21742.         transact: function (callback) {
  21743.           return transact(editor, undoManager, locks, callback);
  21744.         },
  21745.         ignore: function (callback) {
  21746.           ignore(editor, locks, callback);
  21747.         },
  21748.         extra: function (callback1, callback2) {
  21749.           extra(editor, undoManager, index, callback1, callback2);
  21750.         }
  21751.       };
  21752.       if (!isRtc(editor)) {
  21753.         registerEvents(editor, undoManager, locks);
  21754.       }
  21755.       addKeyboardShortcuts(editor);
  21756.       return undoManager;
  21757.     };
  21758.  
  21759.     var nonTypingKeycodes = [
  21760.       9,
  21761.       27,
  21762.       VK.HOME,
  21763.       VK.END,
  21764.       19,
  21765.       20,
  21766.       44,
  21767.       144,
  21768.       145,
  21769.       33,
  21770.       34,
  21771.       45,
  21772.       16,
  21773.       17,
  21774.       18,
  21775.       91,
  21776.       92,
  21777.       93,
  21778.       VK.DOWN,
  21779.       VK.UP,
  21780.       VK.LEFT,
  21781.       VK.RIGHT
  21782.     ].concat(Env.browser.isFirefox() ? [224] : []);
  21783.     var placeholderAttr = 'data-mce-placeholder';
  21784.     var isKeyboardEvent = function (e) {
  21785.       return e.type === 'keydown' || e.type === 'keyup';
  21786.     };
  21787.     var isDeleteEvent = function (e) {
  21788.       var keyCode = e.keyCode;
  21789.       return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
  21790.     };
  21791.     var isNonTypingKeyboardEvent = function (e) {
  21792.       if (isKeyboardEvent(e)) {
  21793.         var keyCode = e.keyCode;
  21794.         return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
  21795.       } else {
  21796.         return false;
  21797.       }
  21798.     };
  21799.     var isTypingKeyboardEvent = function (e) {
  21800.       return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === 'keyup' && e.keyCode === 229);
  21801.     };
  21802.     var isVisuallyEmpty = function (dom, rootElm, forcedRootBlock) {
  21803.       if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
  21804.         var isForcedRootBlockFalse = forcedRootBlock === '';
  21805.         var firstElement = rootElm.firstElementChild;
  21806.         if (!firstElement) {
  21807.           return true;
  21808.         } else if (dom.getStyle(rootElm.firstElementChild, 'padding-left') || dom.getStyle(rootElm.firstElementChild, 'padding-right')) {
  21809.           return false;
  21810.         } else {
  21811.           return isForcedRootBlockFalse ? !dom.isBlock(firstElement) : forcedRootBlock === firstElement.nodeName.toLowerCase();
  21812.         }
  21813.       } else {
  21814.         return false;
  21815.       }
  21816.     };
  21817.     var setup$g = function (editor) {
  21818.       var dom = editor.dom;
  21819.       var rootBlock = getForcedRootBlock(editor);
  21820.       var placeholder = getPlaceholder(editor);
  21821.       var updatePlaceholder = function (e, initial) {
  21822.         if (isNonTypingKeyboardEvent(e)) {
  21823.           return;
  21824.         }
  21825.         var body = editor.getBody();
  21826.         var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom, body, rootBlock);
  21827.         var isPlaceholderShown = dom.getAttrib(body, placeholderAttr) !== '';
  21828.         if (isPlaceholderShown !== showPlaceholder || initial) {
  21829.           dom.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
  21830.           dom.setAttrib(body, 'aria-placeholder', showPlaceholder ? placeholder : null);
  21831.           firePlaceholderToggle(editor, showPlaceholder);
  21832.           editor.on(showPlaceholder ? 'keydown' : 'keyup', updatePlaceholder);
  21833.           editor.off(showPlaceholder ? 'keyup' : 'keydown', updatePlaceholder);
  21834.         }
  21835.       };
  21836.       if (placeholder) {
  21837.         editor.on('init', function (e) {
  21838.           updatePlaceholder(e, true);
  21839.           editor.on('change SetContent ExecCommand', updatePlaceholder);
  21840.           editor.on('paste', function (e) {
  21841.             return Delay.setEditorTimeout(editor, function () {
  21842.               return updatePlaceholder(e);
  21843.             });
  21844.           });
  21845.         });
  21846.       }
  21847.     };
  21848.  
  21849.     var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
  21850.     var hasStrongRtl = function (text) {
  21851.       return strongRtl.test(text);
  21852.     };
  21853.  
  21854.     var isInlineTarget = function (editor, elm) {
  21855.       return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
  21856.     };
  21857.     var isRtl = function (element) {
  21858.       return DOMUtils.DOM.getStyle(element, 'direction', true) === 'rtl' || hasStrongRtl(element.textContent);
  21859.     };
  21860.     var findInlineParents = function (isInlineTarget, rootNode, pos) {
  21861.       return filter$4(DOMUtils.DOM.getParents(pos.container(), '*', rootNode), isInlineTarget);
  21862.     };
  21863.     var findRootInline = function (isInlineTarget, rootNode, pos) {
  21864.       var parents = findInlineParents(isInlineTarget, rootNode, pos);
  21865.       return Optional.from(parents[parents.length - 1]);
  21866.     };
  21867.     var hasSameParentBlock = function (rootNode, node1, node2) {
  21868.       var block1 = getParentBlock$2(node1, rootNode);
  21869.       var block2 = getParentBlock$2(node2, rootNode);
  21870.       return block1 && block1 === block2;
  21871.     };
  21872.     var isAtZwsp = function (pos) {
  21873.       return isBeforeInline(pos) || isAfterInline(pos);
  21874.     };
  21875.     var normalizePosition = function (forward, pos) {
  21876.       if (!pos) {
  21877.         return pos;
  21878.       }
  21879.       var container = pos.container(), offset = pos.offset();
  21880.       if (forward) {
  21881.         if (isCaretContainerInline(container)) {
  21882.           if (isText$7(container.nextSibling)) {
  21883.             return CaretPosition(container.nextSibling, 0);
  21884.           } else {
  21885.             return CaretPosition.after(container);
  21886.           }
  21887.         } else {
  21888.           return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
  21889.         }
  21890.       } else {
  21891.         if (isCaretContainerInline(container)) {
  21892.           if (isText$7(container.previousSibling)) {
  21893.             return CaretPosition(container.previousSibling, container.previousSibling.data.length);
  21894.           } else {
  21895.             return CaretPosition.before(container);
  21896.           }
  21897.         } else {
  21898.           return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
  21899.         }
  21900.       }
  21901.     };
  21902.     var normalizeForwards = curry(normalizePosition, true);
  21903.     var normalizeBackwards = curry(normalizePosition, false);
  21904.  
  21905.     var isBeforeRoot = function (rootNode) {
  21906.       return function (elm) {
  21907.         return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
  21908.       };
  21909.     };
  21910.     var isTextBlockOrListItem = function (element) {
  21911.       return isTextBlock$2(element) || isListItem(element);
  21912.     };
  21913.     var getParentBlock$1 = function (rootNode, elm) {
  21914.       if (contains$1(rootNode, elm)) {
  21915.         return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
  21916.       } else {
  21917.         return Optional.none();
  21918.       }
  21919.     };
  21920.     var placeCaretInEmptyBody = function (editor) {
  21921.       var body = editor.getBody();
  21922.       var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
  21923.       editor.selection.setCursorLocation(node, 0);
  21924.     };
  21925.     var paddEmptyBody = function (editor) {
  21926.       if (editor.dom.isEmpty(editor.getBody())) {
  21927.         editor.setContent('');
  21928.         placeCaretInEmptyBody(editor);
  21929.       }
  21930.     };
  21931.     var willDeleteLastPositionInElement = function (forward, fromPos, elm) {
  21932.       return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  21933.         var normalizedFirstPos = normalizePosition(true, firstPos);
  21934.         var normalizedLastPos = normalizePosition(false, lastPos);
  21935.         var normalizedFromPos = normalizePosition(false, fromPos);
  21936.         if (forward) {
  21937.           return nextPosition(elm, normalizedFromPos).exists(function (nextPos) {
  21938.             return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
  21939.           });
  21940.         } else {
  21941.           return prevPosition(elm, normalizedFromPos).exists(function (prevPos) {
  21942.             return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
  21943.           });
  21944.         }
  21945.       }).getOr(true);
  21946.     };
  21947.  
  21948.     var blockPosition = function (block, position) {
  21949.       return {
  21950.         block: block,
  21951.         position: position
  21952.       };
  21953.     };
  21954.     var blockBoundary = function (from, to) {
  21955.       return {
  21956.         from: from,
  21957.         to: to
  21958.       };
  21959.     };
  21960.     var getBlockPosition = function (rootNode, pos) {
  21961.       var rootElm = SugarElement.fromDom(rootNode);
  21962.       var containerElm = SugarElement.fromDom(pos.container());
  21963.       return getParentBlock$1(rootElm, containerElm).map(function (block) {
  21964.         return blockPosition(block, pos);
  21965.       });
  21966.     };
  21967.     var isDifferentBlocks = function (blockBoundary) {
  21968.       return eq(blockBoundary.from.block, blockBoundary.to.block) === false;
  21969.     };
  21970.     var hasSameParent = function (blockBoundary) {
  21971.       return parent(blockBoundary.from.block).bind(function (parent1) {
  21972.         return parent(blockBoundary.to.block).filter(function (parent2) {
  21973.           return eq(parent1, parent2);
  21974.         });
  21975.       }).isSome();
  21976.     };
  21977.     var isEditable$1 = function (blockBoundary) {
  21978.       return isContentEditableFalse$b(blockBoundary.from.block.dom) === false && isContentEditableFalse$b(blockBoundary.to.block.dom) === false;
  21979.     };
  21980.     var skipLastBr = function (rootNode, forward, blockPosition) {
  21981.       if (isBr$5(blockPosition.position.getNode()) && isEmpty$2(blockPosition.block) === false) {
  21982.         return positionIn(false, blockPosition.block.dom).bind(function (lastPositionInBlock) {
  21983.           if (lastPositionInBlock.isEqual(blockPosition.position)) {
  21984.             return fromPosition(forward, rootNode, lastPositionInBlock).bind(function (to) {
  21985.               return getBlockPosition(rootNode, to);
  21986.             });
  21987.           } else {
  21988.             return Optional.some(blockPosition);
  21989.           }
  21990.         }).getOr(blockPosition);
  21991.       } else {
  21992.         return blockPosition;
  21993.       }
  21994.     };
  21995.     var readFromRange = function (rootNode, forward, rng) {
  21996.       var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
  21997.       var toBlockPos = fromBlockPos.bind(function (blockPos) {
  21998.         return fromPosition(forward, rootNode, blockPos.position).bind(function (to) {
  21999.           return getBlockPosition(rootNode, to).map(function (blockPos) {
  22000.             return skipLastBr(rootNode, forward, blockPos);
  22001.           });
  22002.         });
  22003.       });
  22004.       return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function (blockBoundary) {
  22005.         return isDifferentBlocks(blockBoundary) && hasSameParent(blockBoundary) && isEditable$1(blockBoundary);
  22006.       });
  22007.     };
  22008.     var read$1 = function (rootNode, forward, rng) {
  22009.       return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
  22010.     };
  22011.  
  22012.     var getChildrenUntilBlockBoundary = function (block) {
  22013.       var children$1 = children(block);
  22014.       return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function (index) {
  22015.         return children$1.slice(0, index);
  22016.       });
  22017.     };
  22018.     var extractChildren = function (block) {
  22019.       var children = getChildrenUntilBlockBoundary(block);
  22020.       each$k(children, remove$7);
  22021.       return children;
  22022.     };
  22023.     var removeEmptyRoot = function (rootNode, block) {
  22024.       var parents = parentsAndSelf(block, rootNode);
  22025.       return find$3(parents.reverse(), function (element) {
  22026.         return isEmpty$2(element);
  22027.       }).each(remove$7);
  22028.     };
  22029.     var isEmptyBefore = function (el) {
  22030.       return filter$4(prevSiblings(el), function (el) {
  22031.         return !isEmpty$2(el);
  22032.       }).length === 0;
  22033.     };
  22034.     var nestedBlockMerge = function (rootNode, fromBlock, toBlock, insertionPoint) {
  22035.       if (isEmpty$2(toBlock)) {
  22036.         fillWithPaddingBr(toBlock);
  22037.         return firstPositionIn(toBlock.dom);
  22038.       }
  22039.       if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
  22040.         before$4(insertionPoint, SugarElement.fromTag('br'));
  22041.       }
  22042.       var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
  22043.       each$k(extractChildren(fromBlock), function (child) {
  22044.         before$4(insertionPoint, child);
  22045.       });
  22046.       removeEmptyRoot(rootNode, fromBlock);
  22047.       return position;
  22048.     };
  22049.     var sidelongBlockMerge = function (rootNode, fromBlock, toBlock) {
  22050.       if (isEmpty$2(toBlock)) {
  22051.         remove$7(toBlock);
  22052.         if (isEmpty$2(fromBlock)) {
  22053.           fillWithPaddingBr(fromBlock);
  22054.         }
  22055.         return firstPositionIn(fromBlock.dom);
  22056.       }
  22057.       var position = lastPositionIn(toBlock.dom);
  22058.       each$k(extractChildren(fromBlock), function (child) {
  22059.         append$1(toBlock, child);
  22060.       });
  22061.       removeEmptyRoot(rootNode, fromBlock);
  22062.       return position;
  22063.     };
  22064.     var findInsertionPoint = function (toBlock, block) {
  22065.       var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
  22066.       return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
  22067.     };
  22068.     var getInsertionPoint = function (fromBlock, toBlock) {
  22069.       return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
  22070.     };
  22071.     var trimBr = function (first, block) {
  22072.       positionIn(first, block.dom).map(function (position) {
  22073.         return position.getNode();
  22074.       }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
  22075.     };
  22076.     var mergeBlockInto = function (rootNode, fromBlock, toBlock) {
  22077.       trimBr(true, fromBlock);
  22078.       trimBr(false, toBlock);
  22079.       return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
  22080.     };
  22081.     var mergeBlocks = function (rootNode, forward, block1, block2) {
  22082.       return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
  22083.     };
  22084.  
  22085.     var backspaceDelete$8 = function (editor, forward) {
  22086.       var rootNode = SugarElement.fromDom(editor.getBody());
  22087.       var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function (blockBoundary) {
  22088.         return mergeBlocks(rootNode, forward, blockBoundary.from.block, blockBoundary.to.block);
  22089.       });
  22090.       position.each(function (pos) {
  22091.         editor.selection.setRng(pos.toRange());
  22092.       });
  22093.       return position.isSome();
  22094.     };
  22095.  
  22096.     var deleteRangeMergeBlocks = function (rootNode, selection) {
  22097.       var rng = selection.getRng();
  22098.       return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function (block1, block2) {
  22099.         if (eq(block1, block2) === false) {
  22100.           rng.deleteContents();
  22101.           mergeBlocks(rootNode, true, block1, block2).each(function (pos) {
  22102.             selection.setRng(pos.toRange());
  22103.           });
  22104.           return true;
  22105.         } else {
  22106.           return false;
  22107.         }
  22108.       }).getOr(false);
  22109.     };
  22110.     var isRawNodeInTable = function (root, rawNode) {
  22111.       var node = SugarElement.fromDom(rawNode);
  22112.       var isRoot = curry(eq, root);
  22113.       return ancestor$3(node, isTableCell$4, isRoot).isSome();
  22114.     };
  22115.     var isSelectionInTable = function (root, rng) {
  22116.       return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
  22117.     };
  22118.     var isEverythingSelected = function (root, rng) {
  22119.       var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
  22120.       var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
  22121.       return !isSelectionInTable(root, rng) && noPrevious && noNext;
  22122.     };
  22123.     var emptyEditor = function (editor) {
  22124.       editor.setContent('');
  22125.       editor.selection.setCursorLocation();
  22126.       return true;
  22127.     };
  22128.     var deleteRange$1 = function (editor) {
  22129.       var rootNode = SugarElement.fromDom(editor.getBody());
  22130.       var rng = editor.selection.getRng();
  22131.       return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
  22132.     };
  22133.     var backspaceDelete$7 = function (editor, _forward) {
  22134.       return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
  22135.     };
  22136.  
  22137.     var isContentEditableTrue$2 = isContentEditableTrue$4;
  22138.     var isContentEditableFalse$4 = isContentEditableFalse$b;
  22139.     var showCaret = function (direction, editor, node, before, scrollIntoView) {
  22140.       return Optional.from(editor._selectionOverrides.showCaret(direction, node, before, scrollIntoView));
  22141.     };
  22142.     var getNodeRange = function (node) {
  22143.       var rng = node.ownerDocument.createRange();
  22144.       rng.selectNode(node);
  22145.       return rng;
  22146.     };
  22147.     var selectNode = function (editor, node) {
  22148.       var e = editor.fire('BeforeObjectSelected', { target: node });
  22149.       if (e.isDefaultPrevented()) {
  22150.         return Optional.none();
  22151.       }
  22152.       return Optional.some(getNodeRange(node));
  22153.     };
  22154.     var renderCaretAtRange = function (editor, range, scrollIntoView) {
  22155.       var normalizedRange = normalizeRange(1, editor.getBody(), range);
  22156.       var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
  22157.       var caretPositionNode = caretPosition.getNode();
  22158.       if (isInlineFakeCaretTarget(caretPositionNode)) {
  22159.         return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
  22160.       }
  22161.       var caretPositionBeforeNode = caretPosition.getNode(true);
  22162.       if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
  22163.         return showCaret(1, editor, caretPositionBeforeNode, false, false);
  22164.       }
  22165.       var ceRoot = editor.dom.getParent(caretPosition.getNode(), function (node) {
  22166.         return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
  22167.       });
  22168.       if (isInlineFakeCaretTarget(ceRoot)) {
  22169.         return showCaret(1, editor, ceRoot, false, scrollIntoView);
  22170.       }
  22171.       return Optional.none();
  22172.     };
  22173.     var renderRangeCaret = function (editor, range, scrollIntoView) {
  22174.       return range.collapsed ? renderCaretAtRange(editor, range, scrollIntoView).getOr(range) : range;
  22175.     };
  22176.  
  22177.     var isBeforeBoundary = function (pos) {
  22178.       return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
  22179.     };
  22180.     var isAfterBoundary = function (pos) {
  22181.       return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
  22182.     };
  22183.     var trimEmptyTextNode = function (dom, node) {
  22184.       if (isText$7(node) && node.data.length === 0) {
  22185.         dom.remove(node);
  22186.       }
  22187.     };
  22188.     var deleteContentAndShowCaret = function (editor, range, node, direction, forward, peekCaretPosition) {
  22189.       showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function (caretRange) {
  22190.         if (range.collapsed) {
  22191.           var deleteRange = range.cloneRange();
  22192.           if (forward) {
  22193.             deleteRange.setEnd(caretRange.startContainer, caretRange.startOffset);
  22194.           } else {
  22195.             deleteRange.setStart(caretRange.endContainer, caretRange.endOffset);
  22196.           }
  22197.           deleteRange.deleteContents();
  22198.         } else {
  22199.           range.deleteContents();
  22200.         }
  22201.         editor.selection.setRng(caretRange);
  22202.       });
  22203.       trimEmptyTextNode(editor.dom, node);
  22204.       return true;
  22205.     };
  22206.     var deleteBoundaryText = function (editor, forward) {
  22207.       var range = editor.selection.getRng();
  22208.       if (!isText$7(range.commonAncestorContainer)) {
  22209.         return false;
  22210.       }
  22211.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  22212.       var caretWalker = CaretWalker(editor.getBody());
  22213.       var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
  22214.       var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
  22215.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  22216.       var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
  22217.       if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
  22218.         return false;
  22219.       } else if (isBeforeFn(nextCaretPosition)) {
  22220.         return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, nextCaretPosition);
  22221.       }
  22222.       var peekCaretPosition = getNextPosFn(nextCaretPosition);
  22223.       if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  22224.         if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  22225.           return deleteContentAndShowCaret(editor, range, caretPosition.getNode(), direction, forward, peekCaretPosition);
  22226.         }
  22227.       }
  22228.       return false;
  22229.     };
  22230.     var backspaceDelete$6 = function (editor, forward) {
  22231.       return deleteBoundaryText(editor, forward);
  22232.     };
  22233.  
  22234.     var isCompoundElement = function (node) {
  22235.       return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
  22236.     };
  22237.     var DeleteAction = Adt.generate([
  22238.       { remove: ['element'] },
  22239.       { moveToElement: ['element'] },
  22240.       { moveToPosition: ['position'] }
  22241.     ]);
  22242.     var isAtContentEditableBlockCaret = function (forward, from) {
  22243.       var elm = from.getNode(forward === false);
  22244.       var caretLocation = forward ? 'after' : 'before';
  22245.       return isElement$5(elm) && elm.getAttribute('data-mce-caret') === caretLocation;
  22246.     };
  22247.     var isDeleteFromCefDifferentBlocks = function (root, forward, from, to) {
  22248.       var inSameBlock = function (elm) {
  22249.         return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from, to, root);
  22250.       };
  22251.       return getRelativeCefElm(!forward, from).fold(function () {
  22252.         return getRelativeCefElm(forward, to).fold(never, inSameBlock);
  22253.       }, inSameBlock);
  22254.     };
  22255.     var deleteEmptyBlockOrMoveToCef = function (root, forward, from, to) {
  22256.       var toCefElm = to.getNode(forward === false);
  22257.       return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from.getNode())).map(function (blockElm) {
  22258.         return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
  22259.       }).orThunk(function () {
  22260.         return Optional.some(DeleteAction.moveToElement(toCefElm));
  22261.       });
  22262.     };
  22263.     var findCefPosition = function (root, forward, from) {
  22264.       return fromPosition(forward, root, from).bind(function (to) {
  22265.         if (isCompoundElement(to.getNode())) {
  22266.           return Optional.none();
  22267.         } else if (isDeleteFromCefDifferentBlocks(root, forward, from, to)) {
  22268.           return Optional.none();
  22269.         } else if (forward && isContentEditableFalse$b(to.getNode())) {
  22270.           return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22271.         } else if (forward === false && isContentEditableFalse$b(to.getNode(true))) {
  22272.           return deleteEmptyBlockOrMoveToCef(root, forward, from, to);
  22273.         } else if (forward && isAfterContentEditableFalse(from)) {
  22274.           return Optional.some(DeleteAction.moveToPosition(to));
  22275.         } else if (forward === false && isBeforeContentEditableFalse(from)) {
  22276.           return Optional.some(DeleteAction.moveToPosition(to));
  22277.         } else {
  22278.           return Optional.none();
  22279.         }
  22280.       });
  22281.     };
  22282.     var getContentEditableBlockAction = function (forward, elm) {
  22283.       if (forward && isContentEditableFalse$b(elm.nextSibling)) {
  22284.         return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
  22285.       } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
  22286.         return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
  22287.       } else {
  22288.         return Optional.none();
  22289.       }
  22290.     };
  22291.     var skipMoveToActionFromInlineCefToContent = function (root, from, deleteAction) {
  22292.       return deleteAction.fold(function (elm) {
  22293.         return Optional.some(DeleteAction.remove(elm));
  22294.       }, function (elm) {
  22295.         return Optional.some(DeleteAction.moveToElement(elm));
  22296.       }, function (to) {
  22297.         if (isInSameBlock(from, to, root)) {
  22298.           return Optional.none();
  22299.         } else {
  22300.           return Optional.some(DeleteAction.moveToPosition(to));
  22301.         }
  22302.       });
  22303.     };
  22304.     var getContentEditableAction = function (root, forward, from) {
  22305.       if (isAtContentEditableBlockCaret(forward, from)) {
  22306.         return getContentEditableBlockAction(forward, from.getNode(forward === false)).fold(function () {
  22307.           return findCefPosition(root, forward, from);
  22308.         }, Optional.some);
  22309.       } else {
  22310.         return findCefPosition(root, forward, from).bind(function (deleteAction) {
  22311.           return skipMoveToActionFromInlineCefToContent(root, from, deleteAction);
  22312.         });
  22313.       }
  22314.     };
  22315.     var read = function (root, forward, rng) {
  22316.       var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
  22317.       var from = CaretPosition.fromRangeStart(normalizedRange);
  22318.       var rootElement = SugarElement.fromDom(root);
  22319.       if (forward === false && isAfterContentEditableFalse(from)) {
  22320.         return Optional.some(DeleteAction.remove(from.getNode(true)));
  22321.       } else if (forward && isBeforeContentEditableFalse(from)) {
  22322.         return Optional.some(DeleteAction.remove(from.getNode()));
  22323.       } else if (forward === false && isBeforeContentEditableFalse(from) && isAfterBr(rootElement, from)) {
  22324.         return findPreviousBr(rootElement, from).map(function (br) {
  22325.           return DeleteAction.remove(br.getNode());
  22326.         });
  22327.       } else if (forward && isAfterContentEditableFalse(from) && isBeforeBr$1(rootElement, from)) {
  22328.         return findNextBr(rootElement, from).map(function (br) {
  22329.           return DeleteAction.remove(br.getNode());
  22330.         });
  22331.       } else {
  22332.         return getContentEditableAction(root, forward, from);
  22333.       }
  22334.     };
  22335.  
  22336.     var deleteElement$1 = function (editor, forward) {
  22337.       return function (element) {
  22338.         editor._selectionOverrides.hideFakeCaret();
  22339.         deleteElement$2(editor, forward, SugarElement.fromDom(element));
  22340.         return true;
  22341.       };
  22342.     };
  22343.     var moveToElement = function (editor, forward) {
  22344.       return function (element) {
  22345.         var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
  22346.         editor.selection.setRng(pos.toRange());
  22347.         return true;
  22348.       };
  22349.     };
  22350.     var moveToPosition = function (editor) {
  22351.       return function (pos) {
  22352.         editor.selection.setRng(pos.toRange());
  22353.         return true;
  22354.       };
  22355.     };
  22356.     var getAncestorCe = function (editor, node) {
  22357.       return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
  22358.     };
  22359.     var backspaceDeleteCaret = function (editor, forward) {
  22360.       var selectedNode = editor.selection.getNode();
  22361.       return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function () {
  22362.         return read(editor.getBody(), forward, editor.selection.getRng()).exists(function (deleteAction) {
  22363.           return deleteAction.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
  22364.         });
  22365.       }, always);
  22366.     };
  22367.     var deleteOffscreenSelection = function (rootElement) {
  22368.       each$k(descendants(rootElement, '.mce-offscreen-selection'), remove$7);
  22369.     };
  22370.     var backspaceDeleteRange = function (editor, forward) {
  22371.       var selectedNode = editor.selection.getNode();
  22372.       if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
  22373.         var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
  22374.         return hasCefAncestor.fold(function () {
  22375.           deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
  22376.           deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
  22377.           paddEmptyBody(editor);
  22378.           return true;
  22379.         }, always);
  22380.       }
  22381.       return false;
  22382.     };
  22383.     var paddEmptyElement = function (editor) {
  22384.       var dom = editor.dom, selection = editor.selection;
  22385.       var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
  22386.       if (isContentEditableTrue$4(ceRoot) && dom.isBlock(ceRoot) && dom.isEmpty(ceRoot)) {
  22387.         var br = dom.create('br', { 'data-mce-bogus': '1' });
  22388.         dom.setHTML(ceRoot, '');
  22389.         ceRoot.appendChild(br);
  22390.         selection.setRng(CaretPosition.before(br).toRange());
  22391.       }
  22392.       return true;
  22393.     };
  22394.     var backspaceDelete$5 = function (editor, forward) {
  22395.       if (editor.selection.isCollapsed()) {
  22396.         return backspaceDeleteCaret(editor, forward);
  22397.       } else {
  22398.         return backspaceDeleteRange(editor, forward);
  22399.       }
  22400.     };
  22401.  
  22402.     var deleteCaret$2 = function (editor, forward) {
  22403.       var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  22404.       return fromPosition(forward, editor.getBody(), fromPos).filter(function (pos) {
  22405.         return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
  22406.       }).bind(function (pos) {
  22407.         return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
  22408.       }).exists(function (elm) {
  22409.         editor.selection.select(elm);
  22410.         return true;
  22411.       });
  22412.     };
  22413.     var backspaceDelete$4 = function (editor, forward) {
  22414.       return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
  22415.     };
  22416.  
  22417.     var isText = isText$7;
  22418.     var startsWithCaretContainer = function (node) {
  22419.       return isText(node) && node.data[0] === ZWSP$1;
  22420.     };
  22421.     var endsWithCaretContainer = function (node) {
  22422.       return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
  22423.     };
  22424.     var createZwsp = function (node) {
  22425.       return node.ownerDocument.createTextNode(ZWSP$1);
  22426.     };
  22427.     var insertBefore = function (node) {
  22428.       if (isText(node.previousSibling)) {
  22429.         if (endsWithCaretContainer(node.previousSibling)) {
  22430.           return node.previousSibling;
  22431.         } else {
  22432.           node.previousSibling.appendData(ZWSP$1);
  22433.           return node.previousSibling;
  22434.         }
  22435.       } else if (isText(node)) {
  22436.         if (startsWithCaretContainer(node)) {
  22437.           return node;
  22438.         } else {
  22439.           node.insertData(0, ZWSP$1);
  22440.           return node;
  22441.         }
  22442.       } else {
  22443.         var newNode = createZwsp(node);
  22444.         node.parentNode.insertBefore(newNode, node);
  22445.         return newNode;
  22446.       }
  22447.     };
  22448.     var insertAfter = function (node) {
  22449.       if (isText(node.nextSibling)) {
  22450.         if (startsWithCaretContainer(node.nextSibling)) {
  22451.           return node.nextSibling;
  22452.         } else {
  22453.           node.nextSibling.insertData(0, ZWSP$1);
  22454.           return node.nextSibling;
  22455.         }
  22456.       } else if (isText(node)) {
  22457.         if (endsWithCaretContainer(node)) {
  22458.           return node;
  22459.         } else {
  22460.           node.appendData(ZWSP$1);
  22461.           return node;
  22462.         }
  22463.       } else {
  22464.         var newNode = createZwsp(node);
  22465.         if (node.nextSibling) {
  22466.           node.parentNode.insertBefore(newNode, node.nextSibling);
  22467.         } else {
  22468.           node.parentNode.appendChild(newNode);
  22469.         }
  22470.         return newNode;
  22471.       }
  22472.     };
  22473.     var insertInline = function (before, node) {
  22474.       return before ? insertBefore(node) : insertAfter(node);
  22475.     };
  22476.     var insertInlineBefore = curry(insertInline, true);
  22477.     var insertInlineAfter = curry(insertInline, false);
  22478.  
  22479.     var insertInlinePos = function (pos, before) {
  22480.       if (isText$7(pos.container())) {
  22481.         return insertInline(before, pos.container());
  22482.       } else {
  22483.         return insertInline(before, pos.getNode());
  22484.       }
  22485.     };
  22486.     var isPosCaretContainer = function (pos, caret) {
  22487.       var caretNode = caret.get();
  22488.       return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
  22489.     };
  22490.     var renderCaret = function (caret, location) {
  22491.       return location.fold(function (element) {
  22492.         remove$2(caret.get());
  22493.         var text = insertInlineBefore(element);
  22494.         caret.set(text);
  22495.         return Optional.some(CaretPosition(text, text.length - 1));
  22496.       }, function (element) {
  22497.         return firstPositionIn(element).map(function (pos) {
  22498.           if (!isPosCaretContainer(pos, caret)) {
  22499.             remove$2(caret.get());
  22500.             var text = insertInlinePos(pos, true);
  22501.             caret.set(text);
  22502.             return CaretPosition(text, 1);
  22503.           } else {
  22504.             return CaretPosition(caret.get(), 1);
  22505.           }
  22506.         });
  22507.       }, function (element) {
  22508.         return lastPositionIn(element).map(function (pos) {
  22509.           if (!isPosCaretContainer(pos, caret)) {
  22510.             remove$2(caret.get());
  22511.             var text = insertInlinePos(pos, false);
  22512.             caret.set(text);
  22513.             return CaretPosition(text, text.length - 1);
  22514.           } else {
  22515.             return CaretPosition(caret.get(), caret.get().length - 1);
  22516.           }
  22517.         });
  22518.       }, function (element) {
  22519.         remove$2(caret.get());
  22520.         var text = insertInlineAfter(element);
  22521.         caret.set(text);
  22522.         return Optional.some(CaretPosition(text, 1));
  22523.       });
  22524.     };
  22525.  
  22526.     var evaluateUntil = function (fns, args) {
  22527.       for (var i = 0; i < fns.length; i++) {
  22528.         var result = fns[i].apply(null, args);
  22529.         if (result.isSome()) {
  22530.           return result;
  22531.         }
  22532.       }
  22533.       return Optional.none();
  22534.     };
  22535.  
  22536.     var Location = Adt.generate([
  22537.       { before: ['element'] },
  22538.       { start: ['element'] },
  22539.       { end: ['element'] },
  22540.       { after: ['element'] }
  22541.     ]);
  22542.     var rescope$1 = function (rootNode, node) {
  22543.       var parentBlock = getParentBlock$2(node, rootNode);
  22544.       return parentBlock ? parentBlock : rootNode;
  22545.     };
  22546.     var before = function (isInlineTarget, rootNode, pos) {
  22547.       var nPos = normalizeForwards(pos);
  22548.       var scope = rescope$1(rootNode, nPos.container());
  22549.       return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22550.         return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22551.           return Location.before(inline);
  22552.         });
  22553.       }, Optional.none);
  22554.     };
  22555.     var isNotInsideFormatCaretContainer = function (rootNode, elm) {
  22556.       return getParentCaretContainer(rootNode, elm) === null;
  22557.     };
  22558.     var findInsideRootInline = function (isInlineTarget, rootNode, pos) {
  22559.       return findRootInline(isInlineTarget, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
  22560.     };
  22561.     var start$1 = function (isInlineTarget, rootNode, pos) {
  22562.       var nPos = normalizeBackwards(pos);
  22563.       return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22564.         var prevPos = prevPosition(inline, nPos);
  22565.         return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
  22566.       });
  22567.     };
  22568.     var end = function (isInlineTarget, rootNode, pos) {
  22569.       var nPos = normalizeForwards(pos);
  22570.       return findInsideRootInline(isInlineTarget, rootNode, nPos).bind(function (inline) {
  22571.         var nextPos = nextPosition(inline, nPos);
  22572.         return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
  22573.       });
  22574.     };
  22575.     var after = function (isInlineTarget, rootNode, pos) {
  22576.       var nPos = normalizeBackwards(pos);
  22577.       var scope = rescope$1(rootNode, nPos.container());
  22578.       return findRootInline(isInlineTarget, scope, nPos).fold(function () {
  22579.         return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget, scope)).map(function (inline) {
  22580.           return Location.after(inline);
  22581.         });
  22582.       }, Optional.none);
  22583.     };
  22584.     var isValidLocation = function (location) {
  22585.       return isRtl(getElement(location)) === false;
  22586.     };
  22587.     var readLocation = function (isInlineTarget, rootNode, pos) {
  22588.       var location = evaluateUntil([
  22589.         before,
  22590.         start$1,
  22591.         end,
  22592.         after
  22593.       ], [
  22594.         isInlineTarget,
  22595.         rootNode,
  22596.         pos
  22597.       ]);
  22598.       return location.filter(isValidLocation);
  22599.     };
  22600.     var getElement = function (location) {
  22601.       return location.fold(identity, identity, identity, identity);
  22602.     };
  22603.     var getName = function (location) {
  22604.       return location.fold(constant('before'), constant('start'), constant('end'), constant('after'));
  22605.     };
  22606.     var outside = function (location) {
  22607.       return location.fold(Location.before, Location.before, Location.after, Location.after);
  22608.     };
  22609.     var inside = function (location) {
  22610.       return location.fold(Location.start, Location.start, Location.end, Location.end);
  22611.     };
  22612.     var isEq = function (location1, location2) {
  22613.       return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
  22614.     };
  22615.     var betweenInlines = function (forward, isInlineTarget, rootNode, from, to, location) {
  22616.       return lift2(findRootInline(isInlineTarget, rootNode, from), findRootInline(isInlineTarget, rootNode, to), function (fromInline, toInline) {
  22617.         if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
  22618.           return Location.after(forward ? fromInline : toInline);
  22619.         } else {
  22620.           return location;
  22621.         }
  22622.       }).getOr(location);
  22623.     };
  22624.     var skipNoMovement = function (fromLocation, toLocation) {
  22625.       return fromLocation.fold(always, function (fromLocation) {
  22626.         return !isEq(fromLocation, toLocation);
  22627.       });
  22628.     };
  22629.     var findLocationTraverse = function (forward, isInlineTarget, rootNode, fromLocation, pos) {
  22630.       var from = normalizePosition(forward, pos);
  22631.       var to = fromPosition(forward, rootNode, from).map(curry(normalizePosition, forward));
  22632.       var location = to.fold(function () {
  22633.         return fromLocation.map(outside);
  22634.       }, function (to) {
  22635.         return readLocation(isInlineTarget, rootNode, to).map(curry(betweenInlines, forward, isInlineTarget, rootNode, from, to)).filter(curry(skipNoMovement, fromLocation));
  22636.       });
  22637.       return location.filter(isValidLocation);
  22638.     };
  22639.     var findLocationSimple = function (forward, location) {
  22640.       if (forward) {
  22641.         return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
  22642.       } else {
  22643.         return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
  22644.       }
  22645.     };
  22646.     var findLocation$1 = function (forward, isInlineTarget, rootNode, pos) {
  22647.       var from = normalizePosition(forward, pos);
  22648.       var fromLocation = readLocation(isInlineTarget, rootNode, from);
  22649.       return readLocation(isInlineTarget, rootNode, from).bind(curry(findLocationSimple, forward)).orThunk(function () {
  22650.         return findLocationTraverse(forward, isInlineTarget, rootNode, fromLocation, pos);
  22651.       });
  22652.     };
  22653.     curry(findLocation$1, false);
  22654.     curry(findLocation$1, true);
  22655.  
  22656.     var hasSelectionModifyApi = function (editor) {
  22657.       return isFunction(editor.selection.getSel().modify);
  22658.     };
  22659.     var moveRel = function (forward, selection, pos) {
  22660.       var delta = forward ? 1 : -1;
  22661.       selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
  22662.       selection.getSel().modify('move', forward ? 'forward' : 'backward', 'word');
  22663.       return true;
  22664.     };
  22665.     var moveByWord = function (forward, editor) {
  22666.       var rng = editor.selection.getRng();
  22667.       var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  22668.       if (!hasSelectionModifyApi(editor)) {
  22669.         return false;
  22670.       } else if (forward && isBeforeInline(pos)) {
  22671.         return moveRel(true, editor.selection, pos);
  22672.       } else if (!forward && isAfterInline(pos)) {
  22673.         return moveRel(false, editor.selection, pos);
  22674.       } else {
  22675.         return false;
  22676.       }
  22677.     };
  22678.  
  22679.     var BreakType;
  22680.     (function (BreakType) {
  22681.       BreakType[BreakType['Br'] = 0] = 'Br';
  22682.       BreakType[BreakType['Block'] = 1] = 'Block';
  22683.       BreakType[BreakType['Wrap'] = 2] = 'Wrap';
  22684.       BreakType[BreakType['Eol'] = 3] = 'Eol';
  22685.     }(BreakType || (BreakType = {})));
  22686.     var flip = function (direction, positions) {
  22687.       return direction === HDirection.Backwards ? reverse(positions) : positions;
  22688.     };
  22689.     var walk = function (direction, caretWalker, pos) {
  22690.       return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
  22691.     };
  22692.     var getBreakType = function (scope, direction, currentPos, nextPos) {
  22693.       if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
  22694.         return BreakType.Br;
  22695.       } else if (isInSameBlock(currentPos, nextPos) === false) {
  22696.         return BreakType.Block;
  22697.       } else {
  22698.         return BreakType.Wrap;
  22699.       }
  22700.     };
  22701.     var getPositionsUntil = function (predicate, direction, scope, start) {
  22702.       var caretWalker = CaretWalker(scope);
  22703.       var currentPos = start;
  22704.       var positions = [];
  22705.       while (currentPos) {
  22706.         var nextPos = walk(direction, caretWalker, currentPos);
  22707.         if (!nextPos) {
  22708.           break;
  22709.         }
  22710.         if (isBr$5(nextPos.getNode(false))) {
  22711.           if (direction === HDirection.Forwards) {
  22712.             return {
  22713.               positions: flip(direction, positions).concat([nextPos]),
  22714.               breakType: BreakType.Br,
  22715.               breakAt: Optional.some(nextPos)
  22716.             };
  22717.           } else {
  22718.             return {
  22719.               positions: flip(direction, positions),
  22720.               breakType: BreakType.Br,
  22721.               breakAt: Optional.some(nextPos)
  22722.             };
  22723.           }
  22724.         }
  22725.         if (!nextPos.isVisible()) {
  22726.           currentPos = nextPos;
  22727.           continue;
  22728.         }
  22729.         if (predicate(currentPos, nextPos)) {
  22730.           var breakType = getBreakType(scope, direction, currentPos, nextPos);
  22731.           return {
  22732.             positions: flip(direction, positions),
  22733.             breakType: breakType,
  22734.             breakAt: Optional.some(nextPos)
  22735.           };
  22736.         }
  22737.         positions.push(nextPos);
  22738.         currentPos = nextPos;
  22739.       }
  22740.       return {
  22741.         positions: flip(direction, positions),
  22742.         breakType: BreakType.Eol,
  22743.         breakAt: Optional.none()
  22744.       };
  22745.     };
  22746.     var getAdjacentLinePositions = function (direction, getPositionsUntilBreak, scope, start) {
  22747.       return getPositionsUntilBreak(scope, start).breakAt.map(function (pos) {
  22748.         var positions = getPositionsUntilBreak(scope, pos).positions;
  22749.         return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
  22750.       }).getOr([]);
  22751.     };
  22752.     var findClosestHorizontalPositionFromPoint = function (positions, x) {
  22753.       return foldl(positions, function (acc, newPos) {
  22754.         return acc.fold(function () {
  22755.           return Optional.some(newPos);
  22756.         }, function (lastPos) {
  22757.           return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function (lastRect, newRect) {
  22758.             var lastDist = Math.abs(x - lastRect.left);
  22759.             var newDist = Math.abs(x - newRect.left);
  22760.             return newDist <= lastDist ? newPos : lastPos;
  22761.           }).or(acc);
  22762.         });
  22763.       }, Optional.none());
  22764.     };
  22765.     var findClosestHorizontalPosition = function (positions, pos) {
  22766.       return head(pos.getClientRects()).bind(function (targetRect) {
  22767.         return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
  22768.       });
  22769.     };
  22770.     var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
  22771.     var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
  22772.     var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
  22773.     var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
  22774.     var isAtFirstLine = function (scope, pos) {
  22775.       return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
  22776.     };
  22777.     var isAtLastLine = function (scope, pos) {
  22778.       return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
  22779.     };
  22780.     var getFirstLinePositions = function (scope) {
  22781.       return firstPositionIn(scope).map(function (pos) {
  22782.         return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
  22783.       }).getOr([]);
  22784.     };
  22785.     var getLastLinePositions = function (scope) {
  22786.       return lastPositionIn(scope).map(function (pos) {
  22787.         return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
  22788.       }).getOr([]);
  22789.     };
  22790.  
  22791.     var getNodeClientRects = function (node) {
  22792.       var toArrayWithNode = function (clientRects) {
  22793.         return map$3(clientRects, function (rect) {
  22794.           var clientRect = clone(rect);
  22795.           clientRect.node = node;
  22796.           return clientRect;
  22797.         });
  22798.       };
  22799.       if (isElement$5(node)) {
  22800.         return toArrayWithNode(node.getClientRects());
  22801.       }
  22802.       if (isText$7(node)) {
  22803.         var rng = node.ownerDocument.createRange();
  22804.         rng.setStart(node, 0);
  22805.         rng.setEnd(node, node.data.length);
  22806.         return toArrayWithNode(rng.getClientRects());
  22807.       }
  22808.     };
  22809.     var getClientRects = function (nodes) {
  22810.       return bind(nodes, getNodeClientRects);
  22811.     };
  22812.  
  22813.     var VDirection;
  22814.     (function (VDirection) {
  22815.       VDirection[VDirection['Up'] = -1] = 'Up';
  22816.       VDirection[VDirection['Down'] = 1] = 'Down';
  22817.     }(VDirection || (VDirection = {})));
  22818.     var findUntil = function (direction, root, predicateFn, node) {
  22819.       while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
  22820.         if (predicateFn(node)) {
  22821.           return;
  22822.         }
  22823.       }
  22824.     };
  22825.     var walkUntil$1 = function (direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
  22826.       var line = 0;
  22827.       var result = [];
  22828.       var add = function (node) {
  22829.         var clientRects = getClientRects([node]);
  22830.         if (direction === -1) {
  22831.           clientRects = clientRects.reverse();
  22832.         }
  22833.         for (var i = 0; i < clientRects.length; i++) {
  22834.           var clientRect = clientRects[i];
  22835.           if (isBeflowFn(clientRect, targetClientRect)) {
  22836.             continue;
  22837.           }
  22838.           if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
  22839.             line++;
  22840.           }
  22841.           clientRect.line = line;
  22842.           if (predicateFn(clientRect)) {
  22843.             return true;
  22844.           }
  22845.           result.push(clientRect);
  22846.         }
  22847.       };
  22848.       var targetClientRect = last$1(caretPosition.getClientRects());
  22849.       if (!targetClientRect) {
  22850.         return result;
  22851.       }
  22852.       var node = caretPosition.getNode();
  22853.       add(node);
  22854.       findUntil(direction, root, add, node);
  22855.       return result;
  22856.     };
  22857.     var aboveLineNumber = function (lineNumber, clientRect) {
  22858.       return clientRect.line > lineNumber;
  22859.     };
  22860.     var isLineNumber = function (lineNumber, clientRect) {
  22861.       return clientRect.line === lineNumber;
  22862.     };
  22863.     var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
  22864.     var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
  22865.     var positionsUntil = function (direction, root, predicateFn, node) {
  22866.       var caretWalker = CaretWalker(root);
  22867.       var walkFn;
  22868.       var isBelowFn;
  22869.       var isAboveFn;
  22870.       var caretPosition;
  22871.       var result = [];
  22872.       var line = 0;
  22873.       var getClientRect = function (caretPosition) {
  22874.         if (direction === 1) {
  22875.           return last$1(caretPosition.getClientRects());
  22876.         }
  22877.         return last$1(caretPosition.getClientRects());
  22878.       };
  22879.       if (direction === 1) {
  22880.         walkFn = caretWalker.next;
  22881.         isBelowFn = isBelow$1;
  22882.         isAboveFn = isAbove$1;
  22883.         caretPosition = CaretPosition.after(node);
  22884.       } else {
  22885.         walkFn = caretWalker.prev;
  22886.         isBelowFn = isAbove$1;
  22887.         isAboveFn = isBelow$1;
  22888.         caretPosition = CaretPosition.before(node);
  22889.       }
  22890.       var targetClientRect = getClientRect(caretPosition);
  22891.       do {
  22892.         if (!caretPosition.isVisible()) {
  22893.           continue;
  22894.         }
  22895.         var rect = getClientRect(caretPosition);
  22896.         if (isAboveFn(rect, targetClientRect)) {
  22897.           continue;
  22898.         }
  22899.         if (result.length > 0 && isBelowFn(rect, last$1(result))) {
  22900.           line++;
  22901.         }
  22902.         var clientRect = clone(rect);
  22903.         clientRect.position = caretPosition;
  22904.         clientRect.line = line;
  22905.         if (predicateFn(clientRect)) {
  22906.           return result;
  22907.         }
  22908.         result.push(clientRect);
  22909.       } while (caretPosition = walkFn(caretPosition));
  22910.       return result;
  22911.     };
  22912.     var isAboveLine = function (lineNumber) {
  22913.       return function (clientRect) {
  22914.         return aboveLineNumber(lineNumber, clientRect);
  22915.       };
  22916.     };
  22917.     var isLine = function (lineNumber) {
  22918.       return function (clientRect) {
  22919.         return isLineNumber(lineNumber, clientRect);
  22920.       };
  22921.     };
  22922.  
  22923.     var isContentEditableFalse$3 = isContentEditableFalse$b;
  22924.     var findNode = findNode$1;
  22925.     var distanceToRectLeft = function (clientRect, clientX) {
  22926.       return Math.abs(clientRect.left - clientX);
  22927.     };
  22928.     var distanceToRectRight = function (clientRect, clientX) {
  22929.       return Math.abs(clientRect.right - clientX);
  22930.     };
  22931.     var isInsideX = function (clientX, clientRect) {
  22932.       return clientX >= clientRect.left && clientX <= clientRect.right;
  22933.     };
  22934.     var isInsideY = function (clientY, clientRect) {
  22935.       return clientY >= clientRect.top && clientY <= clientRect.bottom;
  22936.     };
  22937.     var isNodeClientRect = function (rect) {
  22938.       return hasNonNullableKey(rect, 'node');
  22939.     };
  22940.     var findClosestClientRect = function (clientRects, clientX, allowInside) {
  22941.       if (allowInside === void 0) {
  22942.         allowInside = always;
  22943.       }
  22944.       return reduce(clientRects, function (oldClientRect, clientRect) {
  22945.         if (isInsideX(clientX, clientRect)) {
  22946.           return allowInside(clientRect) ? clientRect : oldClientRect;
  22947.         }
  22948.         if (isInsideX(clientX, oldClientRect)) {
  22949.           return allowInside(oldClientRect) ? oldClientRect : clientRect;
  22950.         }
  22951.         var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
  22952.         var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
  22953.         if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
  22954.           return clientRect;
  22955.         }
  22956.         if (newDistance < oldDistance) {
  22957.           return clientRect;
  22958.         }
  22959.         return oldClientRect;
  22960.       });
  22961.     };
  22962.     var walkUntil = function (direction, root, predicateFn, startNode, includeChildren) {
  22963.       var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
  22964.       do {
  22965.         if (!node || predicateFn(node)) {
  22966.           return;
  22967.         }
  22968.       } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
  22969.     };
  22970.     var findLineNodeRects = function (root, targetNodeRect, includeChildren) {
  22971.       if (includeChildren === void 0) {
  22972.         includeChildren = true;
  22973.       }
  22974.       var clientRects = [];
  22975.       var collect = function (checkPosFn, node) {
  22976.         var lineRects = filter$4(getClientRects([node]), function (clientRect) {
  22977.           return !checkPosFn(clientRect, targetNodeRect);
  22978.         });
  22979.         clientRects = clientRects.concat(lineRects);
  22980.         return lineRects.length === 0;
  22981.       };
  22982.       clientRects.push(targetNodeRect);
  22983.       walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
  22984.       walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
  22985.       return clientRects;
  22986.     };
  22987.     var getFakeCaretTargets = function (root) {
  22988.       return filter$4(from(root.getElementsByTagName('*')), isFakeCaretTarget);
  22989.     };
  22990.     var caretInfo = function (clientRect, clientX) {
  22991.       return {
  22992.         node: clientRect.node,
  22993.         before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
  22994.       };
  22995.     };
  22996.     var closestFakeCaret = function (root, clientX, clientY) {
  22997.       var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
  22998.       var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
  22999.       var checkInside = function (clientRect) {
  23000.         return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
  23001.       };
  23002.       var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
  23003.       if (closestNodeRect) {
  23004.         var includeChildren = checkInside(closestNodeRect);
  23005.         closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
  23006.         if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
  23007.           return caretInfo(closestNodeRect, clientX);
  23008.         }
  23009.       }
  23010.       return null;
  23011.     };
  23012.  
  23013.     var moveToRange = function (editor, rng) {
  23014.       editor.selection.setRng(rng);
  23015.       scrollRangeIntoView(editor, editor.selection.getRng());
  23016.     };
  23017.     var renderRangeCaretOpt = function (editor, range, scrollIntoView) {
  23018.       return Optional.some(renderRangeCaret(editor, range, scrollIntoView));
  23019.     };
  23020.     var moveHorizontally = function (editor, direction, range, isBefore, isAfter, isElement) {
  23021.       var forwards = direction === HDirection.Forwards;
  23022.       var caretWalker = CaretWalker(editor.getBody());
  23023.       var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
  23024.       var isBeforeFn = forwards ? isBefore : isAfter;
  23025.       if (!range.collapsed) {
  23026.         var node = getSelectedNode(range);
  23027.         if (isElement(node)) {
  23028.           return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
  23029.         }
  23030.       }
  23031.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  23032.       if (isBeforeFn(caretPosition)) {
  23033.         return selectNode(editor, caretPosition.getNode(!forwards));
  23034.       }
  23035.       var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
  23036.       var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range);
  23037.       if (!nextCaretPosition) {
  23038.         return rangeIsInContainerBlock ? Optional.some(range) : Optional.none();
  23039.       }
  23040.       if (isBeforeFn(nextCaretPosition)) {
  23041.         return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
  23042.       }
  23043.       var peekCaretPosition = getNextPosFn(nextCaretPosition);
  23044.       if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
  23045.         if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
  23046.           return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
  23047.         }
  23048.       }
  23049.       if (rangeIsInContainerBlock) {
  23050.         return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
  23051.       }
  23052.       return Optional.none();
  23053.     };
  23054.     var moveVertically = function (editor, direction, range, isBefore, isAfter, isElement) {
  23055.       var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range);
  23056.       var caretClientRect = last$1(caretPosition.getClientRects());
  23057.       var forwards = direction === VDirection.Down;
  23058.       if (!caretClientRect) {
  23059.         return Optional.none();
  23060.       }
  23061.       var walkerFn = forwards ? downUntil : upUntil;
  23062.       var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
  23063.       var nextLinePositions = filter$4(linePositions, isLine(1));
  23064.       var clientX = caretClientRect.left;
  23065.       var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
  23066.       if (nextLineRect && isElement(nextLineRect.node)) {
  23067.         var dist1 = Math.abs(clientX - nextLineRect.left);
  23068.         var dist2 = Math.abs(clientX - nextLineRect.right);
  23069.         return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
  23070.       }
  23071.       var currentNode;
  23072.       if (isBefore(caretPosition)) {
  23073.         currentNode = caretPosition.getNode();
  23074.       } else if (isAfter(caretPosition)) {
  23075.         currentNode = caretPosition.getNode(true);
  23076.       } else {
  23077.         currentNode = getSelectedNode(range);
  23078.       }
  23079.       if (currentNode) {
  23080.         var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
  23081.         var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
  23082.         if (closestNextLineRect) {
  23083.           return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  23084.         }
  23085.         closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
  23086.         if (closestNextLineRect) {
  23087.           return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
  23088.         }
  23089.       }
  23090.       if (nextLinePositions.length === 0) {
  23091.         return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function (pos) {
  23092.           return renderRangeCaret(editor, pos.toRange(), false);
  23093.         });
  23094.       }
  23095.       return Optional.none();
  23096.     };
  23097.     var getLineEndPoint = function (editor, forward) {
  23098.       var rng = editor.selection.getRng();
  23099.       var body = editor.getBody();
  23100.       if (forward) {
  23101.         var from = CaretPosition.fromRangeEnd(rng);
  23102.         var result = getPositionsUntilNextLine(body, from);
  23103.         return last$2(result.positions);
  23104.       } else {
  23105.         var from = CaretPosition.fromRangeStart(rng);
  23106.         var result = getPositionsUntilPreviousLine(body, from);
  23107.         return head(result.positions);
  23108.       }
  23109.     };
  23110.     var moveToLineEndPoint$3 = function (editor, forward, isElementPosition) {
  23111.       return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function (pos) {
  23112.         editor.selection.setRng(pos.toRange());
  23113.         return true;
  23114.       });
  23115.     };
  23116.  
  23117.     var setCaretPosition = function (editor, pos) {
  23118.       var rng = editor.dom.createRng();
  23119.       rng.setStart(pos.container(), pos.offset());
  23120.       rng.setEnd(pos.container(), pos.offset());
  23121.       editor.selection.setRng(rng);
  23122.     };
  23123.     var setSelected = function (state, elm) {
  23124.       if (state) {
  23125.         elm.setAttribute('data-mce-selected', 'inline-boundary');
  23126.       } else {
  23127.         elm.removeAttribute('data-mce-selected');
  23128.       }
  23129.     };
  23130.     var renderCaretLocation = function (editor, caret, location) {
  23131.       return renderCaret(caret, location).map(function (pos) {
  23132.         setCaretPosition(editor, pos);
  23133.         return location;
  23134.       });
  23135.     };
  23136.     var findLocation = function (editor, caret, forward) {
  23137.       var rootNode = editor.getBody();
  23138.       var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  23139.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23140.       var location = findLocation$1(forward, isInlineTarget$1, rootNode, from);
  23141.       return location.bind(function (location) {
  23142.         return renderCaretLocation(editor, caret, location);
  23143.       });
  23144.     };
  23145.     var toggleInlines = function (isInlineTarget, dom, elms) {
  23146.       var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom.getRoot()), '*[data-mce-selected="inline-boundary"]'), function (e) {
  23147.         return e.dom;
  23148.       });
  23149.       var selectedInlines = filter$4(inlineBoundaries, isInlineTarget);
  23150.       var targetInlines = filter$4(elms, isInlineTarget);
  23151.       each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
  23152.       each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
  23153.     };
  23154.     var safeRemoveCaretContainer = function (editor, caret) {
  23155.       if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
  23156.         var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23157.         if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
  23158.           setCaretPosition(editor, removeAndReposition(caret.get(), pos));
  23159.           caret.set(null);
  23160.         }
  23161.       }
  23162.     };
  23163.     var renderInsideInlineCaret = function (isInlineTarget, editor, caret, elms) {
  23164.       if (editor.selection.isCollapsed()) {
  23165.         var inlines = filter$4(elms, isInlineTarget);
  23166.         each$k(inlines, function (_inline) {
  23167.           var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23168.           readLocation(isInlineTarget, editor.getBody(), pos).bind(function (location) {
  23169.             return renderCaretLocation(editor, caret, location);
  23170.           });
  23171.         });
  23172.       }
  23173.     };
  23174.     var move$2 = function (editor, caret, forward) {
  23175.       return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
  23176.     };
  23177.     var moveWord = function (forward, editor, _caret) {
  23178.       return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
  23179.     };
  23180.     var setupSelectedState = function (editor) {
  23181.       var caret = Cell(null);
  23182.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23183.       editor.on('NodeChange', function (e) {
  23184.         if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
  23185.           toggleInlines(isInlineTarget$1, editor.dom, e.parents);
  23186.           safeRemoveCaretContainer(editor, caret);
  23187.           renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
  23188.         }
  23189.       });
  23190.       return caret;
  23191.     };
  23192.     var moveNextWord = curry(moveWord, true);
  23193.     var movePrevWord = curry(moveWord, false);
  23194.     var moveToLineEndPoint$2 = function (editor, forward, caret) {
  23195.       if (isInlineBoundariesEnabled(editor)) {
  23196.         var linePoint = getLineEndPoint(editor, forward).getOrThunk(function () {
  23197.           var rng = editor.selection.getRng();
  23198.           return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
  23199.         });
  23200.         return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function (loc) {
  23201.           var outsideLoc = outside(loc);
  23202.           return renderCaret(caret, outsideLoc).exists(function (pos) {
  23203.             setCaretPosition(editor, pos);
  23204.             return true;
  23205.           });
  23206.         });
  23207.       } else {
  23208.         return false;
  23209.       }
  23210.     };
  23211.  
  23212.     var rangeFromPositions = function (from, to) {
  23213.       var range = document.createRange();
  23214.       range.setStart(from.container(), from.offset());
  23215.       range.setEnd(to.container(), to.offset());
  23216.       return range;
  23217.     };
  23218.     var hasOnlyTwoOrLessPositionsLeft = function (elm) {
  23219.       return lift2(firstPositionIn(elm), lastPositionIn(elm), function (firstPos, lastPos) {
  23220.         var normalizedFirstPos = normalizePosition(true, firstPos);
  23221.         var normalizedLastPos = normalizePosition(false, lastPos);
  23222.         return nextPosition(elm, normalizedFirstPos).forall(function (pos) {
  23223.           return pos.isEqual(normalizedLastPos);
  23224.         });
  23225.       }).getOr(true);
  23226.     };
  23227.     var setCaretLocation = function (editor, caret) {
  23228.       return function (location) {
  23229.         return renderCaret(caret, location).exists(function (pos) {
  23230.           setCaretPosition(editor, pos);
  23231.           return true;
  23232.         });
  23233.       };
  23234.     };
  23235.     var deleteFromTo = function (editor, caret, from, to) {
  23236.       var rootNode = editor.getBody();
  23237.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23238.       editor.undoManager.ignore(function () {
  23239.         editor.selection.setRng(rangeFromPositions(from, to));
  23240.         editor.execCommand('Delete');
  23241.         readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
  23242.       });
  23243.       editor.nodeChanged();
  23244.     };
  23245.     var rescope = function (rootNode, node) {
  23246.       var parentBlock = getParentBlock$2(node, rootNode);
  23247.       return parentBlock ? parentBlock : rootNode;
  23248.     };
  23249.     var backspaceDeleteCollapsed = function (editor, caret, forward, from) {
  23250.       var rootNode = rescope(editor.getBody(), from.container());
  23251.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  23252.       var fromLocation = readLocation(isInlineTarget$1, rootNode, from);
  23253.       return fromLocation.bind(function (location) {
  23254.         if (forward) {
  23255.           return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
  23256.         } else {
  23257.           return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
  23258.         }
  23259.       }).map(setCaretLocation(editor, caret)).getOrThunk(function () {
  23260.         var toPosition = navigate(forward, rootNode, from);
  23261.         var toLocation = toPosition.bind(function (pos) {
  23262.           return readLocation(isInlineTarget$1, rootNode, pos);
  23263.         });
  23264.         return lift2(fromLocation, toLocation, function () {
  23265.           return findRootInline(isInlineTarget$1, rootNode, from).exists(function (elm) {
  23266.             if (hasOnlyTwoOrLessPositionsLeft(elm)) {
  23267.               deleteElement$2(editor, forward, SugarElement.fromDom(elm));
  23268.               return true;
  23269.             } else {
  23270.               return false;
  23271.             }
  23272.           });
  23273.         }).orThunk(function () {
  23274.           return toLocation.bind(function (_) {
  23275.             return toPosition.map(function (to) {
  23276.               if (forward) {
  23277.                 deleteFromTo(editor, caret, from, to);
  23278.               } else {
  23279.                 deleteFromTo(editor, caret, to, from);
  23280.               }
  23281.               return true;
  23282.             });
  23283.           });
  23284.         }).getOr(false);
  23285.       });
  23286.     };
  23287.     var backspaceDelete$3 = function (editor, caret, forward) {
  23288.       if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
  23289.         var from = CaretPosition.fromRangeStart(editor.selection.getRng());
  23290.         return backspaceDeleteCollapsed(editor, caret, forward, from);
  23291.       }
  23292.       return false;
  23293.     };
  23294.  
  23295.     var getParentInlines = function (rootElm, startElm) {
  23296.       var parents = parentsAndSelf(startElm, rootElm);
  23297.       return findIndex$2(parents, isBlock$2).fold(constant(parents), function (index) {
  23298.         return parents.slice(0, index);
  23299.       });
  23300.     };
  23301.     var hasOnlyOneChild = function (elm) {
  23302.       return childNodesCount(elm) === 1;
  23303.     };
  23304.     var deleteLastPosition = function (forward, editor, target, parentInlines) {
  23305.       var isFormatElement$1 = curry(isFormatElement, editor);
  23306.       var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function (elm) {
  23307.         return elm.dom;
  23308.       });
  23309.       if (formatNodes.length === 0) {
  23310.         deleteElement$2(editor, forward, target);
  23311.       } else {
  23312.         var pos = replaceWithCaretFormat(target.dom, formatNodes);
  23313.         editor.selection.setRng(pos.toRange());
  23314.       }
  23315.     };
  23316.     var deleteCaret$1 = function (editor, forward) {
  23317.       var rootElm = SugarElement.fromDom(editor.getBody());
  23318.       var startElm = SugarElement.fromDom(editor.selection.getStart());
  23319.       var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
  23320.       return last$2(parentInlines).exists(function (target) {
  23321.         var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23322.         if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
  23323.           deleteLastPosition(forward, editor, target, parentInlines);
  23324.           return true;
  23325.         } else {
  23326.           return false;
  23327.         }
  23328.       });
  23329.     };
  23330.     var backspaceDelete$2 = function (editor, forward) {
  23331.       return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
  23332.     };
  23333.  
  23334.     var deleteElement = function (editor, forward, element) {
  23335.       editor._selectionOverrides.hideFakeCaret();
  23336.       deleteElement$2(editor, forward, SugarElement.fromDom(element));
  23337.       return true;
  23338.     };
  23339.     var deleteCaret = function (editor, forward) {
  23340.       var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
  23341.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23342.       var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
  23343.       if (isNearMedia(fromPos)) {
  23344.         return deleteElement(editor, forward, fromPos.getNode(!forward));
  23345.       } else {
  23346.         return Optional.from(normalizePosition(forward, fromPos)).filter(function (pos) {
  23347.           return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
  23348.         }).exists(function (pos) {
  23349.           return deleteElement(editor, forward, pos.getNode(!forward));
  23350.         });
  23351.       }
  23352.     };
  23353.     var deleteRange = function (editor, forward) {
  23354.       var selectedNode = editor.selection.getNode();
  23355.       return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
  23356.     };
  23357.     var backspaceDelete$1 = function (editor, forward) {
  23358.       return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
  23359.     };
  23360.  
  23361.     var isEditable = function (target) {
  23362.       return closest$3(target, function (elm) {
  23363.         return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
  23364.       }).exists(function (elm) {
  23365.         return isContentEditableTrue$4(elm.dom);
  23366.       });
  23367.     };
  23368.     var parseIndentValue = function (value) {
  23369.       var number = parseInt(value, 10);
  23370.       return isNaN(number) ? 0 : number;
  23371.     };
  23372.     var getIndentStyleName = function (useMargin, element) {
  23373.       var indentStyleName = useMargin || isTable$2(element) ? 'margin' : 'padding';
  23374.       var suffix = get$5(element, 'direction') === 'rtl' ? '-right' : '-left';
  23375.       return indentStyleName + suffix;
  23376.     };
  23377.     var indentElement = function (dom, command, useMargin, value, unit, element) {
  23378.       var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
  23379.       if (command === 'outdent') {
  23380.         var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value);
  23381.         dom.setStyle(element, indentStyleName, styleValue ? styleValue + unit : '');
  23382.       } else {
  23383.         var styleValue = parseIndentValue(element.style[indentStyleName]) + value + unit;
  23384.         dom.setStyle(element, indentStyleName, styleValue);
  23385.       }
  23386.     };
  23387.     var validateBlocks = function (editor, blocks) {
  23388.       return forall(blocks, function (block) {
  23389.         var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
  23390.         var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
  23391.         var contentEditable = editor.dom.getContentEditable(block.dom);
  23392.         return contentEditable !== 'false' && intentValue > 0;
  23393.       });
  23394.     };
  23395.     var canOutdent = function (editor) {
  23396.       var blocks = getBlocksToIndent(editor);
  23397.       return !editor.mode.isReadOnly() && (blocks.length > 1 || validateBlocks(editor, blocks));
  23398.     };
  23399.     var isListComponent = function (el) {
  23400.       return isList(el) || isListItem(el);
  23401.     };
  23402.     var parentIsListComponent = function (el) {
  23403.       return parent(el).exists(isListComponent);
  23404.     };
  23405.     var getBlocksToIndent = function (editor) {
  23406.       return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function (el) {
  23407.         return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
  23408.       });
  23409.     };
  23410.     var handle = function (editor, command) {
  23411.       var dom = editor.dom, selection = editor.selection, formatter = editor.formatter;
  23412.       var indentation = getIndentation(editor);
  23413.       var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
  23414.       var indentValue = parseInt(indentation, 10);
  23415.       var useMargin = shouldIndentUseMargin(editor);
  23416.       var forcedRootBlock = getForcedRootBlock(editor);
  23417.       if (!editor.queryCommandState('InsertUnorderedList') && !editor.queryCommandState('InsertOrderedList')) {
  23418.         if (forcedRootBlock === '' && !dom.getParent(selection.getNode(), dom.isBlock)) {
  23419.           formatter.apply('div');
  23420.         }
  23421.       }
  23422.       each$k(getBlocksToIndent(editor), function (block) {
  23423.         indentElement(dom, command, useMargin, indentValue, indentUnit, block.dom);
  23424.       });
  23425.     };
  23426.  
  23427.     var backspaceDelete = function (editor, _forward) {
  23428.       if (editor.selection.isCollapsed() && canOutdent(editor)) {
  23429.         var dom = editor.dom;
  23430.         var rng = editor.selection.getRng();
  23431.         var pos = CaretPosition.fromRangeStart(rng);
  23432.         var block = dom.getParent(rng.startContainer, dom.isBlock);
  23433.         if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
  23434.           handle(editor, 'outdent');
  23435.           return true;
  23436.         }
  23437.       }
  23438.       return false;
  23439.     };
  23440.  
  23441.     var nativeCommand = function (editor, command) {
  23442.       editor.getDoc().execCommand(command, false, null);
  23443.     };
  23444.     var deleteCommand = function (editor, caret) {
  23445.       if (backspaceDelete(editor)) {
  23446.         return;
  23447.       } else if (backspaceDelete$5(editor, false)) {
  23448.         return;
  23449.       } else if (backspaceDelete$6(editor, false)) {
  23450.         return;
  23451.       } else if (backspaceDelete$3(editor, caret, false)) {
  23452.         return;
  23453.       } else if (backspaceDelete$8(editor, false)) {
  23454.         return;
  23455.       } else if (backspaceDelete$9(editor)) {
  23456.         return;
  23457.       } else if (backspaceDelete$4(editor, false)) {
  23458.         return;
  23459.       } else if (backspaceDelete$1(editor, false)) {
  23460.         return;
  23461.       } else if (backspaceDelete$7(editor)) {
  23462.         return;
  23463.       } else if (backspaceDelete$2(editor, false)) {
  23464.         return;
  23465.       } else {
  23466.         nativeCommand(editor, 'Delete');
  23467.         paddEmptyBody(editor);
  23468.       }
  23469.     };
  23470.     var forwardDeleteCommand = function (editor, caret) {
  23471.       if (backspaceDelete$5(editor, true)) {
  23472.         return;
  23473.       } else if (backspaceDelete$6(editor, true)) {
  23474.         return;
  23475.       } else if (backspaceDelete$3(editor, caret, true)) {
  23476.         return;
  23477.       } else if (backspaceDelete$8(editor, true)) {
  23478.         return;
  23479.       } else if (backspaceDelete$9(editor)) {
  23480.         return;
  23481.       } else if (backspaceDelete$4(editor, true)) {
  23482.         return;
  23483.       } else if (backspaceDelete$1(editor, true)) {
  23484.         return;
  23485.       } else if (backspaceDelete$7(editor)) {
  23486.         return;
  23487.       } else if (backspaceDelete$2(editor, true)) {
  23488.         return;
  23489.       } else {
  23490.         nativeCommand(editor, 'ForwardDelete');
  23491.       }
  23492.     };
  23493.     var setup$f = function (editor, caret) {
  23494.       editor.addCommand('delete', function () {
  23495.         deleteCommand(editor, caret);
  23496.       });
  23497.       editor.addCommand('forwardDelete', function () {
  23498.         forwardDeleteCommand(editor, caret);
  23499.       });
  23500.     };
  23501.  
  23502.     var SIGNIFICANT_MOVE = 5;
  23503.     var LONGPRESS_DELAY = 400;
  23504.     var getTouch = function (event) {
  23505.       if (event.touches === undefined || event.touches.length !== 1) {
  23506.         return Optional.none();
  23507.       }
  23508.       return Optional.some(event.touches[0]);
  23509.     };
  23510.     var isFarEnough = function (touch, data) {
  23511.       var distX = Math.abs(touch.clientX - data.x);
  23512.       var distY = Math.abs(touch.clientY - data.y);
  23513.       return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  23514.     };
  23515.     var setup$e = function (editor) {
  23516.       var startData = value();
  23517.       var longpressFired = Cell(false);
  23518.       var debounceLongpress = last(function (e) {
  23519.         editor.fire('longpress', __assign(__assign({}, e), { type: 'longpress' }));
  23520.         longpressFired.set(true);
  23521.       }, LONGPRESS_DELAY);
  23522.       editor.on('touchstart', function (e) {
  23523.         getTouch(e).each(function (touch) {
  23524.           debounceLongpress.cancel();
  23525.           var data = {
  23526.             x: touch.clientX,
  23527.             y: touch.clientY,
  23528.             target: e.target
  23529.           };
  23530.           debounceLongpress.throttle(e);
  23531.           longpressFired.set(false);
  23532.           startData.set(data);
  23533.         });
  23534.       }, true);
  23535.       editor.on('touchmove', function (e) {
  23536.         debounceLongpress.cancel();
  23537.         getTouch(e).each(function (touch) {
  23538.           startData.on(function (data) {
  23539.             if (isFarEnough(touch, data)) {
  23540.               startData.clear();
  23541.               longpressFired.set(false);
  23542.               editor.fire('longpresscancel');
  23543.             }
  23544.           });
  23545.         });
  23546.       }, true);
  23547.       editor.on('touchend touchcancel', function (e) {
  23548.         debounceLongpress.cancel();
  23549.         if (e.type === 'touchcancel') {
  23550.           return;
  23551.         }
  23552.         startData.get().filter(function (data) {
  23553.           return data.target.isEqualNode(e.target);
  23554.         }).each(function () {
  23555.           if (longpressFired.get()) {
  23556.             e.preventDefault();
  23557.           } else {
  23558.             editor.fire('tap', __assign(__assign({}, e), { type: 'tap' }));
  23559.           }
  23560.         });
  23561.       }, true);
  23562.     };
  23563.  
  23564.     var isBlockElement = function (blockElements, node) {
  23565.       return has$2(blockElements, node.nodeName);
  23566.     };
  23567.     var isValidTarget = function (blockElements, node) {
  23568.       if (isText$7(node)) {
  23569.         return true;
  23570.       } else if (isElement$5(node)) {
  23571.         return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
  23572.       } else {
  23573.         return false;
  23574.       }
  23575.     };
  23576.     var hasBlockParent = function (blockElements, root, node) {
  23577.       return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function (elm) {
  23578.         return isBlockElement(blockElements, elm.dom);
  23579.       });
  23580.     };
  23581.     var shouldRemoveTextNode = function (blockElements, node) {
  23582.       if (isText$7(node)) {
  23583.         if (node.nodeValue.length === 0) {
  23584.           return true;
  23585.         } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
  23586.           return true;
  23587.         }
  23588.       }
  23589.       return false;
  23590.     };
  23591.     var addRootBlocks = function (editor) {
  23592.       var dom = editor.dom, selection = editor.selection;
  23593.       var schema = editor.schema, blockElements = schema.getBlockElements();
  23594.       var node = selection.getStart();
  23595.       var rootNode = editor.getBody();
  23596.       var rootBlockNode, tempNode, wrapped;
  23597.       var forcedRootBlock = getForcedRootBlock(editor);
  23598.       if (!node || !isElement$5(node) || !forcedRootBlock) {
  23599.         return;
  23600.       }
  23601.       var rootNodeName = rootNode.nodeName.toLowerCase();
  23602.       if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
  23603.         return;
  23604.       }
  23605.       var rng = selection.getRng();
  23606.       var startContainer = rng.startContainer;
  23607.       var startOffset = rng.startOffset;
  23608.       var endContainer = rng.endContainer;
  23609.       var endOffset = rng.endOffset;
  23610.       var restoreSelection = hasFocus(editor);
  23611.       node = rootNode.firstChild;
  23612.       while (node) {
  23613.         if (isValidTarget(blockElements, node)) {
  23614.           if (shouldRemoveTextNode(blockElements, node)) {
  23615.             tempNode = node;
  23616.             node = node.nextSibling;
  23617.             dom.remove(tempNode);
  23618.             continue;
  23619.           }
  23620.           if (!rootBlockNode) {
  23621.             rootBlockNode = dom.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
  23622.             node.parentNode.insertBefore(rootBlockNode, node);
  23623.             wrapped = true;
  23624.           }
  23625.           tempNode = node;
  23626.           node = node.nextSibling;
  23627.           rootBlockNode.appendChild(tempNode);
  23628.         } else {
  23629.           rootBlockNode = null;
  23630.           node = node.nextSibling;
  23631.         }
  23632.       }
  23633.       if (wrapped && restoreSelection) {
  23634.         rng.setStart(startContainer, startOffset);
  23635.         rng.setEnd(endContainer, endOffset);
  23636.         selection.setRng(rng);
  23637.         editor.nodeChanged();
  23638.       }
  23639.     };
  23640.     var setup$d = function (editor) {
  23641.       if (getForcedRootBlock(editor)) {
  23642.         editor.on('NodeChange', curry(addRootBlocks, editor));
  23643.       }
  23644.     };
  23645.  
  23646.     var findBlockCaretContainer = function (editor) {
  23647.       return descendant(SugarElement.fromDom(editor.getBody()), '*[data-mce-caret]').map(function (elm) {
  23648.         return elm.dom;
  23649.       }).getOrNull();
  23650.     };
  23651.     var removeIeControlRect = function (editor) {
  23652.       editor.selection.setRng(editor.selection.getRng());
  23653.     };
  23654.     var showBlockCaretContainer = function (editor, blockCaretContainer) {
  23655.       if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  23656.         showCaretContainerBlock(blockCaretContainer);
  23657.         removeIeControlRect(editor);
  23658.         editor.selection.scrollIntoView(blockCaretContainer);
  23659.       }
  23660.     };
  23661.     var handleBlockContainer = function (editor, e) {
  23662.       var blockCaretContainer = findBlockCaretContainer(editor);
  23663.       if (!blockCaretContainer) {
  23664.         return;
  23665.       }
  23666.       if (e.type === 'compositionstart') {
  23667.         e.preventDefault();
  23668.         e.stopPropagation();
  23669.         showBlockCaretContainer(editor, blockCaretContainer);
  23670.         return;
  23671.       }
  23672.       if (hasContent(blockCaretContainer)) {
  23673.         showBlockCaretContainer(editor, blockCaretContainer);
  23674.         editor.undoManager.add();
  23675.       }
  23676.     };
  23677.     var setup$c = function (editor) {
  23678.       editor.on('keyup compositionstart', curry(handleBlockContainer, editor));
  23679.     };
  23680.  
  23681.     var isContentEditableFalse$2 = isContentEditableFalse$b;
  23682.     var moveToCeFalseHorizontally = function (direction, editor, range) {
  23683.       return moveHorizontally(editor, direction, range, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
  23684.     };
  23685.     var moveToCeFalseVertically = function (direction, editor, range) {
  23686.       var isBefore = function (caretPosition) {
  23687.         return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
  23688.       };
  23689.       var isAfter = function (caretPosition) {
  23690.         return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
  23691.       };
  23692.       return moveVertically(editor, direction, range, isBefore, isAfter, isContentEditableFalse$2);
  23693.     };
  23694.     var createTextBlock = function (editor) {
  23695.       var textBlock = editor.dom.create(getForcedRootBlock(editor));
  23696.       if (!Env.ie || Env.ie >= 11) {
  23697.         textBlock.innerHTML = '<br data-mce-bogus="1">';
  23698.       }
  23699.       return textBlock;
  23700.     };
  23701.     var exitPreBlock = function (editor, direction, range) {
  23702.       var caretWalker = CaretWalker(editor.getBody());
  23703.       var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
  23704.       if (range.collapsed && hasForcedRootBlock(editor)) {
  23705.         var pre = editor.dom.getParent(range.startContainer, 'PRE');
  23706.         if (!pre) {
  23707.           return;
  23708.         }
  23709.         var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range));
  23710.         if (!caretPos) {
  23711.           var newBlock = createTextBlock(editor);
  23712.           if (direction === 1) {
  23713.             editor.$(pre).after(newBlock);
  23714.           } else {
  23715.             editor.$(pre).before(newBlock);
  23716.           }
  23717.           editor.selection.select(newBlock, true);
  23718.           editor.selection.collapse();
  23719.         }
  23720.       }
  23721.     };
  23722.     var getHorizontalRange = function (editor, forward) {
  23723.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23724.       var range = editor.selection.getRng();
  23725.       return moveToCeFalseHorizontally(direction, editor, range).orThunk(function () {
  23726.         exitPreBlock(editor, direction, range);
  23727.         return Optional.none();
  23728.       });
  23729.     };
  23730.     var getVerticalRange = function (editor, down) {
  23731.       var direction = down ? 1 : -1;
  23732.       var range = editor.selection.getRng();
  23733.       return moveToCeFalseVertically(direction, editor, range).orThunk(function () {
  23734.         exitPreBlock(editor, direction, range);
  23735.         return Optional.none();
  23736.       });
  23737.     };
  23738.     var moveH$2 = function (editor, forward) {
  23739.       return getHorizontalRange(editor, forward).exists(function (newRange) {
  23740.         moveToRange(editor, newRange);
  23741.         return true;
  23742.       });
  23743.     };
  23744.     var moveV$3 = function (editor, down) {
  23745.       return getVerticalRange(editor, down).exists(function (newRange) {
  23746.         moveToRange(editor, newRange);
  23747.         return true;
  23748.       });
  23749.     };
  23750.     var moveToLineEndPoint$1 = function (editor, forward) {
  23751.       var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
  23752.       return moveToLineEndPoint$3(editor, forward, isCefPosition);
  23753.     };
  23754.  
  23755.     var isTarget = function (node) {
  23756.       return contains$3(['figcaption'], name(node));
  23757.     };
  23758.     var rangeBefore = function (target) {
  23759.       var rng = document.createRange();
  23760.       rng.setStartBefore(target.dom);
  23761.       rng.setEndBefore(target.dom);
  23762.       return rng;
  23763.     };
  23764.     var insertElement = function (root, elm, forward) {
  23765.       if (forward) {
  23766.         append$1(root, elm);
  23767.       } else {
  23768.         prepend(root, elm);
  23769.       }
  23770.     };
  23771.     var insertBr = function (root, forward) {
  23772.       var br = SugarElement.fromTag('br');
  23773.       insertElement(root, br, forward);
  23774.       return rangeBefore(br);
  23775.     };
  23776.     var insertBlock = function (root, forward, blockName, attrs) {
  23777.       var block = SugarElement.fromTag(blockName);
  23778.       var br = SugarElement.fromTag('br');
  23779.       setAll$1(block, attrs);
  23780.       append$1(block, br);
  23781.       insertElement(root, block, forward);
  23782.       return rangeBefore(br);
  23783.     };
  23784.     var insertEmptyLine = function (root, rootBlockName, attrs, forward) {
  23785.       if (rootBlockName === '') {
  23786.         return insertBr(root, forward);
  23787.       } else {
  23788.         return insertBlock(root, forward, rootBlockName, attrs);
  23789.       }
  23790.     };
  23791.     var getClosestTargetBlock = function (pos, root) {
  23792.       var isRoot = curry(eq, root);
  23793.       return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
  23794.     };
  23795.     var isAtFirstOrLastLine = function (root, forward, pos) {
  23796.       return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
  23797.     };
  23798.     var moveCaretToNewEmptyLine = function (editor, forward) {
  23799.       var root = SugarElement.fromDom(editor.getBody());
  23800.       var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  23801.       var rootBlock = getForcedRootBlock(editor);
  23802.       var rootBlockAttrs = getForcedRootBlockAttrs(editor);
  23803.       return getClosestTargetBlock(pos, root).exists(function () {
  23804.         if (isAtFirstOrLastLine(root, forward, pos)) {
  23805.           var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
  23806.           editor.selection.setRng(rng);
  23807.           return true;
  23808.         } else {
  23809.           return false;
  23810.         }
  23811.       });
  23812.     };
  23813.     var moveV$2 = function (editor, forward) {
  23814.       if (editor.selection.isCollapsed()) {
  23815.         return moveCaretToNewEmptyLine(editor, forward);
  23816.       } else {
  23817.         return false;
  23818.       }
  23819.     };
  23820.  
  23821.     var defaultPatterns = function (patterns) {
  23822.       return map$3(patterns, function (pattern) {
  23823.         return __assign({
  23824.           shiftKey: false,
  23825.           altKey: false,
  23826.           ctrlKey: false,
  23827.           metaKey: false,
  23828.           keyCode: 0,
  23829.           action: noop
  23830.         }, pattern);
  23831.       });
  23832.     };
  23833.     var matchesEvent = function (pattern, evt) {
  23834.       return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
  23835.     };
  23836.     var match$1 = function (patterns, evt) {
  23837.       return bind(defaultPatterns(patterns), function (pattern) {
  23838.         return matchesEvent(pattern, evt) ? [pattern] : [];
  23839.       });
  23840.     };
  23841.     var action = function (f) {
  23842.       var x = [];
  23843.       for (var _i = 1; _i < arguments.length; _i++) {
  23844.         x[_i - 1] = arguments[_i];
  23845.       }
  23846.       return function () {
  23847.         return f.apply(null, x);
  23848.       };
  23849.     };
  23850.     var execute = function (patterns, evt) {
  23851.       return find$3(match$1(patterns, evt), function (pattern) {
  23852.         return pattern.action();
  23853.       });
  23854.     };
  23855.  
  23856.     var moveH$1 = function (editor, forward) {
  23857.       var direction = forward ? HDirection.Forwards : HDirection.Backwards;
  23858.       var range = editor.selection.getRng();
  23859.       return moveHorizontally(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23860.         moveToRange(editor, newRange);
  23861.         return true;
  23862.       });
  23863.     };
  23864.     var moveV$1 = function (editor, down) {
  23865.       var direction = down ? 1 : -1;
  23866.       var range = editor.selection.getRng();
  23867.       return moveVertically(editor, direction, range, isBeforeMedia, isAfterMedia, isMedia$2).exists(function (newRange) {
  23868.         moveToRange(editor, newRange);
  23869.         return true;
  23870.       });
  23871.     };
  23872.     var moveToLineEndPoint = function (editor, forward) {
  23873.       var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
  23874.       return moveToLineEndPoint$3(editor, forward, isNearMedia);
  23875.     };
  23876.  
  23877.     var deflate = function (rect, delta) {
  23878.       return {
  23879.         left: rect.left - delta,
  23880.         top: rect.top - delta,
  23881.         right: rect.right + delta * 2,
  23882.         bottom: rect.bottom + delta * 2,
  23883.         width: rect.width + delta,
  23884.         height: rect.height + delta
  23885.       };
  23886.     };
  23887.     var getCorners = function (getYAxisValue, tds) {
  23888.       return bind(tds, function (td) {
  23889.         var rect = deflate(clone(td.getBoundingClientRect()), -1);
  23890.         return [
  23891.           {
  23892.             x: rect.left,
  23893.             y: getYAxisValue(rect),
  23894.             cell: td
  23895.           },
  23896.           {
  23897.             x: rect.right,
  23898.             y: getYAxisValue(rect),
  23899.             cell: td
  23900.           }
  23901.         ];
  23902.       });
  23903.     };
  23904.     var findClosestCorner = function (corners, x, y) {
  23905.       return foldl(corners, function (acc, newCorner) {
  23906.         return acc.fold(function () {
  23907.           return Optional.some(newCorner);
  23908.         }, function (oldCorner) {
  23909.           var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
  23910.           var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
  23911.           return Optional.some(newDist < oldDist ? newCorner : oldCorner);
  23912.         });
  23913.       }, Optional.none());
  23914.     };
  23915.     var getClosestCell = function (getYAxisValue, isTargetCorner, table, x, y) {
  23916.       var cells = descendants(SugarElement.fromDom(table), 'td,th,caption').map(function (e) {
  23917.         return e.dom;
  23918.       });
  23919.       var corners = filter$4(getCorners(getYAxisValue, cells), function (corner) {
  23920.         return isTargetCorner(corner, y);
  23921.       });
  23922.       return findClosestCorner(corners, x, y).map(function (corner) {
  23923.         return corner.cell;
  23924.       });
  23925.     };
  23926.     var getBottomValue = function (rect) {
  23927.       return rect.bottom;
  23928.     };
  23929.     var getTopValue = function (rect) {
  23930.       return rect.top;
  23931.     };
  23932.     var isAbove = function (corner, y) {
  23933.       return corner.y < y;
  23934.     };
  23935.     var isBelow = function (corner, y) {
  23936.       return corner.y > y;
  23937.     };
  23938.     var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
  23939.     var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
  23940.     var findClosestPositionInAboveCell = function (table, pos) {
  23941.       return head(pos.getClientRects()).bind(function (rect) {
  23942.         return getClosestCellAbove(table, rect.left, rect.top);
  23943.       }).bind(function (cell) {
  23944.         return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
  23945.       });
  23946.     };
  23947.     var findClosestPositionInBelowCell = function (table, pos) {
  23948.       return last$2(pos.getClientRects()).bind(function (rect) {
  23949.         return getClosestCellBelow(table, rect.left, rect.top);
  23950.       }).bind(function (cell) {
  23951.         return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
  23952.       });
  23953.     };
  23954.  
  23955.     var hasNextBreak = function (getPositionsUntil, scope, lineInfo) {
  23956.       return lineInfo.breakAt.exists(function (breakPos) {
  23957.         return getPositionsUntil(scope, breakPos).breakAt.isSome();
  23958.       });
  23959.     };
  23960.     var startsWithWrapBreak = function (lineInfo) {
  23961.       return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
  23962.     };
  23963.     var startsWithBrBreak = function (lineInfo) {
  23964.       return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
  23965.     };
  23966.     var isAtTableCellLine = function (getPositionsUntil, scope, pos) {
  23967.       var lineInfo = getPositionsUntil(scope, pos);
  23968.       if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
  23969.         return !hasNextBreak(getPositionsUntil, scope, lineInfo);
  23970.       } else {
  23971.         return lineInfo.breakAt.isNone();
  23972.       }
  23973.     };
  23974.     var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
  23975.     var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
  23976.     var isCaretAtStartOrEndOfTable = function (forward, rng, table) {
  23977.       var caretPos = CaretPosition.fromRangeStart(rng);
  23978.       return positionIn(!forward, table).exists(function (pos) {
  23979.         return pos.isEqual(caretPos);
  23980.       });
  23981.     };
  23982.     var navigateHorizontally = function (editor, forward, table, _td) {
  23983.       var rng = editor.selection.getRng();
  23984.       var direction = forward ? 1 : -1;
  23985.       if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
  23986.         showCaret(direction, editor, table, !forward, false).each(function (newRng) {
  23987.           moveToRange(editor, newRng);
  23988.         });
  23989.         return true;
  23990.       }
  23991.       return false;
  23992.     };
  23993.     var getClosestAbovePosition = function (root, table, start) {
  23994.       return findClosestPositionInAboveCell(table, start).orThunk(function () {
  23995.         return head(start.getClientRects()).bind(function (rect) {
  23996.           return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
  23997.         });
  23998.       }).getOr(CaretPosition.before(table));
  23999.     };
  24000.     var getClosestBelowPosition = function (root, table, start) {
  24001.       return findClosestPositionInBelowCell(table, start).orThunk(function () {
  24002.         return head(start.getClientRects()).bind(function (rect) {
  24003.           return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
  24004.         });
  24005.       }).getOr(CaretPosition.after(table));
  24006.     };
  24007.     var getTable = function (previous, pos) {
  24008.       var node = pos.getNode(previous);
  24009.       return isElement$5(node) && node.nodeName === 'TABLE' ? Optional.some(node) : Optional.none();
  24010.     };
  24011.     var renderBlock = function (down, editor, table, pos) {
  24012.       var forcedRootBlock = getForcedRootBlock(editor);
  24013.       if (forcedRootBlock) {
  24014.         editor.undoManager.transact(function () {
  24015.           var element = SugarElement.fromTag(forcedRootBlock);
  24016.           setAll$1(element, getForcedRootBlockAttrs(editor));
  24017.           append$1(element, SugarElement.fromTag('br'));
  24018.           if (down) {
  24019.             after$3(SugarElement.fromDom(table), element);
  24020.           } else {
  24021.             before$4(SugarElement.fromDom(table), element);
  24022.           }
  24023.           var rng = editor.dom.createRng();
  24024.           rng.setStart(element.dom, 0);
  24025.           rng.setEnd(element.dom, 0);
  24026.           moveToRange(editor, rng);
  24027.         });
  24028.       } else {
  24029.         moveToRange(editor, pos.toRange());
  24030.       }
  24031.     };
  24032.     var moveCaret = function (editor, down, pos) {
  24033.       var table = down ? getTable(true, pos) : getTable(false, pos);
  24034.       var last = down === false;
  24035.       table.fold(function () {
  24036.         return moveToRange(editor, pos.toRange());
  24037.       }, function (table) {
  24038.         return positionIn(last, editor.getBody()).filter(function (lastPos) {
  24039.           return lastPos.isEqual(pos);
  24040.         }).fold(function () {
  24041.           return moveToRange(editor, pos.toRange());
  24042.         }, function (_) {
  24043.           return renderBlock(down, editor, table, pos);
  24044.         });
  24045.       });
  24046.     };
  24047.     var navigateVertically = function (editor, down, table, td) {
  24048.       var rng = editor.selection.getRng();
  24049.       var pos = CaretPosition.fromRangeStart(rng);
  24050.       var root = editor.getBody();
  24051.       if (!down && isAtFirstTableCellLine(td, pos)) {
  24052.         var newPos = getClosestAbovePosition(root, table, pos);
  24053.         moveCaret(editor, down, newPos);
  24054.         return true;
  24055.       } else if (down && isAtLastTableCellLine(td, pos)) {
  24056.         var newPos = getClosestBelowPosition(root, table, pos);
  24057.         moveCaret(editor, down, newPos);
  24058.         return true;
  24059.       } else {
  24060.         return false;
  24061.       }
  24062.     };
  24063.     var move$1 = function (editor, forward, mover) {
  24064.       return Optional.from(editor.dom.getParent(editor.selection.getNode(), 'td,th')).bind(function (td) {
  24065.         return Optional.from(editor.dom.getParent(td, 'table')).map(function (table) {
  24066.           return mover(editor, forward, table, td);
  24067.         });
  24068.       }).getOr(false);
  24069.     };
  24070.     var moveH = function (editor, forward) {
  24071.       return move$1(editor, forward, navigateHorizontally);
  24072.     };
  24073.     var moveV = function (editor, forward) {
  24074.       return move$1(editor, forward, navigateVertically);
  24075.     };
  24076.  
  24077.     var executeKeydownOverride$3 = function (editor, caret, evt) {
  24078.       var os = detect().os;
  24079.       execute([
  24080.         {
  24081.           keyCode: VK.RIGHT,
  24082.           action: action(moveH$2, editor, true)
  24083.         },
  24084.         {
  24085.           keyCode: VK.LEFT,
  24086.           action: action(moveH$2, editor, false)
  24087.         },
  24088.         {
  24089.           keyCode: VK.UP,
  24090.           action: action(moveV$3, editor, false)
  24091.         },
  24092.         {
  24093.           keyCode: VK.DOWN,
  24094.           action: action(moveV$3, editor, true)
  24095.         },
  24096.         {
  24097.           keyCode: VK.RIGHT,
  24098.           action: action(moveH, editor, true)
  24099.         },
  24100.         {
  24101.           keyCode: VK.LEFT,
  24102.           action: action(moveH, editor, false)
  24103.         },
  24104.         {
  24105.           keyCode: VK.UP,
  24106.           action: action(moveV, editor, false)
  24107.         },
  24108.         {
  24109.           keyCode: VK.DOWN,
  24110.           action: action(moveV, editor, true)
  24111.         },
  24112.         {
  24113.           keyCode: VK.RIGHT,
  24114.           action: action(moveH$1, editor, true)
  24115.         },
  24116.         {
  24117.           keyCode: VK.LEFT,
  24118.           action: action(moveH$1, editor, false)
  24119.         },
  24120.         {
  24121.           keyCode: VK.UP,
  24122.           action: action(moveV$1, editor, false)
  24123.         },
  24124.         {
  24125.           keyCode: VK.DOWN,
  24126.           action: action(moveV$1, editor, true)
  24127.         },
  24128.         {
  24129.           keyCode: VK.RIGHT,
  24130.           action: action(move$2, editor, caret, true)
  24131.         },
  24132.         {
  24133.           keyCode: VK.LEFT,
  24134.           action: action(move$2, editor, caret, false)
  24135.         },
  24136.         {
  24137.           keyCode: VK.RIGHT,
  24138.           ctrlKey: !os.isOSX(),
  24139.           altKey: os.isOSX(),
  24140.           action: action(moveNextWord, editor, caret)
  24141.         },
  24142.         {
  24143.           keyCode: VK.LEFT,
  24144.           ctrlKey: !os.isOSX(),
  24145.           altKey: os.isOSX(),
  24146.           action: action(movePrevWord, editor, caret)
  24147.         },
  24148.         {
  24149.           keyCode: VK.UP,
  24150.           action: action(moveV$2, editor, false)
  24151.         },
  24152.         {
  24153.           keyCode: VK.DOWN,
  24154.           action: action(moveV$2, editor, true)
  24155.         }
  24156.       ], evt).each(function (_) {
  24157.         evt.preventDefault();
  24158.       });
  24159.     };
  24160.     var setup$b = function (editor, caret) {
  24161.       editor.on('keydown', function (evt) {
  24162.         if (evt.isDefaultPrevented() === false) {
  24163.           executeKeydownOverride$3(editor, caret, evt);
  24164.         }
  24165.       });
  24166.     };
  24167.  
  24168.     var executeKeydownOverride$2 = function (editor, caret, evt) {
  24169.       execute([
  24170.         {
  24171.           keyCode: VK.BACKSPACE,
  24172.           action: action(backspaceDelete, editor, false)
  24173.         },
  24174.         {
  24175.           keyCode: VK.BACKSPACE,
  24176.           action: action(backspaceDelete$5, editor, false)
  24177.         },
  24178.         {
  24179.           keyCode: VK.DELETE,
  24180.           action: action(backspaceDelete$5, editor, true)
  24181.         },
  24182.         {
  24183.           keyCode: VK.BACKSPACE,
  24184.           action: action(backspaceDelete$6, editor, false)
  24185.         },
  24186.         {
  24187.           keyCode: VK.DELETE,
  24188.           action: action(backspaceDelete$6, editor, true)
  24189.         },
  24190.         {
  24191.           keyCode: VK.BACKSPACE,
  24192.           action: action(backspaceDelete$3, editor, caret, false)
  24193.         },
  24194.         {
  24195.           keyCode: VK.DELETE,
  24196.           action: action(backspaceDelete$3, editor, caret, true)
  24197.         },
  24198.         {
  24199.           keyCode: VK.BACKSPACE,
  24200.           action: action(backspaceDelete$9, editor, false)
  24201.         },
  24202.         {
  24203.           keyCode: VK.DELETE,
  24204.           action: action(backspaceDelete$9, editor, true)
  24205.         },
  24206.         {
  24207.           keyCode: VK.BACKSPACE,
  24208.           action: action(backspaceDelete$4, editor, false)
  24209.         },
  24210.         {
  24211.           keyCode: VK.DELETE,
  24212.           action: action(backspaceDelete$4, editor, true)
  24213.         },
  24214.         {
  24215.           keyCode: VK.BACKSPACE,
  24216.           action: action(backspaceDelete$1, editor, false)
  24217.         },
  24218.         {
  24219.           keyCode: VK.DELETE,
  24220.           action: action(backspaceDelete$1, editor, true)
  24221.         },
  24222.         {
  24223.           keyCode: VK.BACKSPACE,
  24224.           action: action(backspaceDelete$7, editor, false)
  24225.         },
  24226.         {
  24227.           keyCode: VK.DELETE,
  24228.           action: action(backspaceDelete$7, editor, true)
  24229.         },
  24230.         {
  24231.           keyCode: VK.BACKSPACE,
  24232.           action: action(backspaceDelete$8, editor, false)
  24233.         },
  24234.         {
  24235.           keyCode: VK.DELETE,
  24236.           action: action(backspaceDelete$8, editor, true)
  24237.         },
  24238.         {
  24239.           keyCode: VK.BACKSPACE,
  24240.           action: action(backspaceDelete$2, editor, false)
  24241.         },
  24242.         {
  24243.           keyCode: VK.DELETE,
  24244.           action: action(backspaceDelete$2, editor, true)
  24245.         }
  24246.       ], evt).each(function (_) {
  24247.         evt.preventDefault();
  24248.       });
  24249.     };
  24250.     var executeKeyupOverride = function (editor, evt) {
  24251.       execute([
  24252.         {
  24253.           keyCode: VK.BACKSPACE,
  24254.           action: action(paddEmptyElement, editor)
  24255.         },
  24256.         {
  24257.           keyCode: VK.DELETE,
  24258.           action: action(paddEmptyElement, editor)
  24259.         }
  24260.       ], evt);
  24261.     };
  24262.     var setup$a = function (editor, caret) {
  24263.       editor.on('keydown', function (evt) {
  24264.         if (evt.isDefaultPrevented() === false) {
  24265.           executeKeydownOverride$2(editor, caret, evt);
  24266.         }
  24267.       });
  24268.       editor.on('keyup', function (evt) {
  24269.         if (evt.isDefaultPrevented() === false) {
  24270.           executeKeyupOverride(editor, evt);
  24271.         }
  24272.       });
  24273.     };
  24274.  
  24275.     var firstNonWhiteSpaceNodeSibling = function (node) {
  24276.       while (node) {
  24277.         if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
  24278.           return node;
  24279.         }
  24280.         node = node.nextSibling;
  24281.       }
  24282.     };
  24283.     var moveToCaretPosition = function (editor, root) {
  24284.       var node, lastNode = root;
  24285.       var dom = editor.dom;
  24286.       var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
  24287.       if (!root) {
  24288.         return;
  24289.       }
  24290.       if (/^(LI|DT|DD)$/.test(root.nodeName)) {
  24291.         var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  24292.         if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) {
  24293.           root.insertBefore(dom.doc.createTextNode(nbsp), root.firstChild);
  24294.         }
  24295.       }
  24296.       var rng = dom.createRng();
  24297.       root.normalize();
  24298.       if (root.hasChildNodes()) {
  24299.         var walker = new DomTreeWalker(root, root);
  24300.         while (node = walker.current()) {
  24301.           if (isText$7(node)) {
  24302.             rng.setStart(node, 0);
  24303.             rng.setEnd(node, 0);
  24304.             break;
  24305.           }
  24306.           if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
  24307.             rng.setStartBefore(node);
  24308.             rng.setEndBefore(node);
  24309.             break;
  24310.           }
  24311.           lastNode = node;
  24312.           node = walker.next();
  24313.         }
  24314.         if (!node) {
  24315.           rng.setStart(lastNode, 0);
  24316.           rng.setEnd(lastNode, 0);
  24317.         }
  24318.       } else {
  24319.         if (isBr$5(root)) {
  24320.           if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  24321.             rng.setStartBefore(root);
  24322.             rng.setEndBefore(root);
  24323.           } else {
  24324.             rng.setStartAfter(root);
  24325.             rng.setEndAfter(root);
  24326.           }
  24327.         } else {
  24328.           rng.setStart(root, 0);
  24329.           rng.setEnd(root, 0);
  24330.         }
  24331.       }
  24332.       editor.selection.setRng(rng);
  24333.       scrollRangeIntoView(editor, rng);
  24334.     };
  24335.     var getEditableRoot$1 = function (dom, node) {
  24336.       var root = dom.getRoot();
  24337.       var parent, editableRoot;
  24338.       parent = node;
  24339.       while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24340.         if (dom.getContentEditable(parent) === 'true') {
  24341.           editableRoot = parent;
  24342.         }
  24343.         parent = parent.parentNode;
  24344.       }
  24345.       return parent !== root ? editableRoot : root;
  24346.     };
  24347.     var getParentBlock = function (editor) {
  24348.       return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
  24349.     };
  24350.     var getParentBlockName = function (editor) {
  24351.       return getParentBlock(editor).fold(constant(''), function (parentBlock) {
  24352.         return parentBlock.nodeName.toUpperCase();
  24353.       });
  24354.     };
  24355.     var isListItemParentBlock = function (editor) {
  24356.       return getParentBlock(editor).filter(function (elm) {
  24357.         return isListItem(SugarElement.fromDom(elm));
  24358.       }).isSome();
  24359.     };
  24360.  
  24361.     var hasFirstChild = function (elm, name) {
  24362.       return elm.firstChild && elm.firstChild.nodeName === name;
  24363.     };
  24364.     var isFirstChild = function (elm) {
  24365.       var _a;
  24366.       return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
  24367.     };
  24368.     var hasParent = function (elm, parentName) {
  24369.       return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
  24370.     };
  24371.     var isListBlock = function (elm) {
  24372.       return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
  24373.     };
  24374.     var isNestedList = function (elm) {
  24375.       return isListBlock(elm) && isListBlock(elm.parentNode);
  24376.     };
  24377.     var getContainerBlock = function (containerBlock) {
  24378.       var containerBlockParent = containerBlock.parentNode;
  24379.       if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
  24380.         return containerBlockParent;
  24381.       }
  24382.       return containerBlock;
  24383.     };
  24384.     var isFirstOrLastLi = function (containerBlock, parentBlock, first) {
  24385.       var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  24386.       while (node) {
  24387.         if (isElement$5(node)) {
  24388.           break;
  24389.         }
  24390.         node = node[first ? 'nextSibling' : 'previousSibling'];
  24391.       }
  24392.       return node === parentBlock;
  24393.     };
  24394.     var insert$3 = function (editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
  24395.       var dom = editor.dom;
  24396.       var rng = editor.selection.getRng();
  24397.       if (containerBlock === editor.getBody()) {
  24398.         return;
  24399.       }
  24400.       if (isNestedList(containerBlock)) {
  24401.         newBlockName = 'LI';
  24402.       }
  24403.       var newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  24404.       if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24405.         if (hasParent(containerBlock, 'LI')) {
  24406.           var containerBlockParent = getContainerBlock(containerBlock);
  24407.           dom.insertAfter(newBlock, containerBlockParent);
  24408.           if (isFirstChild(containerBlock)) {
  24409.             dom.remove(containerBlockParent);
  24410.           } else {
  24411.             dom.remove(containerBlock);
  24412.           }
  24413.         } else {
  24414.           dom.replace(newBlock, containerBlock);
  24415.         }
  24416.       } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
  24417.         if (hasParent(containerBlock, 'LI')) {
  24418.           dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24419.           newBlock.appendChild(dom.doc.createTextNode(' '));
  24420.           newBlock.appendChild(containerBlock);
  24421.         } else {
  24422.           containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  24423.         }
  24424.         dom.remove(parentBlock);
  24425.       } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
  24426.         dom.insertAfter(newBlock, getContainerBlock(containerBlock));
  24427.         dom.remove(parentBlock);
  24428.       } else {
  24429.         containerBlock = getContainerBlock(containerBlock);
  24430.         var tmpRng = rng.cloneRange();
  24431.         tmpRng.setStartAfter(parentBlock);
  24432.         tmpRng.setEndAfter(containerBlock);
  24433.         var fragment = tmpRng.extractContents();
  24434.         if (newBlockName === 'LI' && hasFirstChild(fragment, 'LI')) {
  24435.           newBlock = fragment.firstChild;
  24436.           dom.insertAfter(fragment, containerBlock);
  24437.         } else {
  24438.           dom.insertAfter(fragment, containerBlock);
  24439.           dom.insertAfter(newBlock, containerBlock);
  24440.         }
  24441.         dom.remove(parentBlock);
  24442.       }
  24443.       moveToCaretPosition(editor, newBlock);
  24444.     };
  24445.  
  24446.     var trimZwsp = function (fragment) {
  24447.       each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function (text) {
  24448.         var rawNode = text.dom;
  24449.         rawNode.nodeValue = trim$3(rawNode.nodeValue);
  24450.       });
  24451.     };
  24452.     var isEmptyAnchor = function (dom, elm) {
  24453.       return elm && elm.nodeName === 'A' && dom.isEmpty(elm);
  24454.     };
  24455.     var isTableCell = function (node) {
  24456.       return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
  24457.     };
  24458.     var emptyBlock = function (elm) {
  24459.       elm.innerHTML = '<br data-mce-bogus="1">';
  24460.     };
  24461.     var containerAndSiblingName = function (container, nodeName) {
  24462.       return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
  24463.     };
  24464.     var canSplitBlock = function (dom, node) {
  24465.       return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== 'true';
  24466.     };
  24467.     var trimInlineElementsOnLeftSideOfBlock = function (dom, nonEmptyElementsMap, block) {
  24468.       var node = block;
  24469.       var firstChilds = [];
  24470.       var i;
  24471.       if (!node) {
  24472.         return;
  24473.       }
  24474.       while (node = node.firstChild) {
  24475.         if (dom.isBlock(node)) {
  24476.           return;
  24477.         }
  24478.         if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  24479.           firstChilds.push(node);
  24480.         }
  24481.       }
  24482.       i = firstChilds.length;
  24483.       while (i--) {
  24484.         node = firstChilds[i];
  24485.         if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === '') {
  24486.           dom.remove(node);
  24487.         } else {
  24488.           if (isEmptyAnchor(dom, node)) {
  24489.             dom.remove(node);
  24490.           }
  24491.         }
  24492.       }
  24493.     };
  24494.     var normalizeZwspOffset = function (start, container, offset) {
  24495.       if (isText$7(container) === false) {
  24496.         return offset;
  24497.       } else if (start) {
  24498.         return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
  24499.       } else {
  24500.         return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
  24501.       }
  24502.     };
  24503.     var includeZwspInRange = function (rng) {
  24504.       var newRng = rng.cloneRange();
  24505.       newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
  24506.       newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
  24507.       return newRng;
  24508.     };
  24509.     var trimLeadingLineBreaks = function (node) {
  24510.       do {
  24511.         if (isText$7(node)) {
  24512.           node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  24513.         }
  24514.         node = node.firstChild;
  24515.       } while (node);
  24516.     };
  24517.     var getEditableRoot = function (dom, node) {
  24518.       var root = dom.getRoot();
  24519.       var parent, editableRoot;
  24520.       parent = node;
  24521.       while (parent !== root && dom.getContentEditable(parent) !== 'false') {
  24522.         if (dom.getContentEditable(parent) === 'true') {
  24523.           editableRoot = parent;
  24524.         }
  24525.         parent = parent.parentNode;
  24526.       }
  24527.       return parent !== root ? editableRoot : root;
  24528.     };
  24529.     var applyAttributes = function (editor, node, forcedRootBlockAttrs) {
  24530.       var dom = editor.dom;
  24531.       Optional.from(forcedRootBlockAttrs.style).map(dom.parseStyle).each(function (attrStyles) {
  24532.         var currentStyles = getAllRaw(SugarElement.fromDom(node));
  24533.         var newStyles = __assign(__assign({}, currentStyles), attrStyles);
  24534.         dom.setStyles(node, newStyles);
  24535.       });
  24536.       var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function (attrClasses) {
  24537.         return attrClasses.split(/\s+/);
  24538.       });
  24539.       var currentClassesOpt = Optional.from(node.className).map(function (currentClasses) {
  24540.         return filter$4(currentClasses.split(/\s+/), function (clazz) {
  24541.           return clazz !== '';
  24542.         });
  24543.       });
  24544.       lift2(attrClassesOpt, currentClassesOpt, function (attrClasses, currentClasses) {
  24545.         var filteredClasses = filter$4(currentClasses, function (clazz) {
  24546.           return !contains$3(attrClasses, clazz);
  24547.         });
  24548.         var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
  24549.         dom.setAttrib(node, 'class', newClasses.join(' '));
  24550.       });
  24551.       var appliedAttrs = [
  24552.         'style',
  24553.         'class'
  24554.       ];
  24555.       var remainingAttrs = filter$3(forcedRootBlockAttrs, function (_, attrs) {
  24556.         return !contains$3(appliedAttrs, attrs);
  24557.       });
  24558.       dom.setAttribs(node, remainingAttrs);
  24559.     };
  24560.     var setForcedBlockAttrs = function (editor, node) {
  24561.       var forcedRootBlockName = getForcedRootBlock(editor);
  24562.       if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  24563.         var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
  24564.         applyAttributes(editor, node, forcedRootBlockAttrs);
  24565.       }
  24566.     };
  24567.     var wrapSelfAndSiblingsInDefaultBlock = function (editor, newBlockName, rng, container, offset) {
  24568.       var newBlock, parentBlock, startNode, node, next, rootBlockName;
  24569.       var blockName = newBlockName || 'P';
  24570.       var dom = editor.dom, editableRoot = getEditableRoot(dom, container);
  24571.       parentBlock = dom.getParent(container, dom.isBlock);
  24572.       if (!parentBlock || !canSplitBlock(dom, parentBlock)) {
  24573.         parentBlock = parentBlock || editableRoot;
  24574.         if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
  24575.           rootBlockName = parentBlock.nodeName.toLowerCase();
  24576.         } else {
  24577.           rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
  24578.         }
  24579.         if (!parentBlock.hasChildNodes()) {
  24580.           newBlock = dom.create(blockName);
  24581.           setForcedBlockAttrs(editor, newBlock);
  24582.           parentBlock.appendChild(newBlock);
  24583.           rng.setStart(newBlock, 0);
  24584.           rng.setEnd(newBlock, 0);
  24585.           return newBlock;
  24586.         }
  24587.         node = container;
  24588.         while (node.parentNode !== parentBlock) {
  24589.           node = node.parentNode;
  24590.         }
  24591.         while (node && !dom.isBlock(node)) {
  24592.           startNode = node;
  24593.           node = node.previousSibling;
  24594.         }
  24595.         if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  24596.           newBlock = dom.create(blockName);
  24597.           setForcedBlockAttrs(editor, newBlock);
  24598.           startNode.parentNode.insertBefore(newBlock, startNode);
  24599.           node = startNode;
  24600.           while (node && !dom.isBlock(node)) {
  24601.             next = node.nextSibling;
  24602.             newBlock.appendChild(node);
  24603.             node = next;
  24604.           }
  24605.           rng.setStart(container, offset);
  24606.           rng.setEnd(container, offset);
  24607.         }
  24608.       }
  24609.       return container;
  24610.     };
  24611.     var addBrToBlockIfNeeded = function (dom, block) {
  24612.       block.normalize();
  24613.       var lastChild = block.lastChild;
  24614.       if (!lastChild || /^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true))) {
  24615.         dom.add(block, 'br');
  24616.       }
  24617.     };
  24618.     var insert$2 = function (editor, evt) {
  24619.       var tmpRng, container, offset, parentBlock;
  24620.       var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
  24621.       var dom = editor.dom;
  24622.       var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  24623.       var rng = editor.selection.getRng();
  24624.       var createNewBlock = function (name) {
  24625.         var node = container, block, clonedNode, caretNode;
  24626.         var textInlineElements = schema.getTextInlineElements();
  24627.         if (name || parentBlockName === 'TABLE' || parentBlockName === 'HR') {
  24628.           block = dom.create(name || newBlockName);
  24629.         } else {
  24630.           block = parentBlock.cloneNode(false);
  24631.         }
  24632.         caretNode = block;
  24633.         if (shouldKeepStyles(editor) === false) {
  24634.           dom.setAttrib(block, 'style', null);
  24635.           dom.setAttrib(block, 'class', null);
  24636.         } else {
  24637.           do {
  24638.             if (textInlineElements[node.nodeName]) {
  24639.               if (isCaretNode(node) || isBookmarkNode$1(node)) {
  24640.                 continue;
  24641.               }
  24642.               clonedNode = node.cloneNode(false);
  24643.               dom.setAttrib(clonedNode, 'id', '');
  24644.               if (block.hasChildNodes()) {
  24645.                 clonedNode.appendChild(block.firstChild);
  24646.                 block.appendChild(clonedNode);
  24647.               } else {
  24648.                 caretNode = clonedNode;
  24649.                 block.appendChild(clonedNode);
  24650.               }
  24651.             }
  24652.           } while ((node = node.parentNode) && node !== editableRoot);
  24653.         }
  24654.         setForcedBlockAttrs(editor, block);
  24655.         emptyBlock(caretNode);
  24656.         return block;
  24657.       };
  24658.       var isCaretAtStartOrEndOfBlock = function (start) {
  24659.         var node, name;
  24660.         var normalizedOffset = normalizeZwspOffset(start, container, offset);
  24661.         if (isText$7(container) && (start ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
  24662.           return false;
  24663.         }
  24664.         if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start) {
  24665.           return true;
  24666.         }
  24667.         if (start && isElement$5(container) && container === parentBlock.firstChild) {
  24668.           return true;
  24669.         }
  24670.         if (containerAndSiblingName(container, 'TABLE') || containerAndSiblingName(container, 'HR')) {
  24671.           return isAfterLastNodeInContainer && !start || !isAfterLastNodeInContainer && start;
  24672.         }
  24673.         var walker = new DomTreeWalker(container, parentBlock);
  24674.         if (isText$7(container)) {
  24675.           if (start && normalizedOffset === 0) {
  24676.             walker.prev();
  24677.           } else if (!start && normalizedOffset === container.nodeValue.length) {
  24678.             walker.next();
  24679.           }
  24680.         }
  24681.         while (node = walker.current()) {
  24682.           if (isElement$5(node)) {
  24683.             if (!node.getAttribute('data-mce-bogus')) {
  24684.               name = node.nodeName.toLowerCase();
  24685.               if (nonEmptyElementsMap[name] && name !== 'br') {
  24686.                 return false;
  24687.               }
  24688.             }
  24689.           } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
  24690.             return false;
  24691.           }
  24692.           if (start) {
  24693.             walker.prev();
  24694.           } else {
  24695.             walker.next();
  24696.           }
  24697.         }
  24698.         return true;
  24699.       };
  24700.       var insertNewBlockAfter = function () {
  24701.         if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== 'HGROUP') {
  24702.           newBlock = createNewBlock(newBlockName);
  24703.         } else {
  24704.           newBlock = createNewBlock();
  24705.         }
  24706.         if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom, containerBlock) && dom.isEmpty(parentBlock)) {
  24707.           newBlock = dom.split(containerBlock, parentBlock);
  24708.         } else {
  24709.           dom.insertAfter(newBlock, parentBlock);
  24710.         }
  24711.         moveToCaretPosition(editor, newBlock);
  24712.       };
  24713.       normalize$2(dom, rng).each(function (normRng) {
  24714.         rng.setStart(normRng.startContainer, normRng.startOffset);
  24715.         rng.setEnd(normRng.endContainer, normRng.endOffset);
  24716.       });
  24717.       container = rng.startContainer;
  24718.       offset = rng.startOffset;
  24719.       newBlockName = getForcedRootBlock(editor);
  24720.       var shiftKey = !!(evt && evt.shiftKey);
  24721.       var ctrlKey = !!(evt && evt.ctrlKey);
  24722.       if (isElement$5(container) && container.hasChildNodes()) {
  24723.         isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24724.         container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24725.         if (isAfterLastNodeInContainer && isText$7(container)) {
  24726.           offset = container.nodeValue.length;
  24727.         } else {
  24728.           offset = 0;
  24729.         }
  24730.       }
  24731.       var editableRoot = getEditableRoot(dom, container);
  24732.       if (!editableRoot) {
  24733.         return;
  24734.       }
  24735.       if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
  24736.         container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
  24737.       }
  24738.       parentBlock = dom.getParent(container, dom.isBlock);
  24739.       containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24740.       parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : '';
  24741.       var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24742.       if (containerBlockName === 'LI' && !ctrlKey) {
  24743.         parentBlock = containerBlock;
  24744.         containerBlock = containerBlock.parentNode;
  24745.         parentBlockName = containerBlockName;
  24746.       }
  24747.       if (/^(LI|DT|DD)$/.test(parentBlockName)) {
  24748.         if (dom.isEmpty(parentBlock)) {
  24749.           insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
  24750.           return;
  24751.         }
  24752.       }
  24753.       if (newBlockName && parentBlock === editor.getBody()) {
  24754.         return;
  24755.       }
  24756.       newBlockName = newBlockName || 'P';
  24757.       if (isCaretContainerBlock$1(parentBlock)) {
  24758.         newBlock = showCaretContainerBlock(parentBlock);
  24759.         if (dom.isEmpty(parentBlock)) {
  24760.           emptyBlock(parentBlock);
  24761.         }
  24762.         setForcedBlockAttrs(editor, newBlock);
  24763.         moveToCaretPosition(editor, newBlock);
  24764.       } else if (isCaretAtStartOrEndOfBlock()) {
  24765.         insertNewBlockAfter();
  24766.       } else if (isCaretAtStartOrEndOfBlock(true)) {
  24767.         newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  24768.         moveToCaretPosition(editor, containerAndSiblingName(parentBlock, 'HR') ? newBlock : parentBlock);
  24769.       } else {
  24770.         tmpRng = includeZwspInRange(rng).cloneRange();
  24771.         tmpRng.setEndAfter(parentBlock);
  24772.         fragment = tmpRng.extractContents();
  24773.         trimZwsp(fragment);
  24774.         trimLeadingLineBreaks(fragment);
  24775.         newBlock = fragment.firstChild;
  24776.         dom.insertAfter(fragment, parentBlock);
  24777.         trimInlineElementsOnLeftSideOfBlock(dom, nonEmptyElementsMap, newBlock);
  24778.         addBrToBlockIfNeeded(dom, parentBlock);
  24779.         if (dom.isEmpty(parentBlock)) {
  24780.           emptyBlock(parentBlock);
  24781.         }
  24782.         newBlock.normalize();
  24783.         if (dom.isEmpty(newBlock)) {
  24784.           dom.remove(newBlock);
  24785.           insertNewBlockAfter();
  24786.         } else {
  24787.           setForcedBlockAttrs(editor, newBlock);
  24788.           moveToCaretPosition(editor, newBlock);
  24789.         }
  24790.       }
  24791.       dom.setAttrib(newBlock, 'id', '');
  24792.       editor.fire('NewBlock', { newBlock: newBlock });
  24793.     };
  24794.  
  24795.     var hasRightSideContent = function (schema, container, parentBlock) {
  24796.       var walker = new DomTreeWalker(container, parentBlock);
  24797.       var node;
  24798.       var nonEmptyElementsMap = schema.getNonEmptyElements();
  24799.       while (node = walker.next()) {
  24800.         if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  24801.           return true;
  24802.         }
  24803.       }
  24804.     };
  24805.     var moveSelectionToBr = function (editor, brElm, extraBr) {
  24806.       var rng = editor.dom.createRng();
  24807.       if (!extraBr) {
  24808.         rng.setStartAfter(brElm);
  24809.         rng.setEndAfter(brElm);
  24810.       } else {
  24811.         rng.setStartBefore(brElm);
  24812.         rng.setEndBefore(brElm);
  24813.       }
  24814.       editor.selection.setRng(rng);
  24815.       scrollRangeIntoView(editor, rng);
  24816.     };
  24817.     var insertBrAtCaret = function (editor, evt) {
  24818.       var selection = editor.selection;
  24819.       var dom = editor.dom;
  24820.       var rng = selection.getRng();
  24821.       var brElm;
  24822.       var extraBr;
  24823.       normalize$2(dom, rng).each(function (normRng) {
  24824.         rng.setStart(normRng.startContainer, normRng.startOffset);
  24825.         rng.setEnd(normRng.endContainer, normRng.endOffset);
  24826.       });
  24827.       var offset = rng.startOffset;
  24828.       var container = rng.startContainer;
  24829.       if (container.nodeType === 1 && container.hasChildNodes()) {
  24830.         var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  24831.         container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  24832.         if (isAfterLastNodeInContainer && container.nodeType === 3) {
  24833.           offset = container.nodeValue.length;
  24834.         } else {
  24835.           offset = 0;
  24836.         }
  24837.       }
  24838.       var parentBlock = dom.getParent(container, dom.isBlock);
  24839.       var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  24840.       var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : '';
  24841.       var isControlKey = !!(evt && evt.ctrlKey);
  24842.       if (containerBlockName === 'LI' && !isControlKey) {
  24843.         parentBlock = containerBlock;
  24844.       }
  24845.       if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
  24846.         if (!hasRightSideContent(editor.schema, container, parentBlock)) {
  24847.           brElm = dom.create('br');
  24848.           rng.insertNode(brElm);
  24849.           rng.setStartAfter(brElm);
  24850.           rng.setEndAfter(brElm);
  24851.           extraBr = true;
  24852.         }
  24853.       }
  24854.       brElm = dom.create('br');
  24855.       rangeInsertNode(dom, rng, brElm);
  24856.       moveSelectionToBr(editor, brElm, extraBr);
  24857.       editor.undoManager.add();
  24858.     };
  24859.     var insertBrBefore = function (editor, inline) {
  24860.       var br = SugarElement.fromTag('br');
  24861.       before$4(SugarElement.fromDom(inline), br);
  24862.       editor.undoManager.add();
  24863.     };
  24864.     var insertBrAfter = function (editor, inline) {
  24865.       if (!hasBrAfter(editor.getBody(), inline)) {
  24866.         after$3(SugarElement.fromDom(inline), SugarElement.fromTag('br'));
  24867.       }
  24868.       var br = SugarElement.fromTag('br');
  24869.       after$3(SugarElement.fromDom(inline), br);
  24870.       moveSelectionToBr(editor, br.dom, false);
  24871.       editor.undoManager.add();
  24872.     };
  24873.     var isBeforeBr = function (pos) {
  24874.       return isBr$5(pos.getNode());
  24875.     };
  24876.     var hasBrAfter = function (rootNode, startNode) {
  24877.       if (isBeforeBr(CaretPosition.after(startNode))) {
  24878.         return true;
  24879.       } else {
  24880.         return nextPosition(rootNode, CaretPosition.after(startNode)).map(function (pos) {
  24881.           return isBr$5(pos.getNode());
  24882.         }).getOr(false);
  24883.       }
  24884.     };
  24885.     var isAnchorLink = function (elm) {
  24886.       return elm && elm.nodeName === 'A' && 'href' in elm;
  24887.     };
  24888.     var isInsideAnchor = function (location) {
  24889.       return location.fold(never, isAnchorLink, isAnchorLink, never);
  24890.     };
  24891.     var readInlineAnchorLocation = function (editor) {
  24892.       var isInlineTarget$1 = curry(isInlineTarget, editor);
  24893.       var position = CaretPosition.fromRangeStart(editor.selection.getRng());
  24894.       return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
  24895.     };
  24896.     var insertBrOutsideAnchor = function (editor, location) {
  24897.       location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
  24898.     };
  24899.     var insert$1 = function (editor, evt) {
  24900.       var anchorLocation = readInlineAnchorLocation(editor);
  24901.       if (anchorLocation.isSome()) {
  24902.         anchorLocation.each(curry(insertBrOutsideAnchor, editor));
  24903.       } else {
  24904.         insertBrAtCaret(editor, evt);
  24905.       }
  24906.     };
  24907.  
  24908.     var matchesSelector = function (editor, selector) {
  24909.       return getParentBlock(editor).filter(function (parentBlock) {
  24910.         return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
  24911.       }).isSome();
  24912.     };
  24913.     var shouldInsertBr = function (editor) {
  24914.       return matchesSelector(editor, getBrNewLineSelector(editor));
  24915.     };
  24916.     var shouldBlockNewLine$1 = function (editor) {
  24917.       return matchesSelector(editor, getNoNewLineSelector(editor));
  24918.     };
  24919.  
  24920.     var newLineAction = Adt.generate([
  24921.       { br: [] },
  24922.       { block: [] },
  24923.       { none: [] }
  24924.     ]);
  24925.     var shouldBlockNewLine = function (editor, _shiftKey) {
  24926.       return shouldBlockNewLine$1(editor);
  24927.     };
  24928.     var isBrMode = function (requiredState) {
  24929.       return function (editor, _shiftKey) {
  24930.         var brMode = getForcedRootBlock(editor) === '';
  24931.         return brMode === requiredState;
  24932.       };
  24933.     };
  24934.     var inListBlock = function (requiredState) {
  24935.       return function (editor, _shiftKey) {
  24936.         return isListItemParentBlock(editor) === requiredState;
  24937.       };
  24938.     };
  24939.     var inBlock = function (blockName, requiredState) {
  24940.       return function (editor, _shiftKey) {
  24941.         var state = getParentBlockName(editor) === blockName.toUpperCase();
  24942.         return state === requiredState;
  24943.       };
  24944.     };
  24945.     var inPreBlock = function (requiredState) {
  24946.       return inBlock('pre', requiredState);
  24947.     };
  24948.     var inSummaryBlock = function () {
  24949.       return inBlock('summary', true);
  24950.     };
  24951.     var shouldPutBrInPre = function (requiredState) {
  24952.       return function (editor, _shiftKey) {
  24953.         return shouldPutBrInPre$1(editor) === requiredState;
  24954.       };
  24955.     };
  24956.     var inBrContext = function (editor, _shiftKey) {
  24957.       return shouldInsertBr(editor);
  24958.     };
  24959.     var hasShiftKey = function (_editor, shiftKey) {
  24960.       return shiftKey;
  24961.     };
  24962.     var canInsertIntoEditableRoot = function (editor) {
  24963.       var forcedRootBlock = getForcedRootBlock(editor);
  24964.       var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
  24965.       return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : 'P');
  24966.     };
  24967.     var match = function (predicates, action) {
  24968.       return function (editor, shiftKey) {
  24969.         var isMatch = foldl(predicates, function (res, p) {
  24970.           return res && p(editor, shiftKey);
  24971.         }, true);
  24972.         return isMatch ? Optional.some(action) : Optional.none();
  24973.       };
  24974.     };
  24975.     var getAction = function (editor, evt) {
  24976.       return evaluateUntil([
  24977.         match([shouldBlockNewLine], newLineAction.none()),
  24978.         match([inSummaryBlock()], newLineAction.br()),
  24979.         match([
  24980.           inPreBlock(true),
  24981.           shouldPutBrInPre(false),
  24982.           hasShiftKey
  24983.         ], newLineAction.br()),
  24984.         match([
  24985.           inPreBlock(true),
  24986.           shouldPutBrInPre(false)
  24987.         ], newLineAction.block()),
  24988.         match([
  24989.           inPreBlock(true),
  24990.           shouldPutBrInPre(true),
  24991.           hasShiftKey
  24992.         ], newLineAction.block()),
  24993.         match([
  24994.           inPreBlock(true),
  24995.           shouldPutBrInPre(true)
  24996.         ], newLineAction.br()),
  24997.         match([
  24998.           inListBlock(true),
  24999.           hasShiftKey
  25000.         ], newLineAction.br()),
  25001.         match([inListBlock(true)], newLineAction.block()),
  25002.         match([
  25003.           isBrMode(true),
  25004.           hasShiftKey,
  25005.           canInsertIntoEditableRoot
  25006.         ], newLineAction.block()),
  25007.         match([isBrMode(true)], newLineAction.br()),
  25008.         match([inBrContext], newLineAction.br()),
  25009.         match([
  25010.           isBrMode(false),
  25011.           hasShiftKey
  25012.         ], newLineAction.br()),
  25013.         match([canInsertIntoEditableRoot], newLineAction.block())
  25014.       ], [
  25015.         editor,
  25016.         !!(evt && evt.shiftKey)
  25017.       ]).getOr(newLineAction.none());
  25018.     };
  25019.  
  25020.     var insert = function (editor, evt) {
  25021.       getAction(editor, evt).fold(function () {
  25022.         insert$1(editor, evt);
  25023.       }, function () {
  25024.         insert$2(editor, evt);
  25025.       }, noop);
  25026.     };
  25027.  
  25028.     var handleEnterKeyEvent = function (editor, event) {
  25029.       if (event.isDefaultPrevented()) {
  25030.         return;
  25031.       }
  25032.       event.preventDefault();
  25033.       endTypingLevelIgnoreLocks(editor.undoManager);
  25034.       editor.undoManager.transact(function () {
  25035.         if (editor.selection.isCollapsed() === false) {
  25036.           editor.execCommand('Delete');
  25037.         }
  25038.         insert(editor, event);
  25039.       });
  25040.     };
  25041.     var setup$9 = function (editor) {
  25042.       editor.on('keydown', function (event) {
  25043.         if (event.keyCode === VK.ENTER) {
  25044.           handleEnterKeyEvent(editor, event);
  25045.         }
  25046.       });
  25047.     };
  25048.  
  25049.     var executeKeydownOverride$1 = function (editor, caret, evt) {
  25050.       execute([
  25051.         {
  25052.           keyCode: VK.END,
  25053.           action: action(moveToLineEndPoint$1, editor, true)
  25054.         },
  25055.         {
  25056.           keyCode: VK.HOME,
  25057.           action: action(moveToLineEndPoint$1, editor, false)
  25058.         },
  25059.         {
  25060.           keyCode: VK.END,
  25061.           action: action(moveToLineEndPoint, editor, true)
  25062.         },
  25063.         {
  25064.           keyCode: VK.HOME,
  25065.           action: action(moveToLineEndPoint, editor, false)
  25066.         },
  25067.         {
  25068.           keyCode: VK.END,
  25069.           action: action(moveToLineEndPoint$2, editor, true, caret)
  25070.         },
  25071.         {
  25072.           keyCode: VK.HOME,
  25073.           action: action(moveToLineEndPoint$2, editor, false, caret)
  25074.         }
  25075.       ], evt).each(function (_) {
  25076.         evt.preventDefault();
  25077.       });
  25078.     };
  25079.     var setup$8 = function (editor, caret) {
  25080.       editor.on('keydown', function (evt) {
  25081.         if (evt.isDefaultPrevented() === false) {
  25082.           executeKeydownOverride$1(editor, caret, evt);
  25083.         }
  25084.       });
  25085.     };
  25086.  
  25087.     var browser = detect().browser;
  25088.     var setupIeInput = function (editor) {
  25089.       var keypressThrotter = first(function () {
  25090.         if (!editor.composing) {
  25091.           normalizeNbspsInEditor(editor);
  25092.         }
  25093.       }, 0);
  25094.       if (browser.isIE()) {
  25095.         editor.on('keypress', function (_e) {
  25096.           keypressThrotter.throttle();
  25097.         });
  25098.         editor.on('remove', function (_e) {
  25099.           keypressThrotter.cancel();
  25100.         });
  25101.       }
  25102.     };
  25103.     var setup$7 = function (editor) {
  25104.       setupIeInput(editor);
  25105.       editor.on('input', function (e) {
  25106.         if (e.isComposing === false) {
  25107.           normalizeNbspsInEditor(editor);
  25108.         }
  25109.       });
  25110.     };
  25111.  
  25112.     var platform = detect();
  25113.     var executeKeyupAction = function (editor, caret, evt) {
  25114.       execute([
  25115.         {
  25116.           keyCode: VK.PAGE_UP,
  25117.           action: action(moveToLineEndPoint$2, editor, false, caret)
  25118.         },
  25119.         {
  25120.           keyCode: VK.PAGE_DOWN,
  25121.           action: action(moveToLineEndPoint$2, editor, true, caret)
  25122.         }
  25123.       ], evt);
  25124.     };
  25125.     var stopImmediatePropagation = function (e) {
  25126.       return e.stopImmediatePropagation();
  25127.     };
  25128.     var isPageUpDown = function (evt) {
  25129.       return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
  25130.     };
  25131.     var setNodeChangeBlocker = function (blocked, editor, block) {
  25132.       if (block && !blocked.get()) {
  25133.         editor.on('NodeChange', stopImmediatePropagation, true);
  25134.       } else if (!block && blocked.get()) {
  25135.         editor.off('NodeChange', stopImmediatePropagation);
  25136.       }
  25137.       blocked.set(block);
  25138.     };
  25139.     var setup$6 = function (editor, caret) {
  25140.       if (platform.os.isOSX()) {
  25141.         return;
  25142.       }
  25143.       var blocked = Cell(false);
  25144.       editor.on('keydown', function (evt) {
  25145.         if (isPageUpDown(evt)) {
  25146.           setNodeChangeBlocker(blocked, editor, true);
  25147.         }
  25148.       });
  25149.       editor.on('keyup', function (evt) {
  25150.         if (evt.isDefaultPrevented() === false) {
  25151.           executeKeyupAction(editor, caret, evt);
  25152.         }
  25153.         if (isPageUpDown(evt) && blocked.get()) {
  25154.           setNodeChangeBlocker(blocked, editor, false);
  25155.           editor.nodeChanged();
  25156.         }
  25157.       });
  25158.     };
  25159.  
  25160.     var insertTextAtPosition = function (text, pos) {
  25161.       var container = pos.container();
  25162.       var offset = pos.offset();
  25163.       if (isText$7(container)) {
  25164.         container.insertData(offset, text);
  25165.         return Optional.some(CaretPosition(container, offset + text.length));
  25166.       } else {
  25167.         return getElementFromPosition(pos).map(function (elm) {
  25168.           var textNode = SugarElement.fromText(text);
  25169.           if (pos.isAtEnd()) {
  25170.             after$3(elm, textNode);
  25171.           } else {
  25172.             before$4(elm, textNode);
  25173.           }
  25174.           return CaretPosition(textNode.dom, text.length);
  25175.         });
  25176.       }
  25177.     };
  25178.     var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
  25179.     var insertSpaceAtPosition = curry(insertTextAtPosition, ' ');
  25180.  
  25181.     var locationToCaretPosition = function (root) {
  25182.       return function (location) {
  25183.         return location.fold(function (element) {
  25184.           return prevPosition(root.dom, CaretPosition.before(element));
  25185.         }, function (element) {
  25186.           return firstPositionIn(element);
  25187.         }, function (element) {
  25188.           return lastPositionIn(element);
  25189.         }, function (element) {
  25190.           return nextPosition(root.dom, CaretPosition.after(element));
  25191.         });
  25192.       };
  25193.     };
  25194.     var insertInlineBoundarySpaceOrNbsp = function (root, pos) {
  25195.       return function (checkPos) {
  25196.         return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
  25197.       };
  25198.     };
  25199.     var setSelection = function (editor) {
  25200.       return function (pos) {
  25201.         editor.selection.setRng(pos.toRange());
  25202.         editor.nodeChanged();
  25203.         return true;
  25204.       };
  25205.     };
  25206.     var insertSpaceOrNbspAtSelection = function (editor) {
  25207.       var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
  25208.       var root = SugarElement.fromDom(editor.getBody());
  25209.       if (editor.selection.isCollapsed()) {
  25210.         var isInlineTarget$1 = curry(isInlineTarget, editor);
  25211.         var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
  25212.         return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
  25213.       } else {
  25214.         return false;
  25215.       }
  25216.     };
  25217.  
  25218.     var executeKeydownOverride = function (editor, evt) {
  25219.       execute([{
  25220.           keyCode: VK.SPACEBAR,
  25221.           action: action(insertSpaceOrNbspAtSelection, editor)
  25222.         }], evt).each(function (_) {
  25223.         evt.preventDefault();
  25224.       });
  25225.     };
  25226.     var setup$5 = function (editor) {
  25227.       editor.on('keydown', function (evt) {
  25228.         if (evt.isDefaultPrevented() === false) {
  25229.           executeKeydownOverride(editor, evt);
  25230.         }
  25231.       });
  25232.     };
  25233.  
  25234.     var registerKeyboardOverrides = function (editor) {
  25235.       var caret = setupSelectedState(editor);
  25236.       setup$c(editor);
  25237.       setup$b(editor, caret);
  25238.       setup$a(editor, caret);
  25239.       setup$9(editor);
  25240.       setup$5(editor);
  25241.       setup$7(editor);
  25242.       setup$8(editor, caret);
  25243.       setup$6(editor, caret);
  25244.       return caret;
  25245.     };
  25246.     var setup$4 = function (editor) {
  25247.       if (!isRtc(editor)) {
  25248.         return registerKeyboardOverrides(editor);
  25249.       } else {
  25250.         return Cell(null);
  25251.       }
  25252.     };
  25253.  
  25254.     var NodeChange = function () {
  25255.       function NodeChange(editor) {
  25256.         this.lastPath = [];
  25257.         this.editor = editor;
  25258.         var lastRng;
  25259.         var self = this;
  25260.         if (!('onselectionchange' in editor.getDoc())) {
  25261.           editor.on('NodeChange click mouseup keyup focus', function (e) {
  25262.             var nativeRng = editor.selection.getRng();
  25263.             var fakeRng = {
  25264.               startContainer: nativeRng.startContainer,
  25265.               startOffset: nativeRng.startOffset,
  25266.               endContainer: nativeRng.endContainer,
  25267.               endOffset: nativeRng.endOffset
  25268.             };
  25269.             if (e.type === 'nodechange' || !isEq$4(fakeRng, lastRng)) {
  25270.               editor.fire('SelectionChange');
  25271.             }
  25272.             lastRng = fakeRng;
  25273.           });
  25274.         }
  25275.         editor.on('contextmenu', function () {
  25276.           editor.fire('SelectionChange');
  25277.         });
  25278.         editor.on('SelectionChange', function () {
  25279.           var startElm = editor.selection.getStart(true);
  25280.           if (!startElm || !Env.range && editor.selection.isCollapsed()) {
  25281.             return;
  25282.           }
  25283.           if (hasAnyRanges(editor) && !self.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
  25284.             editor.nodeChanged({ selectionChange: true });
  25285.           }
  25286.         });
  25287.         editor.on('mouseup', function (e) {
  25288.           if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
  25289.             if (editor.selection.getNode().nodeName === 'IMG') {
  25290.               Delay.setEditorTimeout(editor, function () {
  25291.                 editor.nodeChanged();
  25292.               });
  25293.             } else {
  25294.               editor.nodeChanged();
  25295.             }
  25296.           }
  25297.         });
  25298.       }
  25299.       NodeChange.prototype.nodeChanged = function (args) {
  25300.         var selection = this.editor.selection;
  25301.         var node, parents, root;
  25302.         if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
  25303.           root = this.editor.getBody();
  25304.           node = selection.getStart(true) || root;
  25305.           if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
  25306.             node = root;
  25307.           }
  25308.           parents = [];
  25309.           this.editor.dom.getParent(node, function (node) {
  25310.             if (node === root) {
  25311.               return true;
  25312.             }
  25313.             parents.push(node);
  25314.           });
  25315.           args = args || {};
  25316.           args.element = node;
  25317.           args.parents = parents;
  25318.           this.editor.fire('NodeChange', args);
  25319.         }
  25320.       };
  25321.       NodeChange.prototype.isSameElementPath = function (startElm) {
  25322.         var i;
  25323.         var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
  25324.         if (currentPath.length === this.lastPath.length) {
  25325.           for (i = currentPath.length; i >= 0; i--) {
  25326.             if (currentPath[i] !== this.lastPath[i]) {
  25327.               break;
  25328.             }
  25329.           }
  25330.           if (i === -1) {
  25331.             this.lastPath = currentPath;
  25332.             return true;
  25333.           }
  25334.         }
  25335.         this.lastPath = currentPath;
  25336.         return false;
  25337.       };
  25338.       return NodeChange;
  25339.     }();
  25340.  
  25341.     var preventSummaryToggle = function (editor) {
  25342.       editor.on('click', function (e) {
  25343.         if (editor.dom.getParent(e.target, 'details')) {
  25344.           e.preventDefault();
  25345.         }
  25346.       });
  25347.     };
  25348.     var filterDetails = function (editor) {
  25349.       editor.parser.addNodeFilter('details', function (elms) {
  25350.         each$k(elms, function (details) {
  25351.           details.attr('data-mce-open', details.attr('open'));
  25352.           details.attr('open', 'open');
  25353.         });
  25354.       });
  25355.       editor.serializer.addNodeFilter('details', function (elms) {
  25356.         each$k(elms, function (details) {
  25357.           var open = details.attr('data-mce-open');
  25358.           details.attr('open', isString$1(open) ? open : null);
  25359.           details.attr('data-mce-open', null);
  25360.         });
  25361.       });
  25362.     };
  25363.     var setup$3 = function (editor) {
  25364.       preventSummaryToggle(editor);
  25365.       filterDetails(editor);
  25366.     };
  25367.  
  25368.     var isTextBlockNode = function (node) {
  25369.       return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
  25370.     };
  25371.     var normalizeSelection = function (editor) {
  25372.       var rng = editor.selection.getRng();
  25373.       var startPos = CaretPosition.fromRangeStart(rng);
  25374.       var endPos = CaretPosition.fromRangeEnd(rng);
  25375.       if (CaretPosition.isElementPosition(startPos)) {
  25376.         var container = startPos.container();
  25377.         if (isTextBlockNode(container)) {
  25378.           firstPositionIn(container).each(function (pos) {
  25379.             return rng.setStart(pos.container(), pos.offset());
  25380.           });
  25381.         }
  25382.       }
  25383.       if (CaretPosition.isElementPosition(endPos)) {
  25384.         var container = startPos.container();
  25385.         if (isTextBlockNode(container)) {
  25386.           lastPositionIn(container).each(function (pos) {
  25387.             return rng.setEnd(pos.container(), pos.offset());
  25388.           });
  25389.         }
  25390.       }
  25391.       editor.selection.setRng(normalize(rng));
  25392.     };
  25393.     var setup$2 = function (editor) {
  25394.       editor.on('click', function (e) {
  25395.         if (e.detail >= 3) {
  25396.           normalizeSelection(editor);
  25397.         }
  25398.       });
  25399.     };
  25400.  
  25401.     var getAbsolutePosition = function (elm) {
  25402.       var clientRect = elm.getBoundingClientRect();
  25403.       var doc = elm.ownerDocument;
  25404.       var docElem = doc.documentElement;
  25405.       var win = doc.defaultView;
  25406.       return {
  25407.         top: clientRect.top + win.pageYOffset - docElem.clientTop,
  25408.         left: clientRect.left + win.pageXOffset - docElem.clientLeft
  25409.       };
  25410.     };
  25411.     var getBodyPosition = function (editor) {
  25412.       return editor.inline ? getAbsolutePosition(editor.getBody()) : {
  25413.         left: 0,
  25414.         top: 0
  25415.       };
  25416.     };
  25417.     var getScrollPosition = function (editor) {
  25418.       var body = editor.getBody();
  25419.       return editor.inline ? {
  25420.         left: body.scrollLeft,
  25421.         top: body.scrollTop
  25422.       } : {
  25423.         left: 0,
  25424.         top: 0
  25425.       };
  25426.     };
  25427.     var getBodyScroll = function (editor) {
  25428.       var body = editor.getBody(), docElm = editor.getDoc().documentElement;
  25429.       var inlineScroll = {
  25430.         left: body.scrollLeft,
  25431.         top: body.scrollTop
  25432.       };
  25433.       var iframeScroll = {
  25434.         left: body.scrollLeft || docElm.scrollLeft,
  25435.         top: body.scrollTop || docElm.scrollTop
  25436.       };
  25437.       return editor.inline ? inlineScroll : iframeScroll;
  25438.     };
  25439.     var getMousePosition = function (editor, event) {
  25440.       if (event.target.ownerDocument !== editor.getDoc()) {
  25441.         var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
  25442.         var scrollPosition = getBodyScroll(editor);
  25443.         return {
  25444.           left: event.pageX - iframePosition.left + scrollPosition.left,
  25445.           top: event.pageY - iframePosition.top + scrollPosition.top
  25446.         };
  25447.       }
  25448.       return {
  25449.         left: event.pageX,
  25450.         top: event.pageY
  25451.       };
  25452.     };
  25453.     var calculatePosition = function (bodyPosition, scrollPosition, mousePosition) {
  25454.       return {
  25455.         pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
  25456.         pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
  25457.       };
  25458.     };
  25459.     var calc = function (editor, event) {
  25460.       return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
  25461.     };
  25462.  
  25463.     var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
  25464.     var isDraggable = function (rootElm, elm) {
  25465.       return isContentEditableFalse$1(elm) && elm !== rootElm;
  25466.     };
  25467.     var isValidDropTarget = function (editor, targetElement, dragElement) {
  25468.       if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
  25469.         return false;
  25470.       }
  25471.       return !isContentEditableFalse$1(targetElement);
  25472.     };
  25473.     var cloneElement = function (elm) {
  25474.       var cloneElm = elm.cloneNode(true);
  25475.       cloneElm.removeAttribute('data-mce-selected');
  25476.       return cloneElm;
  25477.     };
  25478.     var createGhost = function (editor, elm, width, height) {
  25479.       var dom = editor.dom;
  25480.       var clonedElm = elm.cloneNode(true);
  25481.       dom.setStyles(clonedElm, {
  25482.         width: width,
  25483.         height: height
  25484.       });
  25485.       dom.setAttrib(clonedElm, 'data-mce-selected', null);
  25486.       var ghostElm = dom.create('div', {
  25487.         'class': 'mce-drag-container',
  25488.         'data-mce-bogus': 'all',
  25489.         'unselectable': 'on',
  25490.         'contenteditable': 'false'
  25491.       });
  25492.       dom.setStyles(ghostElm, {
  25493.         position: 'absolute',
  25494.         opacity: 0.5,
  25495.         overflow: 'hidden',
  25496.         border: 0,
  25497.         padding: 0,
  25498.         margin: 0,
  25499.         width: width,
  25500.         height: height
  25501.       });
  25502.       dom.setStyles(clonedElm, {
  25503.         margin: 0,
  25504.         boxSizing: 'border-box'
  25505.       });
  25506.       ghostElm.appendChild(clonedElm);
  25507.       return ghostElm;
  25508.     };
  25509.     var appendGhostToBody = function (ghostElm, bodyElm) {
  25510.       if (ghostElm.parentNode !== bodyElm) {
  25511.         bodyElm.appendChild(ghostElm);
  25512.       }
  25513.     };
  25514.     var moveGhost = function (ghostElm, position, width, height, maxX, maxY) {
  25515.       var overflowX = 0, overflowY = 0;
  25516.       ghostElm.style.left = position.pageX + 'px';
  25517.       ghostElm.style.top = position.pageY + 'px';
  25518.       if (position.pageX + width > maxX) {
  25519.         overflowX = position.pageX + width - maxX;
  25520.       }
  25521.       if (position.pageY + height > maxY) {
  25522.         overflowY = position.pageY + height - maxY;
  25523.       }
  25524.       ghostElm.style.width = width - overflowX + 'px';
  25525.       ghostElm.style.height = height - overflowY + 'px';
  25526.     };
  25527.     var removeElement = function (elm) {
  25528.       if (elm && elm.parentNode) {
  25529.         elm.parentNode.removeChild(elm);
  25530.       }
  25531.     };
  25532.     var isLeftMouseButtonPressed = function (e) {
  25533.       return e.button === 0;
  25534.     };
  25535.     var applyRelPos = function (state, position) {
  25536.       return {
  25537.         pageX: position.pageX - state.relX,
  25538.         pageY: position.pageY + 5
  25539.       };
  25540.     };
  25541.     var start = function (state, editor) {
  25542.       return function (e) {
  25543.         if (isLeftMouseButtonPressed(e)) {
  25544.           var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
  25545.           if (isDraggable(editor.getBody(), ceElm)) {
  25546.             var elmPos = editor.dom.getPos(ceElm);
  25547.             var bodyElm = editor.getBody();
  25548.             var docElm = editor.getDoc().documentElement;
  25549.             state.set({
  25550.               element: ceElm,
  25551.               dragging: false,
  25552.               screenX: e.screenX,
  25553.               screenY: e.screenY,
  25554.               maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
  25555.               maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
  25556.               relX: e.pageX - elmPos.x,
  25557.               relY: e.pageY - elmPos.y,
  25558.               width: ceElm.offsetWidth,
  25559.               height: ceElm.offsetHeight,
  25560.               ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
  25561.             });
  25562.           }
  25563.         }
  25564.       };
  25565.     };
  25566.     var move = function (state, editor) {
  25567.       var throttledPlaceCaretAt = Delay.throttle(function (clientX, clientY) {
  25568.         editor._selectionOverrides.hideFakeCaret();
  25569.         editor.selection.placeCaretAt(clientX, clientY);
  25570.       }, 0);
  25571.       editor.on('remove', throttledPlaceCaretAt.stop);
  25572.       return function (e) {
  25573.         return state.on(function (state) {
  25574.           var movement = Math.max(Math.abs(e.screenX - state.screenX), Math.abs(e.screenY - state.screenY));
  25575.           if (!state.dragging && movement > 10) {
  25576.             var args = editor.fire('dragstart', { target: state.element });
  25577.             if (args.isDefaultPrevented()) {
  25578.               return;
  25579.             }
  25580.             state.dragging = true;
  25581.             editor.focus();
  25582.           }
  25583.           if (state.dragging) {
  25584.             var targetPos = applyRelPos(state, calc(editor, e));
  25585.             appendGhostToBody(state.ghost, editor.getBody());
  25586.             moveGhost(state.ghost, targetPos, state.width, state.height, state.maxX, state.maxY);
  25587.             throttledPlaceCaretAt(e.clientX, e.clientY);
  25588.           }
  25589.         });
  25590.       };
  25591.     };
  25592.     var getRawTarget = function (selection) {
  25593.       var rng = selection.getSel().getRangeAt(0);
  25594.       var startContainer = rng.startContainer;
  25595.       return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
  25596.     };
  25597.     var drop = function (state, editor) {
  25598.       return function (e) {
  25599.         state.on(function (state) {
  25600.           if (state.dragging) {
  25601.             if (isValidDropTarget(editor, getRawTarget(editor.selection), state.element)) {
  25602.               var targetClone_1 = cloneElement(state.element);
  25603.               var args = editor.fire('drop', {
  25604.                 clientX: e.clientX,
  25605.                 clientY: e.clientY
  25606.               });
  25607.               if (!args.isDefaultPrevented()) {
  25608.                 editor.undoManager.transact(function () {
  25609.                   removeElement(state.element);
  25610.                   editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
  25611.                   editor._selectionOverrides.hideFakeCaret();
  25612.                 });
  25613.               }
  25614.             }
  25615.             editor.fire('dragend');
  25616.           }
  25617.         });
  25618.         removeDragState(state);
  25619.       };
  25620.     };
  25621.     var stop = function (state, editor) {
  25622.       return function () {
  25623.         state.on(function (state) {
  25624.           if (state.dragging) {
  25625.             editor.fire('dragend');
  25626.           }
  25627.         });
  25628.         removeDragState(state);
  25629.       };
  25630.     };
  25631.     var removeDragState = function (state) {
  25632.       state.on(function (state) {
  25633.         removeElement(state.ghost);
  25634.       });
  25635.       state.clear();
  25636.     };
  25637.     var bindFakeDragEvents = function (editor) {
  25638.       var state = value();
  25639.       var pageDom = DOMUtils.DOM;
  25640.       var rootDocument = document;
  25641.       var dragStartHandler = start(state, editor);
  25642.       var dragHandler = move(state, editor);
  25643.       var dropHandler = drop(state, editor);
  25644.       var dragEndHandler = stop(state, editor);
  25645.       editor.on('mousedown', dragStartHandler);
  25646.       editor.on('mousemove', dragHandler);
  25647.       editor.on('mouseup', dropHandler);
  25648.       pageDom.bind(rootDocument, 'mousemove', dragHandler);
  25649.       pageDom.bind(rootDocument, 'mouseup', dragEndHandler);
  25650.       editor.on('remove', function () {
  25651.         pageDom.unbind(rootDocument, 'mousemove', dragHandler);
  25652.         pageDom.unbind(rootDocument, 'mouseup', dragEndHandler);
  25653.       });
  25654.       editor.on('keydown', function (e) {
  25655.         if (e.keyCode === VK.ESC) {
  25656.           dragEndHandler();
  25657.         }
  25658.       });
  25659.     };
  25660.     var blockIeDrop = function (editor) {
  25661.       editor.on('drop', function (e) {
  25662.         var realTarget = typeof e.clientX !== 'undefined' ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
  25663.         if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === 'false') {
  25664.           e.preventDefault();
  25665.         }
  25666.       });
  25667.     };
  25668.     var blockUnsupportedFileDrop = function (editor) {
  25669.       var preventFileDrop = function (e) {
  25670.         if (!e.isDefaultPrevented()) {
  25671.           var dataTransfer = e.dataTransfer;
  25672.           if (dataTransfer && (contains$3(dataTransfer.types, 'Files') || dataTransfer.files.length > 0)) {
  25673.             e.preventDefault();
  25674.             if (e.type === 'drop') {
  25675.               displayError(editor, 'Dropped file type is not supported');
  25676.             }
  25677.           }
  25678.         }
  25679.       };
  25680.       var preventFileDropIfUIElement = function (e) {
  25681.         if (isUIElement(editor, e.target)) {
  25682.           preventFileDrop(e);
  25683.         }
  25684.       };
  25685.       var setup = function () {
  25686.         var pageDom = DOMUtils.DOM;
  25687.         var dom = editor.dom;
  25688.         var doc = document;
  25689.         var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
  25690.         var eventNames = [
  25691.           'drop',
  25692.           'dragover'
  25693.         ];
  25694.         each$k(eventNames, function (name) {
  25695.           pageDom.bind(doc, name, preventFileDropIfUIElement);
  25696.           dom.bind(editorRoot, name, preventFileDrop);
  25697.         });
  25698.         editor.on('remove', function () {
  25699.           each$k(eventNames, function (name) {
  25700.             pageDom.unbind(doc, name, preventFileDropIfUIElement);
  25701.             dom.unbind(editorRoot, name, preventFileDrop);
  25702.           });
  25703.         });
  25704.       };
  25705.       editor.on('init', function () {
  25706.         Delay.setEditorTimeout(editor, setup, 0);
  25707.       });
  25708.     };
  25709.     var init$2 = function (editor) {
  25710.       bindFakeDragEvents(editor);
  25711.       blockIeDrop(editor);
  25712.       if (shouldBlockUnsupportedDrop(editor)) {
  25713.         blockUnsupportedFileDrop(editor);
  25714.       }
  25715.     };
  25716.  
  25717.     var setup$1 = function (editor) {
  25718.       var renderFocusCaret = first(function () {
  25719.         if (!editor.removed && editor.getBody().contains(document.activeElement)) {
  25720.           var rng = editor.selection.getRng();
  25721.           if (rng.collapsed) {
  25722.             var caretRange = renderRangeCaret(editor, rng, false);
  25723.             editor.selection.setRng(caretRange);
  25724.           }
  25725.         }
  25726.       }, 0);
  25727.       editor.on('focus', function () {
  25728.         renderFocusCaret.throttle();
  25729.       });
  25730.       editor.on('blur', function () {
  25731.         renderFocusCaret.cancel();
  25732.       });
  25733.     };
  25734.  
  25735.     var setup = function (editor) {
  25736.       editor.on('init', function () {
  25737.         editor.on('focusin', function (e) {
  25738.           var target = e.target;
  25739.           if (isMedia$2(target)) {
  25740.             var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
  25741.             var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
  25742.             if (editor.selection.getNode() !== node) {
  25743.               selectNode(editor, node).each(function (rng) {
  25744.                 return editor.selection.setRng(rng);
  25745.               });
  25746.             }
  25747.           }
  25748.         });
  25749.       });
  25750.     };
  25751.  
  25752.     var isContentEditableTrue = isContentEditableTrue$4;
  25753.     var isContentEditableFalse = isContentEditableFalse$b;
  25754.     var getContentEditableRoot = function (editor, node) {
  25755.       return getContentEditableRoot$1(editor.getBody(), node);
  25756.     };
  25757.     var SelectionOverrides = function (editor) {
  25758.       var selection = editor.selection, dom = editor.dom;
  25759.       var isBlock = dom.isBlock;
  25760.       var rootNode = editor.getBody();
  25761.       var fakeCaret = FakeCaret(editor, rootNode, isBlock, function () {
  25762.         return hasFocus(editor);
  25763.       });
  25764.       var realSelectionId = 'sel-' + dom.uniqueId();
  25765.       var elementSelectionAttr = 'data-mce-selected';
  25766.       var selectedElement;
  25767.       var isFakeSelectionElement = function (node) {
  25768.         return dom.hasClass(node, 'mce-offscreen-selection');
  25769.       };
  25770.       var isFakeSelectionTargetElement = function (node) {
  25771.         return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom.isChildOf(node, rootNode);
  25772.       };
  25773.       var isNearFakeSelectionElement = function (pos) {
  25774.         return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
  25775.       };
  25776.       var getRealSelectionElement = function () {
  25777.         var container = dom.get(realSelectionId);
  25778.         return container ? container.getElementsByTagName('*')[0] : container;
  25779.       };
  25780.       var setRange = function (range) {
  25781.         if (range) {
  25782.           selection.setRng(range);
  25783.         }
  25784.       };
  25785.       var getRange = selection.getRng;
  25786.       var showCaret = function (direction, node, before, scrollIntoView) {
  25787.         if (scrollIntoView === void 0) {
  25788.           scrollIntoView = true;
  25789.         }
  25790.         var e = editor.fire('ShowCaret', {
  25791.           target: node,
  25792.           direction: direction,
  25793.           before: before
  25794.         });
  25795.         if (e.isDefaultPrevented()) {
  25796.           return null;
  25797.         }
  25798.         if (scrollIntoView) {
  25799.           selection.scrollIntoView(node, direction === -1);
  25800.         }
  25801.         return fakeCaret.show(before, node);
  25802.       };
  25803.       var showBlockCaretContainer = function (blockCaretContainer) {
  25804.         if (blockCaretContainer.hasAttribute('data-mce-caret')) {
  25805.           showCaretContainerBlock(blockCaretContainer);
  25806.           setRange(getRange());
  25807.           selection.scrollIntoView(blockCaretContainer);
  25808.         }
  25809.       };
  25810.       var registerEvents = function () {
  25811.         editor.on('mouseup', function (e) {
  25812.           var range = getRange();
  25813.           if (range.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
  25814.             renderCaretAtRange(editor, range, false).each(setRange);
  25815.           }
  25816.         });
  25817.         editor.on('click', function (e) {
  25818.           var contentEditableRoot = getContentEditableRoot(editor, e.target);
  25819.           if (contentEditableRoot) {
  25820.             if (isContentEditableFalse(contentEditableRoot)) {
  25821.               e.preventDefault();
  25822.               editor.focus();
  25823.             }
  25824.             if (isContentEditableTrue(contentEditableRoot)) {
  25825.               if (dom.isChildOf(contentEditableRoot, selection.getNode())) {
  25826.                 removeElementSelection();
  25827.               }
  25828.             }
  25829.           }
  25830.         });
  25831.         editor.on('blur NewBlock', removeElementSelection);
  25832.         editor.on('ResizeWindow FullscreenStateChanged', fakeCaret.reposition);
  25833.         var hasNormalCaretPosition = function (elm) {
  25834.           var start = elm.firstChild;
  25835.           if (isNullable(start)) {
  25836.             return false;
  25837.           }
  25838.           var startPos = CaretPosition.before(start);
  25839.           if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
  25840.             return !isNearFakeSelectionElement(startPos);
  25841.           } else {
  25842.             var caretWalker = CaretWalker(elm);
  25843.             var newPos = caretWalker.next(startPos);
  25844.             return newPos && !isNearFakeSelectionElement(newPos);
  25845.           }
  25846.         };
  25847.         var isInSameBlock = function (node1, node2) {
  25848.           var block1 = dom.getParent(node1, isBlock);
  25849.           var block2 = dom.getParent(node2, isBlock);
  25850.           return block1 === block2;
  25851.         };
  25852.         var hasBetterMouseTarget = function (targetNode, caretNode) {
  25853.           var targetBlock = dom.getParent(targetNode, isBlock);
  25854.           var caretBlock = dom.getParent(caretNode, isBlock);
  25855.           if (isNullable(targetBlock)) {
  25856.             return false;
  25857.           }
  25858.           if (targetNode !== caretBlock && dom.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
  25859.             return true;
  25860.           }
  25861.           return !dom.isChildOf(caretBlock, targetBlock) && !isInSameBlock(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
  25862.         };
  25863.         editor.on('tap', function (e) {
  25864.           var targetElm = e.target;
  25865.           var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25866.           if (isContentEditableFalse(contentEditableRoot)) {
  25867.             e.preventDefault();
  25868.             selectNode(editor, contentEditableRoot).each(setElementSelection);
  25869.           } else if (isFakeSelectionTargetElement(targetElm)) {
  25870.             selectNode(editor, targetElm).each(setElementSelection);
  25871.           }
  25872.         }, true);
  25873.         editor.on('mousedown', function (e) {
  25874.           var targetElm = e.target;
  25875.           if (targetElm !== rootNode && targetElm.nodeName !== 'HTML' && !dom.isChildOf(targetElm, rootNode)) {
  25876.             return;
  25877.           }
  25878.           if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
  25879.             return;
  25880.           }
  25881.           var contentEditableRoot = getContentEditableRoot(editor, targetElm);
  25882.           if (contentEditableRoot) {
  25883.             if (isContentEditableFalse(contentEditableRoot)) {
  25884.               e.preventDefault();
  25885.               selectNode(editor, contentEditableRoot).each(setElementSelection);
  25886.             } else {
  25887.               removeElementSelection();
  25888.               if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
  25889.                 hideFakeCaret();
  25890.                 selection.placeCaretAt(e.clientX, e.clientY);
  25891.               }
  25892.             }
  25893.           } else if (isFakeSelectionTargetElement(targetElm)) {
  25894.             selectNode(editor, targetElm).each(setElementSelection);
  25895.           } else if (isFakeCaretTarget(targetElm) === false) {
  25896.             removeElementSelection();
  25897.             hideFakeCaret();
  25898.             var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
  25899.             if (fakeCaretInfo) {
  25900.               if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
  25901.                 e.preventDefault();
  25902.                 var range = showCaret(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
  25903.                 setRange(range);
  25904.                 editor.getBody().focus();
  25905.               }
  25906.             }
  25907.           }
  25908.         });
  25909.         editor.on('keypress', function (e) {
  25910.           if (VK.modifierPressed(e)) {
  25911.             return;
  25912.           }
  25913.           if (isContentEditableFalse(selection.getNode())) {
  25914.             e.preventDefault();
  25915.           }
  25916.         });
  25917.         editor.on('GetSelectionRange', function (e) {
  25918.           var rng = e.range;
  25919.           if (selectedElement) {
  25920.             if (!selectedElement.parentNode) {
  25921.               selectedElement = null;
  25922.               return;
  25923.             }
  25924.             rng = rng.cloneRange();
  25925.             rng.selectNode(selectedElement);
  25926.             e.range = rng;
  25927.           }
  25928.         });
  25929.         editor.on('SetSelectionRange', function (e) {
  25930.           e.range = normalizeShortEndedElementSelection(e.range);
  25931.           var rng = setElementSelection(e.range, e.forward);
  25932.           if (rng) {
  25933.             e.range = rng;
  25934.           }
  25935.         });
  25936.         var isPasteBin = function (node) {
  25937.           return node.id === 'mcepastebin';
  25938.         };
  25939.         editor.on('AfterSetSelectionRange', function (e) {
  25940.           var rng = e.range;
  25941.           var parentNode = rng.startContainer.parentNode;
  25942.           if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
  25943.             hideFakeCaret();
  25944.           }
  25945.           if (!isFakeSelectionElement(parentNode)) {
  25946.             removeElementSelection();
  25947.           }
  25948.         });
  25949.         editor.on('copy', function (e) {
  25950.           var clipboardData = e.clipboardData;
  25951.           if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
  25952.             var realSelectionElement = getRealSelectionElement();
  25953.             if (realSelectionElement) {
  25954.               e.preventDefault();
  25955.               clipboardData.clearData();
  25956.               clipboardData.setData('text/html', realSelectionElement.outerHTML);
  25957.               clipboardData.setData('text/plain', realSelectionElement.outerText || realSelectionElement.innerText);
  25958.             }
  25959.           }
  25960.         });
  25961.         init$2(editor);
  25962.         setup$1(editor);
  25963.         setup(editor);
  25964.       };
  25965.       var isWithinCaretContainer = function (node) {
  25966.         return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
  25967.       };
  25968.       var isRangeInCaretContainer = function (rng) {
  25969.         return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
  25970.       };
  25971.       var normalizeShortEndedElementSelection = function (rng) {
  25972.         var shortEndedElements = editor.schema.getShortEndedElements();
  25973.         var newRng = dom.createRng();
  25974.         var startContainer = rng.startContainer;
  25975.         var startOffset = rng.startOffset;
  25976.         var endContainer = rng.endContainer;
  25977.         var endOffset = rng.endOffset;
  25978.         if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
  25979.           if (startOffset === 0) {
  25980.             newRng.setStartBefore(startContainer);
  25981.           } else {
  25982.             newRng.setStartAfter(startContainer);
  25983.           }
  25984.         } else {
  25985.           newRng.setStart(startContainer, startOffset);
  25986.         }
  25987.         if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
  25988.           if (endOffset === 0) {
  25989.             newRng.setEndBefore(endContainer);
  25990.           } else {
  25991.             newRng.setEndAfter(endContainer);
  25992.           }
  25993.         } else {
  25994.           newRng.setEnd(endContainer, endOffset);
  25995.         }
  25996.         return newRng;
  25997.       };
  25998.       var setupOffscreenSelection = function (node, targetClone, origTargetClone) {
  25999.         var $ = editor.$;
  26000.         var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).fold(function () {
  26001.           return $([]);
  26002.         }, function (elm) {
  26003.           return $([elm.dom]);
  26004.         });
  26005.         if ($realSelectionContainer.length === 0) {
  26006.           $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr('id', realSelectionId);
  26007.           $realSelectionContainer.appendTo(editor.getBody());
  26008.         }
  26009.         var newRange = dom.createRng();
  26010.         if (targetClone === origTargetClone && Env.ie) {
  26011.           $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
  26012.           newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
  26013.           newRange.setEndAfter(targetClone);
  26014.         } else {
  26015.           $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
  26016.           newRange.setStart($realSelectionContainer[0].firstChild, 1);
  26017.           newRange.setEnd($realSelectionContainer[0].lastChild, 0);
  26018.         }
  26019.         $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y });
  26020.         $realSelectionContainer[0].focus();
  26021.         var sel = selection.getSel();
  26022.         sel.removeAllRanges();
  26023.         sel.addRange(newRange);
  26024.         return newRange;
  26025.       };
  26026.       var selectElement = function (elm) {
  26027.         var targetClone = elm.cloneNode(true);
  26028.         var e = editor.fire('ObjectSelected', {
  26029.           target: elm,
  26030.           targetClone: targetClone
  26031.         });
  26032.         if (e.isDefaultPrevented()) {
  26033.           return null;
  26034.         }
  26035.         var range = setupOffscreenSelection(elm, e.targetClone, targetClone);
  26036.         var nodeElm = SugarElement.fromDom(elm);
  26037.         each$k(descendants(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) {
  26038.           if (!eq(nodeElm, elm)) {
  26039.             remove$6(elm, elementSelectionAttr);
  26040.           }
  26041.         });
  26042.         if (!dom.getAttrib(elm, elementSelectionAttr)) {
  26043.           elm.setAttribute(elementSelectionAttr, '1');
  26044.         }
  26045.         selectedElement = elm;
  26046.         hideFakeCaret();
  26047.         return range;
  26048.       };
  26049.       var setElementSelection = function (range, forward) {
  26050.         if (!range) {
  26051.           return null;
  26052.         }
  26053.         if (range.collapsed) {
  26054.           if (!isRangeInCaretContainer(range)) {
  26055.             var dir = forward ? 1 : -1;
  26056.             var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range);
  26057.             var beforeNode = caretPosition.getNode(!forward);
  26058.             if (isFakeCaretTarget(beforeNode)) {
  26059.               return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
  26060.             }
  26061.             var afterNode = caretPosition.getNode(forward);
  26062.             if (isFakeCaretTarget(afterNode)) {
  26063.               return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
  26064.             }
  26065.           }
  26066.           return null;
  26067.         }
  26068.         var startContainer = range.startContainer;
  26069.         var startOffset = range.startOffset;
  26070.         var endOffset = range.endOffset;
  26071.         if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
  26072.           startContainer = startContainer.parentNode;
  26073.           startOffset = dom.nodeIndex(startContainer);
  26074.           startContainer = startContainer.parentNode;
  26075.         }
  26076.         if (startContainer.nodeType !== 1) {
  26077.           return null;
  26078.         }
  26079.         if (endOffset === startOffset + 1 && startContainer === range.endContainer) {
  26080.           var node = startContainer.childNodes[startOffset];
  26081.           if (isFakeSelectionTargetElement(node)) {
  26082.             return selectElement(node);
  26083.           }
  26084.         }
  26085.         return null;
  26086.       };
  26087.       var removeElementSelection = function () {
  26088.         if (selectedElement) {
  26089.           selectedElement.removeAttribute(elementSelectionAttr);
  26090.         }
  26091.         descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove$7);
  26092.         selectedElement = null;
  26093.       };
  26094.       var destroy = function () {
  26095.         fakeCaret.destroy();
  26096.         selectedElement = null;
  26097.       };
  26098.       var hideFakeCaret = function () {
  26099.         fakeCaret.hide();
  26100.       };
  26101.       if (Env.ceFalse && !isRtc(editor)) {
  26102.         registerEvents();
  26103.       }
  26104.       return {
  26105.         showCaret: showCaret,
  26106.         showBlockCaretContainer: showBlockCaretContainer,
  26107.         hideFakeCaret: hideFakeCaret,
  26108.         destroy: destroy
  26109.       };
  26110.     };
  26111.  
  26112.     var Quirks = function (editor) {
  26113.       var each = Tools.each;
  26114.       var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser;
  26115.       var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  26116.       var mceInternalUrlPrefix = 'data:text/mce-internal,';
  26117.       var mceInternalDataType = isIE ? 'Text' : 'URL';
  26118.       var setEditorCommandState = function (cmd, state) {
  26119.         try {
  26120.           editor.getDoc().execCommand(cmd, false, state);
  26121.         } catch (ex) {
  26122.         }
  26123.       };
  26124.       var isDefaultPrevented = function (e) {
  26125.         return e.isDefaultPrevented();
  26126.       };
  26127.       var setMceInternalContent = function (e) {
  26128.         var selectionHtml, internalContent;
  26129.         if (e.dataTransfer) {
  26130.           if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') {
  26131.             selection.select(e.target);
  26132.           }
  26133.           selectionHtml = editor.selection.getContent();
  26134.           if (selectionHtml.length > 0) {
  26135.             internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
  26136.             e.dataTransfer.setData(mceInternalDataType, internalContent);
  26137.           }
  26138.         }
  26139.       };
  26140.       var getMceInternalContent = function (e) {
  26141.         var internalContent;
  26142.         if (e.dataTransfer) {
  26143.           internalContent = e.dataTransfer.getData(mceInternalDataType);
  26144.           if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
  26145.             internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
  26146.             return {
  26147.               id: unescape(internalContent[0]),
  26148.               html: unescape(internalContent[1])
  26149.             };
  26150.           }
  26151.         }
  26152.         return null;
  26153.       };
  26154.       var insertClipboardContents = function (content, internal) {
  26155.         if (editor.queryCommandSupported('mceInsertClipboardContent')) {
  26156.           editor.execCommand('mceInsertClipboardContent', false, {
  26157.             content: content,
  26158.             internal: internal
  26159.           });
  26160.         } else {
  26161.           editor.execCommand('mceInsertContent', false, content);
  26162.         }
  26163.       };
  26164.       var emptyEditorWhenDeleting = function () {
  26165.         var serializeRng = function (rng) {
  26166.           var body = dom.create('body');
  26167.           var contents = rng.cloneContents();
  26168.           body.appendChild(contents);
  26169.           return selection.serializer.serialize(body, { format: 'html' });
  26170.         };
  26171.         var allContentsSelected = function (rng) {
  26172.           var selection = serializeRng(rng);
  26173.           var allRng = dom.createRng();
  26174.           allRng.selectNode(editor.getBody());
  26175.           var allSelection = serializeRng(allRng);
  26176.           return selection === allSelection;
  26177.         };
  26178.         editor.on('keydown', function (e) {
  26179.           var keyCode = e.keyCode;
  26180.           var isCollapsed, body;
  26181.           if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) {
  26182.             isCollapsed = editor.selection.isCollapsed();
  26183.             body = editor.getBody();
  26184.             if (isCollapsed && !dom.isEmpty(body)) {
  26185.               return;
  26186.             }
  26187.             if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  26188.               return;
  26189.             }
  26190.             e.preventDefault();
  26191.             editor.setContent('');
  26192.             if (body.firstChild && dom.isBlock(body.firstChild)) {
  26193.               editor.selection.setCursorLocation(body.firstChild, 0);
  26194.             } else {
  26195.               editor.selection.setCursorLocation(body, 0);
  26196.             }
  26197.             editor.nodeChanged();
  26198.           }
  26199.         });
  26200.       };
  26201.       var selectAll = function () {
  26202.         editor.shortcuts.add('meta+a', null, 'SelectAll');
  26203.       };
  26204.       var documentElementEditingFocus = function () {
  26205.         if (!editor.inline) {
  26206.           dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) {
  26207.             var rng;
  26208.             if (e.target === editor.getDoc().documentElement) {
  26209.               rng = selection.getRng();
  26210.               editor.getBody().focus();
  26211.               if (e.type === 'mousedown') {
  26212.                 if (isCaretContainer$2(rng.startContainer)) {
  26213.                   return;
  26214.                 }
  26215.                 selection.placeCaretAt(e.clientX, e.clientY);
  26216.               } else {
  26217.                 selection.setRng(rng);
  26218.               }
  26219.             }
  26220.           });
  26221.         }
  26222.       };
  26223.       var removeHrOnBackspace = function () {
  26224.         editor.on('keydown', function (e) {
  26225.           if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26226.             if (!editor.getBody().getElementsByTagName('hr').length) {
  26227.               return;
  26228.             }
  26229.             if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26230.               var node = selection.getNode();
  26231.               var previousSibling = node.previousSibling;
  26232.               if (node.nodeName === 'HR') {
  26233.                 dom.remove(node);
  26234.                 e.preventDefault();
  26235.                 return;
  26236.               }
  26237.               if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') {
  26238.                 dom.remove(previousSibling);
  26239.                 e.preventDefault();
  26240.               }
  26241.             }
  26242.           }
  26243.         });
  26244.       };
  26245.       var focusBody = function () {
  26246.         if (!Range.prototype.getClientRects) {
  26247.           editor.on('mousedown', function (e) {
  26248.             if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') {
  26249.               var body_1 = editor.getBody();
  26250.               body_1.blur();
  26251.               Delay.setEditorTimeout(editor, function () {
  26252.                 body_1.focus();
  26253.               });
  26254.             }
  26255.           });
  26256.         }
  26257.       };
  26258.       var selectControlElements = function () {
  26259.         editor.on('click', function (e) {
  26260.           var target = e.target;
  26261.           if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') {
  26262.             e.preventDefault();
  26263.             editor.selection.select(target);
  26264.             editor.nodeChanged();
  26265.           }
  26266.           if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) {
  26267.             e.preventDefault();
  26268.             selection.select(target);
  26269.           }
  26270.         });
  26271.       };
  26272.       var removeStylesWhenDeletingAcrossBlockElements = function () {
  26273.         var getAttributeApplyFunction = function () {
  26274.           var template = dom.getAttribs(selection.getStart().cloneNode(false));
  26275.           return function () {
  26276.             var target = selection.getStart();
  26277.             if (target !== editor.getBody()) {
  26278.               dom.setAttrib(target, 'style', null);
  26279.               each(template, function (attr) {
  26280.                 target.setAttributeNode(attr.cloneNode(true));
  26281.               });
  26282.             }
  26283.           };
  26284.         };
  26285.         var isSelectionAcrossElements = function () {
  26286.           return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock);
  26287.         };
  26288.         editor.on('keypress', function (e) {
  26289.           var applyAttributes;
  26290.           if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
  26291.             applyAttributes = getAttributeApplyFunction();
  26292.             editor.getDoc().execCommand('delete', false, null);
  26293.             applyAttributes();
  26294.             e.preventDefault();
  26295.             return false;
  26296.           }
  26297.         });
  26298.         dom.bind(editor.getDoc(), 'cut', function (e) {
  26299.           var applyAttributes;
  26300.           if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  26301.             applyAttributes = getAttributeApplyFunction();
  26302.             Delay.setEditorTimeout(editor, function () {
  26303.               applyAttributes();
  26304.             });
  26305.           }
  26306.         });
  26307.       };
  26308.       var disableBackspaceIntoATable = function () {
  26309.         editor.on('keydown', function (e) {
  26310.           if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  26311.             if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
  26312.               var previousSibling = selection.getNode().previousSibling;
  26313.               if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') {
  26314.                 e.preventDefault();
  26315.                 return false;
  26316.               }
  26317.             }
  26318.           }
  26319.         });
  26320.       };
  26321.       var removeBlockQuoteOnBackSpace = function () {
  26322.         editor.on('keydown', function (e) {
  26323.           var rng, parent;
  26324.           if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
  26325.             return;
  26326.           }
  26327.           rng = selection.getRng();
  26328.           var container = rng.startContainer;
  26329.           var offset = rng.startOffset;
  26330.           var root = dom.getRoot();
  26331.           parent = container;
  26332.           if (!rng.collapsed || offset !== 0) {
  26333.             return;
  26334.           }
  26335.           while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) {
  26336.             parent = parent.parentNode;
  26337.           }
  26338.           if (parent.tagName === 'BLOCKQUOTE') {
  26339.             editor.formatter.toggle('blockquote', null, parent);
  26340.             rng = dom.createRng();
  26341.             rng.setStart(container, 0);
  26342.             rng.setEnd(container, 0);
  26343.             selection.setRng(rng);
  26344.           }
  26345.         });
  26346.       };
  26347.       var setGeckoEditingOptions = function () {
  26348.         var setOpts = function () {
  26349.           setEditorCommandState('StyleWithCSS', false);
  26350.           setEditorCommandState('enableInlineTableEditing', false);
  26351.           if (!getObjectResizing(editor)) {
  26352.             setEditorCommandState('enableObjectResizing', false);
  26353.           }
  26354.         };
  26355.         if (!isReadOnly$1(editor)) {
  26356.           editor.on('BeforeExecCommand mousedown', setOpts);
  26357.         }
  26358.       };
  26359.       var addBrAfterLastLinks = function () {
  26360.         var fixLinks = function () {
  26361.           each(dom.select('a'), function (node) {
  26362.             var parentNode = node.parentNode;
  26363.             var root = dom.getRoot();
  26364.             if (parentNode.lastChild === node) {
  26365.               while (parentNode && !dom.isBlock(parentNode)) {
  26366.                 if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  26367.                   return;
  26368.                 }
  26369.                 parentNode = parentNode.parentNode;
  26370.               }
  26371.               dom.add(parentNode, 'br', { 'data-mce-bogus': 1 });
  26372.             }
  26373.           });
  26374.         };
  26375.         editor.on('SetContent ExecCommand', function (e) {
  26376.           if (e.type === 'setcontent' || e.command === 'mceInsertLink') {
  26377.             fixLinks();
  26378.           }
  26379.         });
  26380.       };
  26381.       var setDefaultBlockType = function () {
  26382.         if (getForcedRootBlock(editor)) {
  26383.           editor.on('init', function () {
  26384.             setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor));
  26385.           });
  26386.         }
  26387.       };
  26388.       var normalizeSelection = function () {
  26389.         editor.on('keyup focusin mouseup', function (e) {
  26390.           if (!VK.modifierPressed(e)) {
  26391.             selection.normalize();
  26392.           }
  26393.         }, true);
  26394.       };
  26395.       var showBrokenImageIcon = function () {
  26396.         editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}');
  26397.       };
  26398.       var restoreFocusOnKeyDown = function () {
  26399.         if (!editor.inline) {
  26400.           editor.on('keydown', function () {
  26401.             if (document.activeElement === document.body) {
  26402.               editor.getWin().focus();
  26403.             }
  26404.           });
  26405.         }
  26406.       };
  26407.       var bodyHeight = function () {
  26408.         if (!editor.inline) {
  26409.           editor.contentStyles.push('body {min-height: 150px}');
  26410.           editor.on('click', function (e) {
  26411.             var rng;
  26412.             if (e.target.nodeName === 'HTML') {
  26413.               if (Env.ie > 11) {
  26414.                 editor.getBody().focus();
  26415.                 return;
  26416.               }
  26417.               rng = editor.selection.getRng();
  26418.               editor.getBody().focus();
  26419.               editor.selection.setRng(rng);
  26420.               editor.selection.normalize();
  26421.               editor.nodeChanged();
  26422.             }
  26423.           });
  26424.         }
  26425.       };
  26426.       var blockCmdArrowNavigation = function () {
  26427.         if (Env.mac) {
  26428.           editor.on('keydown', function (e) {
  26429.             if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
  26430.               e.preventDefault();
  26431.               var selection_1 = editor.selection.getSel();
  26432.               selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary');
  26433.             }
  26434.           });
  26435.         }
  26436.       };
  26437.       var disableAutoUrlDetect = function () {
  26438.         setEditorCommandState('AutoUrlDetect', false);
  26439.       };
  26440.       var tapLinksAndImages = function () {
  26441.         editor.on('click', function (e) {
  26442.           var elm = e.target;
  26443.           do {
  26444.             if (elm.tagName === 'A') {
  26445.               e.preventDefault();
  26446.               return;
  26447.             }
  26448.           } while (elm = elm.parentNode);
  26449.         });
  26450.         editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  26451.       };
  26452.       var blockFormSubmitInsideEditor = function () {
  26453.         editor.on('init', function () {
  26454.           editor.dom.bind(editor.getBody(), 'submit', function (e) {
  26455.             e.preventDefault();
  26456.           });
  26457.         });
  26458.       };
  26459.       var removeAppleInterchangeBrs = function () {
  26460.         parser.addNodeFilter('br', function (nodes) {
  26461.           var i = nodes.length;
  26462.           while (i--) {
  26463.             if (nodes[i].attr('class') === 'Apple-interchange-newline') {
  26464.               nodes[i].remove();
  26465.             }
  26466.           }
  26467.         });
  26468.       };
  26469.       var ieInternalDragAndDrop = function () {
  26470.         editor.on('dragstart', function (e) {
  26471.           setMceInternalContent(e);
  26472.         });
  26473.         editor.on('drop', function (e) {
  26474.           if (!isDefaultPrevented(e)) {
  26475.             var internalContent = getMceInternalContent(e);
  26476.             if (internalContent && internalContent.id !== editor.id) {
  26477.               e.preventDefault();
  26478.               var rng = fromPoint(e.x, e.y, editor.getDoc());
  26479.               selection.setRng(rng);
  26480.               insertClipboardContents(internalContent.html, true);
  26481.             }
  26482.           }
  26483.         });
  26484.       };
  26485.       var refreshContentEditable = noop;
  26486.       var isHidden = function () {
  26487.         if (!isGecko || editor.removed) {
  26488.           return false;
  26489.         }
  26490.         var sel = editor.selection.getSel();
  26491.         return !sel || !sel.rangeCount || sel.rangeCount === 0;
  26492.       };
  26493.       var setupRtc = function () {
  26494.         if (isWebKit) {
  26495.           documentElementEditingFocus();
  26496.           selectControlElements();
  26497.           blockFormSubmitInsideEditor();
  26498.           selectAll();
  26499.           if (Env.iOS) {
  26500.             restoreFocusOnKeyDown();
  26501.             bodyHeight();
  26502.             tapLinksAndImages();
  26503.           }
  26504.         }
  26505.         if (isGecko) {
  26506.           focusBody();
  26507.           setGeckoEditingOptions();
  26508.           showBrokenImageIcon();
  26509.           blockCmdArrowNavigation();
  26510.         }
  26511.       };
  26512.       var setup = function () {
  26513.         removeBlockQuoteOnBackSpace();
  26514.         emptyEditorWhenDeleting();
  26515.         if (!Env.windowsPhone) {
  26516.           normalizeSelection();
  26517.         }
  26518.         if (isWebKit) {
  26519.           documentElementEditingFocus();
  26520.           selectControlElements();
  26521.           setDefaultBlockType();
  26522.           blockFormSubmitInsideEditor();
  26523.           disableBackspaceIntoATable();
  26524.           removeAppleInterchangeBrs();
  26525.           if (Env.iOS) {
  26526.             restoreFocusOnKeyDown();
  26527.             bodyHeight();
  26528.             tapLinksAndImages();
  26529.           } else {
  26530.             selectAll();
  26531.           }
  26532.         }
  26533.         if (Env.ie >= 11) {
  26534.           bodyHeight();
  26535.           disableBackspaceIntoATable();
  26536.         }
  26537.         if (Env.ie) {
  26538.           selectAll();
  26539.           disableAutoUrlDetect();
  26540.           ieInternalDragAndDrop();
  26541.         }
  26542.         if (isGecko) {
  26543.           removeHrOnBackspace();
  26544.           focusBody();
  26545.           removeStylesWhenDeletingAcrossBlockElements();
  26546.           setGeckoEditingOptions();
  26547.           addBrAfterLastLinks();
  26548.           showBrokenImageIcon();
  26549.           blockCmdArrowNavigation();
  26550.           disableBackspaceIntoATable();
  26551.         }
  26552.       };
  26553.       if (isRtc(editor)) {
  26554.         setupRtc();
  26555.       } else {
  26556.         setup();
  26557.       }
  26558.       return {
  26559.         refreshContentEditable: refreshContentEditable,
  26560.         isHidden: isHidden
  26561.       };
  26562.     };
  26563.  
  26564.     var DOM$6 = DOMUtils.DOM;
  26565.     var appendStyle = function (editor, text) {
  26566.       var body = SugarElement.fromDom(editor.getBody());
  26567.       var container = getStyleContainer(getRootNode(body));
  26568.       var style = SugarElement.fromTag('style');
  26569.       set$1(style, 'type', 'text/css');
  26570.       append$1(style, SugarElement.fromText(text));
  26571.       append$1(container, style);
  26572.       editor.on('remove', function () {
  26573.         remove$7(style);
  26574.       });
  26575.     };
  26576.     var getRootName = function (editor) {
  26577.       return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined;
  26578.     };
  26579.     var removeUndefined = function (obj) {
  26580.       return filter$3(obj, function (v) {
  26581.         return isUndefined(v) === false;
  26582.       });
  26583.     };
  26584.     var mkSchemaSettings = function (editor) {
  26585.       var settings = editor.settings;
  26586.       return removeUndefined({
  26587.         block_elements: settings.block_elements,
  26588.         boolean_attributes: settings.boolean_attributes,
  26589.         custom_elements: settings.custom_elements,
  26590.         extended_valid_elements: settings.extended_valid_elements,
  26591.         invalid_elements: settings.invalid_elements,
  26592.         invalid_styles: settings.invalid_styles,
  26593.         move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
  26594.         non_empty_elements: settings.non_empty_elements,
  26595.         schema: settings.schema,
  26596.         self_closing_elements: settings.self_closing_elements,
  26597.         short_ended_elements: settings.short_ended_elements,
  26598.         special: settings.special,
  26599.         text_block_elements: settings.text_block_elements,
  26600.         text_inline_elements: settings.text_inline_elements,
  26601.         valid_children: settings.valid_children,
  26602.         valid_classes: settings.valid_classes,
  26603.         valid_elements: settings.valid_elements,
  26604.         valid_styles: settings.valid_styles,
  26605.         verify_html: settings.verify_html,
  26606.         whitespace_elements: settings.whitespace_elements,
  26607.         padd_empty_block_inline_children: settings.format_empty_lines
  26608.       });
  26609.     };
  26610.     var mkParserSettings = function (editor) {
  26611.       var settings = editor.settings;
  26612.       var blobCache = editor.editorUpload.blobCache;
  26613.       return removeUndefined({
  26614.         allow_conditional_comments: settings.allow_conditional_comments,
  26615.         allow_html_data_urls: settings.allow_html_data_urls,
  26616.         allow_svg_data_urls: settings.allow_svg_data_urls,
  26617.         allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
  26618.         allow_script_urls: settings.allow_script_urls,
  26619.         allow_unsafe_link_target: settings.allow_unsafe_link_target,
  26620.         convert_fonts_to_spans: settings.convert_fonts_to_spans,
  26621.         fix_list_elements: settings.fix_list_elements,
  26622.         font_size_legacy_values: settings.font_size_legacy_values,
  26623.         forced_root_block: settings.forced_root_block,
  26624.         forced_root_block_attrs: settings.forced_root_block_attrs,
  26625.         padd_empty_with_br: settings.padd_empty_with_br,
  26626.         preserve_cdata: settings.preserve_cdata,
  26627.         remove_trailing_brs: settings.remove_trailing_brs,
  26628.         inline_styles: settings.inline_styles,
  26629.         root_name: getRootName(editor),
  26630.         validate: true,
  26631.         blob_cache: blobCache,
  26632.         document: editor.getDoc(),
  26633.         images_dataimg_filter: settings.images_dataimg_filter
  26634.       });
  26635.     };
  26636.     var mkSerializerSettings = function (editor) {
  26637.       var settings = editor.settings;
  26638.       return __assign(__assign(__assign({}, mkParserSettings(editor)), mkSchemaSettings(editor)), removeUndefined({
  26639.         url_converter: settings.url_converter,
  26640.         url_converter_scope: settings.url_converter_scope,
  26641.         element_format: settings.element_format,
  26642.         entities: settings.entities,
  26643.         entity_encoding: settings.entity_encoding,
  26644.         indent: settings.indent,
  26645.         indent_after: settings.indent_after,
  26646.         indent_before: settings.indent_before
  26647.       }));
  26648.     };
  26649.     var createParser = function (editor) {
  26650.       var parser = DomParser(mkParserSettings(editor), editor.schema);
  26651.       parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) {
  26652.         var i = nodes.length, node, value;
  26653.         var dom = editor.dom;
  26654.         var internalName = 'data-mce-' + name;
  26655.         while (i--) {
  26656.           node = nodes[i];
  26657.           value = node.attr(name);
  26658.           if (value && !node.attr(internalName)) {
  26659.             if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
  26660.               continue;
  26661.             }
  26662.             if (name === 'style') {
  26663.               value = dom.serializeStyle(dom.parseStyle(value), node.name);
  26664.               if (!value.length) {
  26665.                 value = null;
  26666.               }
  26667.               node.attr(internalName, value);
  26668.               node.attr(name, value);
  26669.             } else if (name === 'tabindex') {
  26670.               node.attr(internalName, value);
  26671.               node.attr(name, null);
  26672.             } else {
  26673.               node.attr(internalName, editor.convertURL(value, name, node.name));
  26674.             }
  26675.           }
  26676.         }
  26677.       });
  26678.       parser.addNodeFilter('script', function (nodes) {
  26679.         var i = nodes.length;
  26680.         while (i--) {
  26681.           var node = nodes[i];
  26682.           var type = node.attr('type') || 'no/type';
  26683.           if (type.indexOf('mce-') !== 0) {
  26684.             node.attr('type', 'mce-' + type);
  26685.           }
  26686.         }
  26687.       });
  26688.       if (editor.settings.preserve_cdata) {
  26689.         parser.addNodeFilter('#cdata', function (nodes) {
  26690.           var i = nodes.length;
  26691.           while (i--) {
  26692.             var node = nodes[i];
  26693.             node.type = 8;
  26694.             node.name = '#comment';
  26695.             node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]';
  26696.           }
  26697.         });
  26698.       }
  26699.       parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) {
  26700.         var i = nodes.length;
  26701.         var nonEmptyElements = editor.schema.getNonEmptyElements();
  26702.         while (i--) {
  26703.           var node = nodes[i];
  26704.           if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) {
  26705.             node.append(new AstNode('br', 1)).shortEnded = true;
  26706.           }
  26707.         }
  26708.       });
  26709.       return parser;
  26710.     };
  26711.     var autoFocus = function (editor) {
  26712.       if (editor.settings.auto_focus) {
  26713.         Delay.setEditorTimeout(editor, function () {
  26714.           var focusEditor;
  26715.           if (editor.settings.auto_focus === true) {
  26716.             focusEditor = editor;
  26717.           } else {
  26718.             focusEditor = editor.editorManager.get(editor.settings.auto_focus);
  26719.           }
  26720.           if (!focusEditor.destroyed) {
  26721.             focusEditor.focus();
  26722.           }
  26723.         }, 100);
  26724.       }
  26725.     };
  26726.     var moveSelectionToFirstCaretPosition = function (editor) {
  26727.       var root = editor.dom.getRoot();
  26728.       if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
  26729.         firstPositionIn(root).each(function (pos) {
  26730.           var node = pos.getNode();
  26731.           var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
  26732.           if (Env.browser.isIE()) {
  26733.             storeNative(editor, caretPos.toRange());
  26734.           } else {
  26735.             editor.selection.setRng(caretPos.toRange());
  26736.           }
  26737.         });
  26738.       }
  26739.     };
  26740.     var initEditor = function (editor) {
  26741.       editor.bindPendingEventDelegates();
  26742.       editor.initialized = true;
  26743.       fireInit(editor);
  26744.       editor.focus(true);
  26745.       moveSelectionToFirstCaretPosition(editor);
  26746.       editor.nodeChanged({ initial: true });
  26747.       editor.execCallback('init_instance_callback', editor);
  26748.       autoFocus(editor);
  26749.     };
  26750.     var getStyleSheetLoader$1 = function (editor) {
  26751.       return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
  26752.     };
  26753.     var makeStylesheetLoadingPromises = function (editor, css, framedFonts) {
  26754.       var promises = [new promiseObj(function (resolve, reject) {
  26755.           return getStyleSheetLoader$1(editor).loadAll(css, resolve, reject);
  26756.         })];
  26757.       if (editor.inline) {
  26758.         return promises;
  26759.       } else {
  26760.         return promises.concat([new promiseObj(function (resolve, reject) {
  26761.             return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve, reject);
  26762.           })]);
  26763.       }
  26764.     };
  26765.     var loadContentCss = function (editor) {
  26766.       var styleSheetLoader = getStyleSheetLoader$1(editor);
  26767.       var fontCss = getFontCss(editor);
  26768.       var css = editor.contentCSS;
  26769.       var removeCss = function () {
  26770.         styleSheetLoader.unloadAll(css);
  26771.         if (!editor.inline) {
  26772.           editor.ui.styleSheetLoader.unloadAll(fontCss);
  26773.         }
  26774.       };
  26775.       var loaded = function () {
  26776.         if (editor.removed) {
  26777.           removeCss();
  26778.         } else {
  26779.           editor.on('remove', removeCss);
  26780.         }
  26781.       };
  26782.       if (editor.contentStyles.length > 0) {
  26783.         var contentCssText_1 = '';
  26784.         Tools.each(editor.contentStyles, function (style) {
  26785.           contentCssText_1 += style + '\r\n';
  26786.         });
  26787.         editor.dom.addStyle(contentCssText_1);
  26788.       }
  26789.       var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
  26790.       if (editor.settings.content_style) {
  26791.         appendStyle(editor, editor.settings.content_style);
  26792.       }
  26793.       return allStylesheets;
  26794.     };
  26795.     var preInit = function (editor) {
  26796.       var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody();
  26797.       firePreInit(editor);
  26798.       if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  26799.         doc.body.spellcheck = false;
  26800.         DOM$6.setAttrib(body, 'spellcheck', 'false');
  26801.       }
  26802.       editor.quirks = Quirks(editor);
  26803.       firePostRender(editor);
  26804.       var directionality = getDirectionality(editor);
  26805.       if (directionality !== undefined) {
  26806.         body.dir = directionality;
  26807.       }
  26808.       if (settings.protect) {
  26809.         editor.on('BeforeSetContent', function (e) {
  26810.           Tools.each(settings.protect, function (pattern) {
  26811.             e.content = e.content.replace(pattern, function (str) {
  26812.               return '<!--mce:protected ' + escape(str) + '-->';
  26813.             });
  26814.           });
  26815.         });
  26816.       }
  26817.       editor.on('SetContent', function () {
  26818.         editor.addVisual(editor.getBody());
  26819.       });
  26820.       editor.on('compositionstart compositionend', function (e) {
  26821.         editor.composing = e.type === 'compositionstart';
  26822.       });
  26823.     };
  26824.     var loadInitialContent = function (editor) {
  26825.       if (!isRtc(editor)) {
  26826.         editor.load({
  26827.           initial: true,
  26828.           format: 'html'
  26829.         });
  26830.       }
  26831.       editor.startContent = editor.getContent({ format: 'raw' });
  26832.     };
  26833.     var initEditorWithInitialContent = function (editor) {
  26834.       if (editor.removed !== true) {
  26835.         loadInitialContent(editor);
  26836.         initEditor(editor);
  26837.       }
  26838.     };
  26839.     var initContentBody = function (editor, skipWrite) {
  26840.       var settings = editor.settings;
  26841.       var targetElm = editor.getElement();
  26842.       var doc = editor.getDoc();
  26843.       if (!settings.inline) {
  26844.         editor.getElement().style.visibility = editor.orgVisibility;
  26845.       }
  26846.       if (!skipWrite && !editor.inline) {
  26847.         doc.open();
  26848.         doc.write(editor.iframeHTML);
  26849.         doc.close();
  26850.       }
  26851.       if (editor.inline) {
  26852.         DOM$6.addClass(targetElm, 'mce-content-body');
  26853.         editor.contentDocument = doc = document;
  26854.         editor.contentWindow = window;
  26855.         editor.bodyElement = targetElm;
  26856.         editor.contentAreaContainer = targetElm;
  26857.       }
  26858.       var body = editor.getBody();
  26859.       body.disabled = true;
  26860.       editor.readonly = !!settings.readonly;
  26861.       if (!editor.readonly) {
  26862.         if (editor.inline && DOM$6.getStyle(body, 'position', true) === 'static') {
  26863.           body.style.position = 'relative';
  26864.         }
  26865.         body.contentEditable = editor.getParam('content_editable_state', true);
  26866.       }
  26867.       body.disabled = false;
  26868.       editor.editorUpload = EditorUpload(editor);
  26869.       editor.schema = Schema(mkSchemaSettings(editor));
  26870.       editor.dom = DOMUtils(doc, {
  26871.         keep_values: true,
  26872.         url_converter: editor.convertURL,
  26873.         url_converter_scope: editor,
  26874.         hex_colors: settings.force_hex_style_colors,
  26875.         update_styles: true,
  26876.         root_element: editor.inline ? editor.getBody() : null,
  26877.         collect: function () {
  26878.           return editor.inline;
  26879.         },
  26880.         schema: editor.schema,
  26881.         contentCssCors: shouldUseContentCssCors(editor),
  26882.         referrerPolicy: getReferrerPolicy(editor),
  26883.         onSetAttrib: function (e) {
  26884.           editor.fire('SetAttrib', e);
  26885.         }
  26886.       });
  26887.       editor.parser = createParser(editor);
  26888.       editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
  26889.       editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
  26890.       editor.annotator = Annotator(editor);
  26891.       editor.formatter = Formatter(editor);
  26892.       editor.undoManager = UndoManager(editor);
  26893.       editor._nodeChangeDispatcher = new NodeChange(editor);
  26894.       editor._selectionOverrides = SelectionOverrides(editor);
  26895.       setup$e(editor);
  26896.       setup$3(editor);
  26897.       if (!isRtc(editor)) {
  26898.         setup$2(editor);
  26899.       }
  26900.       var caret = setup$4(editor);
  26901.       setup$f(editor, caret);
  26902.       setup$d(editor);
  26903.       setup$g(editor);
  26904.       var setupRtcThunk = setup$i(editor);
  26905.       preInit(editor);
  26906.       setupRtcThunk.fold(function () {
  26907.         loadContentCss(editor).then(function () {
  26908.           return initEditorWithInitialContent(editor);
  26909.         });
  26910.       }, function (setupRtc) {
  26911.         editor.setProgressState(true);
  26912.         loadContentCss(editor).then(function () {
  26913.           setupRtc().then(function (_rtcMode) {
  26914.             editor.setProgressState(false);
  26915.             initEditorWithInitialContent(editor);
  26916.           }, function (err) {
  26917.             editor.notificationManager.open({
  26918.               type: 'error',
  26919.               text: String(err)
  26920.             });
  26921.             initEditorWithInitialContent(editor);
  26922.           });
  26923.         });
  26924.       });
  26925.     };
  26926.  
  26927.     var DOM$5 = DOMUtils.DOM;
  26928.     var relaxDomain = function (editor, ifr) {
  26929.       if (document.domain !== window.location.hostname && Env.browser.isIE()) {
  26930.         var bodyUuid = uuid('mce');
  26931.         editor[bodyUuid] = function () {
  26932.           initContentBody(editor);
  26933.         };
  26934.         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);})()';
  26935.         DOM$5.setAttrib(ifr, 'src', domainRelaxUrl);
  26936.         return true;
  26937.       }
  26938.       return false;
  26939.     };
  26940.     var createIframeElement = function (id, title, height, customAttrs) {
  26941.       var iframe = SugarElement.fromTag('iframe');
  26942.       setAll$1(iframe, customAttrs);
  26943.       setAll$1(iframe, {
  26944.         id: id + '_ifr',
  26945.         frameBorder: '0',
  26946.         allowTransparency: 'true',
  26947.         title: title
  26948.       });
  26949.       add$1(iframe, 'tox-edit-area__iframe');
  26950.       return iframe;
  26951.     };
  26952.     var getIframeHtml = function (editor) {
  26953.       var iframeHTML = getDocType(editor) + '<html><head>';
  26954.       if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
  26955.         iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
  26956.       }
  26957.       iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  26958.       var bodyId = getBodyId(editor);
  26959.       var bodyClass = getBodyClass(editor);
  26960.       var translatedAriaText = editor.translate(getIframeAriaText(editor));
  26961.       if (getContentSecurityPolicy(editor)) {
  26962.         iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
  26963.       }
  26964.       iframeHTML += '</head>' + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + '<br>' + '</body></html>';
  26965.       return iframeHTML;
  26966.     };
  26967.     var createIframe = function (editor, o) {
  26968.       var iframeTitle = editor.translate('Rich Text Area');
  26969.       var ifr = createIframeElement(editor.id, iframeTitle, o.height, getIframeAttrs(editor)).dom;
  26970.       ifr.onload = function () {
  26971.         ifr.onload = null;
  26972.         editor.fire('load');
  26973.       };
  26974.       var isDomainRelaxed = relaxDomain(editor, ifr);
  26975.       editor.contentAreaContainer = o.iframeContainer;
  26976.       editor.iframeElement = ifr;
  26977.       editor.iframeHTML = getIframeHtml(editor);
  26978.       DOM$5.add(o.iframeContainer, ifr);
  26979.       return isDomainRelaxed;
  26980.     };
  26981.     var init$1 = function (editor, boxInfo) {
  26982.       var isDomainRelaxed = createIframe(editor, boxInfo);
  26983.       if (boxInfo.editorContainer) {
  26984.         DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
  26985.         editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
  26986.       }
  26987.       editor.getElement().style.display = 'none';
  26988.       DOM$5.setAttrib(editor.id, 'aria-hidden', 'true');
  26989.       if (!isDomainRelaxed) {
  26990.         initContentBody(editor);
  26991.       }
  26992.     };
  26993.  
  26994.     var DOM$4 = DOMUtils.DOM;
  26995.     var initPlugin = function (editor, initializedPlugins, plugin) {
  26996.       var Plugin = PluginManager.get(plugin);
  26997.       var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, '');
  26998.       plugin = Tools.trim(plugin);
  26999.       if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
  27000.         Tools.each(PluginManager.dependencies(plugin), function (dep) {
  27001.           initPlugin(editor, initializedPlugins, dep);
  27002.         });
  27003.         if (editor.plugins[plugin]) {
  27004.           return;
  27005.         }
  27006.         try {
  27007.           var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
  27008.           editor.plugins[plugin] = pluginInstance;
  27009.           if (pluginInstance.init) {
  27010.             pluginInstance.init(editor, pluginUrl);
  27011.             initializedPlugins.push(plugin);
  27012.           }
  27013.         } catch (e) {
  27014.           pluginInitError(editor, plugin, e);
  27015.         }
  27016.       }
  27017.     };
  27018.     var trimLegacyPrefix = function (name) {
  27019.       return name.replace(/^\-/, '');
  27020.     };
  27021.     var initPlugins = function (editor) {
  27022.       var initializedPlugins = [];
  27023.       Tools.each(getPlugins(editor).split(/[ ,]/), function (name) {
  27024.         initPlugin(editor, initializedPlugins, trimLegacyPrefix(name));
  27025.       });
  27026.     };
  27027.     var initIcons = function (editor) {
  27028.       var iconPackName = Tools.trim(getIconPackName(editor));
  27029.       var currentIcons = editor.ui.registry.getAll().icons;
  27030.       var loadIcons = __assign(__assign({}, IconManager.get('default').icons), IconManager.get(iconPackName).icons);
  27031.       each$j(loadIcons, function (svgData, icon) {
  27032.         if (!has$2(currentIcons, icon)) {
  27033.           editor.ui.registry.addIcon(icon, svgData);
  27034.         }
  27035.       });
  27036.     };
  27037.     var initTheme = function (editor) {
  27038.       var theme = getTheme(editor);
  27039.       if (isString$1(theme)) {
  27040.         editor.settings.theme = trimLegacyPrefix(theme);
  27041.         var Theme = ThemeManager.get(theme);
  27042.         editor.theme = new Theme(editor, ThemeManager.urls[theme]);
  27043.         if (editor.theme.init) {
  27044.           editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ''), editor.$);
  27045.         }
  27046.       } else {
  27047.         editor.theme = {};
  27048.       }
  27049.     };
  27050.     var renderFromLoadedTheme = function (editor) {
  27051.       return editor.theme.renderUI();
  27052.     };
  27053.     var renderFromThemeFunc = function (editor) {
  27054.       var elm = editor.getElement();
  27055.       var theme = getTheme(editor);
  27056.       var info = theme(editor, elm);
  27057.       if (info.editorContainer.nodeType) {
  27058.         info.editorContainer.id = info.editorContainer.id || editor.id + '_parent';
  27059.       }
  27060.       if (info.iframeContainer && info.iframeContainer.nodeType) {
  27061.         info.iframeContainer.id = info.iframeContainer.id || editor.id + '_iframecontainer';
  27062.       }
  27063.       info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
  27064.       return info;
  27065.     };
  27066.     var createThemeFalseResult = function (element) {
  27067.       return {
  27068.         editorContainer: element,
  27069.         iframeContainer: element,
  27070.         api: {}
  27071.       };
  27072.     };
  27073.     var renderThemeFalseIframe = function (targetElement) {
  27074.       var iframeContainer = DOM$4.create('div');
  27075.       DOM$4.insertAfter(iframeContainer, targetElement);
  27076.       return createThemeFalseResult(iframeContainer);
  27077.     };
  27078.     var renderThemeFalse = function (editor) {
  27079.       var targetElement = editor.getElement();
  27080.       return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
  27081.     };
  27082.     var renderThemeUi = function (editor) {
  27083.       var elm = editor.getElement();
  27084.       editor.orgDisplay = elm.style.display;
  27085.       if (isString$1(getTheme(editor))) {
  27086.         return renderFromLoadedTheme(editor);
  27087.       } else if (isFunction(getTheme(editor))) {
  27088.         return renderFromThemeFunc(editor);
  27089.       } else {
  27090.         return renderThemeFalse(editor);
  27091.       }
  27092.     };
  27093.     var augmentEditorUiApi = function (editor, api) {
  27094.       var uiApiFacade = {
  27095.         show: Optional.from(api.show).getOr(noop),
  27096.         hide: Optional.from(api.hide).getOr(noop),
  27097.         disable: Optional.from(api.disable).getOr(noop),
  27098.         isDisabled: Optional.from(api.isDisabled).getOr(never),
  27099.         enable: function () {
  27100.           if (!editor.mode.isReadOnly()) {
  27101.             Optional.from(api.enable).map(call);
  27102.           }
  27103.         }
  27104.       };
  27105.       editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
  27106.     };
  27107.     var init = function (editor) {
  27108.       editor.fire('ScriptsLoaded');
  27109.       initIcons(editor);
  27110.       initTheme(editor);
  27111.       initPlugins(editor);
  27112.       var renderInfo = renderThemeUi(editor);
  27113.       augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
  27114.       var boxInfo = {
  27115.         editorContainer: renderInfo.editorContainer,
  27116.         iframeContainer: renderInfo.iframeContainer
  27117.       };
  27118.       editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
  27119.       appendContentCssFromSettings(editor);
  27120.       if (editor.inline) {
  27121.         return initContentBody(editor);
  27122.       } else {
  27123.         return init$1(editor, boxInfo);
  27124.       }
  27125.     };
  27126.  
  27127.     var DOM$3 = DOMUtils.DOM;
  27128.     var hasSkipLoadPrefix = function (name) {
  27129.       return name.charAt(0) === '-';
  27130.     };
  27131.     var loadLanguage = function (scriptLoader, editor) {
  27132.       var languageCode = getLanguageCode(editor);
  27133.       var languageUrl = getLanguageUrl(editor);
  27134.       if (I18n.hasCode(languageCode) === false && languageCode !== 'en') {
  27135.         var url_1 = languageUrl !== '' ? languageUrl : editor.editorManager.baseURL + '/langs/' + languageCode + '.js';
  27136.         scriptLoader.add(url_1, noop, undefined, function () {
  27137.           languageLoadError(editor, url_1, languageCode);
  27138.         });
  27139.       }
  27140.     };
  27141.     var loadTheme = function (scriptLoader, editor, suffix, callback) {
  27142.       var theme = getTheme(editor);
  27143.       if (isString$1(theme)) {
  27144.         if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
  27145.           var themeUrl = getThemeUrl(editor);
  27146.           if (themeUrl) {
  27147.             ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
  27148.           } else {
  27149.             ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
  27150.           }
  27151.         }
  27152.         scriptLoader.loadQueue(function () {
  27153.           ThemeManager.waitFor(theme, callback);
  27154.         });
  27155.       } else {
  27156.         callback();
  27157.       }
  27158.     };
  27159.     var getIconsUrlMetaFromUrl = function (editor) {
  27160.       return Optional.from(getIconsUrl(editor)).filter(function (url) {
  27161.         return url.length > 0;
  27162.       }).map(function (url) {
  27163.         return {
  27164.           url: url,
  27165.           name: Optional.none()
  27166.         };
  27167.       });
  27168.     };
  27169.     var getIconsUrlMetaFromName = function (editor, name, suffix) {
  27170.       return Optional.from(name).filter(function (name) {
  27171.         return name.length > 0 && !IconManager.has(name);
  27172.       }).map(function (name) {
  27173.         return {
  27174.           url: editor.editorManager.baseURL + '/icons/' + name + '/icons' + suffix + '.js',
  27175.           name: Optional.some(name)
  27176.         };
  27177.       });
  27178.     };
  27179.     var loadIcons = function (scriptLoader, editor, suffix) {
  27180.       var defaultIconsUrl = getIconsUrlMetaFromName(editor, 'default', suffix);
  27181.       var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function () {
  27182.         return getIconsUrlMetaFromName(editor, getIconPackName(editor), '');
  27183.       });
  27184.       each$k(cat([
  27185.         defaultIconsUrl,
  27186.         customIconsUrl
  27187.       ]), function (urlMeta) {
  27188.         scriptLoader.add(urlMeta.url, noop, undefined, function () {
  27189.           iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
  27190.         });
  27191.       });
  27192.     };
  27193.     var loadPlugins = function (editor, suffix) {
  27194.       Tools.each(getExternalPlugins$1(editor), function (url, name) {
  27195.         PluginManager.load(name, url, noop, undefined, function () {
  27196.           pluginLoadError(editor, url, name);
  27197.         });
  27198.         editor.settings.plugins += ' ' + name;
  27199.       });
  27200.       Tools.each(getPlugins(editor).split(/[ ,]/), function (plugin) {
  27201.         plugin = Tools.trim(plugin);
  27202.         if (plugin && !PluginManager.urls[plugin]) {
  27203.           if (hasSkipLoadPrefix(plugin)) {
  27204.             plugin = plugin.substr(1, plugin.length);
  27205.             var dependencies = PluginManager.dependencies(plugin);
  27206.             Tools.each(dependencies, function (depPlugin) {
  27207.               var defaultSettings = {
  27208.                 prefix: 'plugins/',
  27209.                 resource: depPlugin,
  27210.                 suffix: '/plugin' + suffix + '.js'
  27211.               };
  27212.               var dep = PluginManager.createUrl(defaultSettings, depPlugin);
  27213.               PluginManager.load(dep.resource, dep, noop, undefined, function () {
  27214.                 pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
  27215.               });
  27216.             });
  27217.           } else {
  27218.             var url_2 = {
  27219.               prefix: 'plugins/',
  27220.               resource: plugin,
  27221.               suffix: '/plugin' + suffix + '.js'
  27222.             };
  27223.             PluginManager.load(plugin, url_2, noop, undefined, function () {
  27224.               pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
  27225.             });
  27226.           }
  27227.         }
  27228.       });
  27229.     };
  27230.     var loadScripts = function (editor, suffix) {
  27231.       var scriptLoader = ScriptLoader.ScriptLoader;
  27232.       loadTheme(scriptLoader, editor, suffix, function () {
  27233.         loadLanguage(scriptLoader, editor);
  27234.         loadIcons(scriptLoader, editor, suffix);
  27235.         loadPlugins(editor, suffix);
  27236.         scriptLoader.loadQueue(function () {
  27237.           if (!editor.removed) {
  27238.             init(editor);
  27239.           }
  27240.         }, editor, function () {
  27241.           if (!editor.removed) {
  27242.             init(editor);
  27243.           }
  27244.         });
  27245.       });
  27246.     };
  27247.     var getStyleSheetLoader = function (element, editor) {
  27248.       return instance.forElement(element, {
  27249.         contentCssCors: hasContentCssCors(editor),
  27250.         referrerPolicy: getReferrerPolicy(editor)
  27251.       });
  27252.     };
  27253.     var render = function (editor) {
  27254.       var id = editor.id;
  27255.       I18n.setCode(getLanguageCode(editor));
  27256.       var readyHandler = function () {
  27257.         DOM$3.unbind(window, 'ready', readyHandler);
  27258.         editor.render();
  27259.       };
  27260.       if (!EventUtils.Event.domLoaded) {
  27261.         DOM$3.bind(window, 'ready', readyHandler);
  27262.         return;
  27263.       }
  27264.       if (!editor.getElement()) {
  27265.         return;
  27266.       }
  27267.       if (!Env.contentEditable) {
  27268.         return;
  27269.       }
  27270.       var element = SugarElement.fromDom(editor.getElement());
  27271.       var snapshot = clone$3(element);
  27272.       editor.on('remove', function () {
  27273.         eachr(element.dom.attributes, function (attr) {
  27274.           return remove$6(element, attr.name);
  27275.         });
  27276.         setAll$1(element, snapshot);
  27277.       });
  27278.       editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
  27279.       if (!isInline(editor)) {
  27280.         editor.orgVisibility = editor.getElement().style.visibility;
  27281.         editor.getElement().style.visibility = 'hidden';
  27282.       } else {
  27283.         editor.inline = true;
  27284.       }
  27285.       var form = editor.getElement().form || DOM$3.getParent(id, 'form');
  27286.       if (form) {
  27287.         editor.formElement = form;
  27288.         if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
  27289.           DOM$3.insertAfter(DOM$3.create('input', {
  27290.             type: 'hidden',
  27291.             name: id
  27292.           }), id);
  27293.           editor.hasHiddenInput = true;
  27294.         }
  27295.         editor.formEventDelegate = function (e) {
  27296.           editor.fire(e.type, e);
  27297.         };
  27298.         DOM$3.bind(form, 'submit reset', editor.formEventDelegate);
  27299.         editor.on('reset', function () {
  27300.           editor.resetContent();
  27301.         });
  27302.         if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  27303.           form._mceOldSubmit = form.submit;
  27304.           form.submit = function () {
  27305.             editor.editorManager.triggerSave();
  27306.             editor.setDirty(false);
  27307.             return form._mceOldSubmit(form);
  27308.           };
  27309.         }
  27310.       }
  27311.       editor.windowManager = WindowManager(editor);
  27312.       editor.notificationManager = NotificationManager(editor);
  27313.       if (isEncodingXml(editor)) {
  27314.         editor.on('GetContent', function (e) {
  27315.           if (e.save) {
  27316.             e.content = DOM$3.encode(e.content);
  27317.           }
  27318.         });
  27319.       }
  27320.       if (shouldAddFormSubmitTrigger(editor)) {
  27321.         editor.on('submit', function () {
  27322.           if (editor.initialized) {
  27323.             editor.save();
  27324.           }
  27325.         });
  27326.       }
  27327.       if (shouldAddUnloadTrigger(editor)) {
  27328.         editor._beforeUnload = function () {
  27329.           if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
  27330.             editor.save({
  27331.               format: 'raw',
  27332.               no_events: true,
  27333.               set_dirty: false
  27334.             });
  27335.           }
  27336.         };
  27337.         editor.editorManager.on('BeforeUnload', editor._beforeUnload);
  27338.       }
  27339.       editor.editorManager.add(editor);
  27340.       loadScripts(editor, editor.suffix);
  27341.     };
  27342.  
  27343.     var addVisual = function (editor, elm) {
  27344.       return addVisual$1(editor, elm);
  27345.     };
  27346.  
  27347.     var legacyPropNames = {
  27348.       'font-size': 'size',
  27349.       'font-family': 'face'
  27350.     };
  27351.     var getSpecifiedFontProp = function (propName, rootElm, elm) {
  27352.       var getProperty = function (elm) {
  27353.         return getRaw(elm, propName).orThunk(function () {
  27354.           if (name(elm) === 'font') {
  27355.             return get$9(legacyPropNames, propName).bind(function (legacyPropName) {
  27356.               return getOpt(elm, legacyPropName);
  27357.             });
  27358.           } else {
  27359.             return Optional.none();
  27360.           }
  27361.         });
  27362.       };
  27363.       var isRoot = function (elm) {
  27364.         return eq(SugarElement.fromDom(rootElm), elm);
  27365.       };
  27366.       return closest$1(SugarElement.fromDom(elm), function (elm) {
  27367.         return getProperty(elm);
  27368.       }, isRoot);
  27369.     };
  27370.     var normalizeFontFamily = function (fontFamily) {
  27371.       return fontFamily.replace(/[\'\"\\]/g, '').replace(/,\s+/g, ',');
  27372.     };
  27373.     var getComputedFontProp = function (propName, elm) {
  27374.       return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
  27375.     };
  27376.     var getFontProp = function (propName) {
  27377.       return function (rootElm, elm) {
  27378.         return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function (element) {
  27379.           return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
  27380.         }).getOr('');
  27381.       };
  27382.     };
  27383.     var getFontSize = getFontProp('font-size');
  27384.     var getFontFamily = compose(normalizeFontFamily, getFontProp('font-family'));
  27385.  
  27386.     var findFirstCaretElement = function (editor) {
  27387.       return firstPositionIn(editor.getBody()).map(function (caret) {
  27388.         var container = caret.container();
  27389.         return isText$7(container) ? container.parentNode : container;
  27390.       });
  27391.     };
  27392.     var getCaretElement = function (editor) {
  27393.       return Optional.from(editor.selection.getRng()).bind(function (rng) {
  27394.         var root = editor.getBody();
  27395.         var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
  27396.         return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
  27397.       });
  27398.     };
  27399.     var bindRange = function (editor, binder) {
  27400.       return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
  27401.     };
  27402.     var mapRange = function (editor, mapper) {
  27403.       return bindRange(editor, compose1(Optional.some, mapper));
  27404.     };
  27405.  
  27406.     var fromFontSizeNumber = function (editor, value) {
  27407.       if (/^[0-9.]+$/.test(value)) {
  27408.         var fontSizeNumber = parseInt(value, 10);
  27409.         if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
  27410.           var fontSizes = getFontStyleValues(editor);
  27411.           var fontClasses = getFontSizeClasses(editor);
  27412.           if (fontClasses) {
  27413.             return fontClasses[fontSizeNumber - 1] || value;
  27414.           } else {
  27415.             return fontSizes[fontSizeNumber - 1] || value;
  27416.           }
  27417.         } else {
  27418.           return value;
  27419.         }
  27420.       } else {
  27421.         return value;
  27422.       }
  27423.     };
  27424.     var normalizeFontNames = function (font) {
  27425.       var fonts = font.split(/\s*,\s*/);
  27426.       return map$3(fonts, function (font) {
  27427.         if (font.indexOf(' ') !== -1 && !(startsWith(font, '"') || startsWith(font, '\''))) {
  27428.           return '\'' + font + '\'';
  27429.         } else {
  27430.           return font;
  27431.         }
  27432.       }).join(',');
  27433.     };
  27434.     var fontNameAction = function (editor, value) {
  27435.       var font = fromFontSizeNumber(editor, value);
  27436.       editor.formatter.toggle('fontname', { value: normalizeFontNames(font) });
  27437.       editor.nodeChanged();
  27438.     };
  27439.     var fontNameQuery = function (editor) {
  27440.       return mapRange(editor, function (elm) {
  27441.         return getFontFamily(editor.getBody(), elm.dom);
  27442.       }).getOr('');
  27443.     };
  27444.     var fontSizeAction = function (editor, value) {
  27445.       editor.formatter.toggle('fontsize', { value: fromFontSizeNumber(editor, value) });
  27446.       editor.nodeChanged();
  27447.     };
  27448.     var fontSizeQuery = function (editor) {
  27449.       return mapRange(editor, function (elm) {
  27450.         return getFontSize(editor.getBody(), elm.dom);
  27451.       }).getOr('');
  27452.     };
  27453.  
  27454.     var lineHeightQuery = function (editor) {
  27455.       return mapRange(editor, function (elm) {
  27456.         var root = SugarElement.fromDom(editor.getBody());
  27457.         var specifiedStyle = closest$1(elm, function (elm) {
  27458.           return getRaw(elm, 'line-height');
  27459.         }, curry(eq, root));
  27460.         var computedStyle = function () {
  27461.           var lineHeight = parseFloat(get$5(elm, 'line-height'));
  27462.           var fontSize = parseFloat(get$5(elm, 'font-size'));
  27463.           return String(lineHeight / fontSize);
  27464.         };
  27465.         return specifiedStyle.getOrThunk(computedStyle);
  27466.       }).getOr('');
  27467.     };
  27468.     var lineHeightAction = function (editor, lineHeight) {
  27469.       editor.formatter.toggle('lineheight', { value: String(lineHeight) });
  27470.       editor.nodeChanged();
  27471.     };
  27472.  
  27473.     var processValue = function (value) {
  27474.       if (typeof value !== 'string') {
  27475.         var details = Tools.extend({
  27476.           paste: value.paste,
  27477.           data: { paste: value.paste }
  27478.         }, value);
  27479.         return {
  27480.           content: value.content,
  27481.           details: details
  27482.         };
  27483.       }
  27484.       return {
  27485.         content: value,
  27486.         details: {}
  27487.       };
  27488.     };
  27489.     var insertAtCaret = function (editor, value) {
  27490.       var result = processValue(value);
  27491.       insertContent(editor, result.content, result.details);
  27492.     };
  27493.  
  27494.     var each$4 = Tools.each;
  27495.     var map = Tools.map, inArray = Tools.inArray;
  27496.     var EditorCommands = function () {
  27497.       function EditorCommands(editor) {
  27498.         this.commands = {
  27499.           state: {},
  27500.           exec: {},
  27501.           value: {}
  27502.         };
  27503.         this.editor = editor;
  27504.         this.setupCommands(editor);
  27505.       }
  27506.       EditorCommands.prototype.execCommand = function (command, ui, value, args) {
  27507.         var func, state = false;
  27508.         var self = this;
  27509.         if (self.editor.removed) {
  27510.           return;
  27511.         }
  27512.         if (command.toLowerCase() !== 'mcefocus') {
  27513.           if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
  27514.             self.editor.focus();
  27515.           } else {
  27516.             restore(self.editor);
  27517.           }
  27518.         }
  27519.         args = self.editor.fire('BeforeExecCommand', {
  27520.           command: command,
  27521.           ui: ui,
  27522.           value: value
  27523.         });
  27524.         if (args.isDefaultPrevented()) {
  27525.           return false;
  27526.         }
  27527.         var customCommand = command.toLowerCase();
  27528.         if (func = self.commands.exec[customCommand]) {
  27529.           func(customCommand, ui, value);
  27530.           self.editor.fire('ExecCommand', {
  27531.             command: command,
  27532.             ui: ui,
  27533.             value: value
  27534.           });
  27535.           return true;
  27536.         }
  27537.         each$4(this.editor.plugins, function (p) {
  27538.           if (p.execCommand && p.execCommand(command, ui, value)) {
  27539.             self.editor.fire('ExecCommand', {
  27540.               command: command,
  27541.               ui: ui,
  27542.               value: value
  27543.             });
  27544.             state = true;
  27545.             return false;
  27546.           }
  27547.         });
  27548.         if (state) {
  27549.           return state;
  27550.         }
  27551.         if (self.editor.theme && self.editor.theme.execCommand && self.editor.theme.execCommand(command, ui, value)) {
  27552.           self.editor.fire('ExecCommand', {
  27553.             command: command,
  27554.             ui: ui,
  27555.             value: value
  27556.           });
  27557.           return true;
  27558.         }
  27559.         try {
  27560.           state = self.editor.getDoc().execCommand(command, ui, value);
  27561.         } catch (ex) {
  27562.         }
  27563.         if (state) {
  27564.           self.editor.fire('ExecCommand', {
  27565.             command: command,
  27566.             ui: ui,
  27567.             value: value
  27568.           });
  27569.           return true;
  27570.         }
  27571.         return false;
  27572.       };
  27573.       EditorCommands.prototype.queryCommandState = function (command) {
  27574.         var func;
  27575.         if (this.editor.quirks.isHidden() || this.editor.removed) {
  27576.           return;
  27577.         }
  27578.         command = command.toLowerCase();
  27579.         if (func = this.commands.state[command]) {
  27580.           return func(command);
  27581.         }
  27582.         try {
  27583.           return this.editor.getDoc().queryCommandState(command);
  27584.         } catch (ex) {
  27585.         }
  27586.         return false;
  27587.       };
  27588.       EditorCommands.prototype.queryCommandValue = function (command) {
  27589.         var func;
  27590.         if (this.editor.quirks.isHidden() || this.editor.removed) {
  27591.           return;
  27592.         }
  27593.         command = command.toLowerCase();
  27594.         if (func = this.commands.value[command]) {
  27595.           return func(command);
  27596.         }
  27597.         try {
  27598.           return this.editor.getDoc().queryCommandValue(command);
  27599.         } catch (ex) {
  27600.         }
  27601.       };
  27602.       EditorCommands.prototype.addCommands = function (commandList, type) {
  27603.         if (type === void 0) {
  27604.           type = 'exec';
  27605.         }
  27606.         var self = this;
  27607.         each$4(commandList, function (callback, command) {
  27608.           each$4(command.toLowerCase().split(','), function (command) {
  27609.             self.commands[type][command] = callback;
  27610.           });
  27611.         });
  27612.       };
  27613.       EditorCommands.prototype.addCommand = function (command, callback, scope) {
  27614.         var _this = this;
  27615.         command = command.toLowerCase();
  27616.         this.commands.exec[command] = function (command, ui, value, args) {
  27617.           return callback.call(scope || _this.editor, ui, value, args);
  27618.         };
  27619.       };
  27620.       EditorCommands.prototype.queryCommandSupported = function (command) {
  27621.         command = command.toLowerCase();
  27622.         if (this.commands.exec[command]) {
  27623.           return true;
  27624.         }
  27625.         try {
  27626.           return this.editor.getDoc().queryCommandSupported(command);
  27627.         } catch (ex) {
  27628.         }
  27629.         return false;
  27630.       };
  27631.       EditorCommands.prototype.addQueryStateHandler = function (command, callback, scope) {
  27632.         var _this = this;
  27633.         command = command.toLowerCase();
  27634.         this.commands.state[command] = function () {
  27635.           return callback.call(scope || _this.editor);
  27636.         };
  27637.       };
  27638.       EditorCommands.prototype.addQueryValueHandler = function (command, callback, scope) {
  27639.         var _this = this;
  27640.         command = command.toLowerCase();
  27641.         this.commands.value[command] = function () {
  27642.           return callback.call(scope || _this.editor);
  27643.         };
  27644.       };
  27645.       EditorCommands.prototype.hasCustomCommand = function (command) {
  27646.         command = command.toLowerCase();
  27647.         return !!this.commands.exec[command];
  27648.       };
  27649.       EditorCommands.prototype.execNativeCommand = function (command, ui, value) {
  27650.         if (ui === undefined) {
  27651.           ui = false;
  27652.         }
  27653.         if (value === undefined) {
  27654.           value = null;
  27655.         }
  27656.         return this.editor.getDoc().execCommand(command, ui, value);
  27657.       };
  27658.       EditorCommands.prototype.isFormatMatch = function (name) {
  27659.         return this.editor.formatter.match(name);
  27660.       };
  27661.       EditorCommands.prototype.toggleFormat = function (name, value) {
  27662.         this.editor.formatter.toggle(name, value);
  27663.         this.editor.nodeChanged();
  27664.       };
  27665.       EditorCommands.prototype.storeSelection = function (type) {
  27666.         this.selectionBookmark = this.editor.selection.getBookmark(type);
  27667.       };
  27668.       EditorCommands.prototype.restoreSelection = function () {
  27669.         this.editor.selection.moveToBookmark(this.selectionBookmark);
  27670.       };
  27671.       EditorCommands.prototype.setupCommands = function (editor) {
  27672.         var self = this;
  27673.         this.addCommands({
  27674.           'mceResetDesignMode,mceBeginUndoLevel': noop,
  27675.           'mceEndUndoLevel,mceAddUndoLevel': function () {
  27676.             editor.undoManager.add();
  27677.           },
  27678.           'mceFocus': function (_command, _ui, value) {
  27679.             focus(editor, value);
  27680.           },
  27681.           'Cut,Copy,Paste': function (command) {
  27682.             var doc = editor.getDoc();
  27683.             var failed;
  27684.             try {
  27685.               self.execNativeCommand(command);
  27686.             } catch (ex) {
  27687.               failed = true;
  27688.             }
  27689.             if (command === 'paste' && !doc.queryCommandEnabled(command)) {
  27690.               failed = true;
  27691.             }
  27692.             if (failed || !doc.queryCommandSupported(command)) {
  27693.               var msg = editor.translate('Your browser doesn\'t support direct access to the clipboard. ' + 'Please use the Ctrl+X/C/V keyboard shortcuts instead.');
  27694.               if (Env.mac) {
  27695.                 msg = msg.replace(/Ctrl\+/g, '\u2318+');
  27696.               }
  27697.               editor.notificationManager.open({
  27698.                 text: msg,
  27699.                 type: 'error'
  27700.               });
  27701.             }
  27702.           },
  27703.           'unlink': function () {
  27704.             if (editor.selection.isCollapsed()) {
  27705.               var elm = editor.dom.getParent(editor.selection.getStart(), 'a');
  27706.               if (elm) {
  27707.                 editor.dom.remove(elm, true);
  27708.               }
  27709.               return;
  27710.             }
  27711.             editor.formatter.remove('link');
  27712.           },
  27713.           'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function (command) {
  27714.             var align = command.substring(7);
  27715.             if (align === 'full') {
  27716.               align = 'justify';
  27717.             }
  27718.             each$4('left,center,right,justify'.split(','), function (name) {
  27719.               if (align !== name) {
  27720.                 editor.formatter.remove('align' + name);
  27721.               }
  27722.             });
  27723.             if (align !== 'none') {
  27724.               self.toggleFormat('align' + align);
  27725.             }
  27726.           },
  27727.           'InsertUnorderedList,InsertOrderedList': function (command) {
  27728.             var listParent;
  27729.             self.execNativeCommand(command);
  27730.             var listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  27731.             if (listElm) {
  27732.               listParent = listElm.parentNode;
  27733.               if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  27734.                 self.storeSelection();
  27735.                 editor.dom.split(listParent, listElm);
  27736.                 self.restoreSelection();
  27737.               }
  27738.             }
  27739.           },
  27740.           'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27741.             self.toggleFormat(command);
  27742.           },
  27743.           'ForeColor,HiliteColor': function (command, ui, value) {
  27744.             self.toggleFormat(command, { value: value });
  27745.           },
  27746.           'FontName': function (command, ui, value) {
  27747.             fontNameAction(editor, value);
  27748.           },
  27749.           'FontSize': function (command, ui, value) {
  27750.             fontSizeAction(editor, value);
  27751.           },
  27752.           'LineHeight': function (command, ui, value) {
  27753.             lineHeightAction(editor, value);
  27754.           },
  27755.           'Lang': function (command, ui, lang) {
  27756.             self.toggleFormat(command, {
  27757.               value: lang.code,
  27758.               customValue: lang.customCode
  27759.             });
  27760.           },
  27761.           'RemoveFormat': function (command) {
  27762.             editor.formatter.remove(command);
  27763.           },
  27764.           'mceBlockQuote': function () {
  27765.             self.toggleFormat('blockquote');
  27766.           },
  27767.           'FormatBlock': function (command, ui, value) {
  27768.             return self.toggleFormat(value || 'p');
  27769.           },
  27770.           'mceCleanup': function () {
  27771.             var bookmark = editor.selection.getBookmark();
  27772.             editor.setContent(editor.getContent());
  27773.             editor.selection.moveToBookmark(bookmark);
  27774.           },
  27775.           'mceRemoveNode': function (command, ui, value) {
  27776.             var node = value || editor.selection.getNode();
  27777.             if (node !== editor.getBody()) {
  27778.               self.storeSelection();
  27779.               editor.dom.remove(node, true);
  27780.               self.restoreSelection();
  27781.             }
  27782.           },
  27783.           'mceSelectNodeDepth': function (command, ui, value) {
  27784.             var counter = 0;
  27785.             editor.dom.getParent(editor.selection.getNode(), function (node) {
  27786.               if (node.nodeType === 1 && counter++ === value) {
  27787.                 editor.selection.select(node);
  27788.                 return false;
  27789.               }
  27790.             }, editor.getBody());
  27791.           },
  27792.           'mceSelectNode': function (command, ui, value) {
  27793.             editor.selection.select(value);
  27794.           },
  27795.           'mceInsertContent': function (command, ui, value) {
  27796.             insertAtCaret(editor, value);
  27797.           },
  27798.           'mceInsertRawHTML': function (command, ui, value) {
  27799.             editor.selection.setContent('tiny_mce_marker');
  27800.             var content = editor.getContent();
  27801.             editor.setContent(content.replace(/tiny_mce_marker/g, function () {
  27802.               return value;
  27803.             }));
  27804.           },
  27805.           'mceInsertNewLine': function (command, ui, value) {
  27806.             insert(editor, value);
  27807.           },
  27808.           'mceToggleFormat': function (command, ui, value) {
  27809.             self.toggleFormat(value);
  27810.           },
  27811.           'mceSetContent': function (command, ui, value) {
  27812.             editor.setContent(value);
  27813.           },
  27814.           'Indent,Outdent': function (command) {
  27815.             handle(editor, command);
  27816.           },
  27817.           'mceRepaint': noop,
  27818.           'InsertHorizontalRule': function () {
  27819.             editor.execCommand('mceInsertContent', false, '<hr />');
  27820.           },
  27821.           'mceToggleVisualAid': function () {
  27822.             editor.hasVisual = !editor.hasVisual;
  27823.             editor.addVisual();
  27824.           },
  27825.           'mceReplaceContent': function (command, ui, value) {
  27826.             editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, editor.selection.getContent({ format: 'text' })));
  27827.           },
  27828.           'mceInsertLink': function (command, ui, value) {
  27829.             if (typeof value === 'string') {
  27830.               value = { href: value };
  27831.             }
  27832.             var anchor = editor.dom.getParent(editor.selection.getNode(), 'a');
  27833.             value.href = value.href.replace(/ /g, '%20');
  27834.             if (!anchor || !value.href) {
  27835.               editor.formatter.remove('link');
  27836.             }
  27837.             if (value.href) {
  27838.               editor.formatter.apply('link', value, anchor);
  27839.             }
  27840.           },
  27841.           'selectAll': function () {
  27842.             var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
  27843.             if (editingHost) {
  27844.               var rng = editor.dom.createRng();
  27845.               rng.selectNodeContents(editingHost);
  27846.               editor.selection.setRng(rng);
  27847.             }
  27848.           },
  27849.           'mceNewDocument': function () {
  27850.             editor.setContent('');
  27851.           },
  27852.           'InsertLineBreak': function (command, ui, value) {
  27853.             insert$1(editor, value);
  27854.             return true;
  27855.           }
  27856.         });
  27857.         var alignStates = function (name) {
  27858.           return function () {
  27859.             var selection = editor.selection;
  27860.             var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
  27861.             var matches = map(nodes, function (node) {
  27862.               return !!editor.formatter.matchNode(node, name);
  27863.             });
  27864.             return inArray(matches, true) !== -1;
  27865.           };
  27866.         };
  27867.         self.addCommands({
  27868.           'JustifyLeft': alignStates('alignleft'),
  27869.           'JustifyCenter': alignStates('aligncenter'),
  27870.           'JustifyRight': alignStates('alignright'),
  27871.           'JustifyFull': alignStates('alignjustify'),
  27872.           'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function (command) {
  27873.             return self.isFormatMatch(command);
  27874.           },
  27875.           'mceBlockQuote': function () {
  27876.             return self.isFormatMatch('blockquote');
  27877.           },
  27878.           'Outdent': function () {
  27879.             return canOutdent(editor);
  27880.           },
  27881.           'InsertUnorderedList,InsertOrderedList': function (command) {
  27882.             var list = editor.dom.getParent(editor.selection.getNode(), 'ul,ol');
  27883.             return list && (command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL');
  27884.           }
  27885.         }, 'state');
  27886.         self.addCommands({
  27887.           Undo: function () {
  27888.             editor.undoManager.undo();
  27889.           },
  27890.           Redo: function () {
  27891.             editor.undoManager.redo();
  27892.           }
  27893.         });
  27894.         self.addQueryValueHandler('FontName', function () {
  27895.           return fontNameQuery(editor);
  27896.         }, this);
  27897.         self.addQueryValueHandler('FontSize', function () {
  27898.           return fontSizeQuery(editor);
  27899.         }, this);
  27900.         self.addQueryValueHandler('LineHeight', function () {
  27901.           return lineHeightQuery(editor);
  27902.         }, this);
  27903.       };
  27904.       return EditorCommands;
  27905.     }();
  27906.  
  27907.     var internalContentEditableAttr = 'data-mce-contenteditable';
  27908.     var toggleClass = function (elm, cls, state) {
  27909.       if (has(elm, cls) && state === false) {
  27910.         remove$3(elm, cls);
  27911.       } else if (state) {
  27912.         add$1(elm, cls);
  27913.       }
  27914.     };
  27915.     var setEditorCommandState = function (editor, cmd, state) {
  27916.       try {
  27917.         editor.getDoc().execCommand(cmd, false, String(state));
  27918.       } catch (ex) {
  27919.       }
  27920.     };
  27921.     var setContentEditable = function (elm, state) {
  27922.       elm.dom.contentEditable = state ? 'true' : 'false';
  27923.     };
  27924.     var switchOffContentEditableTrue = function (elm) {
  27925.       each$k(descendants(elm, '*[contenteditable="true"]'), function (elm) {
  27926.         set$1(elm, internalContentEditableAttr, 'true');
  27927.         setContentEditable(elm, false);
  27928.       });
  27929.     };
  27930.     var switchOnContentEditableTrue = function (elm) {
  27931.       each$k(descendants(elm, '*[' + internalContentEditableAttr + '="true"]'), function (elm) {
  27932.         remove$6(elm, internalContentEditableAttr);
  27933.         setContentEditable(elm, true);
  27934.       });
  27935.     };
  27936.     var removeFakeSelection = function (editor) {
  27937.       Optional.from(editor.selection.getNode()).each(function (elm) {
  27938.         elm.removeAttribute('data-mce-selected');
  27939.       });
  27940.     };
  27941.     var restoreFakeSelection = function (editor) {
  27942.       editor.selection.setRng(editor.selection.getRng());
  27943.     };
  27944.     var toggleReadOnly = function (editor, state) {
  27945.       var body = SugarElement.fromDom(editor.getBody());
  27946.       toggleClass(body, 'mce-content-readonly', state);
  27947.       if (state) {
  27948.         editor.selection.controlSelection.hideResizeRect();
  27949.         editor._selectionOverrides.hideFakeCaret();
  27950.         removeFakeSelection(editor);
  27951.         editor.readonly = true;
  27952.         setContentEditable(body, false);
  27953.         switchOffContentEditableTrue(body);
  27954.       } else {
  27955.         editor.readonly = false;
  27956.         setContentEditable(body, true);
  27957.         switchOnContentEditableTrue(body);
  27958.         setEditorCommandState(editor, 'StyleWithCSS', false);
  27959.         setEditorCommandState(editor, 'enableInlineTableEditing', false);
  27960.         setEditorCommandState(editor, 'enableObjectResizing', false);
  27961.         if (hasEditorOrUiFocus(editor)) {
  27962.           editor.focus();
  27963.         }
  27964.         restoreFakeSelection(editor);
  27965.         editor.nodeChanged();
  27966.       }
  27967.     };
  27968.     var isReadOnly = function (editor) {
  27969.       return editor.readonly;
  27970.     };
  27971.     var registerFilters = function (editor) {
  27972.       editor.parser.addAttributeFilter('contenteditable', function (nodes) {
  27973.         if (isReadOnly(editor)) {
  27974.           each$k(nodes, function (node) {
  27975.             node.attr(internalContentEditableAttr, node.attr('contenteditable'));
  27976.             node.attr('contenteditable', 'false');
  27977.           });
  27978.         }
  27979.       });
  27980.       editor.serializer.addAttributeFilter(internalContentEditableAttr, function (nodes) {
  27981.         if (isReadOnly(editor)) {
  27982.           each$k(nodes, function (node) {
  27983.             node.attr('contenteditable', node.attr(internalContentEditableAttr));
  27984.           });
  27985.         }
  27986.       });
  27987.       editor.serializer.addTempAttr(internalContentEditableAttr);
  27988.     };
  27989.     var registerReadOnlyContentFilters = function (editor) {
  27990.       if (editor.serializer) {
  27991.         registerFilters(editor);
  27992.       } else {
  27993.         editor.on('PreInit', function () {
  27994.           registerFilters(editor);
  27995.         });
  27996.       }
  27997.     };
  27998.     var isClickEvent = function (e) {
  27999.       return e.type === 'click';
  28000.     };
  28001.     var getAnchorHrefOpt = function (editor, elm) {
  28002.       var isRoot = function (elm) {
  28003.         return eq(elm, SugarElement.fromDom(editor.getBody()));
  28004.       };
  28005.       return closest$2(elm, 'a', isRoot).bind(function (a) {
  28006.         return getOpt(a, 'href');
  28007.       });
  28008.     };
  28009.     var processReadonlyEvents = function (editor, e) {
  28010.       if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
  28011.         var elm = SugarElement.fromDom(e.target);
  28012.         getAnchorHrefOpt(editor, elm).each(function (href) {
  28013.           e.preventDefault();
  28014.           if (/^#/.test(href)) {
  28015.             var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, '#') + '"]');
  28016.             if (targetEl.length) {
  28017.               editor.selection.scrollIntoView(targetEl[0], true);
  28018.             }
  28019.           } else {
  28020.             window.open(href, '_blank', 'rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes');
  28021.           }
  28022.         });
  28023.       }
  28024.     };
  28025.     var registerReadOnlySelectionBlockers = function (editor) {
  28026.       editor.on('ShowCaret', function (e) {
  28027.         if (isReadOnly(editor)) {
  28028.           e.preventDefault();
  28029.         }
  28030.       });
  28031.       editor.on('ObjectSelected', function (e) {
  28032.         if (isReadOnly(editor)) {
  28033.           e.preventDefault();
  28034.         }
  28035.       });
  28036.     };
  28037.  
  28038.     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', ' ');
  28039.     var EventDispatcher = function () {
  28040.       function EventDispatcher(settings) {
  28041.         this.bindings = {};
  28042.         this.settings = settings || {};
  28043.         this.scope = this.settings.scope || this;
  28044.         this.toggleEvent = this.settings.toggleEvent || never;
  28045.       }
  28046.       EventDispatcher.isNative = function (name) {
  28047.         return !!nativeEvents[name.toLowerCase()];
  28048.       };
  28049.       EventDispatcher.prototype.fire = function (name, args) {
  28050.         var lcName = name.toLowerCase();
  28051.         var event = normalize$3(lcName, args || {}, this.scope);
  28052.         if (this.settings.beforeFire) {
  28053.           this.settings.beforeFire(event);
  28054.         }
  28055.         var handlers = this.bindings[lcName];
  28056.         if (handlers) {
  28057.           for (var i = 0, l = handlers.length; i < l; i++) {
  28058.             var callback = handlers[i];
  28059.             if (callback.removed) {
  28060.               continue;
  28061.             }
  28062.             if (callback.once) {
  28063.               this.off(lcName, callback.func);
  28064.             }
  28065.             if (event.isImmediatePropagationStopped()) {
  28066.               return event;
  28067.             }
  28068.             if (callback.func.call(this.scope, event) === false) {
  28069.               event.preventDefault();
  28070.               return event;
  28071.             }
  28072.           }
  28073.         }
  28074.         return event;
  28075.       };
  28076.       EventDispatcher.prototype.on = function (name, callback, prepend, extra) {
  28077.         if (callback === false) {
  28078.           callback = never;
  28079.         }
  28080.         if (callback) {
  28081.           var wrappedCallback = {
  28082.             func: callback,
  28083.             removed: false
  28084.           };
  28085.           if (extra) {
  28086.             Tools.extend(wrappedCallback, extra);
  28087.           }
  28088.           var names = name.toLowerCase().split(' ');
  28089.           var i = names.length;
  28090.           while (i--) {
  28091.             var currentName = names[i];
  28092.             var handlers = this.bindings[currentName];
  28093.             if (!handlers) {
  28094.               handlers = [];
  28095.               this.toggleEvent(currentName, true);
  28096.             }
  28097.             if (prepend) {
  28098.               handlers = __spreadArray([wrappedCallback], handlers, true);
  28099.             } else {
  28100.               handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
  28101.             }
  28102.             this.bindings[currentName] = handlers;
  28103.           }
  28104.         }
  28105.         return this;
  28106.       };
  28107.       EventDispatcher.prototype.off = function (name, callback) {
  28108.         var _this = this;
  28109.         if (name) {
  28110.           var names = name.toLowerCase().split(' ');
  28111.           var i = names.length;
  28112.           while (i--) {
  28113.             var currentName = names[i];
  28114.             var handlers = this.bindings[currentName];
  28115.             if (!currentName) {
  28116.               each$j(this.bindings, function (_value, bindingName) {
  28117.                 _this.toggleEvent(bindingName, false);
  28118.                 delete _this.bindings[bindingName];
  28119.               });
  28120.               return this;
  28121.             }
  28122.             if (handlers) {
  28123.               if (!callback) {
  28124.                 handlers.length = 0;
  28125.               } else {
  28126.                 var filteredHandlers = partition(handlers, function (handler) {
  28127.                   return handler.func === callback;
  28128.                 });
  28129.                 handlers = filteredHandlers.fail;
  28130.                 this.bindings[currentName] = handlers;
  28131.                 each$k(filteredHandlers.pass, function (handler) {
  28132.                   handler.removed = true;
  28133.                 });
  28134.               }
  28135.               if (!handlers.length) {
  28136.                 this.toggleEvent(name, false);
  28137.                 delete this.bindings[currentName];
  28138.               }
  28139.             }
  28140.           }
  28141.         } else {
  28142.           each$j(this.bindings, function (_value, name) {
  28143.             _this.toggleEvent(name, false);
  28144.           });
  28145.           this.bindings = {};
  28146.         }
  28147.         return this;
  28148.       };
  28149.       EventDispatcher.prototype.once = function (name, callback, prepend) {
  28150.         return this.on(name, callback, prepend, { once: true });
  28151.       };
  28152.       EventDispatcher.prototype.has = function (name) {
  28153.         name = name.toLowerCase();
  28154.         return !(!this.bindings[name] || this.bindings[name].length === 0);
  28155.       };
  28156.       return EventDispatcher;
  28157.     }();
  28158.  
  28159.     var getEventDispatcher = function (obj) {
  28160.       if (!obj._eventDispatcher) {
  28161.         obj._eventDispatcher = new EventDispatcher({
  28162.           scope: obj,
  28163.           toggleEvent: function (name, state) {
  28164.             if (EventDispatcher.isNative(name) && obj.toggleNativeEvent) {
  28165.               obj.toggleNativeEvent(name, state);
  28166.             }
  28167.           }
  28168.         });
  28169.       }
  28170.       return obj._eventDispatcher;
  28171.     };
  28172.     var Observable = {
  28173.       fire: function (name, args, bubble) {
  28174.         var self = this;
  28175.         if (self.removed && name !== 'remove' && name !== 'detach') {
  28176.           return args;
  28177.         }
  28178.         var dispatcherArgs = getEventDispatcher(self).fire(name, args);
  28179.         if (bubble !== false && self.parent) {
  28180.           var parent_1 = self.parent();
  28181.           while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
  28182.             parent_1.fire(name, dispatcherArgs, false);
  28183.             parent_1 = parent_1.parent();
  28184.           }
  28185.         }
  28186.         return dispatcherArgs;
  28187.       },
  28188.       on: function (name, callback, prepend) {
  28189.         return getEventDispatcher(this).on(name, callback, prepend);
  28190.       },
  28191.       off: function (name, callback) {
  28192.         return getEventDispatcher(this).off(name, callback);
  28193.       },
  28194.       once: function (name, callback) {
  28195.         return getEventDispatcher(this).once(name, callback);
  28196.       },
  28197.       hasEventListeners: function (name) {
  28198.         return getEventDispatcher(this).has(name);
  28199.       }
  28200.     };
  28201.  
  28202.     var DOM$2 = DOMUtils.DOM;
  28203.     var customEventRootDelegates;
  28204.     var getEventTarget = function (editor, eventName) {
  28205.       if (eventName === 'selectionchange') {
  28206.         return editor.getDoc();
  28207.       }
  28208.       if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
  28209.         return editor.getDoc().documentElement;
  28210.       }
  28211.       var eventRoot = getEventRoot(editor);
  28212.       if (eventRoot) {
  28213.         if (!editor.eventRoot) {
  28214.           editor.eventRoot = DOM$2.select(eventRoot)[0];
  28215.         }
  28216.         return editor.eventRoot;
  28217.       }
  28218.       return editor.getBody();
  28219.     };
  28220.     var isListening = function (editor) {
  28221.       return !editor.hidden && !isReadOnly(editor);
  28222.     };
  28223.     var fireEvent = function (editor, eventName, e) {
  28224.       if (isListening(editor)) {
  28225.         editor.fire(eventName, e);
  28226.       } else if (isReadOnly(editor)) {
  28227.         processReadonlyEvents(editor, e);
  28228.       }
  28229.     };
  28230.     var bindEventDelegate = function (editor, eventName) {
  28231.       var delegate;
  28232.       if (!editor.delegates) {
  28233.         editor.delegates = {};
  28234.       }
  28235.       if (editor.delegates[eventName] || editor.removed) {
  28236.         return;
  28237.       }
  28238.       var eventRootElm = getEventTarget(editor, eventName);
  28239.       if (getEventRoot(editor)) {
  28240.         if (!customEventRootDelegates) {
  28241.           customEventRootDelegates = {};
  28242.           editor.editorManager.on('removeEditor', function () {
  28243.             if (!editor.editorManager.activeEditor) {
  28244.               if (customEventRootDelegates) {
  28245.                 each$j(customEventRootDelegates, function (_value, name) {
  28246.                   editor.dom.unbind(getEventTarget(editor, name));
  28247.                 });
  28248.                 customEventRootDelegates = null;
  28249.               }
  28250.             }
  28251.           });
  28252.         }
  28253.         if (customEventRootDelegates[eventName]) {
  28254.           return;
  28255.         }
  28256.         delegate = function (e) {
  28257.           var target = e.target;
  28258.           var editors = editor.editorManager.get();
  28259.           var i = editors.length;
  28260.           while (i--) {
  28261.             var body = editors[i].getBody();
  28262.             if (body === target || DOM$2.isChildOf(target, body)) {
  28263.               fireEvent(editors[i], eventName, e);
  28264.             }
  28265.           }
  28266.         };
  28267.         customEventRootDelegates[eventName] = delegate;
  28268.         DOM$2.bind(eventRootElm, eventName, delegate);
  28269.       } else {
  28270.         delegate = function (e) {
  28271.           fireEvent(editor, eventName, e);
  28272.         };
  28273.         DOM$2.bind(eventRootElm, eventName, delegate);
  28274.         editor.delegates[eventName] = delegate;
  28275.       }
  28276.     };
  28277.     var EditorObservable = __assign(__assign({}, Observable), {
  28278.       bindPendingEventDelegates: function () {
  28279.         var self = this;
  28280.         Tools.each(self._pendingNativeEvents, function (name) {
  28281.           bindEventDelegate(self, name);
  28282.         });
  28283.       },
  28284.       toggleNativeEvent: function (name, state) {
  28285.         var self = this;
  28286.         if (name === 'focus' || name === 'blur') {
  28287.           return;
  28288.         }
  28289.         if (self.removed) {
  28290.           return;
  28291.         }
  28292.         if (state) {
  28293.           if (self.initialized) {
  28294.             bindEventDelegate(self, name);
  28295.           } else {
  28296.             if (!self._pendingNativeEvents) {
  28297.               self._pendingNativeEvents = [name];
  28298.             } else {
  28299.               self._pendingNativeEvents.push(name);
  28300.             }
  28301.           }
  28302.         } else if (self.initialized) {
  28303.           self.dom.unbind(getEventTarget(self, name), name, self.delegates[name]);
  28304.           delete self.delegates[name];
  28305.         }
  28306.       },
  28307.       unbindAllNativeEvents: function () {
  28308.         var self = this;
  28309.         var body = self.getBody();
  28310.         var dom = self.dom;
  28311.         if (self.delegates) {
  28312.           each$j(self.delegates, function (value, name) {
  28313.             self.dom.unbind(getEventTarget(self, name), name, value);
  28314.           });
  28315.           delete self.delegates;
  28316.         }
  28317.         if (!self.inline && body && dom) {
  28318.           body.onload = null;
  28319.           dom.unbind(self.getWin());
  28320.           dom.unbind(self.getDoc());
  28321.         }
  28322.         if (dom) {
  28323.           dom.unbind(body);
  28324.           dom.unbind(self.getContainer());
  28325.         }
  28326.       }
  28327.     });
  28328.  
  28329.     var defaultModes = [
  28330.       'design',
  28331.       'readonly'
  28332.     ];
  28333.     var switchToMode = function (editor, activeMode, availableModes, mode) {
  28334.       var oldMode = availableModes[activeMode.get()];
  28335.       var newMode = availableModes[mode];
  28336.       try {
  28337.         newMode.activate();
  28338.       } catch (e) {
  28339.         console.error('problem while activating editor mode ' + mode + ':', e);
  28340.         return;
  28341.       }
  28342.       oldMode.deactivate();
  28343.       if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
  28344.         toggleReadOnly(editor, newMode.editorReadOnly);
  28345.       }
  28346.       activeMode.set(mode);
  28347.       fireSwitchMode(editor, mode);
  28348.     };
  28349.     var setMode = function (editor, availableModes, activeMode, mode) {
  28350.       if (mode === activeMode.get()) {
  28351.         return;
  28352.       } else if (!has$2(availableModes, mode)) {
  28353.         throw new Error('Editor mode \'' + mode + '\' is invalid');
  28354.       }
  28355.       if (editor.initialized) {
  28356.         switchToMode(editor, activeMode, availableModes, mode);
  28357.       } else {
  28358.         editor.on('init', function () {
  28359.           return switchToMode(editor, activeMode, availableModes, mode);
  28360.         });
  28361.       }
  28362.     };
  28363.     var registerMode = function (availableModes, mode, api) {
  28364.       var _a;
  28365.       if (contains$3(defaultModes, mode)) {
  28366.         throw new Error('Cannot override default mode ' + mode);
  28367.       }
  28368.       return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api), {
  28369.         deactivate: function () {
  28370.           try {
  28371.             api.deactivate();
  28372.           } catch (e) {
  28373.             console.error('problem while deactivating editor mode ' + mode + ':', e);
  28374.           }
  28375.         }
  28376.       }), _a));
  28377.     };
  28378.  
  28379.     var create$4 = function (editor) {
  28380.       var activeMode = Cell('design');
  28381.       var availableModes = Cell({
  28382.         design: {
  28383.           activate: noop,
  28384.           deactivate: noop,
  28385.           editorReadOnly: false
  28386.         },
  28387.         readonly: {
  28388.           activate: noop,
  28389.           deactivate: noop,
  28390.           editorReadOnly: true
  28391.         }
  28392.       });
  28393.       registerReadOnlyContentFilters(editor);
  28394.       registerReadOnlySelectionBlockers(editor);
  28395.       return {
  28396.         isReadOnly: function () {
  28397.           return isReadOnly(editor);
  28398.         },
  28399.         set: function (mode) {
  28400.           return setMode(editor, availableModes.get(), activeMode, mode);
  28401.         },
  28402.         get: function () {
  28403.           return activeMode.get();
  28404.         },
  28405.         register: function (mode, api) {
  28406.           availableModes.set(registerMode(availableModes.get(), mode, api));
  28407.         }
  28408.       };
  28409.     };
  28410.  
  28411.     var each$3 = Tools.each, explode$1 = Tools.explode;
  28412.     var keyCodeLookup = {
  28413.       f1: 112,
  28414.       f2: 113,
  28415.       f3: 114,
  28416.       f4: 115,
  28417.       f5: 116,
  28418.       f6: 117,
  28419.       f7: 118,
  28420.       f8: 119,
  28421.       f9: 120,
  28422.       f10: 121,
  28423.       f11: 122,
  28424.       f12: 123
  28425.     };
  28426.     var modifierNames = Tools.makeMap('alt,ctrl,shift,meta,access');
  28427.     var parseShortcut = function (pattern) {
  28428.       var key;
  28429.       var shortcut = {};
  28430.       each$3(explode$1(pattern.toLowerCase(), '+'), function (value) {
  28431.         if (value in modifierNames) {
  28432.           shortcut[value] = true;
  28433.         } else {
  28434.           if (/^[0-9]{2,}$/.test(value)) {
  28435.             shortcut.keyCode = parseInt(value, 10);
  28436.           } else {
  28437.             shortcut.charCode = value.charCodeAt(0);
  28438.             shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  28439.           }
  28440.         }
  28441.       });
  28442.       var id = [shortcut.keyCode];
  28443.       for (key in modifierNames) {
  28444.         if (shortcut[key]) {
  28445.           id.push(key);
  28446.         } else {
  28447.           shortcut[key] = false;
  28448.         }
  28449.       }
  28450.       shortcut.id = id.join(',');
  28451.       if (shortcut.access) {
  28452.         shortcut.alt = true;
  28453.         if (Env.mac) {
  28454.           shortcut.ctrl = true;
  28455.         } else {
  28456.           shortcut.shift = true;
  28457.         }
  28458.       }
  28459.       if (shortcut.meta) {
  28460.         if (Env.mac) {
  28461.           shortcut.meta = true;
  28462.         } else {
  28463.           shortcut.ctrl = true;
  28464.           shortcut.meta = false;
  28465.         }
  28466.       }
  28467.       return shortcut;
  28468.     };
  28469.     var Shortcuts = function () {
  28470.       function Shortcuts(editor) {
  28471.         this.shortcuts = {};
  28472.         this.pendingPatterns = [];
  28473.         this.editor = editor;
  28474.         var self = this;
  28475.         editor.on('keyup keypress keydown', function (e) {
  28476.           if ((self.hasModifier(e) || self.isFunctionKey(e)) && !e.isDefaultPrevented()) {
  28477.             each$3(self.shortcuts, function (shortcut) {
  28478.               if (self.matchShortcut(e, shortcut)) {
  28479.                 self.pendingPatterns = shortcut.subpatterns.slice(0);
  28480.                 if (e.type === 'keydown') {
  28481.                   self.executeShortcutAction(shortcut);
  28482.                 }
  28483.                 return true;
  28484.               }
  28485.             });
  28486.             if (self.matchShortcut(e, self.pendingPatterns[0])) {
  28487.               if (self.pendingPatterns.length === 1) {
  28488.                 if (e.type === 'keydown') {
  28489.                   self.executeShortcutAction(self.pendingPatterns[0]);
  28490.                 }
  28491.               }
  28492.               self.pendingPatterns.shift();
  28493.             }
  28494.           }
  28495.         });
  28496.       }
  28497.       Shortcuts.prototype.add = function (pattern, desc, cmdFunc, scope) {
  28498.         var self = this;
  28499.         var func = self.normalizeCommandFunc(cmdFunc);
  28500.         each$3(explode$1(Tools.trim(pattern)), function (pattern) {
  28501.           var shortcut = self.createShortcut(pattern, desc, func, scope);
  28502.           self.shortcuts[shortcut.id] = shortcut;
  28503.         });
  28504.         return true;
  28505.       };
  28506.       Shortcuts.prototype.remove = function (pattern) {
  28507.         var shortcut = this.createShortcut(pattern);
  28508.         if (this.shortcuts[shortcut.id]) {
  28509.           delete this.shortcuts[shortcut.id];
  28510.           return true;
  28511.         }
  28512.         return false;
  28513.       };
  28514.       Shortcuts.prototype.normalizeCommandFunc = function (cmdFunc) {
  28515.         var self = this;
  28516.         var cmd = cmdFunc;
  28517.         if (typeof cmd === 'string') {
  28518.           return function () {
  28519.             self.editor.execCommand(cmd, false, null);
  28520.           };
  28521.         } else if (Tools.isArray(cmd)) {
  28522.           return function () {
  28523.             self.editor.execCommand(cmd[0], cmd[1], cmd[2]);
  28524.           };
  28525.         } else {
  28526.           return cmd;
  28527.         }
  28528.       };
  28529.       Shortcuts.prototype.createShortcut = function (pattern, desc, cmdFunc, scope) {
  28530.         var shortcuts = Tools.map(explode$1(pattern, '>'), parseShortcut);
  28531.         shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
  28532.           func: cmdFunc,
  28533.           scope: scope || this.editor
  28534.         });
  28535.         return Tools.extend(shortcuts[0], {
  28536.           desc: this.editor.translate(desc),
  28537.           subpatterns: shortcuts.slice(1)
  28538.         });
  28539.       };
  28540.       Shortcuts.prototype.hasModifier = function (e) {
  28541.         return e.altKey || e.ctrlKey || e.metaKey;
  28542.       };
  28543.       Shortcuts.prototype.isFunctionKey = function (e) {
  28544.         return e.type === 'keydown' && e.keyCode >= 112 && e.keyCode <= 123;
  28545.       };
  28546.       Shortcuts.prototype.matchShortcut = function (e, shortcut) {
  28547.         if (!shortcut) {
  28548.           return false;
  28549.         }
  28550.         if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
  28551.           return false;
  28552.         }
  28553.         if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
  28554.           return false;
  28555.         }
  28556.         if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
  28557.           e.preventDefault();
  28558.           return true;
  28559.         }
  28560.         return false;
  28561.       };
  28562.       Shortcuts.prototype.executeShortcutAction = function (shortcut) {
  28563.         return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
  28564.       };
  28565.       return Shortcuts;
  28566.     }();
  28567.  
  28568.     var create$3 = function () {
  28569.       var buttons = {};
  28570.       var menuItems = {};
  28571.       var popups = {};
  28572.       var icons = {};
  28573.       var contextMenus = {};
  28574.       var contextToolbars = {};
  28575.       var sidebars = {};
  28576.       var add = function (collection, type) {
  28577.         return function (name, spec) {
  28578.           return collection[name.toLowerCase()] = __assign(__assign({}, spec), { type: type });
  28579.         };
  28580.       };
  28581.       var addIcon = function (name, svgData) {
  28582.         return icons[name.toLowerCase()] = svgData;
  28583.       };
  28584.       return {
  28585.         addButton: add(buttons, 'button'),
  28586.         addGroupToolbarButton: add(buttons, 'grouptoolbarbutton'),
  28587.         addToggleButton: add(buttons, 'togglebutton'),
  28588.         addMenuButton: add(buttons, 'menubutton'),
  28589.         addSplitButton: add(buttons, 'splitbutton'),
  28590.         addMenuItem: add(menuItems, 'menuitem'),
  28591.         addNestedMenuItem: add(menuItems, 'nestedmenuitem'),
  28592.         addToggleMenuItem: add(menuItems, 'togglemenuitem'),
  28593.         addAutocompleter: add(popups, 'autocompleter'),
  28594.         addContextMenu: add(contextMenus, 'contextmenu'),
  28595.         addContextToolbar: add(contextToolbars, 'contexttoolbar'),
  28596.         addContextForm: add(contextToolbars, 'contextform'),
  28597.         addSidebar: add(sidebars, 'sidebar'),
  28598.         addIcon: addIcon,
  28599.         getAll: function () {
  28600.           return {
  28601.             buttons: buttons,
  28602.             menuItems: menuItems,
  28603.             icons: icons,
  28604.             popups: popups,
  28605.             contextMenus: contextMenus,
  28606.             contextToolbars: contextToolbars,
  28607.             sidebars: sidebars
  28608.           };
  28609.         }
  28610.       };
  28611.     };
  28612.  
  28613.     var registry = function () {
  28614.       var bridge = create$3();
  28615.       return {
  28616.         addAutocompleter: bridge.addAutocompleter,
  28617.         addButton: bridge.addButton,
  28618.         addContextForm: bridge.addContextForm,
  28619.         addContextMenu: bridge.addContextMenu,
  28620.         addContextToolbar: bridge.addContextToolbar,
  28621.         addIcon: bridge.addIcon,
  28622.         addMenuButton: bridge.addMenuButton,
  28623.         addMenuItem: bridge.addMenuItem,
  28624.         addNestedMenuItem: bridge.addNestedMenuItem,
  28625.         addSidebar: bridge.addSidebar,
  28626.         addSplitButton: bridge.addSplitButton,
  28627.         addToggleButton: bridge.addToggleButton,
  28628.         addGroupToolbarButton: bridge.addGroupToolbarButton,
  28629.         addToggleMenuItem: bridge.addToggleMenuItem,
  28630.         getAll: bridge.getAll
  28631.       };
  28632.     };
  28633.  
  28634.     var DOM$1 = DOMUtils.DOM;
  28635.     var extend$3 = Tools.extend, each$2 = Tools.each;
  28636.     var resolve = Tools.resolve;
  28637.     var ie = Env.ie;
  28638.     var Editor = function () {
  28639.       function Editor(id, settings, editorManager) {
  28640.         var _this = this;
  28641.         this.plugins = {};
  28642.         this.contentCSS = [];
  28643.         this.contentStyles = [];
  28644.         this.loadedCSS = {};
  28645.         this.isNotDirty = false;
  28646.         this.editorManager = editorManager;
  28647.         this.documentBaseUrl = editorManager.documentBaseURL;
  28648.         extend$3(this, EditorObservable);
  28649.         this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
  28650.         if (this.settings.suffix) {
  28651.           editorManager.suffix = this.settings.suffix;
  28652.         }
  28653.         this.suffix = editorManager.suffix;
  28654.         if (this.settings.base_url) {
  28655.           editorManager._setBaseUrl(this.settings.base_url);
  28656.         }
  28657.         this.baseUri = editorManager.baseURI;
  28658.         if (this.settings.referrer_policy) {
  28659.           ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
  28660.           DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
  28661.         }
  28662.         AddOnManager.languageLoad = this.settings.language_load;
  28663.         AddOnManager.baseURL = editorManager.baseURL;
  28664.         this.id = id;
  28665.         this.setDirty(false);
  28666.         this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
  28667.         this.baseURI = this.baseUri;
  28668.         this.inline = !!this.settings.inline;
  28669.         this.shortcuts = new Shortcuts(this);
  28670.         this.editorCommands = new EditorCommands(this);
  28671.         if (this.settings.cache_suffix) {
  28672.           Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, '');
  28673.         }
  28674.         this.ui = {
  28675.           registry: registry(),
  28676.           styleSheetLoader: undefined,
  28677.           show: noop,
  28678.           hide: noop,
  28679.           enable: noop,
  28680.           disable: noop,
  28681.           isDisabled: never
  28682.         };
  28683.         var self = this;
  28684.         var modeInstance = create$4(self);
  28685.         this.mode = modeInstance;
  28686.         this.setMode = modeInstance.set;
  28687.         editorManager.fire('SetupEditor', { editor: this });
  28688.         this.execCallback('setup', this);
  28689.         this.$ = DomQuery.overrideDefaults(function () {
  28690.           return {
  28691.             context: _this.inline ? _this.getBody() : _this.getDoc(),
  28692.             element: _this.getBody()
  28693.           };
  28694.         });
  28695.       }
  28696.       Editor.prototype.render = function () {
  28697.         render(this);
  28698.       };
  28699.       Editor.prototype.focus = function (skipFocus) {
  28700.         this.execCommand('mceFocus', false, skipFocus);
  28701.       };
  28702.       Editor.prototype.hasFocus = function () {
  28703.         return hasFocus(this);
  28704.       };
  28705.       Editor.prototype.execCallback = function (name) {
  28706.         var x = [];
  28707.         for (var _i = 1; _i < arguments.length; _i++) {
  28708.           x[_i - 1] = arguments[_i];
  28709.         }
  28710.         var self = this;
  28711.         var callback = self.settings[name], scope;
  28712.         if (!callback) {
  28713.           return;
  28714.         }
  28715.         if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  28716.           callback = scope.func;
  28717.           scope = scope.scope;
  28718.         }
  28719.         if (typeof callback === 'string') {
  28720.           scope = callback.replace(/\.\w+$/, '');
  28721.           scope = scope ? resolve(scope) : 0;
  28722.           callback = resolve(callback);
  28723.           self.callbackLookup = self.callbackLookup || {};
  28724.           self.callbackLookup[name] = {
  28725.             func: callback,
  28726.             scope: scope
  28727.           };
  28728.         }
  28729.         return callback.apply(scope || self, x);
  28730.       };
  28731.       Editor.prototype.translate = function (text) {
  28732.         return I18n.translate(text);
  28733.       };
  28734.       Editor.prototype.getParam = function (name, defaultVal, type) {
  28735.         return getParam(this, name, defaultVal, type);
  28736.       };
  28737.       Editor.prototype.hasPlugin = function (name, loaded) {
  28738.         var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name);
  28739.         if (hasPlugin) {
  28740.           return loaded ? PluginManager.get(name) !== undefined : true;
  28741.         } else {
  28742.           return false;
  28743.         }
  28744.       };
  28745.       Editor.prototype.nodeChanged = function (args) {
  28746.         this._nodeChangeDispatcher.nodeChanged(args);
  28747.       };
  28748.       Editor.prototype.addCommand = function (name, callback, scope) {
  28749.         this.editorCommands.addCommand(name, callback, scope);
  28750.       };
  28751.       Editor.prototype.addQueryStateHandler = function (name, callback, scope) {
  28752.         this.editorCommands.addQueryStateHandler(name, callback, scope);
  28753.       };
  28754.       Editor.prototype.addQueryValueHandler = function (name, callback, scope) {
  28755.         this.editorCommands.addQueryValueHandler(name, callback, scope);
  28756.       };
  28757.       Editor.prototype.addShortcut = function (pattern, desc, cmdFunc, scope) {
  28758.         this.shortcuts.add(pattern, desc, cmdFunc, scope);
  28759.       };
  28760.       Editor.prototype.execCommand = function (cmd, ui, value, args) {
  28761.         return this.editorCommands.execCommand(cmd, ui, value, args);
  28762.       };
  28763.       Editor.prototype.queryCommandState = function (cmd) {
  28764.         return this.editorCommands.queryCommandState(cmd);
  28765.       };
  28766.       Editor.prototype.queryCommandValue = function (cmd) {
  28767.         return this.editorCommands.queryCommandValue(cmd);
  28768.       };
  28769.       Editor.prototype.queryCommandSupported = function (cmd) {
  28770.         return this.editorCommands.queryCommandSupported(cmd);
  28771.       };
  28772.       Editor.prototype.show = function () {
  28773.         var self = this;
  28774.         if (self.hidden) {
  28775.           self.hidden = false;
  28776.           if (self.inline) {
  28777.             self.getBody().contentEditable = 'true';
  28778.           } else {
  28779.             DOM$1.show(self.getContainer());
  28780.             DOM$1.hide(self.id);
  28781.           }
  28782.           self.load();
  28783.           self.fire('show');
  28784.         }
  28785.       };
  28786.       Editor.prototype.hide = function () {
  28787.         var self = this, doc = self.getDoc();
  28788.         if (!self.hidden) {
  28789.           if (ie && doc && !self.inline) {
  28790.             doc.execCommand('SelectAll');
  28791.           }
  28792.           self.save();
  28793.           if (self.inline) {
  28794.             self.getBody().contentEditable = 'false';
  28795.             if (self === self.editorManager.focusedEditor) {
  28796.               self.editorManager.focusedEditor = null;
  28797.             }
  28798.           } else {
  28799.             DOM$1.hide(self.getContainer());
  28800.             DOM$1.setStyle(self.id, 'display', self.orgDisplay);
  28801.           }
  28802.           self.hidden = true;
  28803.           self.fire('hide');
  28804.         }
  28805.       };
  28806.       Editor.prototype.isHidden = function () {
  28807.         return !!this.hidden;
  28808.       };
  28809.       Editor.prototype.setProgressState = function (state, time) {
  28810.         this.fire('ProgressState', {
  28811.           state: state,
  28812.           time: time
  28813.         });
  28814.       };
  28815.       Editor.prototype.load = function (args) {
  28816.         var self = this;
  28817.         var elm = self.getElement(), html;
  28818.         if (self.removed) {
  28819.           return '';
  28820.         }
  28821.         if (elm) {
  28822.           args = args || {};
  28823.           args.load = true;
  28824.           var value = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
  28825.           html = self.setContent(value, args);
  28826.           args.element = elm;
  28827.           if (!args.no_events) {
  28828.             self.fire('LoadContent', args);
  28829.           }
  28830.           args.element = elm = null;
  28831.           return html;
  28832.         }
  28833.       };
  28834.       Editor.prototype.save = function (args) {
  28835.         var self = this;
  28836.         var elm = self.getElement(), html, form;
  28837.         if (!elm || !self.initialized || self.removed) {
  28838.           return;
  28839.         }
  28840.         args = args || {};
  28841.         args.save = true;
  28842.         args.element = elm;
  28843.         html = args.content = self.getContent(args);
  28844.         if (!args.no_events) {
  28845.           self.fire('SaveContent', args);
  28846.         }
  28847.         if (args.format === 'raw') {
  28848.           self.fire('RawSaveContent', args);
  28849.         }
  28850.         html = args.content;
  28851.         if (!isTextareaOrInput(elm)) {
  28852.           if (args.is_removing || !self.inline) {
  28853.             elm.innerHTML = html;
  28854.           }
  28855.           if (form = DOM$1.getParent(self.id, 'form')) {
  28856.             each$2(form.elements, function (elm) {
  28857.               if (elm.name === self.id) {
  28858.                 elm.value = html;
  28859.                 return false;
  28860.               }
  28861.             });
  28862.           }
  28863.         } else {
  28864.           elm.value = html;
  28865.         }
  28866.         args.element = elm = null;
  28867.         if (args.set_dirty !== false) {
  28868.           self.setDirty(false);
  28869.         }
  28870.         return html;
  28871.       };
  28872.       Editor.prototype.setContent = function (content, args) {
  28873.         return setContent(this, content, args);
  28874.       };
  28875.       Editor.prototype.getContent = function (args) {
  28876.         return getContent(this, args);
  28877.       };
  28878.       Editor.prototype.insertContent = function (content, args) {
  28879.         if (args) {
  28880.           content = extend$3({ content: content }, args);
  28881.         }
  28882.         this.execCommand('mceInsertContent', false, content);
  28883.       };
  28884.       Editor.prototype.resetContent = function (initialContent) {
  28885.         if (initialContent === undefined) {
  28886.           setContent(this, this.startContent, { format: 'raw' });
  28887.         } else {
  28888.           setContent(this, initialContent);
  28889.         }
  28890.         this.undoManager.reset();
  28891.         this.setDirty(false);
  28892.         this.nodeChanged();
  28893.       };
  28894.       Editor.prototype.isDirty = function () {
  28895.         return !this.isNotDirty;
  28896.       };
  28897.       Editor.prototype.setDirty = function (state) {
  28898.         var oldState = !this.isNotDirty;
  28899.         this.isNotDirty = !state;
  28900.         if (state && state !== oldState) {
  28901.           this.fire('dirty');
  28902.         }
  28903.       };
  28904.       Editor.prototype.getContainer = function () {
  28905.         var self = this;
  28906.         if (!self.container) {
  28907.           self.container = DOM$1.get(self.editorContainer || self.id + '_parent');
  28908.         }
  28909.         return self.container;
  28910.       };
  28911.       Editor.prototype.getContentAreaContainer = function () {
  28912.         return this.contentAreaContainer;
  28913.       };
  28914.       Editor.prototype.getElement = function () {
  28915.         if (!this.targetElm) {
  28916.           this.targetElm = DOM$1.get(this.id);
  28917.         }
  28918.         return this.targetElm;
  28919.       };
  28920.       Editor.prototype.getWin = function () {
  28921.         var self = this;
  28922.         var elm;
  28923.         if (!self.contentWindow) {
  28924.           elm = self.iframeElement;
  28925.           if (elm) {
  28926.             self.contentWindow = elm.contentWindow;
  28927.           }
  28928.         }
  28929.         return self.contentWindow;
  28930.       };
  28931.       Editor.prototype.getDoc = function () {
  28932.         var self = this;
  28933.         var win;
  28934.         if (!self.contentDocument) {
  28935.           win = self.getWin();
  28936.           if (win) {
  28937.             self.contentDocument = win.document;
  28938.           }
  28939.         }
  28940.         return self.contentDocument;
  28941.       };
  28942.       Editor.prototype.getBody = function () {
  28943.         var doc = this.getDoc();
  28944.         return this.bodyElement || (doc ? doc.body : null);
  28945.       };
  28946.       Editor.prototype.convertURL = function (url, name, elm) {
  28947.         var self = this, settings = self.settings;
  28948.         if (settings.urlconverter_callback) {
  28949.           return self.execCallback('urlconverter_callback', url, elm, true, name);
  28950.         }
  28951.         if (!settings.convert_urls || elm && elm.nodeName === 'LINK' || url.indexOf('file:') === 0 || url.length === 0) {
  28952.           return url;
  28953.         }
  28954.         if (settings.relative_urls) {
  28955.           return self.documentBaseURI.toRelative(url);
  28956.         }
  28957.         url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  28958.         return url;
  28959.       };
  28960.       Editor.prototype.addVisual = function (elm) {
  28961.         addVisual(this, elm);
  28962.       };
  28963.       Editor.prototype.remove = function () {
  28964.         remove(this);
  28965.       };
  28966.       Editor.prototype.destroy = function (automatic) {
  28967.         destroy(this, automatic);
  28968.       };
  28969.       Editor.prototype.uploadImages = function (callback) {
  28970.         return this.editorUpload.uploadImages(callback);
  28971.       };
  28972.       Editor.prototype._scanForImages = function () {
  28973.         return this.editorUpload.scanForImages();
  28974.       };
  28975.       Editor.prototype.addButton = function () {
  28976.         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');
  28977.       };
  28978.       Editor.prototype.addSidebar = function () {
  28979.         throw new Error('editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead');
  28980.       };
  28981.       Editor.prototype.addMenuItem = function () {
  28982.         throw new Error('editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead');
  28983.       };
  28984.       Editor.prototype.addContextToolbar = function () {
  28985.         throw new Error('editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead');
  28986.       };
  28987.       return Editor;
  28988.     }();
  28989.  
  28990.     var DOM = DOMUtils.DOM;
  28991.     var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
  28992.     var instanceCounter = 0, boundGlobalEvents = false;
  28993.     var beforeUnloadDelegate;
  28994.     var legacyEditors = [];
  28995.     var editors = [];
  28996.     var isValidLegacyKey = function (id) {
  28997.       return id !== 'length';
  28998.     };
  28999.     var globalEventDelegate = function (e) {
  29000.       var type = e.type;
  29001.       each$1(EditorManager.get(), function (editor) {
  29002.         switch (type) {
  29003.         case 'scroll':
  29004.           editor.fire('ScrollWindow', e);
  29005.           break;
  29006.         case 'resize':
  29007.           editor.fire('ResizeWindow', e);
  29008.           break;
  29009.         }
  29010.       });
  29011.     };
  29012.     var toggleGlobalEvents = function (state) {
  29013.       if (state !== boundGlobalEvents) {
  29014.         if (state) {
  29015.           DomQuery(window).on('resize scroll', globalEventDelegate);
  29016.         } else {
  29017.           DomQuery(window).off('resize scroll', globalEventDelegate);
  29018.         }
  29019.         boundGlobalEvents = state;
  29020.       }
  29021.     };
  29022.     var removeEditorFromList = function (targetEditor) {
  29023.       var oldEditors = editors;
  29024.       delete legacyEditors[targetEditor.id];
  29025.       for (var i = 0; i < legacyEditors.length; i++) {
  29026.         if (legacyEditors[i] === targetEditor) {
  29027.           legacyEditors.splice(i, 1);
  29028.           break;
  29029.         }
  29030.       }
  29031.       editors = filter$4(editors, function (editor) {
  29032.         return targetEditor !== editor;
  29033.       });
  29034.       if (EditorManager.activeEditor === targetEditor) {
  29035.         EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
  29036.       }
  29037.       if (EditorManager.focusedEditor === targetEditor) {
  29038.         EditorManager.focusedEditor = null;
  29039.       }
  29040.       return oldEditors.length !== editors.length;
  29041.     };
  29042.     var purgeDestroyedEditor = function (editor) {
  29043.       if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
  29044.         removeEditorFromList(editor);
  29045.         editor.unbindAllNativeEvents();
  29046.         editor.destroy(true);
  29047.         editor.removed = true;
  29048.         editor = null;
  29049.       }
  29050.       return editor;
  29051.     };
  29052.     var isQuirksMode = document.compatMode !== 'CSS1Compat';
  29053.     var EditorManager = __assign(__assign({}, Observable), {
  29054.       baseURI: null,
  29055.       baseURL: null,
  29056.       defaultSettings: {},
  29057.       documentBaseURL: null,
  29058.       suffix: null,
  29059.       $: DomQuery,
  29060.       majorVersion: '5',
  29061.       minorVersion: '10.8',
  29062.       releaseDate: '2023-10-19',
  29063.       editors: legacyEditors,
  29064.       i18n: I18n,
  29065.       activeEditor: null,
  29066.       focusedEditor: null,
  29067.       settings: {},
  29068.       setup: function () {
  29069.         var self = this;
  29070.         var baseURL, documentBaseURL, suffix = '';
  29071.         documentBaseURL = URI.getDocumentBaseUrl(document.location);
  29072.         if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
  29073.           documentBaseURL = documentBaseURL.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  29074.           if (!/[\/\\]$/.test(documentBaseURL)) {
  29075.             documentBaseURL += '/';
  29076.           }
  29077.         }
  29078.         var preInit = window.tinymce || window.tinyMCEPreInit;
  29079.         if (preInit) {
  29080.           baseURL = preInit.base || preInit.baseURL;
  29081.           suffix = preInit.suffix;
  29082.         } else {
  29083.           var scripts = document.getElementsByTagName('script');
  29084.           for (var i = 0; i < scripts.length; i++) {
  29085.             var src = scripts[i].src || '';
  29086.             if (src === '') {
  29087.               continue;
  29088.             }
  29089.             var srcScript = src.substring(src.lastIndexOf('/'));
  29090.             if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  29091.               if (srcScript.indexOf('.min') !== -1) {
  29092.                 suffix = '.min';
  29093.               }
  29094.               baseURL = src.substring(0, src.lastIndexOf('/'));
  29095.               break;
  29096.             }
  29097.           }
  29098.           if (!baseURL && document.currentScript) {
  29099.             var src = document.currentScript.src;
  29100.             if (src.indexOf('.min') !== -1) {
  29101.               suffix = '.min';
  29102.             }
  29103.             baseURL = src.substring(0, src.lastIndexOf('/'));
  29104.           }
  29105.         }
  29106.         self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  29107.         self.documentBaseURL = documentBaseURL;
  29108.         self.baseURI = new URI(self.baseURL);
  29109.         self.suffix = suffix;
  29110.         setup$l(self);
  29111.       },
  29112.       overrideDefaults: function (defaultSettings) {
  29113.         var baseUrl = defaultSettings.base_url;
  29114.         if (baseUrl) {
  29115.           this._setBaseUrl(baseUrl);
  29116.         }
  29117.         var suffix = defaultSettings.suffix;
  29118.         if (defaultSettings.suffix) {
  29119.           this.suffix = suffix;
  29120.         }
  29121.         this.defaultSettings = defaultSettings;
  29122.         var pluginBaseUrls = defaultSettings.plugin_base_urls;
  29123.         if (pluginBaseUrls !== undefined) {
  29124.           each$j(pluginBaseUrls, function (pluginBaseUrl, pluginName) {
  29125.             AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
  29126.           });
  29127.         }
  29128.       },
  29129.       init: function (settings) {
  29130.         var self = this;
  29131.         var result;
  29132.         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', ' ');
  29133.         var isInvalidInlineTarget = function (settings, elm) {
  29134.           return settings.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
  29135.         };
  29136.         var createId = function (elm) {
  29137.           var id = elm.id;
  29138.           if (!id) {
  29139.             id = get$9(elm, 'name').filter(function (name) {
  29140.               return !DOM.get(name);
  29141.             }).getOrThunk(DOM.uniqueId);
  29142.             elm.setAttribute('id', id);
  29143.           }
  29144.           return id;
  29145.         };
  29146.         var execCallback = function (name) {
  29147.           var callback = settings[name];
  29148.           if (!callback) {
  29149.             return;
  29150.           }
  29151.           return callback.apply(self, []);
  29152.         };
  29153.         var hasClass = function (elm, className) {
  29154.           return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
  29155.         };
  29156.         var findTargets = function (settings) {
  29157.           var targets = [];
  29158.           if (Env.browser.isIE() && Env.browser.version.major < 11) {
  29159.             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/');
  29160.             return [];
  29161.           } else if (isQuirksMode) {
  29162.             initError('Failed to initialize the editor as the document is not in standards mode. ' + 'TinyMCE requires standards mode.');
  29163.             return [];
  29164.           }
  29165.           if (settings.types) {
  29166.             each$1(settings.types, function (type) {
  29167.               targets = targets.concat(DOM.select(type.selector));
  29168.             });
  29169.             return targets;
  29170.           } else if (settings.selector) {
  29171.             return DOM.select(settings.selector);
  29172.           } else if (settings.target) {
  29173.             return [settings.target];
  29174.           }
  29175.           switch (settings.mode) {
  29176.           case 'exact':
  29177.             var l = settings.elements || '';
  29178.             if (l.length > 0) {
  29179.               each$1(explode(l), function (id) {
  29180.                 var elm = DOM.get(id);
  29181.                 if (elm) {
  29182.                   targets.push(elm);
  29183.                 } else {
  29184.                   each$1(document.forms, function (f) {
  29185.                     each$1(f.elements, function (e) {
  29186.                       if (e.name === id) {
  29187.                         id = 'mce_editor_' + instanceCounter++;
  29188.                         DOM.setAttrib(e, 'id', id);
  29189.                         targets.push(e);
  29190.                       }
  29191.                     });
  29192.                   });
  29193.                 }
  29194.               });
  29195.             }
  29196.             break;
  29197.           case 'textareas':
  29198.           case 'specific_textareas':
  29199.             each$1(DOM.select('textarea'), function (elm) {
  29200.               if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  29201.                 return;
  29202.               }
  29203.               if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  29204.                 targets.push(elm);
  29205.               }
  29206.             });
  29207.             break;
  29208.           }
  29209.           return targets;
  29210.         };
  29211.         var provideResults = function (editors) {
  29212.           result = editors;
  29213.         };
  29214.         var initEditors = function () {
  29215.           var initCount = 0;
  29216.           var editors = [];
  29217.           var targets;
  29218.           var createEditor = function (id, settings, targetElm) {
  29219.             var editor = new Editor(id, settings, self);
  29220.             editors.push(editor);
  29221.             editor.on('init', function () {
  29222.               if (++initCount === targets.length) {
  29223.                 provideResults(editors);
  29224.               }
  29225.             });
  29226.             editor.targetElm = editor.targetElm || targetElm;
  29227.             editor.render();
  29228.           };
  29229.           DOM.unbind(window, 'ready', initEditors);
  29230.           execCallback('onpageload');
  29231.           targets = DomQuery.unique(findTargets(settings));
  29232.           if (settings.types) {
  29233.             each$1(settings.types, function (type) {
  29234.               Tools.each(targets, function (elm) {
  29235.                 if (DOM.is(elm, type.selector)) {
  29236.                   createEditor(createId(elm), extend$2({}, settings, type), elm);
  29237.                   return false;
  29238.                 }
  29239.                 return true;
  29240.               });
  29241.             });
  29242.             return;
  29243.           }
  29244.           Tools.each(targets, function (elm) {
  29245.             purgeDestroyedEditor(self.get(elm.id));
  29246.           });
  29247.           targets = Tools.grep(targets, function (elm) {
  29248.             return !self.get(elm.id);
  29249.           });
  29250.           if (targets.length === 0) {
  29251.             provideResults([]);
  29252.           } else {
  29253.             each$1(targets, function (elm) {
  29254.               if (isInvalidInlineTarget(settings, elm)) {
  29255.                 initError('Could not initialize inline editor on invalid inline target element', elm);
  29256.               } else {
  29257.                 createEditor(createId(elm), settings, elm);
  29258.               }
  29259.             });
  29260.           }
  29261.         };
  29262.         self.settings = settings;
  29263.         DOM.bind(window, 'ready', initEditors);
  29264.         return new promiseObj(function (resolve) {
  29265.           if (result) {
  29266.             resolve(result);
  29267.           } else {
  29268.             provideResults = function (editors) {
  29269.               resolve(editors);
  29270.             };
  29271.           }
  29272.         });
  29273.       },
  29274.       get: function (id) {
  29275.         if (arguments.length === 0) {
  29276.           return editors.slice(0);
  29277.         } else if (isString$1(id)) {
  29278.           return find$3(editors, function (editor) {
  29279.             return editor.id === id;
  29280.           }).getOr(null);
  29281.         } else if (isNumber(id)) {
  29282.           return editors[id] ? editors[id] : null;
  29283.         } else {
  29284.           return null;
  29285.         }
  29286.       },
  29287.       add: function (editor) {
  29288.         var self = this;
  29289.         var existingEditor = legacyEditors[editor.id];
  29290.         if (existingEditor === editor) {
  29291.           return editor;
  29292.         }
  29293.         if (self.get(editor.id) === null) {
  29294.           if (isValidLegacyKey(editor.id)) {
  29295.             legacyEditors[editor.id] = editor;
  29296.           }
  29297.           legacyEditors.push(editor);
  29298.           editors.push(editor);
  29299.         }
  29300.         toggleGlobalEvents(true);
  29301.         self.activeEditor = editor;
  29302.         self.fire('AddEditor', { editor: editor });
  29303.         if (!beforeUnloadDelegate) {
  29304.           beforeUnloadDelegate = function (e) {
  29305.             var event = self.fire('BeforeUnload');
  29306.             if (event.returnValue) {
  29307.               e.preventDefault();
  29308.               e.returnValue = event.returnValue;
  29309.               return event.returnValue;
  29310.             }
  29311.           };
  29312.           window.addEventListener('beforeunload', beforeUnloadDelegate);
  29313.         }
  29314.         return editor;
  29315.       },
  29316.       createEditor: function (id, settings) {
  29317.         return this.add(new Editor(id, settings, this));
  29318.       },
  29319.       remove: function (selector) {
  29320.         var self = this;
  29321.         var i, editor;
  29322.         if (!selector) {
  29323.           for (i = editors.length - 1; i >= 0; i--) {
  29324.             self.remove(editors[i]);
  29325.           }
  29326.           return;
  29327.         }
  29328.         if (isString$1(selector)) {
  29329.           each$1(DOM.select(selector), function (elm) {
  29330.             editor = self.get(elm.id);
  29331.             if (editor) {
  29332.               self.remove(editor);
  29333.             }
  29334.           });
  29335.           return;
  29336.         }
  29337.         editor = selector;
  29338.         if (isNull(self.get(editor.id))) {
  29339.           return null;
  29340.         }
  29341.         if (removeEditorFromList(editor)) {
  29342.           self.fire('RemoveEditor', { editor: editor });
  29343.         }
  29344.         if (editors.length === 0) {
  29345.           window.removeEventListener('beforeunload', beforeUnloadDelegate);
  29346.         }
  29347.         editor.remove();
  29348.         toggleGlobalEvents(editors.length > 0);
  29349.         return editor;
  29350.       },
  29351.       execCommand: function (cmd, ui, value) {
  29352.         var self = this, editor = self.get(value);
  29353.         switch (cmd) {
  29354.         case 'mceAddEditor':
  29355.           if (!self.get(value)) {
  29356.             new Editor(value, self.settings, self).render();
  29357.           }
  29358.           return true;
  29359.         case 'mceRemoveEditor':
  29360.           if (editor) {
  29361.             editor.remove();
  29362.           }
  29363.           return true;
  29364.         case 'mceToggleEditor':
  29365.           if (!editor) {
  29366.             self.execCommand('mceAddEditor', false, value);
  29367.             return true;
  29368.           }
  29369.           if (editor.isHidden()) {
  29370.             editor.show();
  29371.           } else {
  29372.             editor.hide();
  29373.           }
  29374.           return true;
  29375.         }
  29376.         if (self.activeEditor) {
  29377.           return self.activeEditor.execCommand(cmd, ui, value);
  29378.         }
  29379.         return false;
  29380.       },
  29381.       triggerSave: function () {
  29382.         each$1(editors, function (editor) {
  29383.           editor.save();
  29384.         });
  29385.       },
  29386.       addI18n: function (code, items) {
  29387.         I18n.add(code, items);
  29388.       },
  29389.       translate: function (text) {
  29390.         return I18n.translate(text);
  29391.       },
  29392.       setActive: function (editor) {
  29393.         var activeEditor = this.activeEditor;
  29394.         if (this.activeEditor !== editor) {
  29395.           if (activeEditor) {
  29396.             activeEditor.fire('deactivate', { relatedTarget: editor });
  29397.           }
  29398.           editor.fire('activate', { relatedTarget: activeEditor });
  29399.         }
  29400.         this.activeEditor = editor;
  29401.       },
  29402.       _setBaseUrl: function (baseUrl) {
  29403.         this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ''));
  29404.         this.baseURI = new URI(this.baseURL);
  29405.       }
  29406.     });
  29407.     EditorManager.setup();
  29408.  
  29409.     var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
  29410.     var relativePosition = function (rect, targetRect, rel) {
  29411.       var x = targetRect.x;
  29412.       var y = targetRect.y;
  29413.       var w = rect.w;
  29414.       var h = rect.h;
  29415.       var targetW = targetRect.w;
  29416.       var targetH = targetRect.h;
  29417.       var relChars = (rel || '').split('');
  29418.       if (relChars[0] === 'b') {
  29419.         y += targetH;
  29420.       }
  29421.       if (relChars[1] === 'r') {
  29422.         x += targetW;
  29423.       }
  29424.       if (relChars[0] === 'c') {
  29425.         y += round$1(targetH / 2);
  29426.       }
  29427.       if (relChars[1] === 'c') {
  29428.         x += round$1(targetW / 2);
  29429.       }
  29430.       if (relChars[3] === 'b') {
  29431.         y -= h;
  29432.       }
  29433.       if (relChars[4] === 'r') {
  29434.         x -= w;
  29435.       }
  29436.       if (relChars[3] === 'c') {
  29437.         y -= round$1(h / 2);
  29438.       }
  29439.       if (relChars[4] === 'c') {
  29440.         x -= round$1(w / 2);
  29441.       }
  29442.       return create$2(x, y, w, h);
  29443.     };
  29444.     var findBestRelativePosition = function (rect, targetRect, constrainRect, rels) {
  29445.       var pos, i;
  29446.       for (i = 0; i < rels.length; i++) {
  29447.         pos = relativePosition(rect, targetRect, rels[i]);
  29448.         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) {
  29449.           return rels[i];
  29450.         }
  29451.       }
  29452.       return null;
  29453.     };
  29454.     var inflate = function (rect, w, h) {
  29455.       return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
  29456.     };
  29457.     var intersect = function (rect, cropRect) {
  29458.       var x1 = max$1(rect.x, cropRect.x);
  29459.       var y1 = max$1(rect.y, cropRect.y);
  29460.       var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
  29461.       var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
  29462.       if (x2 - x1 < 0 || y2 - y1 < 0) {
  29463.         return null;
  29464.       }
  29465.       return create$2(x1, y1, x2 - x1, y2 - y1);
  29466.     };
  29467.     var clamp = function (rect, clampRect, fixedSize) {
  29468.       var x1 = rect.x;
  29469.       var y1 = rect.y;
  29470.       var x2 = rect.x + rect.w;
  29471.       var y2 = rect.y + rect.h;
  29472.       var cx2 = clampRect.x + clampRect.w;
  29473.       var cy2 = clampRect.y + clampRect.h;
  29474.       var underflowX1 = max$1(0, clampRect.x - x1);
  29475.       var underflowY1 = max$1(0, clampRect.y - y1);
  29476.       var overflowX2 = max$1(0, x2 - cx2);
  29477.       var overflowY2 = max$1(0, y2 - cy2);
  29478.       x1 += underflowX1;
  29479.       y1 += underflowY1;
  29480.       if (fixedSize) {
  29481.         x2 += underflowX1;
  29482.         y2 += underflowY1;
  29483.         x1 -= overflowX2;
  29484.         y1 -= overflowY2;
  29485.       }
  29486.       x2 -= overflowX2;
  29487.       y2 -= overflowY2;
  29488.       return create$2(x1, y1, x2 - x1, y2 - y1);
  29489.     };
  29490.     var create$2 = function (x, y, w, h) {
  29491.       return {
  29492.         x: x,
  29493.         y: y,
  29494.         w: w,
  29495.         h: h
  29496.       };
  29497.     };
  29498.     var fromClientRect = function (clientRect) {
  29499.       return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
  29500.     };
  29501.     var Rect = {
  29502.       inflate: inflate,
  29503.       relativePosition: relativePosition,
  29504.       findBestRelativePosition: findBestRelativePosition,
  29505.       intersect: intersect,
  29506.       clamp: clamp,
  29507.       create: create$2,
  29508.       fromClientRect: fromClientRect
  29509.     };
  29510.  
  29511.     var awaiter = function (resolveCb, rejectCb, timeout) {
  29512.       if (timeout === void 0) {
  29513.         timeout = 1000;
  29514.       }
  29515.       var done = false;
  29516.       var timer = null;
  29517.       var complete = function (completer) {
  29518.         return function () {
  29519.           var args = [];
  29520.           for (var _i = 0; _i < arguments.length; _i++) {
  29521.             args[_i] = arguments[_i];
  29522.           }
  29523.           if (!done) {
  29524.             done = true;
  29525.             if (timer !== null) {
  29526.               clearTimeout(timer);
  29527.               timer = null;
  29528.             }
  29529.             completer.apply(null, args);
  29530.           }
  29531.         };
  29532.       };
  29533.       var resolve = complete(resolveCb);
  29534.       var reject = complete(rejectCb);
  29535.       var start = function () {
  29536.         var args = [];
  29537.         for (var _i = 0; _i < arguments.length; _i++) {
  29538.           args[_i] = arguments[_i];
  29539.         }
  29540.         if (!done && timer === null) {
  29541.           timer = setTimeout(function () {
  29542.             return reject.apply(null, args);
  29543.           }, timeout);
  29544.         }
  29545.       };
  29546.       return {
  29547.         start: start,
  29548.         resolve: resolve,
  29549.         reject: reject
  29550.       };
  29551.     };
  29552.     var create$1 = function () {
  29553.       var tasks = {};
  29554.       var resultFns = {};
  29555.       var load = function (id, url) {
  29556.         var loadErrMsg = 'Script at URL "' + url + '" failed to load';
  29557.         var runErrMsg = 'Script at URL "' + url + '" did not call `tinymce.Resource.add(\'' + id + '\', data)` within 1 second';
  29558.         if (tasks[id] !== undefined) {
  29559.           return tasks[id];
  29560.         } else {
  29561.           var task = new promiseObj(function (resolve, reject) {
  29562.             var waiter = awaiter(resolve, reject);
  29563.             resultFns[id] = waiter.resolve;
  29564.             ScriptLoader.ScriptLoader.loadScript(url, function () {
  29565.               return waiter.start(runErrMsg);
  29566.             }, function () {
  29567.               return waiter.reject(loadErrMsg);
  29568.             });
  29569.           });
  29570.           tasks[id] = task;
  29571.           return task;
  29572.         }
  29573.       };
  29574.       var add = function (id, data) {
  29575.         if (resultFns[id] !== undefined) {
  29576.           resultFns[id](data);
  29577.           delete resultFns[id];
  29578.         }
  29579.         tasks[id] = promiseObj.resolve(data);
  29580.       };
  29581.       return {
  29582.         load: load,
  29583.         add: add
  29584.       };
  29585.     };
  29586.     var Resource = create$1();
  29587.  
  29588.     var each = Tools.each, extend$1 = Tools.extend;
  29589.     var extendClass, initializing;
  29590.     var Class = function () {
  29591.     };
  29592.     Class.extend = extendClass = function (props) {
  29593.       var self = this;
  29594.       var _super = self.prototype;
  29595.       var Class = function () {
  29596.         var i, mixins, mixin;
  29597.         var self = this;
  29598.         if (!initializing) {
  29599.           if (self.init) {
  29600.             self.init.apply(self, arguments);
  29601.           }
  29602.           mixins = self.Mixins;
  29603.           if (mixins) {
  29604.             i = mixins.length;
  29605.             while (i--) {
  29606.               mixin = mixins[i];
  29607.               if (mixin.init) {
  29608.                 mixin.init.apply(self, arguments);
  29609.               }
  29610.             }
  29611.           }
  29612.         }
  29613.       };
  29614.       var dummy = function () {
  29615.         return this;
  29616.       };
  29617.       var createMethod = function (name, fn) {
  29618.         return function () {
  29619.           var self = this;
  29620.           var tmp = self._super;
  29621.           self._super = _super[name];
  29622.           var ret = fn.apply(self, arguments);
  29623.           self._super = tmp;
  29624.           return ret;
  29625.         };
  29626.       };
  29627.       initializing = true;
  29628.       var prototype = new self();
  29629.       initializing = false;
  29630.       if (props.Mixins) {
  29631.         each(props.Mixins, function (mixin) {
  29632.           for (var name_1 in mixin) {
  29633.             if (name_1 !== 'init') {
  29634.               props[name_1] = mixin[name_1];
  29635.             }
  29636.           }
  29637.         });
  29638.         if (_super.Mixins) {
  29639.           props.Mixins = _super.Mixins.concat(props.Mixins);
  29640.         }
  29641.       }
  29642.       if (props.Methods) {
  29643.         each(props.Methods.split(','), function (name) {
  29644.           props[name] = dummy;
  29645.         });
  29646.       }
  29647.       if (props.Properties) {
  29648.         each(props.Properties.split(','), function (name) {
  29649.           var fieldName = '_' + name;
  29650.           props[name] = function (value) {
  29651.             var self = this;
  29652.             if (value !== undefined) {
  29653.               self[fieldName] = value;
  29654.               return self;
  29655.             }
  29656.             return self[fieldName];
  29657.           };
  29658.         });
  29659.       }
  29660.       if (props.Statics) {
  29661.         each(props.Statics, function (func, name) {
  29662.           Class[name] = func;
  29663.         });
  29664.       }
  29665.       if (props.Defaults && _super.Defaults) {
  29666.         props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
  29667.       }
  29668.       each$j(props, function (member, name) {
  29669.         if (typeof member === 'function' && _super[name]) {
  29670.           prototype[name] = createMethod(name, member);
  29671.         } else {
  29672.           prototype[name] = member;
  29673.         }
  29674.       });
  29675.       Class.prototype = prototype;
  29676.       Class.constructor = Class;
  29677.       Class.extend = extendClass;
  29678.       return Class;
  29679.     };
  29680.  
  29681.     var min = Math.min, max = Math.max, round = Math.round;
  29682.     var Color = function (value) {
  29683.       var self = {};
  29684.       var r = 0, g = 0, b = 0;
  29685.       var rgb2hsv = function (r, g, b) {
  29686.         var h, s, v;
  29687.         h = 0;
  29688.         s = 0;
  29689.         v = 0;
  29690.         r = r / 255;
  29691.         g = g / 255;
  29692.         b = b / 255;
  29693.         var minRGB = min(r, min(g, b));
  29694.         var maxRGB = max(r, max(g, b));
  29695.         if (minRGB === maxRGB) {
  29696.           v = minRGB;
  29697.           return {
  29698.             h: 0,
  29699.             s: 0,
  29700.             v: v * 100
  29701.           };
  29702.         }
  29703.         var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  29704.         h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  29705.         h = 60 * (h - d / (maxRGB - minRGB));
  29706.         s = (maxRGB - minRGB) / maxRGB;
  29707.         v = maxRGB;
  29708.         return {
  29709.           h: round(h),
  29710.           s: round(s * 100),
  29711.           v: round(v * 100)
  29712.         };
  29713.       };
  29714.       var hsvToRgb = function (hue, saturation, brightness) {
  29715.         hue = (parseInt(hue, 10) || 0) % 360;
  29716.         saturation = parseInt(saturation, 10) / 100;
  29717.         brightness = parseInt(brightness, 10) / 100;
  29718.         saturation = max(0, min(saturation, 1));
  29719.         brightness = max(0, min(brightness, 1));
  29720.         if (saturation === 0) {
  29721.           r = g = b = round(255 * brightness);
  29722.           return;
  29723.         }
  29724.         var side = hue / 60;
  29725.         var chroma = brightness * saturation;
  29726.         var x = chroma * (1 - Math.abs(side % 2 - 1));
  29727.         var match = brightness - chroma;
  29728.         switch (Math.floor(side)) {
  29729.         case 0:
  29730.           r = chroma;
  29731.           g = x;
  29732.           b = 0;
  29733.           break;
  29734.         case 1:
  29735.           r = x;
  29736.           g = chroma;
  29737.           b = 0;
  29738.           break;
  29739.         case 2:
  29740.           r = 0;
  29741.           g = chroma;
  29742.           b = x;
  29743.           break;
  29744.         case 3:
  29745.           r = 0;
  29746.           g = x;
  29747.           b = chroma;
  29748.           break;
  29749.         case 4:
  29750.           r = x;
  29751.           g = 0;
  29752.           b = chroma;
  29753.           break;
  29754.         case 5:
  29755.           r = chroma;
  29756.           g = 0;
  29757.           b = x;
  29758.           break;
  29759.         default:
  29760.           r = g = b = 0;
  29761.         }
  29762.         r = round(255 * (r + match));
  29763.         g = round(255 * (g + match));
  29764.         b = round(255 * (b + match));
  29765.       };
  29766.       var toHex = function () {
  29767.         var hex = function (val) {
  29768.           val = parseInt(val, 10).toString(16);
  29769.           return val.length > 1 ? val : '0' + val;
  29770.         };
  29771.         return '#' + hex(r) + hex(g) + hex(b);
  29772.       };
  29773.       var toRgb = function () {
  29774.         return {
  29775.           r: r,
  29776.           g: g,
  29777.           b: b
  29778.         };
  29779.       };
  29780.       var toHsv = function () {
  29781.         return rgb2hsv(r, g, b);
  29782.       };
  29783.       var parse = function (value) {
  29784.         var matches;
  29785.         if (typeof value === 'object') {
  29786.           if ('r' in value) {
  29787.             r = value.r;
  29788.             g = value.g;
  29789.             b = value.b;
  29790.           } else if ('v' in value) {
  29791.             hsvToRgb(value.h, value.s, value.v);
  29792.           }
  29793.         } else {
  29794.           if (matches = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value)) {
  29795.             r = parseInt(matches[1], 10);
  29796.             g = parseInt(matches[2], 10);
  29797.             b = parseInt(matches[3], 10);
  29798.           } else if (matches = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value)) {
  29799.             r = parseInt(matches[1], 16);
  29800.             g = parseInt(matches[2], 16);
  29801.             b = parseInt(matches[3], 16);
  29802.           } else if (matches = /#([0-F])([0-F])([0-F])/gi.exec(value)) {
  29803.             r = parseInt(matches[1] + matches[1], 16);
  29804.             g = parseInt(matches[2] + matches[2], 16);
  29805.             b = parseInt(matches[3] + matches[3], 16);
  29806.           }
  29807.         }
  29808.         r = r < 0 ? 0 : r > 255 ? 255 : r;
  29809.         g = g < 0 ? 0 : g > 255 ? 255 : g;
  29810.         b = b < 0 ? 0 : b > 255 ? 255 : b;
  29811.         return self;
  29812.       };
  29813.       if (value) {
  29814.         parse(value);
  29815.       }
  29816.       self.toRgb = toRgb;
  29817.       self.toHsv = toHsv;
  29818.       self.toHex = toHex;
  29819.       self.parse = parse;
  29820.       return self;
  29821.     };
  29822.  
  29823.     var serialize = function (obj) {
  29824.       var data = JSON.stringify(obj);
  29825.       if (!isString$1(data)) {
  29826.         return data;
  29827.       }
  29828.       return data.replace(/[\u0080-\uFFFF]/g, function (match) {
  29829.         var hexCode = match.charCodeAt(0).toString(16);
  29830.         return '\\u' + '0000'.substring(hexCode.length) + hexCode;
  29831.       });
  29832.     };
  29833.     var JSONUtils = {
  29834.       serialize: serialize,
  29835.       parse: function (text) {
  29836.         try {
  29837.           return JSON.parse(text);
  29838.         } catch (ex) {
  29839.         }
  29840.       }
  29841.     };
  29842.  
  29843.     var JSONP = {
  29844.       callbacks: {},
  29845.       count: 0,
  29846.       send: function (settings) {
  29847.         var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  29848.         var id = 'tinymce_jsonp_' + count;
  29849.         self.callbacks[count] = function (json) {
  29850.           dom.remove(id);
  29851.           delete self.callbacks[count];
  29852.           settings.callback(json);
  29853.         };
  29854.         dom.add(dom.doc.body, 'script', {
  29855.           id: id,
  29856.           src: settings.url,
  29857.           type: 'text/javascript'
  29858.         });
  29859.         self.count++;
  29860.       }
  29861.     };
  29862.  
  29863.     var XHR = __assign(__assign({}, Observable), {
  29864.       send: function (settings) {
  29865.         var xhr, count = 0;
  29866.         var ready = function () {
  29867.           if (!settings.async || xhr.readyState === 4 || count++ > 10000) {
  29868.             if (settings.success && count < 10000 && xhr.status === 200) {
  29869.               settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  29870.             } else if (settings.error) {
  29871.               settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  29872.             }
  29873.             xhr = null;
  29874.           } else {
  29875.             Delay.setTimeout(ready, 10);
  29876.           }
  29877.         };
  29878.         settings.scope = settings.scope || this;
  29879.         settings.success_scope = settings.success_scope || settings.scope;
  29880.         settings.error_scope = settings.error_scope || settings.scope;
  29881.         settings.async = settings.async !== false;
  29882.         settings.data = settings.data || '';
  29883.         XHR.fire('beforeInitialize', { settings: settings });
  29884.         xhr = new XMLHttpRequest();
  29885.         if (xhr.overrideMimeType) {
  29886.           xhr.overrideMimeType(settings.content_type);
  29887.         }
  29888.         xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  29889.         if (settings.crossDomain) {
  29890.           xhr.withCredentials = true;
  29891.         }
  29892.         if (settings.content_type) {
  29893.           xhr.setRequestHeader('Content-Type', settings.content_type);
  29894.         }
  29895.         if (settings.requestheaders) {
  29896.           Tools.each(settings.requestheaders, function (header) {
  29897.             xhr.setRequestHeader(header.key, header.value);
  29898.           });
  29899.         }
  29900.         xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  29901.         xhr = XHR.fire('beforeSend', {
  29902.           xhr: xhr,
  29903.           settings: settings
  29904.         }).xhr;
  29905.         xhr.send(settings.data);
  29906.         if (!settings.async) {
  29907.           return ready();
  29908.         }
  29909.         Delay.setTimeout(ready, 10);
  29910.       }
  29911.     });
  29912.  
  29913.     var extend = Tools.extend;
  29914.     var JSONRequest = function () {
  29915.       function JSONRequest(settings) {
  29916.         this.settings = extend({}, settings);
  29917.         this.count = 0;
  29918.       }
  29919.       JSONRequest.sendRPC = function (o) {
  29920.         return new JSONRequest().send(o);
  29921.       };
  29922.       JSONRequest.prototype.send = function (args) {
  29923.         var ecb = args.error, scb = args.success;
  29924.         var xhrArgs = extend(this.settings, args);
  29925.         xhrArgs.success = function (c, x) {
  29926.           c = JSONUtils.parse(c);
  29927.           if (typeof c === 'undefined') {
  29928.             c = { error: 'JSON Parse error.' };
  29929.           }
  29930.           if (c.error) {
  29931.             ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
  29932.           } else {
  29933.             scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
  29934.           }
  29935.         };
  29936.         xhrArgs.error = function (ty, x) {
  29937.           if (ecb) {
  29938.             ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
  29939.           }
  29940.         };
  29941.         xhrArgs.data = JSONUtils.serialize({
  29942.           id: args.id || 'c' + this.count++,
  29943.           method: args.method,
  29944.           params: args.params
  29945.         });
  29946.         xhrArgs.content_type = 'application/json';
  29947.         XHR.send(xhrArgs);
  29948.       };
  29949.       return JSONRequest;
  29950.     }();
  29951.  
  29952.     var create = function () {
  29953.       return function () {
  29954.         var data = {};
  29955.         var keys = [];
  29956.         var storage = {
  29957.           getItem: function (key) {
  29958.             var item = data[key];
  29959.             return item ? item : null;
  29960.           },
  29961.           setItem: function (key, value) {
  29962.             keys.push(key);
  29963.             data[key] = String(value);
  29964.           },
  29965.           key: function (index) {
  29966.             return keys[index];
  29967.           },
  29968.           removeItem: function (key) {
  29969.             keys = keys.filter(function (k) {
  29970.               return k === key;
  29971.             });
  29972.             delete data[key];
  29973.           },
  29974.           clear: function () {
  29975.             keys = [];
  29976.             data = {};
  29977.           },
  29978.           length: 0
  29979.         };
  29980.         Object.defineProperty(storage, 'length', {
  29981.           get: function () {
  29982.             return keys.length;
  29983.           },
  29984.           configurable: false,
  29985.           enumerable: false
  29986.         });
  29987.         return storage;
  29988.       }();
  29989.     };
  29990.  
  29991.     var localStorage;
  29992.     try {
  29993.       var test = '__storage_test__';
  29994.       localStorage = window.localStorage;
  29995.       localStorage.setItem(test, test);
  29996.       localStorage.removeItem(test);
  29997.     } catch (e) {
  29998.       localStorage = create();
  29999.     }
  30000.     var LocalStorage = localStorage;
  30001.  
  30002.     var publicApi = {
  30003.       geom: { Rect: Rect },
  30004.       util: {
  30005.         Promise: promiseObj,
  30006.         Delay: Delay,
  30007.         Tools: Tools,
  30008.         VK: VK,
  30009.         URI: URI,
  30010.         Class: Class,
  30011.         EventDispatcher: EventDispatcher,
  30012.         Observable: Observable,
  30013.         I18n: I18n,
  30014.         XHR: XHR,
  30015.         JSON: JSONUtils,
  30016.         JSONRequest: JSONRequest,
  30017.         JSONP: JSONP,
  30018.         LocalStorage: LocalStorage,
  30019.         Color: Color,
  30020.         ImageUploader: ImageUploader
  30021.       },
  30022.       dom: {
  30023.         EventUtils: EventUtils,
  30024.         Sizzle: Sizzle,
  30025.         DomQuery: DomQuery,
  30026.         TreeWalker: DomTreeWalker,
  30027.         TextSeeker: TextSeeker,
  30028.         DOMUtils: DOMUtils,
  30029.         ScriptLoader: ScriptLoader,
  30030.         RangeUtils: RangeUtils,
  30031.         Serializer: DomSerializer,
  30032.         StyleSheetLoader: StyleSheetLoader,
  30033.         ControlSelection: ControlSelection,
  30034.         BookmarkManager: BookmarkManager,
  30035.         Selection: EditorSelection,
  30036.         Event: EventUtils.Event
  30037.       },
  30038.       html: {
  30039.         Styles: Styles,
  30040.         Entities: Entities,
  30041.         Node: AstNode,
  30042.         Schema: Schema,
  30043.         SaxParser: SaxParser,
  30044.         DomParser: DomParser,
  30045.         Writer: Writer,
  30046.         Serializer: HtmlSerializer
  30047.       },
  30048.       Env: Env,
  30049.       AddOnManager: AddOnManager,
  30050.       Annotator: Annotator,
  30051.       Formatter: Formatter,
  30052.       UndoManager: UndoManager,
  30053.       EditorCommands: EditorCommands,
  30054.       WindowManager: WindowManager,
  30055.       NotificationManager: NotificationManager,
  30056.       EditorObservable: EditorObservable,
  30057.       Shortcuts: Shortcuts,
  30058.       Editor: Editor,
  30059.       FocusManager: FocusManager,
  30060.       EditorManager: EditorManager,
  30061.       DOM: DOMUtils.DOM,
  30062.       ScriptLoader: ScriptLoader.ScriptLoader,
  30063.       PluginManager: PluginManager,
  30064.       ThemeManager: ThemeManager,
  30065.       IconManager: IconManager,
  30066.       Resource: Resource,
  30067.       trim: Tools.trim,
  30068.       isArray: Tools.isArray,
  30069.       is: Tools.is,
  30070.       toArray: Tools.toArray,
  30071.       makeMap: Tools.makeMap,
  30072.       each: Tools.each,
  30073.       map: Tools.map,
  30074.       grep: Tools.grep,
  30075.       inArray: Tools.inArray,
  30076.       extend: Tools.extend,
  30077.       create: Tools.create,
  30078.       walk: Tools.walk,
  30079.       createNS: Tools.createNS,
  30080.       resolve: Tools.resolve,
  30081.       explode: Tools.explode,
  30082.       _addCacheSuffix: Tools._addCacheSuffix,
  30083.       isOpera: Env.opera,
  30084.       isWebKit: Env.webkit,
  30085.       isIE: Env.ie,
  30086.       isGecko: Env.gecko,
  30087.       isMac: Env.mac
  30088.     };
  30089.     var tinymce = Tools.extend(EditorManager, publicApi);
  30090.  
  30091.     var exportToModuleLoaders = function (tinymce) {
  30092.       if (typeof module === 'object') {
  30093.         try {
  30094.           module.exports = tinymce;
  30095.         } catch (_) {
  30096.         }
  30097.       }
  30098.     };
  30099.     var exportToWindowGlobal = function (tinymce) {
  30100.       window.tinymce = tinymce;
  30101.       window.tinyMCE = tinymce;
  30102.     };
  30103.     exportToWindowGlobal(tinymce);
  30104.     exportToModuleLoaders(tinymce);
  30105.  
  30106. }());
  30107.