import {
  __commonJS,
  init_define_APP_INFO
} from "./chunk-XY75H3MP.js";

// node_modules/tinymce/tinymce.js
var require_tinymce = __commonJS({
  "node_modules/tinymce/tinymce.js"(exports, module) {
    init_define_APP_INFO();
    (function() {
      "use strict";
      var typeOf$1 = function(x) {
        if (x === null) {
          return "null";
        }
        if (x === void 0) {
          return "undefined";
        }
        var t = typeof x;
        if (t === "object" && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "Array")) {
          return "array";
        }
        if (t === "object" && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "String")) {
          return "string";
        }
        return t;
      };
      var isEquatableType = function(x) {
        return [
          "undefined",
          "boolean",
          "number",
          "string",
          "function",
          "xml",
          "null"
        ].indexOf(x) !== -1;
      };
      var sort$1 = function(xs, compareFn) {
        var clone2 = Array.prototype.slice.call(xs);
        return clone2.sort(compareFn);
      };
      var contramap = function(eqa, f) {
        return eq$2(function(x, y) {
          return eqa.eq(f(x), f(y));
        });
      };
      var eq$2 = function(f) {
        return { eq: f };
      };
      var tripleEq = eq$2(function(x, y) {
        return x === y;
      });
      var eqString = tripleEq;
      var eqArray = function(eqa) {
        return eq$2(function(x, y) {
          if (x.length !== y.length) {
            return false;
          }
          var len = x.length;
          for (var i = 0; i < len; i++) {
            if (!eqa.eq(x[i], y[i])) {
              return false;
            }
          }
          return true;
        });
      };
      var eqSortedArray = function(eqa, compareFn) {
        return contramap(eqArray(eqa), function(xs) {
          return sort$1(xs, compareFn);
        });
      };
      var eqRecord = function(eqa) {
        return eq$2(function(x, y) {
          var kx = Object.keys(x);
          var ky = Object.keys(y);
          if (!eqSortedArray(eqString).eq(kx, ky)) {
            return false;
          }
          var len = kx.length;
          for (var i = 0; i < len; i++) {
            var q = kx[i];
            if (!eqa.eq(x[q], y[q])) {
              return false;
            }
          }
          return true;
        });
      };
      var eqAny = eq$2(function(x, y) {
        if (x === y) {
          return true;
        }
        var tx = typeOf$1(x);
        var ty = typeOf$1(y);
        if (tx !== ty) {
          return false;
        }
        if (isEquatableType(tx)) {
          return x === y;
        } else if (tx === "array") {
          return eqArray(eqAny).eq(x, y);
        } else if (tx === "object") {
          return eqRecord(eqAny).eq(x, y);
        }
        return false;
      });
      var typeOf = function(x) {
        var t = typeof x;
        if (x === null) {
          return "null";
        } else if (t === "object" && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "Array")) {
          return "array";
        } else if (t === "object" && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === "String")) {
          return "string";
        } else {
          return t;
        }
      };
      var isType$1 = function(type2) {
        return function(value2) {
          return typeOf(value2) === type2;
        };
      };
      var isSimpleType = function(type2) {
        return function(value2) {
          return typeof value2 === type2;
        };
      };
      var eq$1 = function(t) {
        return function(a) {
          return t === a;
        };
      };
      var isString$1 = isType$1("string");
      var isObject = isType$1("object");
      var isArray$1 = isType$1("array");
      var isNull = eq$1(null);
      var isBoolean = isSimpleType("boolean");
      var isUndefined = eq$1(void 0);
      var isNullable = function(a) {
        return a === null || a === void 0;
      };
      var isNonNullable = function(a) {
        return !isNullable(a);
      };
      var isFunction = isSimpleType("function");
      var isNumber = isSimpleType("number");
      var noop = function() {
      };
      var compose = function(fa, fb) {
        return function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          return fa(fb.apply(null, args));
        };
      };
      var compose1 = function(fbc, fab) {
        return function(a) {
          return fbc(fab(a));
        };
      };
      var constant = function(value2) {
        return function() {
          return value2;
        };
      };
      var identity = function(x) {
        return x;
      };
      var tripleEquals = function(a, b) {
        return a === b;
      };
      function curry(fn) {
        var initialArgs = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          initialArgs[_i - 1] = arguments[_i];
        }
        return function() {
          var restArgs = [];
          for (var _i2 = 0; _i2 < arguments.length; _i2++) {
            restArgs[_i2] = arguments[_i2];
          }
          var all2 = initialArgs.concat(restArgs);
          return fn.apply(null, all2);
        };
      }
      var not = function(f) {
        return function(t) {
          return !f(t);
        };
      };
      var die = function(msg) {
        return function() {
          throw new Error(msg);
        };
      };
      var apply = function(f) {
        return f();
      };
      var call = function(f) {
        f();
      };
      var never = constant(false);
      var always = constant(true);
      var none = function() {
        return NONE;
      };
      var NONE = function() {
        var call2 = function(thunk) {
          return thunk();
        };
        var id = identity;
        var me = {
          fold: function(n, _s) {
            return n();
          },
          isSome: never,
          isNone: always,
          getOr: id,
          getOrThunk: call2,
          getOrDie: function(msg) {
            throw new Error(msg || "error: getOrDie called on none.");
          },
          getOrNull: constant(null),
          getOrUndefined: constant(void 0),
          or: id,
          orThunk: call2,
          map: none,
          each: noop,
          bind: none,
          exists: never,
          forall: always,
          filter: function() {
            return none();
          },
          toArray: function() {
            return [];
          },
          toString: constant("none()")
        };
        return me;
      }();
      var some = function(a) {
        var constant_a = constant(a);
        var self2 = function() {
          return me;
        };
        var bind2 = function(f) {
          return f(a);
        };
        var me = {
          fold: function(n, s) {
            return s(a);
          },
          isSome: always,
          isNone: never,
          getOr: constant_a,
          getOrThunk: constant_a,
          getOrDie: constant_a,
          getOrNull: constant_a,
          getOrUndefined: constant_a,
          or: self2,
          orThunk: self2,
          map: function(f) {
            return some(f(a));
          },
          each: function(f) {
            f(a);
          },
          bind: bind2,
          exists: bind2,
          forall: bind2,
          filter: function(f) {
            return f(a) ? me : NONE;
          },
          toArray: function() {
            return [a];
          },
          toString: function() {
            return "some(" + a + ")";
          }
        };
        return me;
      };
      var from$1 = function(value2) {
        return value2 === null || value2 === void 0 ? NONE : some(value2);
      };
      var Optional = {
        some,
        none,
        from: from$1
      };
      var nativeSlice = Array.prototype.slice;
      var nativeIndexOf = Array.prototype.indexOf;
      var nativePush = Array.prototype.push;
      var rawIndexOf = function(ts, t) {
        return nativeIndexOf.call(ts, t);
      };
      var indexOf$2 = function(xs, x) {
        var r2 = rawIndexOf(xs, x);
        return r2 === -1 ? Optional.none() : Optional.some(r2);
      };
      var contains$3 = function(xs, x) {
        return rawIndexOf(xs, x) > -1;
      };
      var exists = function(xs, pred) {
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          if (pred(x, i)) {
            return true;
          }
        }
        return false;
      };
      var map$3 = function(xs, f) {
        var len = xs.length;
        var r2 = new Array(len);
        for (var i = 0; i < len; i++) {
          var x = xs[i];
          r2[i] = f(x, i);
        }
        return r2;
      };
      var each$k = function(xs, f) {
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          f(x, i);
        }
      };
      var eachr = function(xs, f) {
        for (var i = xs.length - 1; i >= 0; i--) {
          var x = xs[i];
          f(x, i);
        }
      };
      var partition = function(xs, pred) {
        var pass = [];
        var fail = [];
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          var arr2 = pred(x, i) ? pass : fail;
          arr2.push(x);
        }
        return {
          pass,
          fail
        };
      };
      var filter$4 = function(xs, pred) {
        var r2 = [];
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          if (pred(x, i)) {
            r2.push(x);
          }
        }
        return r2;
      };
      var foldr = function(xs, f, acc) {
        eachr(xs, function(x, i) {
          acc = f(acc, x, i);
        });
        return acc;
      };
      var foldl = function(xs, f, acc) {
        each$k(xs, function(x, i) {
          acc = f(acc, x, i);
        });
        return acc;
      };
      var findUntil$1 = function(xs, pred, until) {
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          if (pred(x, i)) {
            return Optional.some(x);
          } else if (until(x, i)) {
            break;
          }
        }
        return Optional.none();
      };
      var find$3 = function(xs, pred) {
        return findUntil$1(xs, pred, never);
      };
      var findIndex$2 = function(xs, pred) {
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          if (pred(x, i)) {
            return Optional.some(i);
          }
        }
        return Optional.none();
      };
      var flatten = function(xs) {
        var r2 = [];
        for (var i = 0, len = xs.length; i < len; ++i) {
          if (!isArray$1(xs[i])) {
            throw new Error("Arr.flatten item " + i + " was not an array, input: " + xs);
          }
          nativePush.apply(r2, xs[i]);
        }
        return r2;
      };
      var bind = function(xs, f) {
        return flatten(map$3(xs, f));
      };
      var forall = function(xs, pred) {
        for (var i = 0, len = xs.length; i < len; ++i) {
          var x = xs[i];
          if (pred(x, i) !== true) {
            return false;
          }
        }
        return true;
      };
      var reverse = function(xs) {
        var r2 = nativeSlice.call(xs, 0);
        r2.reverse();
        return r2;
      };
      var difference = function(a1, a2) {
        return filter$4(a1, function(x) {
          return !contains$3(a2, x);
        });
      };
      var mapToObject = function(xs, f) {
        var r2 = {};
        for (var i = 0, len = xs.length; i < len; i++) {
          var x = xs[i];
          r2[String(x)] = f(x, i);
        }
        return r2;
      };
      var sort = function(xs, comparator) {
        var copy = nativeSlice.call(xs, 0);
        copy.sort(comparator);
        return copy;
      };
      var get$a = function(xs, i) {
        return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
      };
      var head = function(xs) {
        return get$a(xs, 0);
      };
      var last$2 = function(xs) {
        return get$a(xs, xs.length - 1);
      };
      var from = isFunction(Array.from) ? Array.from : function(x) {
        return nativeSlice.call(x);
      };
      var findMap = function(arr2, f) {
        for (var i = 0; i < arr2.length; i++) {
          var r2 = f(arr2[i], i);
          if (r2.isSome()) {
            return r2;
          }
        }
        return Optional.none();
      };
      var keys = Object.keys;
      var hasOwnProperty$1 = Object.hasOwnProperty;
      var each$j = function(obj, f) {
        var props = keys(obj);
        for (var k = 0, len = props.length; k < len; k++) {
          var i = props[k];
          var x = obj[i];
          f(x, i);
        }
      };
      var map$2 = function(obj, f) {
        return tupleMap(obj, function(x, i) {
          return {
            k: i,
            v: f(x, i)
          };
        });
      };
      var tupleMap = function(obj, f) {
        var r2 = {};
        each$j(obj, function(x, i) {
          var tuple = f(x, i);
          r2[tuple.k] = tuple.v;
        });
        return r2;
      };
      var objAcc = function(r2) {
        return function(x, i) {
          r2[i] = x;
        };
      };
      var internalFilter = function(obj, pred, onTrue, onFalse) {
        var r2 = {};
        each$j(obj, function(x, i) {
          (pred(x, i) ? onTrue : onFalse)(x, i);
        });
        return r2;
      };
      var bifilter = function(obj, pred) {
        var t = {};
        var f = {};
        internalFilter(obj, pred, objAcc(t), objAcc(f));
        return {
          t,
          f
        };
      };
      var filter$3 = function(obj, pred) {
        var t = {};
        internalFilter(obj, pred, objAcc(t), noop);
        return t;
      };
      var mapToArray = function(obj, f) {
        var r2 = [];
        each$j(obj, function(value2, name2) {
          r2.push(f(value2, name2));
        });
        return r2;
      };
      var values = function(obj) {
        return mapToArray(obj, identity);
      };
      var get$9 = function(obj, key) {
        return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
      };
      var has$2 = function(obj, key) {
        return hasOwnProperty$1.call(obj, key);
      };
      var hasNonNullableKey = function(obj, key) {
        return has$2(obj, key) && obj[key] !== void 0 && obj[key] !== null;
      };
      var equal$1 = function(a1, a2, eq2) {
        if (eq2 === void 0) {
          eq2 = eqAny;
        }
        return eqRecord(eq2).eq(a1, a2);
      };
      var isArray = Array.isArray;
      var toArray$1 = function(obj) {
        if (!isArray(obj)) {
          var array = [];
          for (var i = 0, l = obj.length; i < l; i++) {
            array[i] = obj[i];
          }
          return array;
        } else {
          return obj;
        }
      };
      var each$i = function(o, cb, s) {
        var n, l;
        if (!o) {
          return false;
        }
        s = s || o;
        if (o.length !== void 0) {
          for (n = 0, l = o.length; n < l; n++) {
            if (cb.call(s, o[n], n, o) === false) {
              return false;
            }
          }
        } else {
          for (n in o) {
            if (has$2(o, n)) {
              if (cb.call(s, o[n], n, o) === false) {
                return false;
              }
            }
          }
        }
        return true;
      };
      var map$1 = function(array, callback) {
        var out = [];
        each$i(array, function(item, index) {
          out.push(callback(item, index, array));
        });
        return out;
      };
      var filter$2 = function(a, f) {
        var o = [];
        each$i(a, function(v, index) {
          if (!f || f(v, index, a)) {
            o.push(v);
          }
        });
        return o;
      };
      var indexOf$1 = function(a, v) {
        if (a) {
          for (var i = 0, l = a.length; i < l; i++) {
            if (a[i] === v) {
              return i;
            }
          }
        }
        return -1;
      };
      var reduce = function(collection, iteratee, accumulator, thisArg) {
        var acc = isUndefined(accumulator) ? collection[0] : accumulator;
        for (var i = 0; i < collection.length; i++) {
          acc = iteratee.call(thisArg, acc, collection[i], i);
        }
        return acc;
      };
      var findIndex$1 = function(array, predicate, thisArg) {
        var i, l;
        for (i = 0, l = array.length; i < l; i++) {
          if (predicate.call(thisArg, array[i], i, array)) {
            return i;
          }
        }
        return -1;
      };
      var last$1 = function(collection) {
        return collection[collection.length - 1];
      };
      var __assign = function() {
        __assign = Object.assign || function __assign2(t) {
          for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s)
              if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
          }
          return t;
        };
        return __assign.apply(this, arguments);
      };
      function __rest(s, e) {
        var t = {};
        for (var p in s)
          if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
            t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
          for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
              t[p[i]] = s[p[i]];
          }
        return t;
      }
      function __spreadArray(to2, from2, pack) {
        if (pack || arguments.length === 2)
          for (var i = 0, l = from2.length, ar; i < l; i++) {
            if (ar || !(i in from2)) {
              if (!ar)
                ar = Array.prototype.slice.call(from2, 0, i);
              ar[i] = from2[i];
            }
          }
        return to2.concat(ar || Array.prototype.slice.call(from2));
      }
      var cached = function(f) {
        var called = false;
        var r2;
        return function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          if (!called) {
            called = true;
            r2 = f.apply(null, args);
          }
          return r2;
        };
      };
      var DeviceType = function(os2, browser2, userAgent2, mediaMatch2) {
        var isiPad = os2.isiOS() && /ipad/i.test(userAgent2) === true;
        var isiPhone = os2.isiOS() && !isiPad;
        var isMobile = os2.isiOS() || os2.isAndroid();
        var isTouch2 = isMobile || mediaMatch2("(pointer:coarse)");
        var isTablet2 = isiPad || !isiPhone && isMobile && mediaMatch2("(min-device-width:768px)");
        var isPhone2 = isiPhone || isMobile && !isTablet2;
        var iOSwebview = browser2.isSafari() && os2.isiOS() && /safari/i.test(userAgent2) === false;
        var isDesktop = !isPhone2 && !isTablet2 && !iOSwebview;
        return {
          isiPad: constant(isiPad),
          isiPhone: constant(isiPhone),
          isTablet: constant(isTablet2),
          isPhone: constant(isPhone2),
          isTouch: constant(isTouch2),
          isAndroid: os2.isAndroid,
          isiOS: os2.isiOS,
          isWebView: constant(iOSwebview),
          isDesktop: constant(isDesktop)
        };
      };
      var firstMatch = function(regexes, s) {
        for (var i = 0; i < regexes.length; i++) {
          var x = regexes[i];
          if (x.test(s)) {
            return x;
          }
        }
        return void 0;
      };
      var find$2 = function(regexes, agent) {
        var r2 = firstMatch(regexes, agent);
        if (!r2) {
          return {
            major: 0,
            minor: 0
          };
        }
        var group = function(i) {
          return Number(agent.replace(r2, "$" + i));
        };
        return nu$4(group(1), group(2));
      };
      var detect$3 = function(versionRegexes, agent) {
        var cleanedAgent = String(agent).toLowerCase();
        if (versionRegexes.length === 0) {
          return unknown$2();
        }
        return find$2(versionRegexes, cleanedAgent);
      };
      var unknown$2 = function() {
        return nu$4(0, 0);
      };
      var nu$4 = function(major, minor) {
        return {
          major,
          minor
        };
      };
      var Version = {
        nu: nu$4,
        detect: detect$3,
        unknown: unknown$2
      };
      var detectBrowser$1 = function(browsers2, userAgentData) {
        return findMap(userAgentData.brands, function(uaBrand) {
          var lcBrand = uaBrand.brand.toLowerCase();
          return find$3(browsers2, function(browser2) {
            var _a;
            return lcBrand === ((_a = browser2.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
          }).map(function(info) {
            return {
              current: info.name,
              version: Version.nu(parseInt(uaBrand.version, 10), 0)
            };
          });
        });
      };
      var detect$2 = function(candidates, userAgent2) {
        var agent = String(userAgent2).toLowerCase();
        return find$3(candidates, function(candidate) {
          return candidate.search(agent);
        });
      };
      var detectBrowser = function(browsers2, userAgent2) {
        return detect$2(browsers2, userAgent2).map(function(browser2) {
          var version = Version.detect(browser2.versionRegexes, userAgent2);
          return {
            current: browser2.name,
            version
          };
        });
      };
      var detectOs = function(oses2, userAgent2) {
        return detect$2(oses2, userAgent2).map(function(os2) {
          var version = Version.detect(os2.versionRegexes, userAgent2);
          return {
            current: os2.name,
            version
          };
        });
      };
      var removeFromStart = function(str, numChars) {
        return str.substring(numChars);
      };
      var checkRange = function(str, substr, start2) {
        return substr === "" || str.length >= substr.length && str.substr(start2, start2 + substr.length) === substr;
      };
      var removeLeading = function(str, prefix) {
        return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
      };
      var contains$2 = function(str, substr) {
        return str.indexOf(substr) !== -1;
      };
      var startsWith = function(str, prefix) {
        return checkRange(str, prefix, 0);
      };
      var blank = function(r2) {
        return function(s) {
          return s.replace(r2, "");
        };
      };
      var trim$4 = blank(/^\s+|\s+$/g);
      var lTrim = blank(/^\s+/g);
      var rTrim = blank(/\s+$/g);
      var isNotEmpty = function(s) {
        return s.length > 0;
      };
      var isEmpty$3 = function(s) {
        return !isNotEmpty(s);
      };
      var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
      var checkContains = function(target) {
        return function(uastring) {
          return contains$2(uastring, target);
        };
      };
      var browsers = [
        {
          name: "Edge",
          versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
          search: function(uastring) {
            return contains$2(uastring, "edge/") && contains$2(uastring, "chrome") && contains$2(uastring, "safari") && contains$2(uastring, "applewebkit");
          }
        },
        {
          name: "Chrome",
          brand: "Chromium",
          versionRegexes: [
            /.*?chrome\/([0-9]+)\.([0-9]+).*/,
            normalVersionRegex
          ],
          search: function(uastring) {
            return contains$2(uastring, "chrome") && !contains$2(uastring, "chromeframe");
          }
        },
        {
          name: "IE",
          versionRegexes: [
            /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
            /.*?rv:([0-9]+)\.([0-9]+).*/
          ],
          search: function(uastring) {
            return contains$2(uastring, "msie") || contains$2(uastring, "trident");
          }
        },
        {
          name: "Opera",
          versionRegexes: [
            normalVersionRegex,
            /.*?opera\/([0-9]+)\.([0-9]+).*/
          ],
          search: checkContains("opera")
        },
        {
          name: "Firefox",
          versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
          search: checkContains("firefox")
        },
        {
          name: "Safari",
          versionRegexes: [
            normalVersionRegex,
            /.*?cpu os ([0-9]+)_([0-9]+).*/
          ],
          search: function(uastring) {
            return (contains$2(uastring, "safari") || contains$2(uastring, "mobile/")) && contains$2(uastring, "applewebkit");
          }
        }
      ];
      var oses = [
        {
          name: "Windows",
          search: checkContains("win"),
          versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
        },
        {
          name: "iOS",
          search: function(uastring) {
            return contains$2(uastring, "iphone") || contains$2(uastring, "ipad");
          },
          versionRegexes: [
            /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
            /.*cpu os ([0-9]+)_([0-9]+).*/,
            /.*cpu iphone os ([0-9]+)_([0-9]+).*/
          ]
        },
        {
          name: "Android",
          search: checkContains("android"),
          versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
        },
        {
          name: "OSX",
          search: checkContains("mac os x"),
          versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
        },
        {
          name: "Linux",
          search: checkContains("linux"),
          versionRegexes: []
        },
        {
          name: "Solaris",
          search: checkContains("sunos"),
          versionRegexes: []
        },
        {
          name: "FreeBSD",
          search: checkContains("freebsd"),
          versionRegexes: []
        },
        {
          name: "ChromeOS",
          search: checkContains("cros"),
          versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
        }
      ];
      var PlatformInfo = {
        browsers: constant(browsers),
        oses: constant(oses)
      };
      var edge = "Edge";
      var chrome = "Chrome";
      var ie$1 = "IE";
      var opera = "Opera";
      var firefox = "Firefox";
      var safari = "Safari";
      var unknown$1 = function() {
        return nu$3({
          current: void 0,
          version: Version.unknown()
        });
      };
      var nu$3 = function(info) {
        var current = info.current;
        var version = info.version;
        var isBrowser = function(name2) {
          return function() {
            return current === name2;
          };
        };
        return {
          current,
          version,
          isEdge: isBrowser(edge),
          isChrome: isBrowser(chrome),
          isIE: isBrowser(ie$1),
          isOpera: isBrowser(opera),
          isFirefox: isBrowser(firefox),
          isSafari: isBrowser(safari)
        };
      };
      var Browser = {
        unknown: unknown$1,
        nu: nu$3,
        edge: constant(edge),
        chrome: constant(chrome),
        ie: constant(ie$1),
        opera: constant(opera),
        firefox: constant(firefox),
        safari: constant(safari)
      };
      var windows = "Windows";
      var ios = "iOS";
      var android = "Android";
      var linux = "Linux";
      var osx = "OSX";
      var solaris = "Solaris";
      var freebsd = "FreeBSD";
      var chromeos = "ChromeOS";
      var unknown = function() {
        return nu$2({
          current: void 0,
          version: Version.unknown()
        });
      };
      var nu$2 = function(info) {
        var current = info.current;
        var version = info.version;
        var isOS = function(name2) {
          return function() {
            return current === name2;
          };
        };
        return {
          current,
          version,
          isWindows: isOS(windows),
          isiOS: isOS(ios),
          isAndroid: isOS(android),
          isOSX: isOS(osx),
          isLinux: isOS(linux),
          isSolaris: isOS(solaris),
          isFreeBSD: isOS(freebsd),
          isChromeOS: isOS(chromeos)
        };
      };
      var OperatingSystem = {
        unknown,
        nu: nu$2,
        windows: constant(windows),
        ios: constant(ios),
        android: constant(android),
        linux: constant(linux),
        osx: constant(osx),
        solaris: constant(solaris),
        freebsd: constant(freebsd),
        chromeos: constant(chromeos)
      };
      var detect$1 = function(userAgent2, userAgentDataOpt, mediaMatch2) {
        var browsers2 = PlatformInfo.browsers();
        var oses2 = PlatformInfo.oses();
        var browser2 = userAgentDataOpt.bind(function(userAgentData) {
          return detectBrowser$1(browsers2, userAgentData);
        }).orThunk(function() {
          return detectBrowser(browsers2, userAgent2);
        }).fold(Browser.unknown, Browser.nu);
        var os2 = detectOs(oses2, userAgent2).fold(OperatingSystem.unknown, OperatingSystem.nu);
        var deviceType2 = DeviceType(os2, browser2, userAgent2, mediaMatch2);
        return {
          browser: browser2,
          os: os2,
          deviceType: deviceType2
        };
      };
      var PlatformDetection = { detect: detect$1 };
      var mediaMatch = function(query) {
        return window.matchMedia(query).matches;
      };
      var platform$2 = cached(function() {
        return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
      });
      var detect = function() {
        return platform$2();
      };
      var userAgent = navigator.userAgent;
      var platform$1 = detect();
      var browser$4 = platform$1.browser;
      var os = platform$1.os;
      var deviceType = platform$1.deviceType;
      var webkit = /WebKit/.test(userAgent) && !browser$4.isEdge();
      var fileApi = "FormData" in window && "FileReader" in window && "URL" in window && !!URL.createObjectURL;
      var windowsPhone = userAgent.indexOf("Windows Phone") !== -1;
      var Env = {
        opera: browser$4.isOpera(),
        webkit,
        ie: browser$4.isIE() || browser$4.isEdge() ? browser$4.version.major : false,
        gecko: browser$4.isFirefox(),
        mac: os.isOSX() || os.isiOS(),
        iOS: deviceType.isiPad() || deviceType.isiPhone(),
        android: os.isAndroid(),
        contentEditable: true,
        transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
        caretAfter: true,
        range: window.getSelection && "Range" in window,
        documentMode: browser$4.isIE() ? document.documentMode || 7 : 10,
        fileApi,
        ceFalse: true,
        cacheSuffix: null,
        container: null,
        experimentalShadowDom: false,
        canHaveCSP: !browser$4.isIE(),
        desktop: deviceType.isDesktop(),
        windowsPhone,
        browser: {
          current: browser$4.current,
          version: browser$4.version,
          isChrome: browser$4.isChrome,
          isEdge: browser$4.isEdge,
          isFirefox: browser$4.isFirefox,
          isIE: browser$4.isIE,
          isOpera: browser$4.isOpera,
          isSafari: browser$4.isSafari
        },
        os: {
          current: os.current,
          version: os.version,
          isAndroid: os.isAndroid,
          isChromeOS: os.isChromeOS,
          isFreeBSD: os.isFreeBSD,
          isiOS: os.isiOS,
          isLinux: os.isLinux,
          isOSX: os.isOSX,
          isSolaris: os.isSolaris,
          isWindows: os.isWindows
        },
        deviceType: {
          isDesktop: deviceType.isDesktop,
          isiPad: deviceType.isiPad,
          isiPhone: deviceType.isiPhone,
          isPhone: deviceType.isPhone,
          isTablet: deviceType.isTablet,
          isTouch: deviceType.isTouch,
          isWebView: deviceType.isWebView
        }
      };
      var whiteSpaceRegExp$2 = /^\s*|\s*$/g;
      var trim$3 = function(str) {
        return str === null || str === void 0 ? "" : ("" + str).replace(whiteSpaceRegExp$2, "");
      };
      var is$3 = function(obj, type2) {
        if (!type2) {
          return obj !== void 0;
        }
        if (type2 === "array" && isArray(obj)) {
          return true;
        }
        return typeof obj === type2;
      };
      var makeMap$4 = function(items, delim, map2) {
        var i;
        items = items || [];
        delim = delim || ",";
        if (typeof items === "string") {
          items = items.split(delim);
        }
        map2 = map2 || {};
        i = items.length;
        while (i--) {
          map2[items[i]] = {};
        }
        return map2;
      };
      var hasOwnProperty = has$2;
      var create$9 = function(s, p, root) {
        var self2 = this;
        var sp, scn, c, de = 0;
        s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
        var cn = s[3].match(/(^|\.)(\w+)$/i)[2];
        var ns = self2.createNS(s[3].replace(/\.\w+$/, ""), root);
        if (ns[cn]) {
          return;
        }
        if (s[2] === "static") {
          ns[cn] = p;
          if (this.onCreate) {
            this.onCreate(s[2], s[3], ns[cn]);
          }
          return;
        }
        if (!p[cn]) {
          p[cn] = function() {
          };
          de = 1;
        }
        ns[cn] = p[cn];
        self2.extend(ns[cn].prototype, p);
        if (s[5]) {
          sp = self2.resolve(s[5]).prototype;
          scn = s[5].match(/\.(\w+)$/i)[1];
          c = ns[cn];
          if (de) {
            ns[cn] = function() {
              return sp[scn].apply(this, arguments);
            };
          } else {
            ns[cn] = function() {
              this.parent = sp[scn];
              return c.apply(this, arguments);
            };
          }
          ns[cn].prototype[cn] = ns[cn];
          self2.each(sp, function(f, n) {
            ns[cn].prototype[n] = sp[n];
          });
          self2.each(p, function(f, n) {
            if (sp[n]) {
              ns[cn].prototype[n] = function() {
                this.parent = sp[n];
                return f.apply(this, arguments);
              };
            } else {
              if (n !== cn) {
                ns[cn].prototype[n] = f;
              }
            }
          });
        }
        self2.each(p.static, function(f, n) {
          ns[cn][n] = f;
        });
      };
      var extend$6 = function(obj) {
        var exts = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          exts[_i - 1] = arguments[_i];
        }
        for (var i = 0; i < exts.length; i++) {
          var ext = exts[i];
          for (var name_1 in ext) {
            if (has$2(ext, name_1)) {
              var value2 = ext[name_1];
              if (value2 !== void 0) {
                obj[name_1] = value2;
              }
            }
          }
        }
        return obj;
      };
      var walk$3 = function(o, f, n, s) {
        s = s || this;
        if (o) {
          if (n) {
            o = o[n];
          }
          each$i(o, function(o2, i) {
            if (f.call(s, o2, i, n) === false) {
              return false;
            }
            walk$3(o2, f, n, s);
          });
        }
      };
      var createNS = function(n, o) {
        var i, v;
        o = o || window;
        n = n.split(".");
        for (i = 0; i < n.length; i++) {
          v = n[i];
          if (!o[v]) {
            o[v] = {};
          }
          o = o[v];
        }
        return o;
      };
      var resolve$3 = function(n, o) {
        var i, l;
        o = o || window;
        n = n.split(".");
        for (i = 0, l = n.length; i < l; i++) {
          o = o[n[i]];
          if (!o) {
            break;
          }
        }
        return o;
      };
      var explode$4 = function(s, d) {
        if (!s || is$3(s, "array")) {
          return s;
        }
        return map$1(s.split(d || ","), trim$3);
      };
      var _addCacheSuffix = function(url) {
        var cacheSuffix = Env.cacheSuffix;
        if (cacheSuffix) {
          url += (url.indexOf("?") === -1 ? "?" : "&") + cacheSuffix;
        }
        return url;
      };
      var Tools = {
        trim: trim$3,
        isArray,
        is: is$3,
        toArray: toArray$1,
        makeMap: makeMap$4,
        each: each$i,
        map: map$1,
        grep: filter$2,
        inArray: indexOf$1,
        hasOwn: hasOwnProperty,
        extend: extend$6,
        create: create$9,
        walk: walk$3,
        createNS,
        resolve: resolve$3,
        explode: explode$4,
        _addCacheSuffix
      };
      var fromHtml$1 = function(html, scope) {
        var doc2 = scope || document;
        var div = doc2.createElement("div");
        div.innerHTML = html;
        if (!div.hasChildNodes() || div.childNodes.length > 1) {
          console.error("HTML does not have a single root node", html);
          throw new Error("HTML must have a single root node");
        }
        return fromDom$2(div.childNodes[0]);
      };
      var fromTag = function(tag, scope) {
        var doc2 = scope || document;
        var node = doc2.createElement(tag);
        return fromDom$2(node);
      };
      var fromText = function(text, scope) {
        var doc2 = scope || document;
        var node = doc2.createTextNode(text);
        return fromDom$2(node);
      };
      var fromDom$2 = function(node) {
        if (node === null || node === void 0) {
          throw new Error("Node cannot be null or undefined");
        }
        return { dom: node };
      };
      var fromPoint$1 = function(docElm, x, y) {
        return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$2);
      };
      var SugarElement = {
        fromHtml: fromHtml$1,
        fromTag,
        fromText,
        fromDom: fromDom$2,
        fromPoint: fromPoint$1
      };
      var toArray = function(target, f) {
        var r2 = [];
        var recurse = function(e) {
          r2.push(e);
          return f(e);
        };
        var cur = f(target);
        do {
          cur = cur.bind(recurse);
        } while (cur.isSome());
        return r2;
      };
      var compareDocumentPosition = function(a, b, match2) {
        return (a.compareDocumentPosition(b) & match2) !== 0;
      };
      var documentPositionContainedBy = function(a, b) {
        return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
      };
      var COMMENT = 8;
      var DOCUMENT = 9;
      var DOCUMENT_FRAGMENT = 11;
      var ELEMENT = 1;
      var TEXT = 3;
      var is$2 = function(element, selector) {
        var dom2 = element.dom;
        if (dom2.nodeType !== ELEMENT) {
          return false;
        } else {
          var elem = dom2;
          if (elem.matches !== void 0) {
            return elem.matches(selector);
          } else if (elem.msMatchesSelector !== void 0) {
            return elem.msMatchesSelector(selector);
          } else if (elem.webkitMatchesSelector !== void 0) {
            return elem.webkitMatchesSelector(selector);
          } else if (elem.mozMatchesSelector !== void 0) {
            return elem.mozMatchesSelector(selector);
          } else {
            throw new Error("Browser lacks native selectors");
          }
        }
      };
      var bypassSelector = function(dom2) {
        return dom2.nodeType !== ELEMENT && dom2.nodeType !== DOCUMENT && dom2.nodeType !== DOCUMENT_FRAGMENT || dom2.childElementCount === 0;
      };
      var all = function(selector, scope) {
        var base = scope === void 0 ? document : scope.dom;
        return bypassSelector(base) ? [] : map$3(base.querySelectorAll(selector), SugarElement.fromDom);
      };
      var one = function(selector, scope) {
        var base = scope === void 0 ? document : scope.dom;
        return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
      };
      var eq = function(e1, e2) {
        return e1.dom === e2.dom;
      };
      var regularContains = function(e1, e2) {
        var d1 = e1.dom;
        var d2 = e2.dom;
        return d1 === d2 ? false : d1.contains(d2);
      };
      var ieContains = function(e1, e2) {
        return documentPositionContainedBy(e1.dom, e2.dom);
      };
      var contains$1 = function(e1, e2) {
        return detect().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
      };
      typeof window !== "undefined" ? window : Function("return this;")();
      var name = function(element) {
        var r2 = element.dom.nodeName;
        return r2.toLowerCase();
      };
      var type = function(element) {
        return element.dom.nodeType;
      };
      var isType = function(t) {
        return function(element) {
          return type(element) === t;
        };
      };
      var isComment$1 = function(element) {
        return type(element) === COMMENT || name(element) === "#comment";
      };
      var isElement$6 = isType(ELEMENT);
      var isText$8 = isType(TEXT);
      var isDocument$2 = isType(DOCUMENT);
      var isDocumentFragment$1 = isType(DOCUMENT_FRAGMENT);
      var isTag = function(tag) {
        return function(e) {
          return isElement$6(e) && name(e) === tag;
        };
      };
      var owner$1 = function(element) {
        return SugarElement.fromDom(element.dom.ownerDocument);
      };
      var documentOrOwner = function(dos) {
        return isDocument$2(dos) ? dos : owner$1(dos);
      };
      var documentElement = function(element) {
        return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
      };
      var defaultView = function(element) {
        return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
      };
      var parent = function(element) {
        return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
      };
      var parents$1 = function(element, isRoot) {
        var stop2 = isFunction(isRoot) ? isRoot : never;
        var dom2 = element.dom;
        var ret = [];
        while (dom2.parentNode !== null && dom2.parentNode !== void 0) {
          var rawParent = dom2.parentNode;
          var p = SugarElement.fromDom(rawParent);
          ret.push(p);
          if (stop2(p) === true) {
            break;
          } else {
            dom2 = rawParent;
          }
        }
        return ret;
      };
      var siblings = function(element) {
        var filterSelf = function(elements) {
          return filter$4(elements, function(x) {
            return !eq(element, x);
          });
        };
        return parent(element).map(children).map(filterSelf).getOr([]);
      };
      var prevSibling = function(element) {
        return Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
      };
      var nextSibling = function(element) {
        return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
      };
      var prevSiblings = function(element) {
        return reverse(toArray(element, prevSibling));
      };
      var nextSiblings = function(element) {
        return toArray(element, nextSibling);
      };
      var children = function(element) {
        return map$3(element.dom.childNodes, SugarElement.fromDom);
      };
      var child$1 = function(element, index) {
        var cs = element.dom.childNodes;
        return Optional.from(cs[index]).map(SugarElement.fromDom);
      };
      var firstChild = function(element) {
        return child$1(element, 0);
      };
      var lastChild = function(element) {
        return child$1(element, element.dom.childNodes.length - 1);
      };
      var childNodesCount = function(element) {
        return element.dom.childNodes.length;
      };
      var getHead = function(doc2) {
        var b = doc2.dom.head;
        if (b === null || b === void 0) {
          throw new Error("Head is not available yet");
        }
        return SugarElement.fromDom(b);
      };
      var isShadowRoot = function(dos) {
        return isDocumentFragment$1(dos) && isNonNullable(dos.dom.host);
      };
      var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
      var isSupported$1 = constant(supported);
      var getRootNode = supported ? function(e) {
        return SugarElement.fromDom(e.dom.getRootNode());
      } : documentOrOwner;
      var getStyleContainer = function(dos) {
        return isShadowRoot(dos) ? dos : getHead(documentOrOwner(dos));
      };
      var getShadowRoot = function(e) {
        var r2 = getRootNode(e);
        return isShadowRoot(r2) ? Optional.some(r2) : Optional.none();
      };
      var getShadowHost = function(e) {
        return SugarElement.fromDom(e.dom.host);
      };
      var getOriginalEventTarget = function(event) {
        if (isSupported$1() && isNonNullable(event.target)) {
          var el = SugarElement.fromDom(event.target);
          if (isElement$6(el) && isOpenShadowHost(el)) {
            if (event.composed && event.composedPath) {
              var composedPath = event.composedPath();
              if (composedPath) {
                return head(composedPath);
              }
            }
          }
        }
        return Optional.from(event.target);
      };
      var isOpenShadowHost = function(element) {
        return isNonNullable(element.dom.shadowRoot);
      };
      var before$4 = function(marker, element) {
        var parent$1 = parent(marker);
        parent$1.each(function(v) {
          v.dom.insertBefore(element.dom, marker.dom);
        });
      };
      var after$3 = function(marker, element) {
        var sibling2 = nextSibling(marker);
        sibling2.fold(function() {
          var parent$1 = parent(marker);
          parent$1.each(function(v) {
            append$1(v, element);
          });
        }, function(v) {
          before$4(v, element);
        });
      };
      var prepend = function(parent2, element) {
        var firstChild$1 = firstChild(parent2);
        firstChild$1.fold(function() {
          append$1(parent2, element);
        }, function(v) {
          parent2.dom.insertBefore(element.dom, v.dom);
        });
      };
      var append$1 = function(parent2, element) {
        parent2.dom.appendChild(element.dom);
      };
      var wrap$3 = function(element, wrapper) {
        before$4(element, wrapper);
        append$1(wrapper, element);
      };
      var before$3 = function(marker, elements) {
        each$k(elements, function(x) {
          before$4(marker, x);
        });
      };
      var append = function(parent2, elements) {
        each$k(elements, function(x) {
          append$1(parent2, x);
        });
      };
      var empty = function(element) {
        element.dom.textContent = "";
        each$k(children(element), function(rogue) {
          remove$7(rogue);
        });
      };
      var remove$7 = function(element) {
        var dom2 = element.dom;
        if (dom2.parentNode !== null) {
          dom2.parentNode.removeChild(dom2);
        }
      };
      var unwrap = function(wrapper) {
        var children$1 = children(wrapper);
        if (children$1.length > 0) {
          before$3(wrapper, children$1);
        }
        remove$7(wrapper);
      };
      var inBody = function(element) {
        var dom2 = isText$8(element) ? element.dom.parentNode : element.dom;
        if (dom2 === void 0 || dom2 === null || dom2.ownerDocument === null) {
          return false;
        }
        var doc2 = dom2.ownerDocument;
        return getShadowRoot(SugarElement.fromDom(dom2)).fold(function() {
          return doc2.body.contains(dom2);
        }, compose1(inBody, getShadowHost));
      };
      var r = function(left, top) {
        var translate2 = function(x, y) {
          return r(left + x, top + y);
        };
        return {
          left,
          top,
          translate: translate2
        };
      };
      var SugarPosition = r;
      var boxPosition = function(dom2) {
        var box = dom2.getBoundingClientRect();
        return SugarPosition(box.left, box.top);
      };
      var firstDefinedOrZero = function(a, b) {
        if (a !== void 0) {
          return a;
        } else {
          return b !== void 0 ? b : 0;
        }
      };
      var absolute = function(element) {
        var doc2 = element.dom.ownerDocument;
        var body = doc2.body;
        var win = doc2.defaultView;
        var html = doc2.documentElement;
        if (body === element.dom) {
          return SugarPosition(body.offsetLeft, body.offsetTop);
        }
        var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
        var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
        var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
        var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
        return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
      };
      var viewport = function(element) {
        var dom2 = element.dom;
        var doc2 = dom2.ownerDocument;
        var body = doc2.body;
        if (body === dom2) {
          return SugarPosition(body.offsetLeft, body.offsetTop);
        }
        if (!inBody(element)) {
          return SugarPosition(0, 0);
        }
        return boxPosition(dom2);
      };
      var get$8 = function(_DOC) {
        var doc2 = _DOC !== void 0 ? _DOC.dom : document;
        var x = doc2.body.scrollLeft || doc2.documentElement.scrollLeft;
        var y = doc2.body.scrollTop || doc2.documentElement.scrollTop;
        return SugarPosition(x, y);
      };
      var to = function(x, y, _DOC) {
        var doc2 = _DOC !== void 0 ? _DOC.dom : document;
        var win = doc2.defaultView;
        if (win) {
          win.scrollTo(x, y);
        }
      };
      var intoView = function(element, alignToTop) {
        var isSafari = detect().browser.isSafari();
        if (isSafari && isFunction(element.dom.scrollIntoViewIfNeeded)) {
          element.dom.scrollIntoViewIfNeeded(false);
        } else {
          element.dom.scrollIntoView(alignToTop);
        }
      };
      var get$7 = function(_win) {
        var win = _win === void 0 ? window : _win;
        if (detect().browser.isFirefox()) {
          return Optional.none();
        } else {
          return Optional.from(win["visualViewport"]);
        }
      };
      var bounds = function(x, y, width, height) {
        return {
          x,
          y,
          width,
          height,
          right: x + width,
          bottom: y + height
        };
      };
      var getBounds = function(_win) {
        var win = _win === void 0 ? window : _win;
        var doc2 = win.document;
        var scroll = get$8(SugarElement.fromDom(doc2));
        return get$7(win).fold(function() {
          var html = win.document.documentElement;
          var width = html.clientWidth;
          var height = html.clientHeight;
          return bounds(scroll.left, scroll.top, width, height);
        }, function(visualViewport) {
          return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
        });
      };
      var isNodeType = function(type2) {
        return function(node) {
          return !!node && node.nodeType === type2;
        };
      };
      var isRestrictedNode = function(node) {
        return !!node && !Object.getPrototypeOf(node);
      };
      var isElement$5 = isNodeType(1);
      var matchNodeNames = function(names) {
        var lowercasedNames = names.map(function(s) {
          return s.toLowerCase();
        });
        return function(node) {
          if (node && node.nodeName) {
            var nodeName = node.nodeName.toLowerCase();
            return contains$3(lowercasedNames, nodeName);
          }
          return false;
        };
      };
      var matchStyleValues = function(name2, values2) {
        var items = values2.toLowerCase().split(" ");
        return function(node) {
          if (isElement$5(node)) {
            for (var i = 0; i < items.length; i++) {
              var computed = node.ownerDocument.defaultView.getComputedStyle(node, null);
              var cssValue = computed ? computed.getPropertyValue(name2) : null;
              if (cssValue === items[i]) {
                return true;
              }
            }
          }
          return false;
        };
      };
      var hasAttribute = function(attrName) {
        return function(node) {
          return isElement$5(node) && node.hasAttribute(attrName);
        };
      };
      var hasAttributeValue = function(attrName, attrValue) {
        return function(node) {
          return isElement$5(node) && node.getAttribute(attrName) === attrValue;
        };
      };
      var isBogus$2 = function(node) {
        return isElement$5(node) && node.hasAttribute("data-mce-bogus");
      };
      var isBogusAll$1 = function(node) {
        return isElement$5(node) && node.getAttribute("data-mce-bogus") === "all";
      };
      var isTable$3 = function(node) {
        return isElement$5(node) && node.tagName === "TABLE";
      };
      var hasContentEditableState = function(value2) {
        return function(node) {
          if (isElement$5(node)) {
            if (node.contentEditable === value2) {
              return true;
            }
            if (node.getAttribute("data-mce-contenteditable") === value2) {
              return true;
            }
          }
          return false;
        };
      };
      var isTextareaOrInput = matchNodeNames([
        "textarea",
        "input"
      ]);
      var isText$7 = isNodeType(3);
      var isComment = isNodeType(8);
      var isDocument$1 = isNodeType(9);
      var isDocumentFragment = isNodeType(11);
      var isBr$5 = matchNodeNames(["br"]);
      var isImg = matchNodeNames(["img"]);
      var isContentEditableTrue$4 = hasContentEditableState("true");
      var isContentEditableFalse$b = hasContentEditableState("false");
      var isTableCell$5 = matchNodeNames([
        "td",
        "th"
      ]);
      var isMedia$2 = matchNodeNames([
        "video",
        "audio",
        "object",
        "embed"
      ]);
      var is$1 = function(lhs, rhs, comparator) {
        if (comparator === void 0) {
          comparator = tripleEquals;
        }
        return lhs.exists(function(left) {
          return comparator(left, rhs);
        });
      };
      var cat = function(arr2) {
        var r2 = [];
        var push2 = function(x) {
          r2.push(x);
        };
        for (var i = 0; i < arr2.length; i++) {
          arr2[i].each(push2);
        }
        return r2;
      };
      var lift2 = function(oa, ob, f) {
        return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
      };
      var lift3 = function(oa, ob, oc, f) {
        return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
      };
      var someIf = function(b, a) {
        return b ? Optional.some(a) : Optional.none();
      };
      var isSupported = function(dom2) {
        return dom2.style !== void 0 && isFunction(dom2.style.getPropertyValue);
      };
      var rawSet = function(dom2, key, value2) {
        if (isString$1(value2) || isBoolean(value2) || isNumber(value2)) {
          dom2.setAttribute(key, value2 + "");
        } else {
          console.error("Invalid call to Attribute.set. Key ", key, ":: Value ", value2, ":: Element ", dom2);
          throw new Error("Attribute value was not simple");
        }
      };
      var set$1 = function(element, key, value2) {
        rawSet(element.dom, key, value2);
      };
      var setAll$1 = function(element, attrs) {
        var dom2 = element.dom;
        each$j(attrs, function(v, k) {
          rawSet(dom2, k, v);
        });
      };
      var get$6 = function(element, key) {
        var v = element.dom.getAttribute(key);
        return v === null ? void 0 : v;
      };
      var getOpt = function(element, key) {
        return Optional.from(get$6(element, key));
      };
      var has$1 = function(element, key) {
        var dom2 = element.dom;
        return dom2 && dom2.hasAttribute ? dom2.hasAttribute(key) : false;
      };
      var remove$6 = function(element, key) {
        element.dom.removeAttribute(key);
      };
      var clone$3 = function(element) {
        return foldl(element.dom.attributes, function(acc, attr) {
          acc[attr.name] = attr.value;
          return acc;
        }, {});
      };
      var internalSet = function(dom2, property, value2) {
        if (!isString$1(value2)) {
          console.error("Invalid call to CSS.set. Property ", property, ":: Value ", value2, ":: Element ", dom2);
          throw new Error("CSS value must be a string: " + value2);
        }
        if (isSupported(dom2)) {
          dom2.style.setProperty(property, value2);
        }
      };
      var setAll = function(element, css) {
        var dom2 = element.dom;
        each$j(css, function(v, k) {
          internalSet(dom2, k, v);
        });
      };
      var get$5 = function(element, property) {
        var dom2 = element.dom;
        var styles = window.getComputedStyle(dom2);
        var r2 = styles.getPropertyValue(property);
        return r2 === "" && !inBody(element) ? getUnsafeProperty(dom2, property) : r2;
      };
      var getUnsafeProperty = function(dom2, property) {
        return isSupported(dom2) ? dom2.style.getPropertyValue(property) : "";
      };
      var getRaw = function(element, property) {
        var dom2 = element.dom;
        var raw = getUnsafeProperty(dom2, property);
        return Optional.from(raw).filter(function(r2) {
          return r2.length > 0;
        });
      };
      var getAllRaw = function(element) {
        var css = {};
        var dom2 = element.dom;
        if (isSupported(dom2)) {
          for (var i = 0; i < dom2.style.length; i++) {
            var ruleName = dom2.style.item(i);
            css[ruleName] = dom2.style[ruleName];
          }
        }
        return css;
      };
      var reflow = function(e) {
        return e.dom.offsetWidth;
      };
      var browser$3 = detect().browser;
      var firstElement = function(nodes) {
        return find$3(nodes, isElement$6);
      };
      var getTableCaptionDeltaY = function(elm) {
        if (browser$3.isFirefox() && name(elm) === "table") {
          return firstElement(children(elm)).filter(function(elm2) {
            return name(elm2) === "caption";
          }).bind(function(caption) {
            return firstElement(nextSiblings(caption)).map(function(body) {
              var bodyTop = body.dom.offsetTop;
              var captionTop = caption.dom.offsetTop;
              var captionHeight = caption.dom.offsetHeight;
              return bodyTop <= captionTop ? -captionHeight : 0;
            });
          }).getOr(0);
        } else {
          return 0;
        }
      };
      var hasChild = function(elm, child2) {
        return elm.children && contains$3(elm.children, child2);
      };
      var getPos = function(body, elm, rootElm) {
        var x = 0, y = 0;
        var doc2 = body.ownerDocument;
        rootElm = rootElm ? rootElm : body;
        if (elm) {
          if (rootElm === body && elm.getBoundingClientRect && get$5(SugarElement.fromDom(body), "position") === "static") {
            var pos = elm.getBoundingClientRect();
            x = pos.left + (doc2.documentElement.scrollLeft || body.scrollLeft) - doc2.documentElement.clientLeft;
            y = pos.top + (doc2.documentElement.scrollTop || body.scrollTop) - doc2.documentElement.clientTop;
            return {
              x,
              y
            };
          }
          var offsetParent = elm;
          while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
            var castOffsetParent = offsetParent;
            x += castOffsetParent.offsetLeft || 0;
            y += castOffsetParent.offsetTop || 0;
            offsetParent = castOffsetParent.offsetParent;
          }
          offsetParent = elm.parentNode;
          while (offsetParent && offsetParent !== rootElm && offsetParent.nodeType && !hasChild(offsetParent, rootElm)) {
            x -= offsetParent.scrollLeft || 0;
            y -= offsetParent.scrollTop || 0;
            offsetParent = offsetParent.parentNode;
          }
          y += getTableCaptionDeltaY(SugarElement.fromDom(elm));
        }
        return {
          x,
          y
        };
      };
      var exports$1 = {}, module$1 = { exports: exports$1 };
      (function(define, exports2, module2, require2) {
        (function(global2, factory) {
          typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.EphoxContactWrapper = factory());
        })(this, function() {
          var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
          var promise = { exports: {} };
          (function(module3) {
            (function(root) {
              var setTimeoutFunc = setTimeout;
              function noop2() {
              }
              function bind2(fn, thisArg) {
                return function() {
                  fn.apply(thisArg, arguments);
                };
              }
              function Promise2(fn) {
                if (typeof this !== "object")
                  throw new TypeError("Promises must be constructed via new");
                if (typeof fn !== "function")
                  throw new TypeError("not a function");
                this._state = 0;
                this._handled = false;
                this._value = void 0;
                this._deferreds = [];
                doResolve(fn, this);
              }
              function handle2(self2, deferred) {
                while (self2._state === 3) {
                  self2 = self2._value;
                }
                if (self2._state === 0) {
                  self2._deferreds.push(deferred);
                  return;
                }
                self2._handled = true;
                Promise2._immediateFn(function() {
                  var cb = self2._state === 1 ? deferred.onFulfilled : deferred.onRejected;
                  if (cb === null) {
                    (self2._state === 1 ? resolve2 : reject)(deferred.promise, self2._value);
                    return;
                  }
                  var ret;
                  try {
                    ret = cb(self2._value);
                  } catch (e) {
                    reject(deferred.promise, e);
                    return;
                  }
                  resolve2(deferred.promise, ret);
                });
              }
              function resolve2(self2, newValue) {
                try {
                  if (newValue === self2)
                    throw new TypeError("A promise cannot be resolved with itself.");
                  if (newValue && (typeof newValue === "object" || typeof newValue === "function")) {
                    var then = newValue.then;
                    if (newValue instanceof Promise2) {
                      self2._state = 3;
                      self2._value = newValue;
                      finale(self2);
                      return;
                    } else if (typeof then === "function") {
                      doResolve(bind2(then, newValue), self2);
                      return;
                    }
                  }
                  self2._state = 1;
                  self2._value = newValue;
                  finale(self2);
                } catch (e) {
                  reject(self2, e);
                }
              }
              function reject(self2, newValue) {
                self2._state = 2;
                self2._value = newValue;
                finale(self2);
              }
              function finale(self2) {
                if (self2._state === 2 && self2._deferreds.length === 0) {
                  Promise2._immediateFn(function() {
                    if (!self2._handled) {
                      Promise2._unhandledRejectionFn(self2._value);
                    }
                  });
                }
                for (var i = 0, len = self2._deferreds.length; i < len; i++) {
                  handle2(self2, self2._deferreds[i]);
                }
                self2._deferreds = null;
              }
              function Handler(onFulfilled, onRejected, promise2) {
                this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null;
                this.onRejected = typeof onRejected === "function" ? onRejected : null;
                this.promise = promise2;
              }
              function doResolve(fn, self2) {
                var done2 = false;
                try {
                  fn(function(value2) {
                    if (done2)
                      return;
                    done2 = true;
                    resolve2(self2, value2);
                  }, function(reason) {
                    if (done2)
                      return;
                    done2 = true;
                    reject(self2, reason);
                  });
                } catch (ex) {
                  if (done2)
                    return;
                  done2 = true;
                  reject(self2, ex);
                }
              }
              Promise2.prototype["catch"] = function(onRejected) {
                return this.then(null, onRejected);
              };
              Promise2.prototype.then = function(onFulfilled, onRejected) {
                var prom = new this.constructor(noop2);
                handle2(this, new Handler(onFulfilled, onRejected, prom));
                return prom;
              };
              Promise2.all = function(arr2) {
                var args = Array.prototype.slice.call(arr2);
                return new Promise2(function(resolve3, reject2) {
                  if (args.length === 0)
                    return resolve3([]);
                  var remaining = args.length;
                  function res(i2, val) {
                    try {
                      if (val && (typeof val === "object" || typeof val === "function")) {
                        var then = val.then;
                        if (typeof then === "function") {
                          then.call(val, function(val2) {
                            res(i2, val2);
                          }, reject2);
                          return;
                        }
                      }
                      args[i2] = val;
                      if (--remaining === 0) {
                        resolve3(args);
                      }
                    } catch (ex) {
                      reject2(ex);
                    }
                  }
                  for (var i = 0; i < args.length; i++) {
                    res(i, args[i]);
                  }
                });
              };
              Promise2.resolve = function(value2) {
                if (value2 && typeof value2 === "object" && value2.constructor === Promise2) {
                  return value2;
                }
                return new Promise2(function(resolve3) {
                  resolve3(value2);
                });
              };
              Promise2.reject = function(value2) {
                return new Promise2(function(resolve3, reject2) {
                  reject2(value2);
                });
              };
              Promise2.race = function(values2) {
                return new Promise2(function(resolve3, reject2) {
                  for (var i = 0, len = values2.length; i < len; i++) {
                    values2[i].then(resolve3, reject2);
                  }
                });
              };
              Promise2._immediateFn = typeof setImmediate === "function" ? function(fn) {
                setImmediate(fn);
              } : function(fn) {
                setTimeoutFunc(fn, 0);
              };
              Promise2._unhandledRejectionFn = function _unhandledRejectionFn(err) {
                if (typeof console !== "undefined" && console) {
                  console.warn("Possible Unhandled Promise Rejection:", err);
                }
              };
              Promise2._setImmediateFn = function _setImmediateFn(fn) {
                Promise2._immediateFn = fn;
              };
              Promise2._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
                Promise2._unhandledRejectionFn = fn;
              };
              if (module3.exports) {
                module3.exports = Promise2;
              } else if (!root.Promise) {
                root.Promise = Promise2;
              }
            })(commonjsGlobal);
          })(promise);
          var promisePolyfill = promise.exports;
          var Global = function() {
            if (typeof window !== "undefined") {
              return window;
            } else {
              return Function("return this;")();
            }
          }();
          var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
          return promisePolyfill_1;
        });
      })(void 0, exports$1, module$1);
      var Promise$1 = module$1.exports.boltExport;
      var nu$1 = function(baseFn) {
        var data2 = Optional.none();
        var callbacks = [];
        var map2 = function(f) {
          return nu$1(function(nCallback) {
            get2(function(data3) {
              nCallback(f(data3));
            });
          });
        };
        var get2 = function(nCallback) {
          if (isReady()) {
            call2(nCallback);
          } else {
            callbacks.push(nCallback);
          }
        };
        var set2 = function(x) {
          if (!isReady()) {
            data2 = Optional.some(x);
            run(callbacks);
            callbacks = [];
          }
        };
        var isReady = function() {
          return data2.isSome();
        };
        var run = function(cbs) {
          each$k(cbs, call2);
        };
        var call2 = function(cb) {
          data2.each(function(x) {
            setTimeout(function() {
              cb(x);
            }, 0);
          });
        };
        baseFn(set2);
        return {
          get: get2,
          map: map2,
          isReady
        };
      };
      var pure$1 = function(a) {
        return nu$1(function(callback) {
          callback(a);
        });
      };
      var LazyValue = {
        nu: nu$1,
        pure: pure$1
      };
      var errorReporter = function(err) {
        setTimeout(function() {
          throw err;
        }, 0);
      };
      var make = function(run) {
        var get2 = function(callback) {
          run().then(callback, errorReporter);
        };
        var map2 = function(fab) {
          return make(function() {
            return run().then(fab);
          });
        };
        var bind2 = function(aFutureB) {
          return make(function() {
            return run().then(function(v) {
              return aFutureB(v).toPromise();
            });
          });
        };
        var anonBind = function(futureB) {
          return make(function() {
            return run().then(function() {
              return futureB.toPromise();
            });
          });
        };
        var toLazy = function() {
          return LazyValue.nu(get2);
        };
        var toCached = function() {
          var cache = null;
          return make(function() {
            if (cache === null) {
              cache = run();
            }
            return cache;
          });
        };
        var toPromise = run;
        return {
          map: map2,
          bind: bind2,
          anonBind,
          toLazy,
          toCached,
          toPromise,
          get: get2
        };
      };
      var nu = function(baseFn) {
        return make(function() {
          return new Promise$1(baseFn);
        });
      };
      var pure = function(a) {
        return make(function() {
          return Promise$1.resolve(a);
        });
      };
      var Future = {
        nu,
        pure
      };
      var par$1 = function(asyncValues, nu2) {
        return nu2(function(callback) {
          var r2 = [];
          var count2 = 0;
          var cb = function(i) {
            return function(value2) {
              r2[i] = value2;
              count2++;
              if (count2 >= asyncValues.length) {
                callback(r2);
              }
            };
          };
          if (asyncValues.length === 0) {
            callback([]);
          } else {
            each$k(asyncValues, function(asyncValue, i) {
              asyncValue.get(cb(i));
            });
          }
        });
      };
      var par = function(futures) {
        return par$1(futures, Future.nu);
      };
      var value$1 = function(o) {
        var or2 = function(_opt) {
          return value$1(o);
        };
        var orThunk = function(_f) {
          return value$1(o);
        };
        var map2 = function(f) {
          return value$1(f(o));
        };
        var mapError = function(_f) {
          return value$1(o);
        };
        var each2 = function(f) {
          f(o);
        };
        var bind2 = function(f) {
          return f(o);
        };
        var fold = function(_, onValue) {
          return onValue(o);
        };
        var exists2 = function(f) {
          return f(o);
        };
        var forall2 = function(f) {
          return f(o);
        };
        var toOptional = function() {
          return Optional.some(o);
        };
        return {
          isValue: always,
          isError: never,
          getOr: constant(o),
          getOrThunk: constant(o),
          getOrDie: constant(o),
          or: or2,
          orThunk,
          fold,
          map: map2,
          mapError,
          each: each2,
          bind: bind2,
          exists: exists2,
          forall: forall2,
          toOptional
        };
      };
      var error = function(message) {
        var getOrThunk = function(f) {
          return f();
        };
        var getOrDie = function() {
          return die(String(message))();
        };
        var or2 = identity;
        var orThunk = function(f) {
          return f();
        };
        var map2 = function(_f) {
          return error(message);
        };
        var mapError = function(f) {
          return error(f(message));
        };
        var bind2 = function(_f) {
          return error(message);
        };
        var fold = function(onError, _) {
          return onError(message);
        };
        return {
          isValue: never,
          isError: always,
          getOr: identity,
          getOrThunk,
          getOrDie,
          or: or2,
          orThunk,
          fold,
          map: map2,
          mapError,
          each: noop,
          bind: bind2,
          exists: never,
          forall: always,
          toOptional: Optional.none
        };
      };
      var fromOption = function(opt, err) {
        return opt.fold(function() {
          return error(err);
        }, value$1);
      };
      var Result = {
        value: value$1,
        error,
        fromOption
      };
      var generate$1 = function(cases) {
        if (!isArray$1(cases)) {
          throw new Error("cases must be an array");
        }
        if (cases.length === 0) {
          throw new Error("there must be at least one case");
        }
        var constructors = [];
        var adt2 = {};
        each$k(cases, function(acase, count2) {
          var keys$1 = keys(acase);
          if (keys$1.length !== 1) {
            throw new Error("one and only one name per case");
          }
          var key = keys$1[0];
          var value2 = acase[key];
          if (adt2[key] !== void 0) {
            throw new Error("duplicate key detected:" + key);
          } else if (key === "cata") {
            throw new Error("cannot have a case named cata (sorry)");
          } else if (!isArray$1(value2)) {
            throw new Error("case arguments must be an array");
          }
          constructors.push(key);
          adt2[key] = function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            var argLength = args.length;
            if (argLength !== value2.length) {
              throw new Error("Wrong number of arguments to case " + key + ". Expected " + value2.length + " (" + value2 + "), got " + argLength);
            }
            var match2 = function(branches) {
              var branchKeys = keys(branches);
              if (constructors.length !== branchKeys.length) {
                throw new Error("Wrong number of arguments to match. Expected: " + constructors.join(",") + "\nActual: " + branchKeys.join(","));
              }
              var allReqd = forall(constructors, function(reqKey) {
                return contains$3(branchKeys, reqKey);
              });
              if (!allReqd) {
                throw new Error("Not all branches were specified when using match. Specified: " + branchKeys.join(", ") + "\nRequired: " + constructors.join(", "));
              }
              return branches[key].apply(null, args);
            };
            return {
              fold: function() {
                var foldArgs = [];
                for (var _i2 = 0; _i2 < arguments.length; _i2++) {
                  foldArgs[_i2] = arguments[_i2];
                }
                if (foldArgs.length !== cases.length) {
                  throw new Error("Wrong number of arguments to fold. Expected " + cases.length + ", got " + foldArgs.length);
                }
                var target = foldArgs[count2];
                return target.apply(null, args);
              },
              match: match2,
              log: function(label) {
                console.log(label, {
                  constructors,
                  constructor: key,
                  params: args
                });
              }
            };
          };
        });
        return adt2;
      };
      var Adt = { generate: generate$1 };
      Adt.generate([
        {
          bothErrors: [
            "error1",
            "error2"
          ]
        },
        {
          firstError: [
            "error1",
            "value2"
          ]
        },
        {
          secondError: [
            "value1",
            "error2"
          ]
        },
        {
          bothValues: [
            "value1",
            "value2"
          ]
        }
      ]);
      var unite = function(result) {
        return result.fold(identity, identity);
      };
      function ClosestOrAncestor(is2, ancestor2, scope, a, isRoot) {
        if (is2(scope, a)) {
          return Optional.some(scope);
        } else if (isFunction(isRoot) && isRoot(scope)) {
          return Optional.none();
        } else {
          return ancestor2(scope, a, isRoot);
        }
      }
      var ancestor$3 = function(scope, predicate, isRoot) {
        var element = scope.dom;
        var stop2 = isFunction(isRoot) ? isRoot : never;
        while (element.parentNode) {
          element = element.parentNode;
          var el = SugarElement.fromDom(element);
          if (predicate(el)) {
            return Optional.some(el);
          } else if (stop2(el)) {
            break;
          }
        }
        return Optional.none();
      };
      var closest$3 = function(scope, predicate, isRoot) {
        var is2 = function(s, test2) {
          return test2(s);
        };
        return ClosestOrAncestor(is2, ancestor$3, scope, predicate, isRoot);
      };
      var sibling$2 = function(scope, predicate) {
        var element = scope.dom;
        if (!element.parentNode) {
          return Optional.none();
        }
        return child(SugarElement.fromDom(element.parentNode), function(x) {
          return !eq(scope, x) && predicate(x);
        });
      };
      var child = function(scope, predicate) {
        var pred = function(node) {
          return predicate(SugarElement.fromDom(node));
        };
        var result = find$3(scope.dom.childNodes, pred);
        return result.map(SugarElement.fromDom);
      };
      var ancestor$2 = function(scope, selector, isRoot) {
        return ancestor$3(scope, function(e) {
          return is$2(e, selector);
        }, isRoot);
      };
      var descendant = function(scope, selector) {
        return one(selector, scope);
      };
      var closest$2 = function(scope, selector, isRoot) {
        var is2 = function(element, selector2) {
          return is$2(element, selector2);
        };
        return ClosestOrAncestor(is2, ancestor$2, scope, selector, isRoot);
      };
      var promiseObj = window.Promise ? window.Promise : Promise$1;
      var requestAnimationFramePromise;
      var requestAnimationFrame = function(callback, element) {
        var requestAnimationFrameFunc = window.requestAnimationFrame;
        var vendors = [
          "ms",
          "moz",
          "webkit"
        ];
        var featurefill = function(cb) {
          window.setTimeout(cb, 0);
        };
        for (var i = 0; i < vendors.length && !requestAnimationFrameFunc; i++) {
          requestAnimationFrameFunc = window[vendors[i] + "RequestAnimationFrame"];
        }
        if (!requestAnimationFrameFunc) {
          requestAnimationFrameFunc = featurefill;
        }
        requestAnimationFrameFunc(callback, element);
      };
      var wrappedSetTimeout = function(callback, time) {
        if (typeof time !== "number") {
          time = 0;
        }
        return setTimeout(callback, time);
      };
      var wrappedSetInterval = function(callback, time) {
        if (typeof time !== "number") {
          time = 1;
        }
        return setInterval(callback, time);
      };
      var wrappedClearTimeout = function(id) {
        return clearTimeout(id);
      };
      var wrappedClearInterval = function(id) {
        return clearInterval(id);
      };
      var debounce = function(callback, time) {
        var timer;
        var func = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          clearTimeout(timer);
          timer = wrappedSetTimeout(function() {
            callback.apply(this, args);
          }, time);
        };
        func.stop = function() {
          clearTimeout(timer);
        };
        return func;
      };
      var Delay = {
        requestAnimationFrame: function(callback, element) {
          if (requestAnimationFramePromise) {
            requestAnimationFramePromise.then(callback);
            return;
          }
          requestAnimationFramePromise = new promiseObj(function(resolve2) {
            if (!element) {
              element = document.body;
            }
            requestAnimationFrame(resolve2, element);
          }).then(callback);
        },
        setTimeout: wrappedSetTimeout,
        setInterval: wrappedSetInterval,
        setEditorTimeout: function(editor, callback, time) {
          return wrappedSetTimeout(function() {
            if (!editor.removed) {
              callback();
            }
          }, time);
        },
        setEditorInterval: function(editor, callback, time) {
          var timer = wrappedSetInterval(function() {
            if (!editor.removed) {
              callback();
            } else {
              clearInterval(timer);
            }
          }, time);
          return timer;
        },
        debounce,
        throttle: debounce,
        clearInterval: wrappedClearInterval,
        clearTimeout: wrappedClearTimeout
      };
      var StyleSheetLoader = function(documentOrShadowRoot, settings) {
        if (settings === void 0) {
          settings = {};
        }
        var idCount = 0;
        var loadedStates = {};
        var edos = SugarElement.fromDom(documentOrShadowRoot);
        var doc2 = documentOrOwner(edos);
        var maxLoadTime = settings.maxLoadTime || 5e3;
        var _setReferrerPolicy = function(referrerPolicy) {
          settings.referrerPolicy = referrerPolicy;
        };
        var addStyle = function(element) {
          append$1(getStyleContainer(edos), element);
        };
        var removeStyle = function(id) {
          var styleContainer = getStyleContainer(edos);
          descendant(styleContainer, "#" + id).each(remove$7);
        };
        var getOrCreateState = function(url) {
          return get$9(loadedStates, url).getOrThunk(function() {
            return {
              id: "mce-u" + idCount++,
              passed: [],
              failed: [],
              count: 0
            };
          });
        };
        var load = function(url, success, failure) {
          var link;
          var urlWithSuffix = Tools._addCacheSuffix(url);
          var state = getOrCreateState(urlWithSuffix);
          loadedStates[urlWithSuffix] = state;
          state.count++;
          var resolve2 = function(callbacks, status) {
            var i = callbacks.length;
            while (i--) {
              callbacks[i]();
            }
            state.status = status;
            state.passed = [];
            state.failed = [];
            if (link) {
              link.onload = null;
              link.onerror = null;
              link = null;
            }
          };
          var passed = function() {
            return resolve2(state.passed, 2);
          };
          var failed = function() {
            return resolve2(state.failed, 3);
          };
          var wait = function(testCallback, waitCallback) {
            if (!testCallback()) {
              if (Date.now() - startTime < maxLoadTime) {
                Delay.setTimeout(waitCallback);
              } else {
                failed();
              }
            }
          };
          var waitForWebKitLinkLoaded = function() {
            wait(function() {
              var styleSheets = documentOrShadowRoot.styleSheets;
              var i = styleSheets.length;
              while (i--) {
                var styleSheet = styleSheets[i];
                var owner2 = styleSheet.ownerNode;
                if (owner2 && owner2.id === link.id) {
                  passed();
                  return true;
                }
              }
              return false;
            }, waitForWebKitLinkLoaded);
          };
          if (success) {
            state.passed.push(success);
          }
          if (failure) {
            state.failed.push(failure);
          }
          if (state.status === 1) {
            return;
          }
          if (state.status === 2) {
            passed();
            return;
          }
          if (state.status === 3) {
            failed();
            return;
          }
          state.status = 1;
          var linkElem = SugarElement.fromTag("link", doc2.dom);
          setAll$1(linkElem, {
            rel: "stylesheet",
            type: "text/css",
            id: state.id
          });
          var startTime = Date.now();
          if (settings.contentCssCors) {
            set$1(linkElem, "crossOrigin", "anonymous");
          }
          if (settings.referrerPolicy) {
            set$1(linkElem, "referrerpolicy", settings.referrerPolicy);
          }
          link = linkElem.dom;
          link.onload = waitForWebKitLinkLoaded;
          link.onerror = failed;
          addStyle(linkElem);
          set$1(linkElem, "href", urlWithSuffix);
        };
        var loadF = function(url) {
          return Future.nu(function(resolve2) {
            load(url, compose(resolve2, constant(Result.value(url))), compose(resolve2, constant(Result.error(url))));
          });
        };
        var loadAll = function(urls, success, failure) {
          par(map$3(urls, loadF)).get(function(result) {
            var parts = partition(result, function(r2) {
              return r2.isValue();
            });
            if (parts.fail.length > 0) {
              failure(parts.fail.map(unite));
            } else {
              success(parts.pass.map(unite));
            }
          });
        };
        var unload = function(url) {
          var urlWithSuffix = Tools._addCacheSuffix(url);
          get$9(loadedStates, urlWithSuffix).each(function(state) {
            var count2 = --state.count;
            if (count2 === 0) {
              delete loadedStates[urlWithSuffix];
              removeStyle(state.id);
            }
          });
        };
        var unloadAll = function(urls) {
          each$k(urls, function(url) {
            unload(url);
          });
        };
        return {
          load,
          loadAll,
          unload,
          unloadAll,
          _setReferrerPolicy
        };
      };
      var create$8 = function() {
        var map2 = /* @__PURE__ */ new WeakMap();
        var forElement = function(referenceElement, settings) {
          var root = getRootNode(referenceElement);
          var rootDom = root.dom;
          return Optional.from(map2.get(rootDom)).getOrThunk(function() {
            var sl = StyleSheetLoader(rootDom, settings);
            map2.set(rootDom, sl);
            return sl;
          });
        };
        return { forElement };
      };
      var instance = create$8();
      var DomTreeWalker = function() {
        function DomTreeWalker2(startNode, rootNode) {
          this.node = startNode;
          this.rootNode = rootNode;
          this.current = this.current.bind(this);
          this.next = this.next.bind(this);
          this.prev = this.prev.bind(this);
          this.prev2 = this.prev2.bind(this);
        }
        DomTreeWalker2.prototype.current = function() {
          return this.node;
        };
        DomTreeWalker2.prototype.next = function(shallow2) {
          this.node = this.findSibling(this.node, "firstChild", "nextSibling", shallow2);
          return this.node;
        };
        DomTreeWalker2.prototype.prev = function(shallow2) {
          this.node = this.findSibling(this.node, "lastChild", "previousSibling", shallow2);
          return this.node;
        };
        DomTreeWalker2.prototype.prev2 = function(shallow2) {
          this.node = this.findPreviousNode(this.node, "lastChild", "previousSibling", shallow2);
          return this.node;
        };
        DomTreeWalker2.prototype.findSibling = function(node, startName, siblingName, shallow2) {
          var sibling2, parent2;
          if (node) {
            if (!shallow2 && node[startName]) {
              return node[startName];
            }
            if (node !== this.rootNode) {
              sibling2 = node[siblingName];
              if (sibling2) {
                return sibling2;
              }
              for (parent2 = node.parentNode; parent2 && parent2 !== this.rootNode; parent2 = parent2.parentNode) {
                sibling2 = parent2[siblingName];
                if (sibling2) {
                  return sibling2;
                }
              }
            }
          }
        };
        DomTreeWalker2.prototype.findPreviousNode = function(node, startName, siblingName, shallow2) {
          var sibling2, parent2, child2;
          if (node) {
            sibling2 = node[siblingName];
            if (this.rootNode && sibling2 === this.rootNode) {
              return;
            }
            if (sibling2) {
              if (!shallow2) {
                for (child2 = sibling2[startName]; child2; child2 = child2[startName]) {
                  if (!child2[startName]) {
                    return child2;
                  }
                }
              }
              return sibling2;
            }
            parent2 = node.parentNode;
            if (parent2 && parent2 !== this.rootNode) {
              return parent2;
            }
          }
        };
        return DomTreeWalker2;
      }();
      var blocks = [
        "article",
        "aside",
        "details",
        "div",
        "dt",
        "figcaption",
        "footer",
        "form",
        "fieldset",
        "header",
        "hgroup",
        "html",
        "main",
        "nav",
        "section",
        "summary",
        "body",
        "p",
        "dl",
        "multicol",
        "dd",
        "figure",
        "address",
        "center",
        "blockquote",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "listing",
        "xmp",
        "pre",
        "plaintext",
        "menu",
        "dir",
        "ul",
        "ol",
        "li",
        "hr",
        "table",
        "tbody",
        "thead",
        "tfoot",
        "th",
        "tr",
        "td",
        "caption"
      ];
      var tableCells = [
        "td",
        "th"
      ];
      var tableSections = [
        "thead",
        "tbody",
        "tfoot"
      ];
      var textBlocks = [
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "p",
        "div",
        "address",
        "pre",
        "form",
        "blockquote",
        "center",
        "dir",
        "fieldset",
        "header",
        "footer",
        "article",
        "section",
        "hgroup",
        "aside",
        "nav",
        "figure"
      ];
      var headings = [
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6"
      ];
      var listItems$1 = [
        "li",
        "dd",
        "dt"
      ];
      var lists = [
        "ul",
        "ol",
        "dl"
      ];
      var wsElements = [
        "pre",
        "script",
        "textarea",
        "style"
      ];
      var lazyLookup = function(items) {
        var lookup;
        return function(node) {
          lookup = lookup ? lookup : mapToObject(items, always);
          return has$2(lookup, name(node));
        };
      };
      var isHeading = lazyLookup(headings);
      var isBlock$2 = lazyLookup(blocks);
      var isTable$2 = function(node) {
        return name(node) === "table";
      };
      var isInline$1 = function(node) {
        return isElement$6(node) && !isBlock$2(node);
      };
      var isBr$4 = function(node) {
        return isElement$6(node) && name(node) === "br";
      };
      var isTextBlock$2 = lazyLookup(textBlocks);
      var isList = lazyLookup(lists);
      var isListItem = lazyLookup(listItems$1);
      var isTableSection = lazyLookup(tableSections);
      var isTableCell$4 = lazyLookup(tableCells);
      var isWsPreserveElement = lazyLookup(wsElements);
      var ancestor$1 = function(scope, selector, isRoot) {
        return ancestor$2(scope, selector, isRoot).isSome();
      };
      var zeroWidth = "\uFEFF";
      var nbsp = "\xA0";
      var isZwsp$1 = function(char) {
        return char === zeroWidth;
      };
      var removeZwsp = function(s) {
        return s.replace(/\uFEFF/g, "");
      };
      var ZWSP$1 = zeroWidth;
      var isZwsp = isZwsp$1;
      var trim$2 = removeZwsp;
      var isElement$4 = isElement$5;
      var isText$6 = isText$7;
      var isCaretContainerBlock$1 = function(node) {
        if (isText$6(node)) {
          node = node.parentNode;
        }
        return isElement$4(node) && node.hasAttribute("data-mce-caret");
      };
      var isCaretContainerInline = function(node) {
        return isText$6(node) && isZwsp(node.data);
      };
      var isCaretContainer$2 = function(node) {
        return isCaretContainerBlock$1(node) || isCaretContainerInline(node);
      };
      var hasContent = function(node) {
        return node.firstChild !== node.lastChild || !isBr$5(node.firstChild);
      };
      var insertInline$1 = function(node, before2) {
        var doc2 = node.ownerDocument;
        var textNode = doc2.createTextNode(ZWSP$1);
        var parentNode = node.parentNode;
        if (!before2) {
          var sibling2 = node.nextSibling;
          if (isText$6(sibling2)) {
            if (isCaretContainer$2(sibling2)) {
              return sibling2;
            }
            if (startsWithCaretContainer$1(sibling2)) {
              sibling2.splitText(1);
              return sibling2;
            }
          }
          if (node.nextSibling) {
            parentNode.insertBefore(textNode, node.nextSibling);
          } else {
            parentNode.appendChild(textNode);
          }
        } else {
          var sibling2 = node.previousSibling;
          if (isText$6(sibling2)) {
            if (isCaretContainer$2(sibling2)) {
              return sibling2;
            }
            if (endsWithCaretContainer$1(sibling2)) {
              return sibling2.splitText(sibling2.data.length - 1);
            }
          }
          parentNode.insertBefore(textNode, node);
        }
        return textNode;
      };
      var isBeforeInline = function(pos) {
        var container = pos.container();
        if (!isText$7(container)) {
          return false;
        }
        return container.data.charAt(pos.offset()) === ZWSP$1 || pos.isAtStart() && isCaretContainerInline(container.previousSibling);
      };
      var isAfterInline = function(pos) {
        var container = pos.container();
        if (!isText$7(container)) {
          return false;
        }
        return container.data.charAt(pos.offset() - 1) === ZWSP$1 || pos.isAtEnd() && isCaretContainerInline(container.nextSibling);
      };
      var createBogusBr = function() {
        var br = document.createElement("br");
        br.setAttribute("data-mce-bogus", "1");
        return br;
      };
      var insertBlock$1 = function(blockName, node, before2) {
        var doc2 = node.ownerDocument;
        var blockNode = doc2.createElement(blockName);
        blockNode.setAttribute("data-mce-caret", before2 ? "before" : "after");
        blockNode.setAttribute("data-mce-bogus", "all");
        blockNode.appendChild(createBogusBr());
        var parentNode = node.parentNode;
        if (!before2) {
          if (node.nextSibling) {
            parentNode.insertBefore(blockNode, node.nextSibling);
          } else {
            parentNode.appendChild(blockNode);
          }
        } else {
          parentNode.insertBefore(blockNode, node);
        }
        return blockNode;
      };
      var startsWithCaretContainer$1 = function(node) {
        return isText$6(node) && node.data[0] === ZWSP$1;
      };
      var endsWithCaretContainer$1 = function(node) {
        return isText$6(node) && node.data[node.data.length - 1] === ZWSP$1;
      };
      var trimBogusBr = function(elm) {
        var brs = elm.getElementsByTagName("br");
        var lastBr = brs[brs.length - 1];
        if (isBogus$2(lastBr)) {
          lastBr.parentNode.removeChild(lastBr);
        }
      };
      var showCaretContainerBlock = function(caretContainer) {
        if (caretContainer && caretContainer.hasAttribute("data-mce-caret")) {
          trimBogusBr(caretContainer);
          caretContainer.removeAttribute("data-mce-caret");
          caretContainer.removeAttribute("data-mce-bogus");
          caretContainer.removeAttribute("style");
          caretContainer.removeAttribute("_moz_abspos");
          return caretContainer;
        }
        return null;
      };
      var isRangeInCaretContainerBlock = function(range2) {
        return isCaretContainerBlock$1(range2.startContainer);
      };
      var isContentEditableTrue$3 = isContentEditableTrue$4;
      var isContentEditableFalse$a = isContentEditableFalse$b;
      var isBr$3 = isBr$5;
      var isText$5 = isText$7;
      var isInvalidTextElement = matchNodeNames([
        "script",
        "style",
        "textarea"
      ]);
      var isAtomicInline = matchNodeNames([
        "img",
        "input",
        "textarea",
        "hr",
        "iframe",
        "video",
        "audio",
        "object",
        "embed"
      ]);
      var isTable$1 = matchNodeNames(["table"]);
      var isCaretContainer$1 = isCaretContainer$2;
      var isCaretCandidate$3 = function(node) {
        if (isCaretContainer$1(node)) {
          return false;
        }
        if (isText$5(node)) {
          return !isInvalidTextElement(node.parentNode);
        }
        return isAtomicInline(node) || isBr$3(node) || isTable$1(node) || isNonUiContentEditableFalse(node);
      };
      var isUnselectable = function(node) {
        return isElement$5(node) && node.getAttribute("unselectable") === "true";
      };
      var isNonUiContentEditableFalse = function(node) {
        return isUnselectable(node) === false && isContentEditableFalse$a(node);
      };
      var isInEditable = function(node, root) {
        for (node = node.parentNode; node && node !== root; node = node.parentNode) {
          if (isNonUiContentEditableFalse(node)) {
            return false;
          }
          if (isContentEditableTrue$3(node)) {
            return true;
          }
        }
        return true;
      };
      var isAtomicContentEditableFalse = function(node) {
        if (!isNonUiContentEditableFalse(node)) {
          return false;
        }
        return foldl(from(node.getElementsByTagName("*")), function(result, elm) {
          return result || isContentEditableTrue$3(elm);
        }, false) !== true;
      };
      var isAtomic$1 = function(node) {
        return isAtomicInline(node) || isAtomicContentEditableFalse(node);
      };
      var isEditableCaretCandidate$1 = function(node, root) {
        return isCaretCandidate$3(node) && isInEditable(node, root);
      };
      var whiteSpaceRegExp$1 = /^[ \t\r\n]*$/;
      var isWhitespaceText = function(text) {
        return whiteSpaceRegExp$1.test(text);
      };
      var hasWhitespacePreserveParent = function(node, rootNode) {
        var rootElement = SugarElement.fromDom(rootNode);
        var startNode = SugarElement.fromDom(node);
        return ancestor$1(startNode, "pre,code", curry(eq, rootElement));
      };
      var isWhitespace = function(node, rootNode) {
        return isText$7(node) && isWhitespaceText(node.data) && hasWhitespacePreserveParent(node, rootNode) === false;
      };
      var isNamedAnchor = function(node) {
        return isElement$5(node) && node.nodeName === "A" && !node.hasAttribute("href") && (node.hasAttribute("name") || node.hasAttribute("id"));
      };
      var isContent$1 = function(node, rootNode) {
        return isCaretCandidate$3(node) && isWhitespace(node, rootNode) === false || isNamedAnchor(node) || isBookmark(node);
      };
      var isBookmark = hasAttribute("data-mce-bookmark");
      var isBogus$1 = hasAttribute("data-mce-bogus");
      var isBogusAll = hasAttributeValue("data-mce-bogus", "all");
      var isEmptyNode = function(targetNode, skipBogus) {
        var brCount = 0;
        if (isContent$1(targetNode, targetNode)) {
          return false;
        } else {
          var node = targetNode.firstChild;
          if (!node) {
            return true;
          }
          var walker = new DomTreeWalker(node, targetNode);
          do {
            if (skipBogus) {
              if (isBogusAll(node)) {
                node = walker.next(true);
                continue;
              }
              if (isBogus$1(node)) {
                node = walker.next();
                continue;
              }
            }
            if (isBr$5(node)) {
              brCount++;
              node = walker.next();
              continue;
            }
            if (isContent$1(node, targetNode)) {
              return false;
            }
            node = walker.next();
          } while (node);
          return brCount <= 1;
        }
      };
      var isEmpty$2 = function(elm, skipBogus) {
        if (skipBogus === void 0) {
          skipBogus = true;
        }
        return isEmptyNode(elm.dom, skipBogus);
      };
      var isSpan = function(node) {
        return node.nodeName.toLowerCase() === "span";
      };
      var isInlineContent = function(node, root) {
        return isNonNullable(node) && (isContent$1(node, root) || isInline$1(SugarElement.fromDom(node)));
      };
      var surroundedByInlineContent = function(node, root) {
        var prev = new DomTreeWalker(node, root).prev(false);
        var next = new DomTreeWalker(node, root).next(false);
        var prevIsInline = isUndefined(prev) || isInlineContent(prev, root);
        var nextIsInline = isUndefined(next) || isInlineContent(next, root);
        return prevIsInline && nextIsInline;
      };
      var isBookmarkNode$2 = function(node) {
        return isSpan(node) && node.getAttribute("data-mce-type") === "bookmark";
      };
      var isKeepTextNode = function(node, root) {
        return isText$7(node) && node.data.length > 0 && surroundedByInlineContent(node, root);
      };
      var isKeepElement = function(node) {
        return isElement$5(node) ? node.childNodes.length > 0 : false;
      };
      var isDocument = function(node) {
        return isDocumentFragment(node) || isDocument$1(node);
      };
      var trimNode = function(dom2, node, root) {
        var rootNode = root || node;
        if (isElement$5(node) && isBookmarkNode$2(node)) {
          return node;
        }
        var children2 = node.childNodes;
        for (var i = children2.length - 1; i >= 0; i--) {
          trimNode(dom2, children2[i], rootNode);
        }
        if (isElement$5(node)) {
          var currentChildren = node.childNodes;
          if (currentChildren.length === 1 && isBookmarkNode$2(currentChildren[0])) {
            node.parentNode.insertBefore(currentChildren[0], node);
          }
        }
        if (!isDocument(node) && !isContent$1(node, rootNode) && !isKeepElement(node) && !isKeepTextNode(node, rootNode)) {
          dom2.remove(node);
        }
        return node;
      };
      var makeMap$3 = Tools.makeMap;
      var attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
      var textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
      var rawCharsRegExp = /[<>&\"\']/g;
      var entityRegExp = /&#([a-z0-9]+);?|&([a-z0-9]+);/gi;
      var asciiMap = {
        128: "\u20AC",
        130: "\u201A",
        131: "\u0192",
        132: "\u201E",
        133: "\u2026",
        134: "\u2020",
        135: "\u2021",
        136: "\u02C6",
        137: "\u2030",
        138: "\u0160",
        139: "\u2039",
        140: "\u0152",
        142: "\u017D",
        145: "\u2018",
        146: "\u2019",
        147: "\u201C",
        148: "\u201D",
        149: "\u2022",
        150: "\u2013",
        151: "\u2014",
        152: "\u02DC",
        153: "\u2122",
        154: "\u0161",
        155: "\u203A",
        156: "\u0153",
        158: "\u017E",
        159: "\u0178"
      };
      var baseEntities = {
        '"': "&quot;",
        "'": "&#39;",
        "<": "&lt;",
        ">": "&gt;",
        "&": "&amp;",
        "`": "&#96;"
      };
      var reverseEntities = {
        "&lt;": "<",
        "&gt;": ">",
        "&amp;": "&",
        "&quot;": '"',
        "&apos;": "'"
      };
      var nativeDecode = function(text) {
        var elm = SugarElement.fromTag("div").dom;
        elm.innerHTML = text;
        return elm.textContent || elm.innerText || text;
      };
      var buildEntitiesLookup = function(items, radix) {
        var i, chr, entity;
        var lookup = {};
        if (items) {
          items = items.split(",");
          radix = radix || 10;
          for (i = 0; i < items.length; i += 2) {
            chr = String.fromCharCode(parseInt(items[i], radix));
            if (!baseEntities[chr]) {
              entity = "&" + items[i + 1] + ";";
              lookup[chr] = entity;
              lookup[entity] = chr;
            }
          }
          return lookup;
        }
      };
      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);
      var encodeRaw = function(text, attr) {
        return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
          return baseEntities[chr] || chr;
        });
      };
      var encodeAllRaw = function(text) {
        return ("" + text).replace(rawCharsRegExp, function(chr) {
          return baseEntities[chr] || chr;
        });
      };
      var encodeNumeric = function(text, attr) {
        return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
          if (chr.length > 1) {
            return "&#" + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ";";
          }
          return baseEntities[chr] || "&#" + chr.charCodeAt(0) + ";";
        });
      };
      var encodeNamed = function(text, attr, entities) {
        entities = entities || namedEntities;
        return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
          return baseEntities[chr] || entities[chr] || chr;
        });
      };
      var getEncodeFunc = function(name2, entities) {
        var entitiesMap = buildEntitiesLookup(entities) || namedEntities;
        var encodeNamedAndNumeric = function(text, attr) {
          return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
            if (baseEntities[chr] !== void 0) {
              return baseEntities[chr];
            }
            if (entitiesMap[chr] !== void 0) {
              return entitiesMap[chr];
            }
            if (chr.length > 1) {
              return "&#" + ((chr.charCodeAt(0) - 55296) * 1024 + (chr.charCodeAt(1) - 56320) + 65536) + ";";
            }
            return "&#" + chr.charCodeAt(0) + ";";
          });
        };
        var encodeCustomNamed = function(text, attr) {
          return encodeNamed(text, attr, entitiesMap);
        };
        var nameMap = makeMap$3(name2.replace(/\+/g, ","));
        if (nameMap.named && nameMap.numeric) {
          return encodeNamedAndNumeric;
        }
        if (nameMap.named) {
          if (entities) {
            return encodeCustomNamed;
          }
          return encodeNamed;
        }
        if (nameMap.numeric) {
          return encodeNumeric;
        }
        return encodeRaw;
      };
      var decode = function(text) {
        return text.replace(entityRegExp, function(all2, numeric) {
          if (numeric) {
            if (numeric.charAt(0).toLowerCase() === "x") {
              numeric = parseInt(numeric.substr(1), 16);
            } else {
              numeric = parseInt(numeric, 10);
            }
            if (numeric > 65535) {
              numeric -= 65536;
              return String.fromCharCode(55296 + (numeric >> 10), 56320 + (numeric & 1023));
            }
            return asciiMap[numeric] || String.fromCharCode(numeric);
          }
          return reverseEntities[all2] || namedEntities[all2] || nativeDecode(all2);
        });
      };
      var Entities = {
        encodeRaw,
        encodeAllRaw,
        encodeNumeric,
        encodeNamed,
        getEncodeFunc,
        decode
      };
      var mapCache = {}, dummyObj = {};
      var makeMap$2 = Tools.makeMap, each$h = Tools.each, extend$5 = Tools.extend, explode$3 = Tools.explode, inArray$2 = Tools.inArray;
      var split$1 = function(items, delim) {
        items = Tools.trim(items);
        return items ? items.split(delim || " ") : [];
      };
      var createMap = function(defaultValue, extendWith) {
        var value2 = makeMap$2(defaultValue, " ", makeMap$2(defaultValue.toUpperCase(), " "));
        return extend$5(value2, extendWith);
      };
      var getTextRootBlockElements = function(schema) {
        return createMap("td th li dt dd figcaption caption details summary", schema.getTextBlockElements());
      };
      var compileSchema = function(type2) {
        var schema = {};
        var globalAttributes, blockContent;
        var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
        var add2 = function(name2, attributes2, children2) {
          var ni, attributesOrder, element;
          var arrayToMap = function(array, obj) {
            var map2 = {};
            var i, l;
            for (i = 0, l = array.length; i < l; i++) {
              map2[array[i]] = obj || {};
            }
            return map2;
          };
          children2 = children2 || [];
          attributes2 = attributes2 || "";
          if (typeof children2 === "string") {
            children2 = split$1(children2);
          }
          var names = split$1(name2);
          ni = names.length;
          while (ni--) {
            attributesOrder = split$1([
              globalAttributes,
              attributes2
            ].join(" "));
            element = {
              attributes: arrayToMap(attributesOrder),
              attributesOrder,
              children: arrayToMap(children2, dummyObj)
            };
            schema[names[ni]] = element;
          }
        };
        var addAttrs = function(name2, attributes2) {
          var ni, schemaItem, i, l;
          var names = split$1(name2);
          ni = names.length;
          var attrs = split$1(attributes2);
          while (ni--) {
            schemaItem = schema[names[ni]];
            for (i = 0, l = attrs.length; i < l; i++) {
              schemaItem.attributes[attrs[i]] = {};
              schemaItem.attributesOrder.push(attrs[i]);
            }
          }
        };
        if (mapCache[type2]) {
          return mapCache[type2];
        }
        globalAttributes = "id accesskey class dir lang style tabindex title role";
        blockContent = "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul";
        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";
        if (type2 !== "html4") {
          globalAttributes += " contenteditable contextmenu draggable dropzone hidden spellcheck translate";
          blockContent += " article aside details dialog figure main header footer hgroup section nav";
          phrasingContent += " audio canvas command datalist mark meter output picture progress time wbr video ruby bdi keygen";
        }
        if (type2 !== "html5-strict") {
          globalAttributes += " xml:lang";
          html4PhrasingContent = "acronym applet basefont big font strike tt";
          phrasingContent = [
            phrasingContent,
            html4PhrasingContent
          ].join(" ");
          each$h(split$1(html4PhrasingContent), function(name2) {
            add2(name2, "", phrasingContent);
          });
          html4BlockContent = "center dir isindex noframes";
          blockContent = [
            blockContent,
            html4BlockContent
          ].join(" ");
          flowContent = [
            blockContent,
            phrasingContent
          ].join(" ");
          each$h(split$1(html4BlockContent), function(name2) {
            add2(name2, "", flowContent);
          });
        }
        flowContent = flowContent || [
          blockContent,
          phrasingContent
        ].join(" ");
        add2("html", "manifest", "head body");
        add2("head", "", "base command link meta noscript script style title");
        add2("title hr noscript br");
        add2("base", "href target");
        add2("link", "href rel media hreflang type sizes hreflang");
        add2("meta", "name http-equiv content charset");
        add2("style", "media type scoped");
        add2("script", "src async defer type charset");
        add2("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus onhashchange onload onmessage onoffline ononline onpagehide onpageshow onpopstate onresize onscroll onstorage onunload", flowContent);
        add2("address dt dd div caption", "", flowContent);
        add2("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);
        add2("blockquote", "cite", flowContent);
        add2("ol", "reversed start type", "li");
        add2("ul", "", "li");
        add2("li", "value", flowContent);
        add2("dl", "", "dt dd");
        add2("a", "href target rel media hreflang type", phrasingContent);
        add2("q", "cite", phrasingContent);
        add2("ins del", "cite datetime", flowContent);
        add2("img", "src sizes srcset alt usemap ismap width height");
        add2("iframe", "src name width height", flowContent);
        add2("embed", "src type width height");
        add2("object", "data type typemustmatch name usemap form width height", [
          flowContent,
          "param"
        ].join(" "));
        add2("param", "name value");
        add2("map", "name", [
          flowContent,
          "area"
        ].join(" "));
        add2("area", "alt coords shape href target rel media hreflang type");
        add2("table", "border", "caption colgroup thead tfoot tbody tr" + (type2 === "html4" ? " col" : ""));
        add2("colgroup", "span", "col");
        add2("col", "span");
        add2("tbody thead tfoot", "", "tr");
        add2("tr", "", "td th");
        add2("td", "colspan rowspan headers", flowContent);
        add2("th", "colspan rowspan headers scope abbr", flowContent);
        add2("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent);
        add2("fieldset", "disabled form name", [
          flowContent,
          "legend"
        ].join(" "));
        add2("label", "form for", phrasingContent);
        add2("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");
        add2("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value", type2 === "html4" ? flowContent : phrasingContent);
        add2("select", "disabled form multiple name required size", "option optgroup");
        add2("optgroup", "disabled label", "option");
        add2("option", "disabled label selected value");
        add2("textarea", "cols dirname disabled form maxlength name readonly required rows wrap");
        add2("menu", "type label", [
          flowContent,
          "li"
        ].join(" "));
        add2("noscript", "", flowContent);
        if (type2 !== "html4") {
          add2("wbr");
          add2("ruby", "", [
            phrasingContent,
            "rt rp"
          ].join(" "));
          add2("figcaption", "", flowContent);
          add2("mark rt rp summary bdi", "", phrasingContent);
          add2("canvas", "width height", flowContent);
          add2("video", "src crossorigin poster preload autoplay mediagroup loop muted controls width height buffered", [
            flowContent,
            "track source"
          ].join(" "));
          add2("audio", "src crossorigin preload autoplay mediagroup loop muted controls buffered volume", [
            flowContent,
            "track source"
          ].join(" "));
          add2("picture", "", "img source");
          add2("source", "src srcset type media sizes");
          add2("track", "kind src srclang label default");
          add2("datalist", "", [
            phrasingContent,
            "option"
          ].join(" "));
          add2("article section nav aside main header footer", "", flowContent);
          add2("hgroup", "", "h1 h2 h3 h4 h5 h6");
          add2("figure", "", [
            flowContent,
            "figcaption"
          ].join(" "));
          add2("time", "datetime", phrasingContent);
          add2("dialog", "open", flowContent);
          add2("command", "type label icon disabled checked radiogroup command");
          add2("output", "for form name", phrasingContent);
          add2("progress", "value max", phrasingContent);
          add2("meter", "value min max low high optimum", phrasingContent);
          add2("details", "open", [
            flowContent,
            "summary"
          ].join(" "));
          add2("keygen", "autofocus challenge disabled form keytype name");
        }
        if (type2 !== "html5-strict") {
          addAttrs("script", "language xml:space");
          addAttrs("style", "xml:space");
          addAttrs("object", "declare classid code codebase codetype archive standby align border hspace vspace");
          addAttrs("embed", "align name hspace vspace");
          addAttrs("param", "valuetype type");
          addAttrs("a", "charset name rev shape coords");
          addAttrs("br", "clear");
          addAttrs("applet", "codebase archive code object alt name width height align hspace vspace");
          addAttrs("img", "name longdesc align border hspace vspace");
          addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align");
          addAttrs("font basefont", "size color face");
          addAttrs("input", "usemap align");
          addAttrs("select");
          addAttrs("textarea");
          addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align");
          addAttrs("ul", "type compact");
          addAttrs("li", "type");
          addAttrs("ol dl menu dir", "compact");
          addAttrs("pre", "width xml:space");
          addAttrs("hr", "align noshade size width");
          addAttrs("isindex", "prompt");
          addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor");
          addAttrs("col", "width align char charoff valign");
          addAttrs("colgroup", "width align char charoff valign");
          addAttrs("thead", "align char charoff valign");
          addAttrs("tr", "align char charoff valign bgcolor");
          addAttrs("th", "axis align char charoff valign nowrap bgcolor width height");
          addAttrs("form", "accept");
          addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height");
          addAttrs("tfoot", "align char charoff valign");
          addAttrs("tbody", "align char charoff valign");
          addAttrs("area", "nohref");
          addAttrs("body", "background bgcolor text link vlink alink");
        }
        if (type2 !== "html4") {
          addAttrs("input button select textarea", "autofocus");
          addAttrs("input textarea", "placeholder");
          addAttrs("a", "download");
          addAttrs("link script img", "crossorigin");
          addAttrs("img", "loading");
          addAttrs("iframe", "sandbox seamless allowfullscreen loading");
        }
        each$h(split$1("a form meter progress dfn"), function(name2) {
          if (schema[name2]) {
            delete schema[name2].children[name2];
          }
        });
        delete schema.caption.children.table;
        delete schema.script;
        mapCache[type2] = schema;
        return schema;
      };
      var compileElementMap = function(value2, mode) {
        var styles;
        if (value2) {
          styles = {};
          if (typeof value2 === "string") {
            value2 = { "*": value2 };
          }
          each$h(value2, function(value3, key) {
            styles[key] = styles[key.toUpperCase()] = mode === "map" ? makeMap$2(value3, /[, ]/) : explode$3(value3, /[, ]/);
          });
        }
        return styles;
      };
      var Schema = function(settings) {
        var elements = {};
        var children2 = {};
        var patternElements = [];
        var customElementsMap = {}, specialElements = {};
        var createLookupTable = function(option, defaultValue, extendWith) {
          var value2 = settings[option];
          if (!value2) {
            value2 = mapCache[option];
            if (!value2) {
              value2 = createMap(defaultValue, extendWith);
              mapCache[option] = value2;
            }
          } else {
            value2 = makeMap$2(value2, /[, ]/, makeMap$2(value2.toUpperCase(), /[, ]/));
          }
          return value2;
        };
        settings = settings || {};
        var schemaItems = compileSchema(settings.schema);
        if (settings.verify_html === false) {
          settings.valid_elements = "*[*]";
        }
        var validStyles = compileElementMap(settings.valid_styles);
        var invalidStyles = compileElementMap(settings.invalid_styles, "map");
        var validClasses = compileElementMap(settings.valid_classes, "map");
        var whiteSpaceElementsMap = createLookupTable("whitespace_elements", "pre script noscript style textarea video audio iframe object code");
        var selfClosingElementsMap = createLookupTable("self_closing_elements", "colgroup dd dt li option p td tfoot th thead tr");
        var shortEndedElementsMap = createLookupTable("short_ended_elements", "area base basefont br col frame hr img input isindex link meta param embed source wbr track");
        var boolAttrMap = createLookupTable("boolean_attributes", "checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls");
        var nonEmptyOrMoveCaretBeforeOnEnter = "td th iframe video audio object script code";
        var nonEmptyElementsMap = createLookupTable("non_empty_elements", nonEmptyOrMoveCaretBeforeOnEnter + " pre", shortEndedElementsMap);
        var moveCaretBeforeOnEnterElementsMap = createLookupTable("move_caret_before_on_enter_elements", nonEmptyOrMoveCaretBeforeOnEnter + " table", shortEndedElementsMap);
        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");
        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);
        var textInlineElementsMap = createLookupTable("text_inline_elements", "span strong b em i font s strike u var cite dfn code mark q sup sub samp");
        each$h((settings.special || "script noscript iframe noframes noembed title style textarea xmp").split(" "), function(name2) {
          specialElements[name2] = new RegExp("</" + name2 + "[^>]*>", "gi");
        });
        var patternToRegExp = function(str) {
          return new RegExp("^" + str.replace(/([?+*])/g, ".$1") + "$");
        };
        var addValidElements = function(validElements) {
          var ei, el, ai, al, matches2, element, attr, attrData, elementName, attrName, attrType, attributes2, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, value2;
          var elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)])?$/, attrRuleRegExp = /^([!\-])?(\w+[\\:]:\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/;
          if (validElements) {
            var validElementsArr = split$1(validElements, ",");
            if (elements["@"]) {
              globalAttributes = elements["@"].attributes;
              globalAttributesOrder = elements["@"].attributesOrder;
            }
            for (ei = 0, el = validElementsArr.length; ei < el; ei++) {
              matches2 = elementRuleRegExp.exec(validElementsArr[ei]);
              if (matches2) {
                prefix = matches2[1];
                elementName = matches2[2];
                outputName = matches2[3];
                attrData = matches2[5];
                attributes2 = {};
                attributesOrder = [];
                element = {
                  attributes: attributes2,
                  attributesOrder
                };
                if (prefix === "#") {
                  element.paddEmpty = true;
                }
                if (prefix === "-") {
                  element.removeEmpty = true;
                }
                if (matches2[4] === "!") {
                  element.removeEmptyAttrs = true;
                }
                if (globalAttributes) {
                  each$j(globalAttributes, function(value3, key) {
                    attributes2[key] = value3;
                  });
                  attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
                }
                if (attrData) {
                  attrData = split$1(attrData, "|");
                  for (ai = 0, al = attrData.length; ai < al; ai++) {
                    matches2 = attrRuleRegExp.exec(attrData[ai]);
                    if (matches2) {
                      attr = {};
                      attrType = matches2[1];
                      attrName = matches2[2].replace(/[\\:]:/g, ":");
                      prefix = matches2[3];
                      value2 = matches2[4];
                      if (attrType === "!") {
                        element.attributesRequired = element.attributesRequired || [];
                        element.attributesRequired.push(attrName);
                        attr.required = true;
                      }
                      if (attrType === "-") {
                        delete attributes2[attrName];
                        attributesOrder.splice(inArray$2(attributesOrder, attrName), 1);
                        continue;
                      }
                      if (prefix) {
                        if (prefix === "=") {
                          element.attributesDefault = element.attributesDefault || [];
                          element.attributesDefault.push({
                            name: attrName,
                            value: value2
                          });
                          attr.defaultValue = value2;
                        }
                        if (prefix === ":") {
                          element.attributesForced = element.attributesForced || [];
                          element.attributesForced.push({
                            name: attrName,
                            value: value2
                          });
                          attr.forcedValue = value2;
                        }
                        if (prefix === "<") {
                          attr.validValues = makeMap$2(value2, "?");
                        }
                      }
                      if (hasPatternsRegExp.test(attrName)) {
                        element.attributePatterns = element.attributePatterns || [];
                        attr.pattern = patternToRegExp(attrName);
                        element.attributePatterns.push(attr);
                      } else {
                        if (!attributes2[attrName]) {
                          attributesOrder.push(attrName);
                        }
                        attributes2[attrName] = attr;
                      }
                    }
                  }
                }
                if (!globalAttributes && elementName === "@") {
                  globalAttributes = attributes2;
                  globalAttributesOrder = attributesOrder;
                }
                if (outputName) {
                  element.outputName = elementName;
                  elements[outputName] = element;
                }
                if (hasPatternsRegExp.test(elementName)) {
                  element.pattern = patternToRegExp(elementName);
                  patternElements.push(element);
                } else {
                  elements[elementName] = element;
                }
              }
            }
          }
        };
        var setValidElements = function(validElements) {
          elements = {};
          patternElements = [];
          addValidElements(validElements);
          each$h(schemaItems, function(element, name2) {
            children2[name2] = element.children;
          });
        };
        var addCustomElements = function(customElements) {
          var customElementRegExp = /^(~)?(.+)$/;
          if (customElements) {
            mapCache.text_block_elements = mapCache.block_elements = null;
            each$h(split$1(customElements, ","), function(rule) {
              var matches2 = customElementRegExp.exec(rule), inline = matches2[1] === "~", cloneName = inline ? "span" : "div", name2 = matches2[2];
              children2[name2] = children2[cloneName];
              customElementsMap[name2] = cloneName;
              if (!inline) {
                blockElementsMap[name2.toUpperCase()] = {};
                blockElementsMap[name2] = {};
              }
              if (!elements[name2]) {
                var customRule = elements[cloneName];
                customRule = extend$5({}, customRule);
                delete customRule.removeEmptyAttrs;
                delete customRule.removeEmpty;
                elements[name2] = customRule;
              }
              each$h(children2, function(element, elmName) {
                if (element[cloneName]) {
                  children2[elmName] = element = extend$5({}, children2[elmName]);
                  element[name2] = element[cloneName];
                }
              });
            });
          }
        };
        var addValidChildren = function(validChildren) {
          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]+)\[([^\]]+)]$/;
          mapCache[settings.schema] = null;
          if (validChildren) {
            each$h(split$1(validChildren, ","), function(rule) {
              var matches2 = childRuleRegExp.exec(rule);
              var parent2, prefix;
              if (matches2) {
                prefix = matches2[1];
                if (prefix) {
                  parent2 = children2[matches2[2]];
                } else {
                  parent2 = children2[matches2[2]] = { "#comment": {} };
                }
                parent2 = children2[matches2[2]];
                each$h(split$1(matches2[3], "|"), function(child2) {
                  if (prefix === "-") {
                    delete parent2[child2];
                  } else {
                    parent2[child2] = {};
                  }
                });
              }
            });
          }
        };
        var getElementRule = function(name2) {
          var element = elements[name2], i;
          if (element) {
            return element;
          }
          i = patternElements.length;
          while (i--) {
            element = patternElements[i];
            if (element.pattern.test(name2)) {
              return element;
            }
          }
        };
        if (!settings.valid_elements) {
          each$h(schemaItems, function(element, name2) {
            elements[name2] = {
              attributes: element.attributes,
              attributesOrder: element.attributesOrder
            };
            children2[name2] = element.children;
          });
          if (settings.schema !== "html5") {
            each$h(split$1("strong/b em/i"), function(item) {
              var items = split$1(item, "/");
              elements[items[1]].outputName = items[0];
            });
          }
          each$h(textInlineElementsMap, function(_val, name2) {
            if (elements[name2]) {
              if (settings.padd_empty_block_inline_children) {
                elements[name2].paddInEmptyBlock = true;
              }
              elements[name2].removeEmpty = true;
            }
          });
          each$h(split$1("ol ul blockquote a table tbody"), function(name2) {
            if (elements[name2]) {
              elements[name2].removeEmpty = true;
            }
          });
          each$h(split$1("p h1 h2 h3 h4 h5 h6 th td pre div address caption li"), function(name2) {
            elements[name2].paddEmpty = true;
          });
          each$h(split$1("span"), function(name2) {
            elements[name2].removeEmptyAttrs = true;
          });
        } else {
          setValidElements(settings.valid_elements);
        }
        addCustomElements(settings.custom_elements);
        addValidChildren(settings.valid_children);
        addValidElements(settings.extended_valid_elements);
        addValidChildren("+ol[ul|ol],+ul[ul|ol]");
        each$h({
          dd: "dl",
          dt: "dl",
          li: "ul ol",
          td: "tr",
          th: "tr",
          tr: "tbody thead tfoot",
          tbody: "table",
          thead: "table",
          tfoot: "table",
          legend: "fieldset",
          area: "map",
          param: "video audio object"
        }, function(parents2, item) {
          if (elements[item]) {
            elements[item].parentsRequired = split$1(parents2);
          }
        });
        if (settings.invalid_elements) {
          each$h(explode$3(settings.invalid_elements), function(item) {
            if (elements[item]) {
              delete elements[item];
            }
          });
        }
        if (!getElementRule("span")) {
          addValidElements("span[!data-mce-type|*]");
        }
        var getValidStyles = constant(validStyles);
        var getInvalidStyles = constant(invalidStyles);
        var getValidClasses = constant(validClasses);
        var getBoolAttrs = constant(boolAttrMap);
        var getBlockElements = constant(blockElementsMap);
        var getTextBlockElements = constant(textBlockElementsMap);
        var getTextInlineElements = constant(textInlineElementsMap);
        var getShortEndedElements = constant(shortEndedElementsMap);
        var getSelfClosingElements = constant(selfClosingElementsMap);
        var getNonEmptyElements = constant(nonEmptyElementsMap);
        var getMoveCaretBeforeOnEnterElements = constant(moveCaretBeforeOnEnterElementsMap);
        var getWhiteSpaceElements = constant(whiteSpaceElementsMap);
        var getSpecialElements = constant(specialElements);
        var isValidChild = function(name2, child2) {
          var parent2 = children2[name2.toLowerCase()];
          return !!(parent2 && parent2[child2.toLowerCase()]);
        };
        var isValid2 = function(name2, attr) {
          var attrPatterns, i;
          var rule = getElementRule(name2);
          if (rule) {
            if (attr) {
              if (rule.attributes[attr]) {
                return true;
              }
              attrPatterns = rule.attributePatterns;
              if (attrPatterns) {
                i = attrPatterns.length;
                while (i--) {
                  if (attrPatterns[i].pattern.test(name2)) {
                    return true;
                  }
                }
              }
            } else {
              return true;
            }
          }
          return false;
        };
        var getCustomElements = constant(customElementsMap);
        return {
          children: children2,
          elements,
          getValidStyles,
          getValidClasses,
          getBlockElements,
          getInvalidStyles,
          getShortEndedElements,
          getTextBlockElements,
          getTextInlineElements,
          getBoolAttrs,
          getElementRule,
          getSelfClosingElements,
          getNonEmptyElements,
          getMoveCaretBeforeOnEnterElements,
          getWhiteSpaceElements,
          getSpecialElements,
          isValidChild,
          isValid: isValid2,
          getCustomElements,
          addValidElements,
          setValidElements,
          addCustomElements,
          addValidChildren
        };
      };
      var toHex = function(match2, r2, g, b) {
        var hex = function(val) {
          val = parseInt(val, 10).toString(16);
          return val.length > 1 ? val : "0" + val;
        };
        return "#" + hex(r2) + hex(g) + hex(b);
      };
      var Styles = function(settings, schema) {
        var _this = this;
        var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi;
        var urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi;
        var styleRegExp = /\s*([^:]+):\s*([^;]+);?/g;
        var trimRightRegExp = /\s+$/;
        var i;
        var encodingLookup = {};
        var validStyles;
        var invalidStyles;
        var invisibleChar = zeroWidth;
        settings = settings || {};
        if (schema) {
          validStyles = schema.getValidStyles();
          invalidStyles = schema.getInvalidStyles();
        }
        var encodingItems = (`\\" \\' \\; \\: ; : ` + invisibleChar).split(" ");
        for (i = 0; i < encodingItems.length; i++) {
          encodingLookup[encodingItems[i]] = invisibleChar + i;
          encodingLookup[invisibleChar + i] = encodingItems[i];
        }
        return {
          toHex: function(color) {
            return color.replace(rgbRegExp, toHex);
          },
          parse: function(css) {
            var styles = {};
            var matches2, name2, value2, isEncoded;
            var urlConverter = settings.url_converter;
            var urlConverterScope = settings.url_converter_scope || _this;
            var compress = function(prefix, suffix, noJoin) {
              var top = styles[prefix + "-top" + suffix];
              if (!top) {
                return;
              }
              var right = styles[prefix + "-right" + suffix];
              if (!right) {
                return;
              }
              var bottom = styles[prefix + "-bottom" + suffix];
              if (!bottom) {
                return;
              }
              var left = styles[prefix + "-left" + suffix];
              if (!left) {
                return;
              }
              var box = [
                top,
                right,
                bottom,
                left
              ];
              i = box.length - 1;
              while (i--) {
                if (box[i] !== box[i + 1]) {
                  break;
                }
              }
              if (i > -1 && noJoin) {
                return;
              }
              styles[prefix + suffix] = i === -1 ? box[0] : box.join(" ");
              delete styles[prefix + "-top" + suffix];
              delete styles[prefix + "-right" + suffix];
              delete styles[prefix + "-bottom" + suffix];
              delete styles[prefix + "-left" + suffix];
            };
            var canCompress = function(key) {
              var value3 = styles[key], i2;
              if (!value3) {
                return;
              }
              value3 = value3.split(" ");
              i2 = value3.length;
              while (i2--) {
                if (value3[i2] !== value3[0]) {
                  return false;
                }
              }
              styles[key] = value3[0];
              return true;
            };
            var compress2 = function(target, a, b, c) {
              if (!canCompress(a)) {
                return;
              }
              if (!canCompress(b)) {
                return;
              }
              if (!canCompress(c)) {
                return;
              }
              styles[target] = styles[a] + " " + styles[b] + " " + styles[c];
              delete styles[a];
              delete styles[b];
              delete styles[c];
            };
            var encode = function(str) {
              isEncoded = true;
              return encodingLookup[str];
            };
            var decode2 = function(str, keepSlashes) {
              if (isEncoded) {
                str = str.replace(/\uFEFF[0-9]/g, function(str2) {
                  return encodingLookup[str2];
                });
              }
              if (!keepSlashes) {
                str = str.replace(/\\([\'\";:])/g, "$1");
              }
              return str;
            };
            var decodeSingleHexSequence = function(escSeq) {
              return String.fromCharCode(parseInt(escSeq.slice(1), 16));
            };
            var decodeHexSequences = function(value3) {
              return value3.replace(/\\[0-9a-f]+/gi, decodeSingleHexSequence);
            };
            var processUrl = function(match2, url, url2, url3, str, str2) {
              str = str || str2;
              if (str) {
                str = decode2(str);
                return "'" + str.replace(/\'/g, "\\'") + "'";
              }
              url = decode2(url || url2 || url3);
              if (!settings.allow_script_urls) {
                var scriptUrl = url.replace(/[\s\r\n]+/g, "");
                if (/(java|vb)script:/i.test(scriptUrl)) {
                  return "";
                }
                if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
                  return "";
                }
              }
              if (urlConverter) {
                url = urlConverter.call(urlConverterScope, url, "style");
              }
              return "url('" + url.replace(/\'/g, "\\'") + "')";
            };
            if (css) {
              css = css.replace(/[\u0000-\u001F]/g, "");
              css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
                return str.replace(/[;:]/g, encode);
              });
              while (matches2 = styleRegExp.exec(css)) {
                styleRegExp.lastIndex = matches2.index + matches2[0].length;
                name2 = matches2[1].replace(trimRightRegExp, "").toLowerCase();
                value2 = matches2[2].replace(trimRightRegExp, "");
                if (name2 && value2) {
                  name2 = decodeHexSequences(name2);
                  value2 = decodeHexSequences(value2);
                  if (name2.indexOf(invisibleChar) !== -1 || name2.indexOf('"') !== -1) {
                    continue;
                  }
                  if (!settings.allow_script_urls && (name2 === "behavior" || /expression\s*\(|\/\*|\*\//.test(value2))) {
                    continue;
                  }
                  if (name2 === "font-weight" && value2 === "700") {
                    value2 = "bold";
                  } else if (name2 === "color" || name2 === "background-color") {
                    value2 = value2.toLowerCase();
                  }
                  value2 = value2.replace(rgbRegExp, toHex);
                  value2 = value2.replace(urlOrStrRegExp, processUrl);
                  styles[name2] = isEncoded ? decode2(value2, true) : value2;
                }
              }
              compress("border", "", true);
              compress("border", "-width");
              compress("border", "-color");
              compress("border", "-style");
              compress("padding", "");
              compress("margin", "");
              compress2("border", "border-width", "border-style", "border-color");
              if (styles.border === "medium none") {
                delete styles.border;
              }
              if (styles["border-image"] === "none") {
                delete styles["border-image"];
              }
            }
            return styles;
          },
          serialize: function(styles, elementName) {
            var css = "";
            var serializeStyles = function(name2) {
              var value2;
              var styleList = validStyles[name2];
              if (styleList) {
                for (var i_1 = 0, l = styleList.length; i_1 < l; i_1++) {
                  name2 = styleList[i_1];
                  value2 = styles[name2];
                  if (value2) {
                    css += (css.length > 0 ? " " : "") + name2 + ": " + value2 + ";";
                  }
                }
              }
            };
            var isValid2 = function(name2, elementName2) {
              var styleMap = invalidStyles["*"];
              if (styleMap && styleMap[name2]) {
                return false;
              }
              styleMap = invalidStyles[elementName2];
              return !(styleMap && styleMap[name2]);
            };
            if (elementName && validStyles) {
              serializeStyles("*");
              serializeStyles(elementName);
            } else {
              each$j(styles, function(value2, name2) {
                if (value2 && (!invalidStyles || isValid2(name2, elementName))) {
                  css += (css.length > 0 ? " " : "") + name2 + ": " + value2 + ";";
                }
              });
            }
            return css;
          }
        };
      };
      var deprecated = {
        keyLocation: true,
        layerX: true,
        layerY: true,
        returnValue: true,
        webkitMovementX: true,
        webkitMovementY: true,
        keyIdentifier: true,
        mozPressure: true
      };
      var isNativeEvent = function(event) {
        return event instanceof Event || isFunction(event.initEvent);
      };
      var hasIsDefaultPrevented = function(event) {
        return event.isDefaultPrevented === always || event.isDefaultPrevented === never;
      };
      var needsNormalizing = function(event) {
        return isNullable(event.preventDefault) || isNativeEvent(event);
      };
      var clone$2 = function(originalEvent, data2) {
        var event = data2 !== null && data2 !== void 0 ? data2 : {};
        for (var name_1 in originalEvent) {
          if (!has$2(deprecated, name_1)) {
            event[name_1] = originalEvent[name_1];
          }
        }
        if (isNonNullable(event.composedPath)) {
          event.composedPath = function() {
            return originalEvent.composedPath();
          };
        }
        return event;
      };
      var normalize$3 = function(type2, originalEvent, fallbackTarget, data2) {
        var _a;
        var event = clone$2(originalEvent, data2);
        event.type = type2;
        if (isNullable(event.target)) {
          event.target = (_a = event.srcElement) !== null && _a !== void 0 ? _a : fallbackTarget;
        }
        if (needsNormalizing(originalEvent)) {
          event.preventDefault = function() {
            event.defaultPrevented = true;
            event.isDefaultPrevented = always;
            if (isFunction(originalEvent.preventDefault)) {
              originalEvent.preventDefault();
            } else if (isNativeEvent(originalEvent)) {
              originalEvent.returnValue = false;
            }
          };
          event.stopPropagation = function() {
            event.cancelBubble = true;
            event.isPropagationStopped = always;
            if (isFunction(originalEvent.stopPropagation)) {
              originalEvent.stopPropagation();
            } else if (isNativeEvent(originalEvent)) {
              originalEvent.cancelBubble = true;
            }
          };
          event.stopImmediatePropagation = function() {
            event.isImmediatePropagationStopped = always;
            event.stopPropagation();
          };
          if (!hasIsDefaultPrevented(event)) {
            event.isDefaultPrevented = event.defaultPrevented === true ? always : never;
            event.isPropagationStopped = event.cancelBubble === true ? always : never;
            event.isImmediatePropagationStopped = never;
          }
        }
        return event;
      };
      var eventExpandoPrefix = "mce-data-";
      var mouseEventRe = /^(?:mouse|contextmenu)|click/;
      var addEvent = function(target, name2, callback, capture) {
        if (target.addEventListener) {
          target.addEventListener(name2, callback, capture || false);
        } else if (target.attachEvent) {
          target.attachEvent("on" + name2, callback);
        }
      };
      var removeEvent = function(target, name2, callback, capture) {
        if (target.removeEventListener) {
          target.removeEventListener(name2, callback, capture || false);
        } else if (target.detachEvent) {
          target.detachEvent("on" + name2, callback);
        }
      };
      var isMouseEvent = function(event) {
        return isNonNullable(event) && mouseEventRe.test(event.type);
      };
      var fix = function(originalEvent, data2) {
        var event = normalize$3(originalEvent.type, originalEvent, document, data2);
        if (isMouseEvent(originalEvent) && isUndefined(originalEvent.pageX) && !isUndefined(originalEvent.clientX)) {
          var eventDoc = event.target.ownerDocument || document;
          var doc2 = eventDoc.documentElement;
          var body = eventDoc.body;
          var mouseEvent = event;
          mouseEvent.pageX = originalEvent.clientX + (doc2 && doc2.scrollLeft || body && body.scrollLeft || 0) - (doc2 && doc2.clientLeft || body && body.clientLeft || 0);
          mouseEvent.pageY = originalEvent.clientY + (doc2 && doc2.scrollTop || body && body.scrollTop || 0) - (doc2 && doc2.clientTop || body && body.clientTop || 0);
        }
        if (isUndefined(event.metaKey)) {
          event.metaKey = false;
        }
        return event;
      };
      var bindOnReady = function(win, callback, eventUtils) {
        var doc2 = win.document, event = { type: "ready" };
        if (eventUtils.domLoaded) {
          callback(event);
          return;
        }
        var isDocReady = function() {
          return doc2.readyState === "complete" || doc2.readyState === "interactive" && doc2.body;
        };
        var readyHandler = function() {
          removeEvent(win, "DOMContentLoaded", readyHandler);
          removeEvent(win, "load", readyHandler);
          if (!eventUtils.domLoaded) {
            eventUtils.domLoaded = true;
            callback(event);
          }
          win = null;
        };
        if (isDocReady()) {
          readyHandler();
        } else {
          addEvent(win, "DOMContentLoaded", readyHandler);
        }
        if (!eventUtils.domLoaded) {
          addEvent(win, "load", readyHandler);
        }
      };
      var EventUtils = function() {
        function EventUtils2() {
          this.domLoaded = false;
          this.events = {};
          this.count = 1;
          this.expando = eventExpandoPrefix + (+new Date()).toString(32);
          this.hasMouseEnterLeave = "onmouseenter" in document.documentElement;
          this.hasFocusIn = "onfocusin" in document.documentElement;
          this.count = 1;
        }
        EventUtils2.prototype.bind = function(target, names, callback, scope) {
          var self2 = this;
          var id, callbackList, i, name2, fakeName, nativeHandler, capture;
          var win = window;
          var defaultNativeHandler = function(evt) {
            self2.executeHandlers(fix(evt || win.event), id);
          };
          if (!target || target.nodeType === 3 || target.nodeType === 8) {
            return;
          }
          if (!target[self2.expando]) {
            id = self2.count++;
            target[self2.expando] = id;
            self2.events[id] = {};
          } else {
            id = target[self2.expando];
          }
          scope = scope || target;
          var namesList = names.split(" ");
          i = namesList.length;
          while (i--) {
            name2 = namesList[i];
            nativeHandler = defaultNativeHandler;
            fakeName = capture = false;
            if (name2 === "DOMContentLoaded") {
              name2 = "ready";
            }
            if (self2.domLoaded && name2 === "ready" && target.readyState === "complete") {
              callback.call(scope, fix({ type: name2 }));
              continue;
            }
            if (!self2.hasMouseEnterLeave) {
              fakeName = self2.mouseEnterLeave[name2];
              if (fakeName) {
                nativeHandler = function(evt) {
                  var current = evt.currentTarget;
                  var related = evt.relatedTarget;
                  if (related && current.contains) {
                    related = current.contains(related);
                  } else {
                    while (related && related !== current) {
                      related = related.parentNode;
                    }
                  }
                  if (!related) {
                    evt = fix(evt || win.event);
                    evt.type = evt.type === "mouseout" ? "mouseleave" : "mouseenter";
                    evt.target = current;
                    self2.executeHandlers(evt, id);
                  }
                };
              }
            }
            if (!self2.hasFocusIn && (name2 === "focusin" || name2 === "focusout")) {
              capture = true;
              fakeName = name2 === "focusin" ? "focus" : "blur";
              nativeHandler = function(evt) {
                evt = fix(evt || win.event);
                evt.type = evt.type === "focus" ? "focusin" : "focusout";
                self2.executeHandlers(evt, id);
              };
            }
            callbackList = self2.events[id][name2];
            if (!callbackList) {
              self2.events[id][name2] = callbackList = [{
                func: callback,
                scope
              }];
              callbackList.fakeName = fakeName;
              callbackList.capture = capture;
              callbackList.nativeHandler = nativeHandler;
              if (name2 === "ready") {
                bindOnReady(target, nativeHandler, self2);
              } else {
                addEvent(target, fakeName || name2, nativeHandler, capture);
              }
            } else {
              if (name2 === "ready" && self2.domLoaded) {
                callback(fix({ type: name2 }));
              } else {
                callbackList.push({
                  func: callback,
                  scope
                });
              }
            }
          }
          target = callbackList = null;
          return callback;
        };
        EventUtils2.prototype.unbind = function(target, names, callback) {
          var callbackList, i, ci, name2, eventMap;
          if (!target || target.nodeType === 3 || target.nodeType === 8) {
            return this;
          }
          var id = target[this.expando];
          if (id) {
            eventMap = this.events[id];
            if (names) {
              var namesList = names.split(" ");
              i = namesList.length;
              while (i--) {
                name2 = namesList[i];
                callbackList = eventMap[name2];
                if (callbackList) {
                  if (callback) {
                    ci = callbackList.length;
                    while (ci--) {
                      if (callbackList[ci].func === callback) {
                        var nativeHandler = callbackList.nativeHandler;
                        var fakeName = callbackList.fakeName, capture = callbackList.capture;
                        callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
                        callbackList.nativeHandler = nativeHandler;
                        callbackList.fakeName = fakeName;
                        callbackList.capture = capture;
                        eventMap[name2] = callbackList;
                      }
                    }
                  }
                  if (!callback || callbackList.length === 0) {
                    delete eventMap[name2];
                    removeEvent(target, callbackList.fakeName || name2, callbackList.nativeHandler, callbackList.capture);
                  }
                }
              }
            } else {
              each$j(eventMap, function(callbackList2, name3) {
                removeEvent(target, callbackList2.fakeName || name3, callbackList2.nativeHandler, callbackList2.capture);
              });
              eventMap = {};
            }
            for (name2 in eventMap) {
              if (has$2(eventMap, name2)) {
                return this;
              }
            }
            delete this.events[id];
            try {
              delete target[this.expando];
            } catch (ex) {
              target[this.expando] = null;
            }
          }
          return this;
        };
        EventUtils2.prototype.fire = function(target, name2, args) {
          var id;
          if (!target || target.nodeType === 3 || target.nodeType === 8) {
            return this;
          }
          var event = fix({
            type: name2,
            target
          }, args);
          do {
            id = target[this.expando];
            if (id) {
              this.executeHandlers(event, id);
            }
            target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
          } while (target && !event.isPropagationStopped());
          return this;
        };
        EventUtils2.prototype.clean = function(target) {
          var i, children2;
          if (!target || target.nodeType === 3 || target.nodeType === 8) {
            return this;
          }
          if (target[this.expando]) {
            this.unbind(target);
          }
          if (!target.getElementsByTagName) {
            target = target.document;
          }
          if (target && target.getElementsByTagName) {
            this.unbind(target);
            children2 = target.getElementsByTagName("*");
            i = children2.length;
            while (i--) {
              target = children2[i];
              if (target[this.expando]) {
                this.unbind(target);
              }
            }
          }
          return this;
        };
        EventUtils2.prototype.destroy = function() {
          this.events = {};
        };
        EventUtils2.prototype.cancel = function(e) {
          if (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
          }
          return false;
        };
        EventUtils2.prototype.executeHandlers = function(evt, id) {
          var container = this.events[id];
          var callbackList = container && container[evt.type];
          if (callbackList) {
            for (var i = 0, l = callbackList.length; i < l; i++) {
              var callback = callbackList[i];
              if (callback && callback.func.call(callback.scope, evt) === false) {
                evt.preventDefault();
              }
              if (evt.isImmediatePropagationStopped()) {
                return;
              }
            }
          }
        };
        EventUtils2.Event = new EventUtils2();
        return EventUtils2;
      }();
      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) {
        if (a === b) {
          hasDuplicate = true;
        }
        return 0;
      }, strundefined = "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) {
        var i = 0, len = this.length;
        for (; i < len; i++) {
          if (this[i] === elem) {
            return i;
          }
        }
        return -1;
      }, 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 = {
        ID: new RegExp("^#(" + identifier + ")"),
        CLASS: new RegExp("^\\.(" + identifier + ")"),
        TAG: new RegExp("^(" + identifier + "|[*])"),
        ATTR: new RegExp("^" + attributes),
        PSEUDO: new RegExp("^" + pseudos),
        CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
        bool: new RegExp("^(?:" + booleans + ")$", "i"),
        needsContext: new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
      }, 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) {
        var high = "0x" + escaped - 65536;
        return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320);
      };
      try {
        push$1.apply(arr = slice$1.call(preferredDoc.childNodes), preferredDoc.childNodes);
        arr[preferredDoc.childNodes.length].nodeType;
      } catch (e) {
        push$1 = {
          apply: arr.length ? function(target, els) {
            push_native.apply(target, slice$1.call(els));
          } : function(target, els) {
            var j = target.length, i = 0;
            while (target[j++] = els[i++]) {
            }
            target.length = j - 1;
          }
        };
      }
      var Sizzle = function(selector, context2, results, seed2) {
        var match2, elem, m, nodeType, i, groups, old, nid, newContext, newSelector;
        if ((context2 ? context2.ownerDocument || context2 : preferredDoc) !== document$1) {
          setDocument(context2);
        }
        context2 = context2 || document$1;
        results = results || [];
        if (!selector || typeof selector !== "string") {
          return results;
        }
        if ((nodeType = context2.nodeType) !== 1 && nodeType !== 9) {
          return [];
        }
        if (documentIsHTML && !seed2) {
          if (match2 = rquickExpr$1.exec(selector)) {
            if (m = match2[1]) {
              if (nodeType === 9) {
                elem = context2.getElementById(m);
                if (elem && elem.parentNode) {
                  if (elem.id === m) {
                    results.push(elem);
                    return results;
                  }
                } else {
                  return results;
                }
              } else {
                if (context2.ownerDocument && (elem = context2.ownerDocument.getElementById(m)) && contains(context2, elem) && elem.id === m) {
                  results.push(elem);
                  return results;
                }
              }
            } else if (match2[2]) {
              push$1.apply(results, context2.getElementsByTagName(selector));
              return results;
            } else if ((m = match2[3]) && support.getElementsByClassName) {
              push$1.apply(results, context2.getElementsByClassName(m));
              return results;
            }
          }
          if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
            nid = old = expando;
            newContext = context2;
            newSelector = nodeType === 9 && selector;
            if (nodeType === 1 && context2.nodeName.toLowerCase() !== "object") {
              groups = tokenize(selector);
              if (old = context2.getAttribute("id")) {
                nid = old.replace(rescape, "\\$&");
              } else {
                context2.setAttribute("id", nid);
              }
              nid = "[id='" + nid + "'] ";
              i = groups.length;
              while (i--) {
                groups[i] = nid + toSelector(groups[i]);
              }
              newContext = rsibling.test(selector) && testContext(context2.parentNode) || context2;
              newSelector = groups.join(",");
            }
            if (newSelector) {
              try {
                push$1.apply(results, newContext.querySelectorAll(newSelector));
                return results;
              } catch (qsaError) {
              } finally {
                if (!old) {
                  context2.removeAttribute("id");
                }
              }
            }
          }
        }
        return select$1(selector.replace(rtrim, "$1"), context2, results, seed2);
      };
      function createCache() {
        var keys2 = [];
        function cache(key, value2) {
          if (keys2.push(key + " ") > Expr.cacheLength) {
            delete cache[keys2.shift()];
          }
          return cache[key + " "] = value2;
        }
        return cache;
      }
      function markFunction(fn) {
        fn[expando] = true;
        return fn;
      }
      function siblingCheck(a, b) {
        var cur = b && a, diff2 = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE);
        if (diff2) {
          return diff2;
        }
        if (cur) {
          while (cur = cur.nextSibling) {
            if (cur === b) {
              return -1;
            }
          }
        }
        return a ? 1 : -1;
      }
      function createInputPseudo(type2) {
        return function(elem) {
          var name2 = elem.nodeName.toLowerCase();
          return name2 === "input" && elem.type === type2;
        };
      }
      function createButtonPseudo(type2) {
        return function(elem) {
          var name2 = elem.nodeName.toLowerCase();
          return (name2 === "input" || name2 === "button") && elem.type === type2;
        };
      }
      function createPositionalPseudo(fn) {
        return markFunction(function(argument) {
          argument = +argument;
          return markFunction(function(seed2, matches2) {
            var j, matchIndexes = fn([], seed2.length, argument), i = matchIndexes.length;
            while (i--) {
              if (seed2[j = matchIndexes[i]]) {
                seed2[j] = !(matches2[j] = seed2[j]);
              }
            }
          });
        });
      }
      function testContext(context2) {
        return context2 && typeof context2.getElementsByTagName !== strundefined && context2;
      }
      support = Sizzle.support = {};
      isXML = Sizzle.isXML = function(elem) {
        var documentElement2 = elem && (elem.ownerDocument || elem).documentElement;
        return documentElement2 ? documentElement2.nodeName !== "HTML" : false;
      };
      setDocument = Sizzle.setDocument = function(node) {
        var hasCompare, doc2 = node ? node.ownerDocument || node : preferredDoc, parent2 = doc2.defaultView;
        function getTop(win) {
          try {
            return win.top;
          } catch (ex) {
          }
          return null;
        }
        if (doc2 === document$1 || doc2.nodeType !== 9 || !doc2.documentElement) {
          return document$1;
        }
        document$1 = doc2;
        docElem = doc2.documentElement;
        documentIsHTML = !isXML(doc2);
        if (parent2 && parent2 !== getTop(parent2)) {
          if (parent2.addEventListener) {
            parent2.addEventListener("unload", function() {
              setDocument();
            }, false);
          } else if (parent2.attachEvent) {
            parent2.attachEvent("onunload", function() {
              setDocument();
            });
          }
        }
        support.attributes = true;
        support.getElementsByTagName = true;
        support.getElementsByClassName = rnative.test(doc2.getElementsByClassName);
        support.getById = true;
        Expr.find.ID = function(id, context2) {
          if (typeof context2.getElementById !== strundefined && documentIsHTML) {
            var m = context2.getElementById(id);
            return m && m.parentNode ? [m] : [];
          }
        };
        Expr.filter.ID = function(id) {
          var attrId = id.replace(runescape, funescape);
          return function(elem) {
            return elem.getAttribute("id") === attrId;
          };
        };
        Expr.find.TAG = support.getElementsByTagName ? function(tag, context2) {
          if (typeof context2.getElementsByTagName !== strundefined) {
            return context2.getElementsByTagName(tag);
          }
        } : function(tag, context2) {
          var elem, tmp = [], i = 0, results = context2.getElementsByTagName(tag);
          if (tag === "*") {
            while (elem = results[i++]) {
              if (elem.nodeType === 1) {
                tmp.push(elem);
              }
            }
            return tmp;
          }
          return results;
        };
        Expr.find.CLASS = support.getElementsByClassName && function(className, context2) {
          if (documentIsHTML) {
            return context2.getElementsByClassName(className);
          }
        };
        rbuggyMatches = [];
        rbuggyQSA = [];
        support.disconnectedMatch = true;
        rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
        rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
        hasCompare = rnative.test(docElem.compareDocumentPosition);
        contains = hasCompare || rnative.test(docElem.contains) ? function(a, b) {
          var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
          return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
        } : function(a, b) {
          if (b) {
            while (b = b.parentNode) {
              if (b === a) {
                return true;
              }
            }
          }
          return false;
        };
        sortOrder = hasCompare ? function(a, b) {
          if (a === b) {
            hasDuplicate = true;
            return 0;
          }
          var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
          if (compare) {
            return compare;
          }
          compare = (a.ownerDocument || a) === (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
          if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
            if (a === doc2 || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
              return -1;
            }
            if (b === doc2 || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
              return 1;
            }
            return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
          }
          return compare & 4 ? -1 : 1;
        } : function(a, b) {
          if (a === b) {
            hasDuplicate = true;
            return 0;
          }
          var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b];
          if (!aup || !bup) {
            return a === doc2 ? -1 : b === doc2 ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0;
          } else if (aup === bup) {
            return siblingCheck(a, b);
          }
          cur = a;
          while (cur = cur.parentNode) {
            ap.unshift(cur);
          }
          cur = b;
          while (cur = cur.parentNode) {
            bp.unshift(cur);
          }
          while (ap[i] === bp[i]) {
            i++;
          }
          return i ? siblingCheck(ap[i], bp[i]) : ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0;
        };
        return doc2;
      };
      Sizzle.matches = function(expr, elements) {
        return Sizzle(expr, null, null, elements);
      };
      Sizzle.matchesSelector = function(elem, expr) {
        if ((elem.ownerDocument || elem) !== document$1) {
          setDocument(elem);
        }
        expr = expr.replace(rattributeQuotes, "='$1']");
        if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
          try {
            var ret = matches.call(elem, expr);
            if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
              return ret;
            }
          } catch (e) {
          }
        }
        return Sizzle(expr, document$1, null, [elem]).length > 0;
      };
      Sizzle.contains = function(context2, elem) {
        if ((context2.ownerDocument || context2) !== document$1) {
          setDocument(context2);
        }
        return contains(context2, elem);
      };
      Sizzle.attr = function(elem, name2) {
        if ((elem.ownerDocument || elem) !== document$1) {
          setDocument(elem);
        }
        var fn = Expr.attrHandle[name2.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name2.toLowerCase()) ? fn(elem, name2, !documentIsHTML) : void 0;
        return val !== void 0 ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name2) : (val = elem.getAttributeNode(name2)) && val.specified ? val.value : null;
      };
      Sizzle.error = function(msg) {
        throw new Error("Syntax error, unrecognized expression: " + msg);
      };
      Sizzle.uniqueSort = function(results) {
        var elem, duplicates = [], j = 0, i = 0;
        hasDuplicate = !support.detectDuplicates;
        sortInput = !support.sortStable && results.slice(0);
        results.sort(sortOrder);
        if (hasDuplicate) {
          while (elem = results[i++]) {
            if (elem === results[i]) {
              j = duplicates.push(i);
            }
          }
          while (j--) {
            results.splice(duplicates[j], 1);
          }
        }
        sortInput = null;
        return results;
      };
      getText = Sizzle.getText = function(elem) {
        var node, ret = "", i = 0, nodeType = elem.nodeType;
        if (!nodeType) {
          while (node = elem[i++]) {
            ret += getText(node);
          }
        } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
          if (typeof elem.textContent === "string") {
            return elem.textContent;
          } else {
            for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
              ret += getText(elem);
            }
          }
        } else if (nodeType === 3 || nodeType === 4) {
          return elem.nodeValue;
        }
        return ret;
      };
      Expr = Sizzle.selectors = {
        cacheLength: 50,
        createPseudo: markFunction,
        match: matchExpr,
        attrHandle: {},
        find: {},
        relative: {
          ">": {
            dir: "parentNode",
            first: true
          },
          " ": { dir: "parentNode" },
          "+": {
            dir: "previousSibling",
            first: true
          },
          "~": { dir: "previousSibling" }
        },
        preFilter: {
          ATTR: function(match2) {
            match2[1] = match2[1].replace(runescape, funescape);
            match2[3] = (match2[3] || match2[4] || match2[5] || "").replace(runescape, funescape);
            if (match2[2] === "~=") {
              match2[3] = " " + match2[3] + " ";
            }
            return match2.slice(0, 4);
          },
          CHILD: function(match2) {
            match2[1] = match2[1].toLowerCase();
            if (match2[1].slice(0, 3) === "nth") {
              if (!match2[3]) {
                Sizzle.error(match2[0]);
              }
              match2[4] = +(match2[4] ? match2[5] + (match2[6] || 1) : 2 * (match2[3] === "even" || match2[3] === "odd"));
              match2[5] = +(match2[7] + match2[8] || match2[3] === "odd");
            } else if (match2[3]) {
              Sizzle.error(match2[0]);
            }
            return match2;
          },
          PSEUDO: function(match2) {
            var excess, unquoted = !match2[6] && match2[2];
            if (matchExpr.CHILD.test(match2[0])) {
              return null;
            }
            if (match2[3]) {
              match2[2] = match2[4] || match2[5] || "";
            } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
              match2[0] = match2[0].slice(0, excess);
              match2[2] = unquoted.slice(0, excess);
            }
            return match2.slice(0, 3);
          }
        },
        filter: {
          TAG: function(nodeNameSelector) {
            var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
            return nodeNameSelector === "*" ? function() {
              return true;
            } : function(elem) {
              return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
            };
          },
          CLASS: function(className) {
            var pattern = classCache[className + " "];
            return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) {
              return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "");
            });
          },
          ATTR: function(name2, operator, check) {
            return function(elem) {
              var result = Sizzle.attr(elem, name2);
              if (result == null) {
                return operator === "!=";
              }
              if (!operator) {
                return true;
              }
              result += "";
              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;
            };
          },
          CHILD: function(type2, what, argument, first2, last2) {
            var simple = type2.slice(0, 3) !== "nth", forward = type2.slice(-4) !== "last", ofType = what === "of-type";
            return first2 === 1 && last2 === 0 ? function(elem) {
              return !!elem.parentNode;
            } : function(elem, context2, xml) {
              var cache, outerCache, node, diff2, nodeIndex2, start2, dir2 = simple !== forward ? "nextSibling" : "previousSibling", parent2 = elem.parentNode, name2 = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType;
              if (parent2) {
                if (simple) {
                  while (dir2) {
                    node = elem;
                    while (node = node[dir2]) {
                      if (ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) {
                        return false;
                      }
                    }
                    start2 = dir2 = type2 === "only" && !start2 && "nextSibling";
                  }
                  return true;
                }
                start2 = [forward ? parent2.firstChild : parent2.lastChild];
                if (forward && useCache) {
                  outerCache = parent2[expando] || (parent2[expando] = {});
                  cache = outerCache[type2] || [];
                  nodeIndex2 = cache[0] === dirruns && cache[1];
                  diff2 = cache[0] === dirruns && cache[2];
                  node = nodeIndex2 && parent2.childNodes[nodeIndex2];
                  while (node = ++nodeIndex2 && node && node[dir2] || (diff2 = nodeIndex2 = 0) || start2.pop()) {
                    if (node.nodeType === 1 && ++diff2 && node === elem) {
                      outerCache[type2] = [
                        dirruns,
                        nodeIndex2,
                        diff2
                      ];
                      break;
                    }
                  }
                } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type2]) && cache[0] === dirruns) {
                  diff2 = cache[1];
                } else {
                  while (node = ++nodeIndex2 && node && node[dir2] || (diff2 = nodeIndex2 = 0) || start2.pop()) {
                    if ((ofType ? node.nodeName.toLowerCase() === name2 : node.nodeType === 1) && ++diff2) {
                      if (useCache) {
                        (node[expando] || (node[expando] = {}))[type2] = [
                          dirruns,
                          diff2
                        ];
                      }
                      if (node === elem) {
                        break;
                      }
                    }
                  }
                }
                diff2 -= last2;
                return diff2 === first2 || diff2 % first2 === 0 && diff2 / first2 >= 0;
              }
            };
          },
          PSEUDO: function(pseudo, argument) {
            var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
            if (fn[expando]) {
              return fn(argument);
            }
            if (fn.length > 1) {
              args = [
                pseudo,
                pseudo,
                "",
                argument
              ];
              return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed2, matches2) {
                var idx, matched = fn(seed2, argument), i = matched.length;
                while (i--) {
                  idx = indexOf.call(seed2, matched[i]);
                  seed2[idx] = !(matches2[idx] = matched[i]);
                }
              }) : function(elem) {
                return fn(elem, 0, args);
              };
            }
            return fn;
          }
        },
        pseudos: {
          not: markFunction(function(selector) {
            var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1"));
            return matcher[expando] ? markFunction(function(seed2, matches2, context2, xml) {
              var elem, unmatched = matcher(seed2, null, xml, []), i = seed2.length;
              while (i--) {
                if (elem = unmatched[i]) {
                  seed2[i] = !(matches2[i] = elem);
                }
              }
            }) : function(elem, context2, xml) {
              input[0] = elem;
              matcher(input, null, xml, results);
              input[0] = null;
              return !results.pop();
            };
          }),
          has: markFunction(function(selector) {
            return function(elem) {
              return Sizzle(selector, elem).length > 0;
            };
          }),
          contains: markFunction(function(text) {
            text = text.replace(runescape, funescape);
            return function(elem) {
              return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1;
            };
          }),
          lang: markFunction(function(lang) {
            if (!ridentifier.test(lang || "")) {
              Sizzle.error("unsupported lang: " + lang);
            }
            lang = lang.replace(runescape, funescape).toLowerCase();
            return function(elem) {
              var elemLang;
              do {
                if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
                  elemLang = elemLang.toLowerCase();
                  return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
                }
              } while ((elem = elem.parentNode) && elem.nodeType === 1);
              return false;
            };
          }),
          target: function(elem) {
            var hash = window.location && window.location.hash;
            return hash && hash.slice(1) === elem.id;
          },
          root: function(elem) {
            return elem === docElem;
          },
          focus: function(elem) {
            return elem === document$1.activeElement && (!document$1.hasFocus || document$1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
          },
          enabled: function(elem) {
            return elem.disabled === false;
          },
          disabled: function(elem) {
            return elem.disabled === true;
          },
          checked: function(elem) {
            var nodeName = elem.nodeName.toLowerCase();
            return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
          },
          selected: function(elem) {
            if (elem.parentNode) {
              elem.parentNode.selectedIndex;
            }
            return elem.selected === true;
          },
          empty: function(elem) {
            for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
              if (elem.nodeType < 6) {
                return false;
              }
            }
            return true;
          },
          parent: function(elem) {
            return !Expr.pseudos.empty(elem);
          },
          header: function(elem) {
            return rheader.test(elem.nodeName);
          },
          input: function(elem) {
            return rinputs.test(elem.nodeName);
          },
          button: function(elem) {
            var name2 = elem.nodeName.toLowerCase();
            return name2 === "input" && elem.type === "button" || name2 === "button";
          },
          text: function(elem) {
            var attr;
            return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
          },
          first: createPositionalPseudo(function() {
            return [0];
          }),
          last: createPositionalPseudo(function(matchIndexes, length) {
            return [length - 1];
          }),
          eq: createPositionalPseudo(function(matchIndexes, length, argument) {
            return [argument < 0 ? argument + length : argument];
          }),
          even: createPositionalPseudo(function(matchIndexes, length) {
            var i = 0;
            for (; i < length; i += 2) {
              matchIndexes.push(i);
            }
            return matchIndexes;
          }),
          odd: createPositionalPseudo(function(matchIndexes, length) {
            var i = 1;
            for (; i < length; i += 2) {
              matchIndexes.push(i);
            }
            return matchIndexes;
          }),
          lt: createPositionalPseudo(function(matchIndexes, length, argument) {
            var i = argument < 0 ? argument + length : argument;
            for (; --i >= 0; ) {
              matchIndexes.push(i);
            }
            return matchIndexes;
          }),
          gt: createPositionalPseudo(function(matchIndexes, length, argument) {
            var i = argument < 0 ? argument + length : argument;
            for (; ++i < length; ) {
              matchIndexes.push(i);
            }
            return matchIndexes;
          })
        }
      };
      Expr.pseudos.nth = Expr.pseudos.eq;
      each$k([
        "radio",
        "checkbox",
        "file",
        "password",
        "image"
      ], function(i) {
        Expr.pseudos[i] = createInputPseudo(i);
      });
      each$k([
        "submit",
        "reset"
      ], function(i) {
        Expr.pseudos[i] = createButtonPseudo(i);
      });
      function setFilters() {
      }
      setFilters.prototype = Expr.filters = Expr.pseudos;
      Expr.setFilters = new setFilters();
      tokenize = Sizzle.tokenize = function(selector, parseOnly) {
        var matched, match2, tokens, type2, soFar, groups, preFilters, cached2 = tokenCache[selector + " "];
        if (cached2) {
          return parseOnly ? 0 : cached2.slice(0);
        }
        soFar = selector;
        groups = [];
        preFilters = Expr.preFilter;
        while (soFar) {
          if (!matched || (match2 = rcomma.exec(soFar))) {
            if (match2) {
              soFar = soFar.slice(match2[0].length) || soFar;
            }
            groups.push(tokens = []);
          }
          matched = false;
          if (match2 = rcombinators.exec(soFar)) {
            matched = match2.shift();
            tokens.push({
              value: matched,
              type: match2[0].replace(rtrim, " ")
            });
            soFar = soFar.slice(matched.length);
          }
          for (type2 in Expr.filter) {
            if (!Expr.filter.hasOwnProperty(type2)) {
              continue;
            }
            if ((match2 = matchExpr[type2].exec(soFar)) && (!preFilters[type2] || (match2 = preFilters[type2](match2)))) {
              matched = match2.shift();
              tokens.push({
                value: matched,
                type: type2,
                matches: match2
              });
              soFar = soFar.slice(matched.length);
            }
          }
          if (!matched) {
            break;
          }
        }
        return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
      };
      function toSelector(tokens) {
        var i = 0, len = tokens.length, selector = "";
        for (; i < len; i++) {
          selector += tokens[i].value;
        }
        return selector;
      }
      function addCombinator(matcher, combinator, base) {
        var dir2 = combinator.dir, checkNonElements = base && dir2 === "parentNode", doneName = done++;
        return combinator.first ? function(elem, context2, xml) {
          while (elem = elem[dir2]) {
            if (elem.nodeType === 1 || checkNonElements) {
              return matcher(elem, context2, xml);
            }
          }
        } : function(elem, context2, xml) {
          var oldCache, outerCache, newCache = [
            dirruns,
            doneName
          ];
          if (xml) {
            while (elem = elem[dir2]) {
              if (elem.nodeType === 1 || checkNonElements) {
                if (matcher(elem, context2, xml)) {
                  return true;
                }
              }
            }
          } else {
            while (elem = elem[dir2]) {
              if (elem.nodeType === 1 || checkNonElements) {
                outerCache = elem[expando] || (elem[expando] = {});
                if ((oldCache = outerCache[dir2]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                  return newCache[2] = oldCache[2];
                } else {
                  outerCache[dir2] = newCache;
                  if (newCache[2] = matcher(elem, context2, xml)) {
                    return true;
                  }
                }
              }
            }
          }
        };
      }
      function elementMatcher(matchers) {
        return matchers.length > 1 ? function(elem, context2, xml) {
          var i = matchers.length;
          while (i--) {
            if (!matchers[i](elem, context2, xml)) {
              return false;
            }
          }
          return true;
        } : matchers[0];
      }
      function multipleContexts(selector, contexts, results) {
        var i = 0, len = contexts.length;
        for (; i < len; i++) {
          Sizzle(selector, contexts[i], results);
        }
        return results;
      }
      function condense(unmatched, map2, filter2, context2, xml) {
        var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map2 != null;
        for (; i < len; i++) {
          if (elem = unmatched[i]) {
            if (!filter2 || filter2(elem, context2, xml)) {
              newUnmatched.push(elem);
              if (mapped) {
                map2.push(i);
              }
            }
          }
        }
        return newUnmatched;
      }
      function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
        if (postFilter && !postFilter[expando]) {
          postFilter = setMatcher(postFilter);
        }
        if (postFinder && !postFinder[expando]) {
          postFinder = setMatcher(postFinder, postSelector);
        }
        return markFunction(function(seed2, results, context2, xml) {
          var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed2 || multipleContexts(selector || "*", context2.nodeType ? [context2] : context2, []), matcherIn = preFilter && (seed2 || !selector) ? condense(elems, preMap, preFilter, context2, xml) : elems, matcherOut = matcher ? postFinder || (seed2 ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
          if (matcher) {
            matcher(matcherIn, matcherOut, context2, xml);
          }
          if (postFilter) {
            temp = condense(matcherOut, postMap);
            postFilter(temp, [], context2, xml);
            i = temp.length;
            while (i--) {
              if (elem = temp[i]) {
                matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
              }
            }
          }
          if (seed2) {
            if (postFinder || preFilter) {
              if (postFinder) {
                temp = [];
                i = matcherOut.length;
                while (i--) {
                  if (elem = matcherOut[i]) {
                    temp.push(matcherIn[i] = elem);
                  }
                }
                postFinder(null, matcherOut = [], temp, xml);
              }
              i = matcherOut.length;
              while (i--) {
                if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed2, elem) : preMap[i]) > -1) {
                  seed2[temp] = !(results[temp] = elem);
                }
              }
            }
          } else {
            matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
            if (postFinder) {
              postFinder(null, results, matcherOut, xml);
            } else {
              push$1.apply(results, matcherOut);
            }
          }
        });
      }
      function matcherFromTokens(tokens) {
        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) {
          return elem === checkContext;
        }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) {
          return indexOf.call(checkContext, elem) > -1;
        }, implicitRelative, true), matchers = [function(elem, context2, xml) {
          var ret = !leadingRelative && (xml || context2 !== outermostContext) || ((checkContext = context2).nodeType ? matchContext(elem, context2, xml) : matchAnyContext(elem, context2, xml));
          checkContext = null;
          return ret;
        }];
        for (; i < len; i++) {
          if (matcher = Expr.relative[tokens[i].type]) {
            matchers = [addCombinator(elementMatcher(matchers), matcher)];
          } else {
            matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
            if (matcher[expando]) {
              j = ++i;
              for (; j < len; j++) {
                if (Expr.relative[tokens[j].type]) {
                  break;
                }
              }
              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));
            }
            matchers.push(matcher);
          }
        }
        return elementMatcher(matchers);
      }
      function matcherFromGroupMatchers(elementMatchers, setMatchers) {
        var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed2, context2, xml, results, outermost) {
          var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed2 && [], setMatched = [], contextBackup = outermostContext, elems = seed2 || byElement && Expr.find.TAG("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
          if (outermost) {
            outermostContext = context2 !== document$1 && context2;
          }
          for (; i !== len && (elem = elems[i]) != null; i++) {
            if (byElement && elem) {
              j = 0;
              while (matcher = elementMatchers[j++]) {
                if (matcher(elem, context2, xml)) {
                  results.push(elem);
                  break;
                }
              }
              if (outermost) {
                dirruns = dirrunsUnique;
              }
            }
            if (bySet) {
              if (elem = !matcher && elem) {
                matchedCount--;
              }
              if (seed2) {
                unmatched.push(elem);
              }
            }
          }
          matchedCount += i;
          if (bySet && i !== matchedCount) {
            j = 0;
            while (matcher = setMatchers[j++]) {
              matcher(unmatched, setMatched, context2, xml);
            }
            if (seed2) {
              if (matchedCount > 0) {
                while (i--) {
                  if (!(unmatched[i] || setMatched[i])) {
                    setMatched[i] = pop.call(results);
                  }
                }
              }
              setMatched = condense(setMatched);
            }
            push$1.apply(results, setMatched);
            if (outermost && !seed2 && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
              Sizzle.uniqueSort(results);
            }
          }
          if (outermost) {
            dirruns = dirrunsUnique;
            outermostContext = contextBackup;
          }
          return unmatched;
        };
        return bySet ? markFunction(superMatcher) : superMatcher;
      }
      compile = Sizzle.compile = function(selector, match2) {
        var i, setMatchers = [], elementMatchers = [], cached2 = compilerCache[selector + " "];
        if (!cached2) {
          if (!match2) {
            match2 = tokenize(selector);
          }
          i = match2.length;
          while (i--) {
            cached2 = matcherFromTokens(match2[i]);
            if (cached2[expando]) {
              setMatchers.push(cached2);
            } else {
              elementMatchers.push(cached2);
            }
          }
          cached2 = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
          cached2.selector = selector;
        }
        return cached2;
      };
      select$1 = Sizzle.select = function(selector, context2, results, seed2) {
        var i, tokens, token, type2, find2, compiled = typeof selector === "function" && selector, match2 = !seed2 && tokenize(selector = compiled.selector || selector);
        results = results || [];
        if (match2.length === 1) {
          tokens = match2[0] = match2[0].slice(0);
          if (tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context2.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
            context2 = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context2) || [])[0];
            if (!context2) {
              return results;
            } else if (compiled) {
              context2 = context2.parentNode;
            }
            selector = selector.slice(tokens.shift().value.length);
          }
          i = matchExpr.needsContext.test(selector) ? 0 : tokens.length;
          while (i--) {
            token = tokens[i];
            if (Expr.relative[type2 = token.type]) {
              break;
            }
            if (find2 = Expr.find[type2]) {
              if (seed2 = find2(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context2.parentNode) || context2)) {
                tokens.splice(i, 1);
                selector = seed2.length && toSelector(tokens);
                if (!selector) {
                  push$1.apply(results, seed2);
                  return results;
                }
                break;
              }
            }
          }
        }
        (compiled || compile(selector, match2))(seed2, context2, !documentIsHTML, results, rsibling.test(selector) && testContext(context2.parentNode) || context2);
        return results;
      };
      support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
      support.detectDuplicates = !!hasDuplicate;
      setDocument();
      support.sortDetached = true;
      var doc = document;
      var push = Array.prototype.push;
      var slice = Array.prototype.slice;
      var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
      var Event$1 = EventUtils.Event;
      var skipUniques = Tools.makeMap("children,contents,next,prev");
      var isDefined = function(obj) {
        return typeof obj !== "undefined";
      };
      var isString = function(obj) {
        return typeof obj === "string";
      };
      var isWindow = function(obj) {
        return obj && obj === obj.window;
      };
      var createFragment$1 = function(html, fragDoc) {
        fragDoc = fragDoc || doc;
        var container = fragDoc.createElement("div");
        var frag = fragDoc.createDocumentFragment();
        container.innerHTML = html;
        var node;
        while (node = container.firstChild) {
          frag.appendChild(node);
        }
        return frag;
      };
      var domManipulate = function(targetNodes, sourceItem, callback, reverse2) {
        var i;
        if (isString(sourceItem)) {
          sourceItem = createFragment$1(sourceItem, getElementDocument(targetNodes[0]));
        } else if (sourceItem.length && !sourceItem.nodeType) {
          sourceItem = DomQuery.makeArray(sourceItem);
          if (reverse2) {
            for (i = sourceItem.length - 1; i >= 0; i--) {
              domManipulate(targetNodes, sourceItem[i], callback, reverse2);
            }
          } else {
            for (i = 0; i < sourceItem.length; i++) {
              domManipulate(targetNodes, sourceItem[i], callback, reverse2);
            }
          }
          return targetNodes;
        }
        if (sourceItem.nodeType) {
          i = targetNodes.length;
          while (i--) {
            callback.call(targetNodes[i], sourceItem);
          }
        }
        return targetNodes;
      };
      var hasClass = function(node, className) {
        return node && className && (" " + node.className + " ").indexOf(" " + className + " ") !== -1;
      };
      var wrap$2 = function(elements, wrapper, all2) {
        var lastParent, newWrapper;
        wrapper = DomQuery(wrapper)[0];
        elements.each(function() {
          var self2 = this;
          if (!all2 || lastParent !== self2.parentNode) {
            lastParent = self2.parentNode;
            newWrapper = wrapper.cloneNode(false);
            self2.parentNode.insertBefore(newWrapper, self2);
            newWrapper.appendChild(self2);
          } else {
            newWrapper.appendChild(self2);
          }
        });
        return elements;
      };
      var numericCssMap = Tools.makeMap("fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom", " ");
      var booleanMap = Tools.makeMap("checked compact declare defer disabled ismap multiple nohref noshade nowrap readonly selected", " ");
      var propFix = {
        for: "htmlFor",
        class: "className",
        readonly: "readOnly"
      };
      var cssFix = { float: "cssFloat" };
      var attrHooks = {}, cssHooks = {};
      var DomQueryConstructor = function(selector, context2) {
        return new DomQuery.fn.init(selector, context2);
      };
      var inArray$1 = function(item, array) {
        var i;
        if (array.indexOf) {
          return array.indexOf(item);
        }
        i = array.length;
        while (i--) {
          if (array[i] === item) {
            return i;
          }
        }
        return -1;
      };
      var whiteSpaceRegExp = /^\s*|\s*$/g;
      var trim$1 = function(str) {
        return str === null || str === void 0 ? "" : ("" + str).replace(whiteSpaceRegExp, "");
      };
      var each$g = function(obj, callback) {
        var length, key, i, value2;
        if (obj) {
          length = obj.length;
          if (length === void 0) {
            for (key in obj) {
              if (obj.hasOwnProperty(key)) {
                value2 = obj[key];
                if (callback.call(value2, key, value2) === false) {
                  break;
                }
              }
            }
          } else {
            for (i = 0; i < length; i++) {
              value2 = obj[i];
              if (callback.call(value2, i, value2) === false) {
                break;
              }
            }
          }
        }
        return obj;
      };
      var grep$2 = function(array, callback) {
        var out = [];
        each$g(array, function(i, item) {
          if (callback(item, i)) {
            out.push(item);
          }
        });
        return out;
      };
      var getElementDocument = function(element) {
        if (!element) {
          return doc;
        }
        if (element.nodeType === 9) {
          return element;
        }
        return element.ownerDocument;
      };
      DomQueryConstructor.fn = DomQueryConstructor.prototype = {
        constructor: DomQueryConstructor,
        selector: "",
        context: null,
        length: 0,
        init: function(selector, context2) {
          var self2 = this;
          var match2, node;
          if (!selector) {
            return self2;
          }
          if (selector.nodeType) {
            self2.context = self2[0] = selector;
            self2.length = 1;
            return self2;
          }
          if (context2 && context2.nodeType) {
            self2.context = context2;
          } else {
            if (context2) {
              return DomQuery(selector).attr(context2);
            }
            self2.context = context2 = document;
          }
          if (isString(selector)) {
            self2.selector = selector;
            if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
              match2 = [
                null,
                selector,
                null
              ];
            } else {
              match2 = rquickExpr.exec(selector);
            }
            if (match2) {
              if (match2[1]) {
                node = createFragment$1(selector, getElementDocument(context2)).firstChild;
                while (node) {
                  push.call(self2, node);
                  node = node.nextSibling;
                }
              } else {
                node = getElementDocument(context2).getElementById(match2[2]);
                if (!node) {
                  return self2;
                }
                if (node.id !== match2[2]) {
                  return self2.find(selector);
                }
                self2.length = 1;
                self2[0] = node;
              }
            } else {
              return DomQuery(context2).find(selector);
            }
          } else {
            this.add(selector, false);
          }
          return self2;
        },
        toArray: function() {
          return Tools.toArray(this);
        },
        add: function(items, sort2) {
          var self2 = this;
          var nodes, i;
          if (isString(items)) {
            return self2.add(DomQuery(items));
          }
          if (sort2 !== false) {
            nodes = DomQuery.unique(self2.toArray().concat(DomQuery.makeArray(items)));
            self2.length = nodes.length;
            for (i = 0; i < nodes.length; i++) {
              self2[i] = nodes[i];
            }
          } else {
            push.apply(self2, DomQuery.makeArray(items));
          }
          return self2;
        },
        attr: function(name2, value2) {
          var self2 = this;
          var hook;
          if (typeof name2 === "object") {
            each$g(name2, function(name3, value3) {
              self2.attr(name3, value3);
            });
          } else if (isDefined(value2)) {
            this.each(function() {
              var hook2;
              if (this.nodeType === 1) {
                hook2 = attrHooks[name2];
                if (hook2 && hook2.set) {
                  hook2.set(this, value2);
                  return;
                }
                if (value2 === null) {
                  this.removeAttribute(name2, 2);
                } else {
                  this.setAttribute(name2, value2, 2);
                }
              }
            });
          } else {
            if (self2[0] && self2[0].nodeType === 1) {
              hook = attrHooks[name2];
              if (hook && hook.get) {
                return hook.get(self2[0], name2);
              }
              if (booleanMap[name2]) {
                return self2.prop(name2) ? name2 : void 0;
              }
              value2 = self2[0].getAttribute(name2, 2);
              if (value2 === null) {
                value2 = void 0;
              }
            }
            return value2;
          }
          return self2;
        },
        removeAttr: function(name2) {
          return this.attr(name2, null);
        },
        prop: function(name2, value2) {
          var self2 = this;
          name2 = propFix[name2] || name2;
          if (typeof name2 === "object") {
            each$g(name2, function(name3, value3) {
              self2.prop(name3, value3);
            });
          } else if (isDefined(value2)) {
            this.each(function() {
              if (this.nodeType === 1) {
                this[name2] = value2;
              }
            });
          } else {
            if (self2[0] && self2[0].nodeType && name2 in self2[0]) {
              return self2[0][name2];
            }
            return value2;
          }
          return self2;
        },
        css: function(name2, value2) {
          var self2 = this;
          var elm, hook;
          var camel = function(name3) {
            return name3.replace(/-(\D)/g, function(a, b) {
              return b.toUpperCase();
            });
          };
          var dashed = function(name3) {
            return name3.replace(/[A-Z]/g, function(a) {
              return "-" + a;
            });
          };
          if (typeof name2 === "object") {
            each$g(name2, function(name3, value3) {
              self2.css(name3, value3);
            });
          } else {
            if (isDefined(value2)) {
              name2 = camel(name2);
              if (typeof value2 === "number" && !numericCssMap[name2]) {
                value2 = value2.toString() + "px";
              }
              self2.each(function() {
                var style = this.style;
                hook = cssHooks[name2];
                if (hook && hook.set) {
                  hook.set(this, value2);
                  return;
                }
                try {
                  this.style[cssFix[name2] || name2] = value2;
                } catch (ex) {
                }
                if (value2 === null || value2 === "") {
                  if (style.removeProperty) {
                    style.removeProperty(dashed(name2));
                  } else {
                    style.removeAttribute(name2);
                  }
                }
              });
            } else {
              elm = self2[0];
              hook = cssHooks[name2];
              if (hook && hook.get) {
                return hook.get(elm);
              }
              if (elm.ownerDocument.defaultView) {
                try {
                  return elm.ownerDocument.defaultView.getComputedStyle(elm, null).getPropertyValue(dashed(name2));
                } catch (ex) {
                  return void 0;
                }
              } else if (elm.currentStyle) {
                return elm.currentStyle[camel(name2)];
              } else {
                return "";
              }
            }
          }
          return self2;
        },
        remove: function() {
          var self2 = this;
          var node, i = this.length;
          while (i--) {
            node = self2[i];
            Event$1.clean(node);
            if (node.parentNode) {
              node.parentNode.removeChild(node);
            }
          }
          return this;
        },
        empty: function() {
          var self2 = this;
          var node, i = this.length;
          while (i--) {
            node = self2[i];
            while (node.firstChild) {
              node.removeChild(node.firstChild);
            }
          }
          return this;
        },
        html: function(value2) {
          var self2 = this;
          var i;
          if (isDefined(value2)) {
            i = self2.length;
            try {
              while (i--) {
                self2[i].innerHTML = value2;
              }
            } catch (ex) {
              DomQuery(self2[i]).empty().append(value2);
            }
            return self2;
          }
          return self2[0] ? self2[0].innerHTML : "";
        },
        text: function(value2) {
          var self2 = this;
          var i;
          if (isDefined(value2)) {
            i = self2.length;
            while (i--) {
              if ("innerText" in self2[i]) {
                self2[i].innerText = value2;
              } else {
                self2[0].textContent = value2;
              }
            }
            return self2;
          }
          return self2[0] ? self2[0].innerText || self2[0].textContent : "";
        },
        append: function() {
          return domManipulate(this, arguments, function(node) {
            if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
              this.appendChild(node);
            }
          });
        },
        prepend: function() {
          return domManipulate(this, arguments, function(node) {
            if (this.nodeType === 1 || this.host && this.host.nodeType === 1) {
              this.insertBefore(node, this.firstChild);
            }
          }, true);
        },
        before: function() {
          var self2 = this;
          if (self2[0] && self2[0].parentNode) {
            return domManipulate(self2, arguments, function(node) {
              this.parentNode.insertBefore(node, this);
            });
          }
          return self2;
        },
        after: function() {
          var self2 = this;
          if (self2[0] && self2[0].parentNode) {
            return domManipulate(self2, arguments, function(node) {
              this.parentNode.insertBefore(node, this.nextSibling);
            }, true);
          }
          return self2;
        },
        appendTo: function(val) {
          DomQuery(val).append(this);
          return this;
        },
        prependTo: function(val) {
          DomQuery(val).prepend(this);
          return this;
        },
        replaceWith: function(content) {
          return this.before(content).remove();
        },
        wrap: function(content) {
          return wrap$2(this, content);
        },
        wrapAll: function(content) {
          return wrap$2(this, content, true);
        },
        wrapInner: function(content) {
          this.each(function() {
            DomQuery(this).contents().wrapAll(content);
          });
          return this;
        },
        unwrap: function() {
          return this.parent().each(function() {
            DomQuery(this).replaceWith(this.childNodes);
          });
        },
        clone: function() {
          var result = [];
          this.each(function() {
            result.push(this.cloneNode(true));
          });
          return DomQuery(result);
        },
        addClass: function(className) {
          return this.toggleClass(className, true);
        },
        removeClass: function(className) {
          return this.toggleClass(className, false);
        },
        toggleClass: function(className, state) {
          var self2 = this;
          if (typeof className !== "string") {
            return self2;
          }
          if (className.indexOf(" ") !== -1) {
            each$g(className.split(" "), function() {
              self2.toggleClass(this, state);
            });
          } else {
            self2.each(function(index, node) {
              var classState = hasClass(node, className);
              if (classState !== state) {
                var existingClassName = node.className;
                if (classState) {
                  node.className = trim$1((" " + existingClassName + " ").replace(" " + className + " ", " "));
                } else {
                  node.className += existingClassName ? " " + className : className;
                }
              }
            });
          }
          return self2;
        },
        hasClass: function(className) {
          return hasClass(this[0], className);
        },
        each: function(callback) {
          return each$g(this, callback);
        },
        on: function(name2, callback) {
          return this.each(function() {
            Event$1.bind(this, name2, callback);
          });
        },
        off: function(name2, callback) {
          return this.each(function() {
            Event$1.unbind(this, name2, callback);
          });
        },
        trigger: function(name2) {
          return this.each(function() {
            if (typeof name2 === "object") {
              Event$1.fire(this, name2.type, name2);
            } else {
              Event$1.fire(this, name2);
            }
          });
        },
        show: function() {
          return this.css("display", "");
        },
        hide: function() {
          return this.css("display", "none");
        },
        slice: function() {
          return DomQuery(slice.apply(this, arguments));
        },
        eq: function(index) {
          return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
        },
        first: function() {
          return this.eq(0);
        },
        last: function() {
          return this.eq(-1);
        },
        find: function(selector) {
          var i, l;
          var ret = [];
          for (i = 0, l = this.length; i < l; i++) {
            DomQuery.find(selector, this[i], ret);
          }
          return DomQuery(ret);
        },
        filter: function(selector) {
          if (typeof selector === "function") {
            return DomQuery(grep$2(this.toArray(), function(item, i) {
              return selector(i, item);
            }));
          }
          return DomQuery(DomQuery.filter(selector, this.toArray()));
        },
        closest: function(selector) {
          var result = [];
          if (selector instanceof DomQuery) {
            selector = selector[0];
          }
          this.each(function(i, node) {
            while (node) {
              if (typeof selector === "string" && DomQuery(node).is(selector)) {
                result.push(node);
                break;
              } else if (node === selector) {
                result.push(node);
                break;
              }
              node = node.parentNode;
            }
          });
          return DomQuery(result);
        },
        offset: function(offset) {
          var elm, doc2, docElm;
          var x = 0, y = 0, pos;
          if (!offset) {
            elm = this[0];
            if (elm) {
              doc2 = elm.ownerDocument;
              docElm = doc2.documentElement;
              if (elm.getBoundingClientRect) {
                pos = elm.getBoundingClientRect();
                x = pos.left + (docElm.scrollLeft || doc2.body.scrollLeft) - docElm.clientLeft;
                y = pos.top + (docElm.scrollTop || doc2.body.scrollTop) - docElm.clientTop;
              }
            }
            return {
              left: x,
              top: y
            };
          }
          return this.css(offset);
        },
        push,
        sort: Array.prototype.sort,
        splice: Array.prototype.splice
      };
      Tools.extend(DomQueryConstructor, {
        extend: Tools.extend,
        makeArray: function(object) {
          if (isWindow(object) || object.nodeType) {
            return [object];
          }
          return Tools.toArray(object);
        },
        inArray: inArray$1,
        isArray: Tools.isArray,
        each: each$g,
        trim: trim$1,
        grep: grep$2,
        find: Sizzle,
        expr: Sizzle.selectors,
        unique: Sizzle.uniqueSort,
        text: Sizzle.getText,
        contains: Sizzle.contains,
        filter: function(expr, elems, not2) {
          var i = elems.length;
          if (not2) {
            expr = ":not(" + expr + ")";
          }
          while (i--) {
            if (elems[i].nodeType !== 1) {
              elems.splice(i, 1);
            }
          }
          if (elems.length === 1) {
            elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [];
          } else {
            elems = DomQuery.find.matches(expr, elems);
          }
          return elems;
        }
      });
      var dir = function(el, prop, until) {
        var matched = [];
        var cur = el[prop];
        if (typeof until !== "string" && until instanceof DomQuery) {
          until = until[0];
        }
        while (cur && cur.nodeType !== 9) {
          if (until !== void 0) {
            if (cur === until) {
              break;
            }
            if (typeof until === "string" && DomQuery(cur).is(until)) {
              break;
            }
          }
          if (cur.nodeType === 1) {
            matched.push(cur);
          }
          cur = cur[prop];
        }
        return matched;
      };
      var sibling$1 = function(node, siblingName, nodeType, until) {
        var result = [];
        if (until instanceof DomQuery) {
          until = until[0];
        }
        for (; node; node = node[siblingName]) {
          if (nodeType && node.nodeType !== nodeType) {
            continue;
          }
          if (until !== void 0) {
            if (node === until) {
              break;
            }
            if (typeof until === "string" && DomQuery(node).is(until)) {
              break;
            }
          }
          result.push(node);
        }
        return result;
      };
      var firstSibling = function(node, siblingName, nodeType) {
        for (node = node[siblingName]; node; node = node[siblingName]) {
          if (node.nodeType === nodeType) {
            return node;
          }
        }
        return null;
      };
      each$g({
        parent: function(node) {
          var parent2 = node.parentNode;
          return parent2 && parent2.nodeType !== 11 ? parent2 : null;
        },
        parents: function(node) {
          return dir(node, "parentNode");
        },
        next: function(node) {
          return firstSibling(node, "nextSibling", 1);
        },
        prev: function(node) {
          return firstSibling(node, "previousSibling", 1);
        },
        children: function(node) {
          return sibling$1(node.firstChild, "nextSibling", 1);
        },
        contents: function(node) {
          return Tools.toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes);
        }
      }, function(name2, fn) {
        DomQueryConstructor.fn[name2] = function(selector) {
          var self2 = this;
          var result = [];
          self2.each(function() {
            var nodes = fn.call(result, this, selector, result);
            if (nodes) {
              if (DomQuery.isArray(nodes)) {
                result.push.apply(result, nodes);
              } else {
                result.push(nodes);
              }
            }
          });
          if (this.length > 1) {
            if (!skipUniques[name2]) {
              result = DomQuery.unique(result);
            }
            if (name2.indexOf("parents") === 0) {
              result = result.reverse();
            }
          }
          var wrappedResult = DomQuery(result);
          if (selector) {
            return wrappedResult.filter(selector);
          }
          return wrappedResult;
        };
      });
      each$g({
        parentsUntil: function(node, until) {
          return dir(node, "parentNode", until);
        },
        nextUntil: function(node, until) {
          return sibling$1(node, "nextSibling", 1, until).slice(1);
        },
        prevUntil: function(node, until) {
          return sibling$1(node, "previousSibling", 1, until).slice(1);
        }
      }, function(name2, fn) {
        DomQueryConstructor.fn[name2] = function(selector, filter2) {
          var self2 = this;
          var result = [];
          self2.each(function() {
            var nodes = fn.call(result, this, selector, result);
            if (nodes) {
              if (DomQuery.isArray(nodes)) {
                result.push.apply(result, nodes);
              } else {
                result.push(nodes);
              }
            }
          });
          if (this.length > 1) {
            result = DomQuery.unique(result);
            if (name2.indexOf("parents") === 0 || name2 === "prevUntil") {
              result = result.reverse();
            }
          }
          var wrappedResult = DomQuery(result);
          if (filter2) {
            return wrappedResult.filter(filter2);
          }
          return wrappedResult;
        };
      });
      DomQueryConstructor.fn.is = function(selector) {
        return !!selector && this.filter(selector).length > 0;
      };
      DomQueryConstructor.fn.init.prototype = DomQueryConstructor.fn;
      DomQueryConstructor.overrideDefaults = function(callback) {
        var defaults;
        var sub = function(selector, context2) {
          defaults = defaults || callback();
          if (arguments.length === 0) {
            selector = defaults.element;
          }
          if (!context2) {
            context2 = defaults.context;
          }
          return new sub.fn.init(selector, context2);
        };
        DomQuery.extend(sub, this);
        return sub;
      };
      DomQueryConstructor.attrHooks = attrHooks;
      DomQueryConstructor.cssHooks = cssHooks;
      var DomQuery = DomQueryConstructor;
      var each$f = Tools.each;
      var grep$1 = Tools.grep;
      var isIE = Env.ie;
      var simpleSelectorRe = /^([a-z0-9],?)+$/i;
      var setupAttrHooks = function(styles, settings, getContext) {
        var keepValues = settings.keep_values;
        var keepUrlHook = {
          set: function($elm, value2, name2) {
            if (settings.url_converter && value2 !== null) {
              value2 = settings.url_converter.call(settings.url_converter_scope || getContext(), value2, name2, $elm[0]);
            }
            $elm.attr("data-mce-" + name2, value2).attr(name2, value2);
          },
          get: function($elm, name2) {
            return $elm.attr("data-mce-" + name2) || $elm.attr(name2);
          }
        };
        var attrHooks2 = {
          style: {
            set: function($elm, value2) {
              if (value2 !== null && typeof value2 === "object") {
                $elm.css(value2);
                return;
              }
              if (keepValues) {
                $elm.attr("data-mce-style", value2);
              }
              if (value2 !== null && typeof value2 === "string") {
                $elm.removeAttr("style");
                $elm.css(styles.parse(value2));
              } else {
                $elm.attr("style", value2);
              }
            },
            get: function($elm) {
              var value2 = $elm.attr("data-mce-style") || $elm.attr("style");
              value2 = styles.serialize(styles.parse(value2), $elm[0].nodeName);
              return value2;
            }
          }
        };
        if (keepValues) {
          attrHooks2.href = attrHooks2.src = keepUrlHook;
        }
        return attrHooks2;
      };
      var updateInternalStyleAttr = function(styles, $elm) {
        var rawValue = $elm.attr("style");
        var value2 = styles.serialize(styles.parse(rawValue), $elm[0].nodeName);
        if (!value2) {
          value2 = null;
        }
        $elm.attr("data-mce-style", value2);
      };
      var findNodeIndex = function(node, normalized) {
        var idx = 0, lastNodeType, nodeType;
        if (node) {
          for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
            nodeType = node.nodeType;
            if (normalized && nodeType === 3) {
              if (nodeType === lastNodeType || !node.nodeValue.length) {
                continue;
              }
            }
            idx++;
            lastNodeType = nodeType;
          }
        }
        return idx;
      };
      var DOMUtils = function(doc2, settings) {
        if (settings === void 0) {
          settings = {};
        }
        var addedStyles = {};
        var win = window;
        var files = {};
        var counter = 0;
        var stdMode = true;
        var boxModel = true;
        var styleSheetLoader = instance.forElement(SugarElement.fromDom(doc2), {
          contentCssCors: settings.contentCssCors,
          referrerPolicy: settings.referrerPolicy
        });
        var boundEvents = [];
        var schema = settings.schema ? settings.schema : Schema({});
        var styles = Styles({
          url_converter: settings.url_converter,
          url_converter_scope: settings.url_converter_scope
        }, settings.schema);
        var events = settings.ownEvents ? new EventUtils() : EventUtils.Event;
        var blockElementsMap = schema.getBlockElements();
        var $ = DomQuery.overrideDefaults(function() {
          return {
            context: doc2,
            element: self2.getRoot()
          };
        });
        var isBlock2 = function(node) {
          if (typeof node === "string") {
            return !!blockElementsMap[node];
          } else if (node) {
            var type2 = node.nodeType;
            if (type2) {
              return !!(type2 === 1 && blockElementsMap[node.nodeName]);
            }
          }
          return false;
        };
        var get2 = function(elm) {
          return elm && doc2 && isString$1(elm) ? doc2.getElementById(elm) : elm;
        };
        var $$ = function(elm) {
          return $(typeof elm === "string" ? get2(elm) : elm);
        };
        var getAttrib = function(elm, name2, defaultVal) {
          var hook, value2;
          var $elm = $$(elm);
          if ($elm.length) {
            hook = attrHooks2[name2];
            if (hook && hook.get) {
              value2 = hook.get($elm, name2);
            } else {
              value2 = $elm.attr(name2);
            }
          }
          if (typeof value2 === "undefined") {
            value2 = defaultVal || "";
          }
          return value2;
        };
        var getAttribs = function(elm) {
          var node = get2(elm);
          if (!node) {
            return [];
          }
          return node.attributes;
        };
        var setAttrib = function(elm, name2, value2) {
          if (value2 === "") {
            value2 = null;
          }
          var $elm = $$(elm);
          var originalValue = $elm.attr(name2);
          if (!$elm.length) {
            return;
          }
          var hook = attrHooks2[name2];
          if (hook && hook.set) {
            hook.set($elm, value2, name2);
          } else {
            $elm.attr(name2, value2);
          }
          if (originalValue !== value2 && settings.onSetAttrib) {
            settings.onSetAttrib({
              attrElm: $elm,
              attrName: name2,
              attrValue: value2
            });
          }
        };
        var clone2 = function(node, deep2) {
          if (!isIE || node.nodeType !== 1 || deep2) {
            return node.cloneNode(deep2);
          } else {
            var clone_1 = doc2.createElement(node.nodeName);
            each$f(getAttribs(node), function(attr) {
              setAttrib(clone_1, attr.nodeName, getAttrib(node, attr.nodeName));
            });
            return clone_1;
          }
        };
        var getRoot = function() {
          return settings.root_element || doc2.body;
        };
        var getViewPort = function(argWin) {
          var vp = getBounds(argWin);
          return {
            x: vp.x,
            y: vp.y,
            w: vp.width,
            h: vp.height
          };
        };
        var getPos$1 = function(elm, rootElm) {
          return getPos(doc2.body, get2(elm), rootElm);
        };
        var setStyle = function(elm, name2, value2) {
          var $elm = isString$1(name2) ? $$(elm).css(name2, value2) : $$(elm).css(name2);
          if (settings.update_styles) {
            updateInternalStyleAttr(styles, $elm);
          }
        };
        var setStyles = function(elm, stylesArg) {
          var $elm = $$(elm).css(stylesArg);
          if (settings.update_styles) {
            updateInternalStyleAttr(styles, $elm);
          }
        };
        var getStyle2 = function(elm, name2, computed) {
          var $elm = $$(elm);
          if (computed) {
            return $elm.css(name2);
          }
          name2 = name2.replace(/-(\D)/g, function(a, b) {
            return b.toUpperCase();
          });
          if (name2 === "float") {
            name2 = Env.browser.isIE() ? "styleFloat" : "cssFloat";
          }
          return $elm[0] && $elm[0].style ? $elm[0].style[name2] : void 0;
        };
        var getSize = function(elm) {
          var w, h;
          elm = get2(elm);
          w = getStyle2(elm, "width");
          h = getStyle2(elm, "height");
          if (w.indexOf("px") === -1) {
            w = 0;
          }
          if (h.indexOf("px") === -1) {
            h = 0;
          }
          return {
            w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
            h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
          };
        };
        var getRect = function(elm) {
          elm = get2(elm);
          var pos = getPos$1(elm);
          var size = getSize(elm);
          return {
            x: pos.x,
            y: pos.y,
            w: size.w,
            h: size.h
          };
        };
        var is2 = function(elm, selector) {
          var i;
          if (!elm) {
            return false;
          }
          if (!Array.isArray(elm)) {
            if (selector === "*") {
              return elm.nodeType === 1;
            }
            if (simpleSelectorRe.test(selector)) {
              var selectors = selector.toLowerCase().split(/,/);
              var elmName = elm.nodeName.toLowerCase();
              for (i = selectors.length - 1; i >= 0; i--) {
                if (selectors[i] === elmName) {
                  return true;
                }
              }
              return false;
            }
            if (elm.nodeType && elm.nodeType !== 1) {
              return false;
            }
          }
          var elms = !Array.isArray(elm) ? [elm] : elm;
          return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
        };
        var getParents2 = function(elm, selector, root, collect) {
          var result = [];
          var selectorVal;
          var node = get2(elm);
          collect = collect === void 0;
          root = root || (getRoot().nodeName !== "BODY" ? getRoot().parentNode : null);
          if (Tools.is(selector, "string")) {
            selectorVal = selector;
            if (selector === "*") {
              selector = function(node2) {
                return node2.nodeType === 1;
              };
            } else {
              selector = function(node2) {
                return is2(node2, selectorVal);
              };
            }
          }
          while (node) {
            if (node === root || isNullable(node.nodeType) || isDocument$1(node) || isDocumentFragment(node)) {
              break;
            }
            if (!selector || typeof selector === "function" && selector(node)) {
              if (collect) {
                result.push(node);
              } else {
                return [node];
              }
            }
            node = node.parentNode;
          }
          return collect ? result : null;
        };
        var getParent = function(node, selector, root) {
          var parents2 = getParents2(node, selector, root, false);
          return parents2 && parents2.length > 0 ? parents2[0] : null;
        };
        var _findSib = function(node, selector, name2) {
          var func = selector;
          if (node) {
            if (typeof selector === "string") {
              func = function(node2) {
                return is2(node2, selector);
              };
            }
            for (node = node[name2]; node; node = node[name2]) {
              if (typeof func === "function" && func(node)) {
                return node;
              }
            }
          }
          return null;
        };
        var getNext = function(node, selector) {
          return _findSib(node, selector, "nextSibling");
        };
        var getPrev = function(node, selector) {
          return _findSib(node, selector, "previousSibling");
        };
        var select2 = function(selector, scope) {
          return Sizzle(selector, get2(scope) || settings.root_element || doc2, []);
        };
        var run = function(elm, func, scope) {
          var result;
          var node = typeof elm === "string" ? get2(elm) : elm;
          if (!node) {
            return false;
          }
          if (Tools.isArray(node) && (node.length || node.length === 0)) {
            result = [];
            each$f(node, function(elm2, i) {
              if (elm2) {
                result.push(func.call(scope, typeof elm2 === "string" ? get2(elm2) : elm2, i));
              }
            });
            return result;
          }
          var context2 = scope ? scope : this;
          return func.call(context2, node);
        };
        var setAttribs = function(elm, attrs) {
          $$(elm).each(function(i, node) {
            each$f(attrs, function(value2, name2) {
              setAttrib(node, name2, value2);
            });
          });
        };
        var setHTML = function(elm, html) {
          var $elm = $$(elm);
          if (isIE) {
            $elm.each(function(i, target) {
              if (target.canHaveHTML === false) {
                return;
              }
              while (target.firstChild) {
                target.removeChild(target.firstChild);
              }
              try {
                target.innerHTML = "<br>" + html;
                target.removeChild(target.firstChild);
              } catch (ex) {
                DomQuery("<div></div>").html("<br>" + html).contents().slice(1).appendTo(target);
              }
              return html;
            });
          } else {
            $elm.html(html);
          }
        };
        var add2 = function(parentElm, name2, attrs, html, create3) {
          return run(parentElm, function(parentElm2) {
            var newElm = typeof name2 === "string" ? doc2.createElement(name2) : name2;
            setAttribs(newElm, attrs);
            if (html) {
              if (typeof html !== "string" && html.nodeType) {
                newElm.appendChild(html);
              } else if (typeof html === "string") {
                setHTML(newElm, html);
              }
            }
            return !create3 ? parentElm2.appendChild(newElm) : newElm;
          });
        };
        var create2 = function(name2, attrs, html) {
          return add2(doc2.createElement(name2), name2, attrs, html, true);
        };
        var decode2 = Entities.decode;
        var encode = Entities.encodeAllRaw;
        var createHTML = function(name2, attrs, html) {
          var outHtml = "", key;
          outHtml += "<" + name2;
          for (key in attrs) {
            if (hasNonNullableKey(attrs, key)) {
              outHtml += " " + key + '="' + encode(attrs[key]) + '"';
            }
          }
          if (typeof html !== "undefined") {
            return outHtml + ">" + html + "</" + name2 + ">";
          }
          return outHtml + " />";
        };
        var createFragment2 = function(html) {
          var node;
          var container = doc2.createElement("div");
          var frag = doc2.createDocumentFragment();
          frag.appendChild(container);
          if (html) {
            container.innerHTML = html;
          }
          while (node = container.firstChild) {
            frag.appendChild(node);
          }
          frag.removeChild(container);
          return frag;
        };
        var remove2 = function(node, keepChildren) {
          var $node = $$(node);
          if (keepChildren) {
            $node.each(function() {
              var child2;
              while (child2 = this.firstChild) {
                if (child2.nodeType === 3 && child2.data.length === 0) {
                  this.removeChild(child2);
                } else {
                  this.parentNode.insertBefore(child2, this);
                }
              }
            }).remove();
          } else {
            $node.remove();
          }
          return $node.length > 1 ? $node.toArray() : $node[0];
        };
        var removeAllAttribs = function(e) {
          return run(e, function(e2) {
            var i;
            var attrs = e2.attributes;
            for (i = attrs.length - 1; i >= 0; i--) {
              e2.removeAttributeNode(attrs.item(i));
            }
          });
        };
        var parseStyle = function(cssText) {
          return styles.parse(cssText);
        };
        var serializeStyle = function(stylesArg, name2) {
          return styles.serialize(stylesArg, name2);
        };
        var addStyle = function(cssText) {
          var head2, styleElm;
          if (self2 !== DOMUtils.DOM && doc2 === document) {
            if (addedStyles[cssText]) {
              return;
            }
            addedStyles[cssText] = true;
          }
          styleElm = doc2.getElementById("mceDefaultStyles");
          if (!styleElm) {
            styleElm = doc2.createElement("style");
            styleElm.id = "mceDefaultStyles";
            styleElm.type = "text/css";
            head2 = doc2.getElementsByTagName("head")[0];
            if (head2.firstChild) {
              head2.insertBefore(styleElm, head2.firstChild);
            } else {
              head2.appendChild(styleElm);
            }
          }
          if (styleElm.styleSheet) {
            styleElm.styleSheet.cssText += cssText;
          } else {
            styleElm.appendChild(doc2.createTextNode(cssText));
          }
        };
        var loadCSS = function(urls) {
          if (!urls) {
            urls = "";
          }
          each$k(urls.split(","), function(url) {
            files[url] = true;
            styleSheetLoader.load(url, noop);
          });
        };
        var toggleClass2 = function(elm, cls, state) {
          $$(elm).toggleClass(cls, state).each(function() {
            if (this.className === "") {
              DomQuery(this).attr("class", null);
            }
          });
        };
        var addClass = function(elm, cls) {
          $$(elm).addClass(cls);
        };
        var removeClass = function(elm, cls) {
          toggleClass2(elm, cls, false);
        };
        var hasClass2 = function(elm, cls) {
          return $$(elm).hasClass(cls);
        };
        var show = function(elm) {
          $$(elm).show();
        };
        var hide = function(elm) {
          $$(elm).hide();
        };
        var isHidden = function(elm) {
          return $$(elm).css("display") === "none";
        };
        var uniqueId2 = function(prefix) {
          return (!prefix ? "mce_" : prefix) + counter++;
        };
        var getOuterHTML = function(elm) {
          var node = typeof elm === "string" ? get2(elm) : elm;
          return isElement$5(node) ? node.outerHTML : DomQuery("<div></div>").append(DomQuery(node).clone()).html();
        };
        var setOuterHTML = function(elm, html) {
          $$(elm).each(function() {
            try {
              if ("outerHTML" in this) {
                this.outerHTML = html;
                return;
              }
            } catch (ex) {
            }
            remove2(DomQuery(this).html(html), true);
          });
        };
        var insertAfter2 = function(node, reference) {
          var referenceNode = get2(reference);
          return run(node, function(node2) {
            var parent2 = referenceNode.parentNode;
            var nextSibling2 = referenceNode.nextSibling;
            if (nextSibling2) {
              parent2.insertBefore(node2, nextSibling2);
            } else {
              parent2.appendChild(node2);
            }
            return node2;
          });
        };
        var replace = function(newElm, oldElm, keepChildren) {
          return run(oldElm, function(oldElm2) {
            if (Tools.is(oldElm2, "array")) {
              newElm = newElm.cloneNode(true);
            }
            if (keepChildren) {
              each$f(grep$1(oldElm2.childNodes), function(node) {
                newElm.appendChild(node);
              });
            }
            return oldElm2.parentNode.replaceChild(newElm, oldElm2);
          });
        };
        var rename = function(elm, name2) {
          var newElm;
          if (elm.nodeName !== name2.toUpperCase()) {
            newElm = create2(name2);
            each$f(getAttribs(elm), function(attrNode) {
              setAttrib(newElm, attrNode.nodeName, getAttrib(elm, attrNode.nodeName));
            });
            replace(newElm, elm, true);
          }
          return newElm || elm;
        };
        var findCommonAncestor = function(a, b) {
          var ps = a, pe;
          while (ps) {
            pe = b;
            while (pe && ps !== pe) {
              pe = pe.parentNode;
            }
            if (ps === pe) {
              break;
            }
            ps = ps.parentNode;
          }
          if (!ps && a.ownerDocument) {
            return a.ownerDocument.documentElement;
          }
          return ps;
        };
        var toHex2 = function(rgbVal) {
          return styles.toHex(Tools.trim(rgbVal));
        };
        var isNonEmptyElement2 = function(node) {
          if (isElement$5(node)) {
            var isNamedAnchor2 = node.nodeName.toLowerCase() === "a" && !getAttrib(node, "href") && getAttrib(node, "id");
            if (getAttrib(node, "name") || getAttrib(node, "data-mce-bookmark") || isNamedAnchor2) {
              return true;
            }
          }
          return false;
        };
        var isEmpty2 = function(node, elements) {
          var type2, name2, brCount = 0;
          if (isNonEmptyElement2(node)) {
            return false;
          }
          node = node.firstChild;
          if (node) {
            var walker = new DomTreeWalker(node, node.parentNode);
            var whitespace2 = schema ? schema.getWhiteSpaceElements() : {};
            elements = elements || (schema ? schema.getNonEmptyElements() : null);
            do {
              type2 = node.nodeType;
              if (isElement$5(node)) {
                var bogusVal = node.getAttribute("data-mce-bogus");
                if (bogusVal) {
                  node = walker.next(bogusVal === "all");
                  continue;
                }
                name2 = node.nodeName.toLowerCase();
                if (elements && elements[name2]) {
                  if (name2 === "br") {
                    brCount++;
                    node = walker.next();
                    continue;
                  }
                  return false;
                }
                if (isNonEmptyElement2(node)) {
                  return false;
                }
              }
              if (type2 === 8) {
                return false;
              }
              if (type2 === 3 && !isWhitespaceText(node.nodeValue)) {
                return false;
              }
              if (type2 === 3 && node.parentNode && whitespace2[node.parentNode.nodeName] && isWhitespaceText(node.nodeValue)) {
                return false;
              }
              node = walker.next();
            } while (node);
          }
          return brCount <= 1;
        };
        var createRng = function() {
          return doc2.createRange();
        };
        var split2 = function(parentElm, splitElm, replacementElm) {
          var range2 = createRng();
          var beforeFragment;
          var afterFragment;
          var parentNode;
          if (parentElm && splitElm) {
            range2.setStart(parentElm.parentNode, findNodeIndex(parentElm));
            range2.setEnd(splitElm.parentNode, findNodeIndex(splitElm));
            beforeFragment = range2.extractContents();
            range2 = createRng();
            range2.setStart(splitElm.parentNode, findNodeIndex(splitElm) + 1);
            range2.setEnd(parentElm.parentNode, findNodeIndex(parentElm) + 1);
            afterFragment = range2.extractContents();
            parentNode = parentElm.parentNode;
            parentNode.insertBefore(trimNode(self2, beforeFragment), parentElm);
            if (replacementElm) {
              parentNode.insertBefore(replacementElm, parentElm);
            } else {
              parentNode.insertBefore(splitElm, parentElm);
            }
            parentNode.insertBefore(trimNode(self2, afterFragment), parentElm);
            remove2(parentElm);
            return replacementElm || splitElm;
          }
        };
        var bind2 = function(target, name2, func, scope) {
          if (Tools.isArray(target)) {
            var i = target.length;
            var rv = [];
            while (i--) {
              rv[i] = bind2(target[i], name2, func, scope);
            }
            return rv;
          }
          if (settings.collect && (target === doc2 || target === win)) {
            boundEvents.push([
              target,
              name2,
              func,
              scope
            ]);
          }
          var output = events.bind(target, name2, func, scope || self2);
          return output;
        };
        var unbind = function(target, name2, func) {
          if (Tools.isArray(target)) {
            var i = target.length;
            var rv = [];
            while (i--) {
              rv[i] = unbind(target[i], name2, func);
            }
            return rv;
          } else {
            if (boundEvents.length > 0 && (target === doc2 || target === win)) {
              var i = boundEvents.length;
              while (i--) {
                var item = boundEvents[i];
                if (target === item[0] && (!name2 || name2 === item[1]) && (!func || func === item[2])) {
                  events.unbind(item[0], item[1], item[2]);
                }
              }
            }
            return events.unbind(target, name2, func);
          }
        };
        var fire = function(target, name2, evt) {
          return events.fire(target, name2, evt);
        };
        var getContentEditable = function(node) {
          if (node && isElement$5(node)) {
            var contentEditable = node.getAttribute("data-mce-contenteditable");
            if (contentEditable && contentEditable !== "inherit") {
              return contentEditable;
            }
            return node.contentEditable !== "inherit" ? node.contentEditable : null;
          } else {
            return null;
          }
        };
        var getContentEditableParent = function(node) {
          var root = getRoot();
          var state = null;
          for (; node && node !== root; node = node.parentNode) {
            state = getContentEditable(node);
            if (state !== null) {
              break;
            }
          }
          return state;
        };
        var destroy2 = function() {
          if (boundEvents.length > 0) {
            var i = boundEvents.length;
            while (i--) {
              var item = boundEvents[i];
              events.unbind(item[0], item[1], item[2]);
            }
          }
          each$j(files, function(_, url) {
            styleSheetLoader.unload(url);
            delete files[url];
          });
          if (Sizzle.setDocument) {
            Sizzle.setDocument();
          }
        };
        var isChildOf = function(node, parent2) {
          if (!isIE) {
            return node === parent2 || parent2.contains(node);
          } else {
            while (node) {
              if (parent2 === node) {
                return true;
              }
              node = node.parentNode;
            }
            return false;
          }
        };
        var dumpRng = function(r2) {
          return "startContainer: " + r2.startContainer.nodeName + ", startOffset: " + r2.startOffset + ", endContainer: " + r2.endContainer.nodeName + ", endOffset: " + r2.endOffset;
        };
        var self2 = {
          doc: doc2,
          settings,
          win,
          files,
          stdMode,
          boxModel,
          styleSheetLoader,
          boundEvents,
          styles,
          schema,
          events,
          isBlock: isBlock2,
          $,
          $$,
          root: null,
          clone: clone2,
          getRoot,
          getViewPort,
          getRect,
          getSize,
          getParent,
          getParents: getParents2,
          get: get2,
          getNext,
          getPrev,
          select: select2,
          is: is2,
          add: add2,
          create: create2,
          createHTML,
          createFragment: createFragment2,
          remove: remove2,
          setStyle,
          getStyle: getStyle2,
          setStyles,
          removeAllAttribs,
          setAttrib,
          setAttribs,
          getAttrib,
          getPos: getPos$1,
          parseStyle,
          serializeStyle,
          addStyle,
          loadCSS,
          addClass,
          removeClass,
          hasClass: hasClass2,
          toggleClass: toggleClass2,
          show,
          hide,
          isHidden,
          uniqueId: uniqueId2,
          setHTML,
          getOuterHTML,
          setOuterHTML,
          decode: decode2,
          encode,
          insertAfter: insertAfter2,
          replace,
          rename,
          findCommonAncestor,
          toHex: toHex2,
          run,
          getAttribs,
          isEmpty: isEmpty2,
          createRng,
          nodeIndex: findNodeIndex,
          split: split2,
          bind: bind2,
          unbind,
          fire,
          getContentEditable,
          getContentEditableParent,
          destroy: destroy2,
          isChildOf,
          dumpRng
        };
        var attrHooks2 = setupAttrHooks(styles, settings, constant(self2));
        return self2;
      };
      DOMUtils.DOM = DOMUtils(document);
      DOMUtils.nodeIndex = findNodeIndex;
      var DOM$a = DOMUtils.DOM;
      var each$e = Tools.each, grep = Tools.grep;
      var QUEUED = 0;
      var LOADING = 1;
      var LOADED = 2;
      var FAILED = 3;
      var ScriptLoader = function() {
        function ScriptLoader2(settings) {
          if (settings === void 0) {
            settings = {};
          }
          this.states = {};
          this.queue = [];
          this.scriptLoadedCallbacks = {};
          this.queueLoadedCallbacks = [];
          this.loading = 0;
          this.settings = settings;
        }
        ScriptLoader2.prototype._setReferrerPolicy = function(referrerPolicy) {
          this.settings.referrerPolicy = referrerPolicy;
        };
        ScriptLoader2.prototype.loadScript = function(url, success, failure) {
          var dom2 = DOM$a;
          var elm;
          var cleanup = function() {
            dom2.remove(id);
            if (elm) {
              elm.onerror = elm.onload = elm = null;
            }
          };
          var done2 = function() {
            cleanup();
            success();
          };
          var error2 = function() {
            cleanup();
            if (isFunction(failure)) {
              failure();
            } else {
              if (typeof console !== "undefined" && console.log) {
                console.log("Failed to load script: " + url);
              }
            }
          };
          var id = dom2.uniqueId();
          elm = document.createElement("script");
          elm.id = id;
          elm.type = "text/javascript";
          elm.src = Tools._addCacheSuffix(url);
          if (this.settings.referrerPolicy) {
            dom2.setAttrib(elm, "referrerpolicy", this.settings.referrerPolicy);
          }
          elm.onload = done2;
          elm.onerror = error2;
          (document.getElementsByTagName("head")[0] || document.body).appendChild(elm);
        };
        ScriptLoader2.prototype.isDone = function(url) {
          return this.states[url] === LOADED;
        };
        ScriptLoader2.prototype.markDone = function(url) {
          this.states[url] = LOADED;
        };
        ScriptLoader2.prototype.add = function(url, success, scope, failure) {
          var state = this.states[url];
          this.queue.push(url);
          if (state === void 0) {
            this.states[url] = QUEUED;
          }
          if (success) {
            if (!this.scriptLoadedCallbacks[url]) {
              this.scriptLoadedCallbacks[url] = [];
            }
            this.scriptLoadedCallbacks[url].push({
              success,
              failure,
              scope: scope || this
            });
          }
        };
        ScriptLoader2.prototype.load = function(url, success, scope, failure) {
          return this.add(url, success, scope, failure);
        };
        ScriptLoader2.prototype.remove = function(url) {
          delete this.states[url];
          delete this.scriptLoadedCallbacks[url];
        };
        ScriptLoader2.prototype.loadQueue = function(success, scope, failure) {
          this.loadScripts(this.queue, success, scope, failure);
        };
        ScriptLoader2.prototype.loadScripts = function(scripts, success, scope, failure) {
          var self2 = this;
          var failures = [];
          var execCallbacks = function(name2, url) {
            each$e(self2.scriptLoadedCallbacks[url], function(callback) {
              if (isFunction(callback[name2])) {
                callback[name2].call(callback.scope);
              }
            });
            self2.scriptLoadedCallbacks[url] = void 0;
          };
          self2.queueLoadedCallbacks.push({
            success,
            failure,
            scope: scope || this
          });
          var loadScripts2 = function() {
            var loadingScripts = grep(scripts);
            scripts.length = 0;
            each$e(loadingScripts, function(url) {
              if (self2.states[url] === LOADED) {
                execCallbacks("success", url);
                return;
              }
              if (self2.states[url] === FAILED) {
                execCallbacks("failure", url);
                return;
              }
              if (self2.states[url] !== LOADING) {
                self2.states[url] = LOADING;
                self2.loading++;
                self2.loadScript(url, function() {
                  self2.states[url] = LOADED;
                  self2.loading--;
                  execCallbacks("success", url);
                  loadScripts2();
                }, function() {
                  self2.states[url] = FAILED;
                  self2.loading--;
                  failures.push(url);
                  execCallbacks("failure", url);
                  loadScripts2();
                });
              }
            });
            if (!self2.loading) {
              var notifyCallbacks = self2.queueLoadedCallbacks.slice(0);
              self2.queueLoadedCallbacks.length = 0;
              each$e(notifyCallbacks, function(callback) {
                if (failures.length === 0) {
                  if (isFunction(callback.success)) {
                    callback.success.call(callback.scope);
                  }
                } else {
                  if (isFunction(callback.failure)) {
                    callback.failure.call(callback.scope, failures);
                  }
                }
              });
            }
          };
          loadScripts2();
        };
        ScriptLoader2.ScriptLoader = new ScriptLoader2();
        return ScriptLoader2;
      }();
      var Cell = function(initial) {
        var value2 = initial;
        var get2 = function() {
          return value2;
        };
        var set2 = function(v) {
          value2 = v;
        };
        return {
          get: get2,
          set: set2
        };
      };
      var isRaw = function(str) {
        return isObject(str) && has$2(str, "raw");
      };
      var isTokenised = function(str) {
        return isArray$1(str) && str.length > 1;
      };
      var data = {};
      var currentCode = Cell("en");
      var getLanguageData = function() {
        return get$9(data, currentCode.get());
      };
      var getData = function() {
        return map$2(data, function(value2) {
          return __assign({}, value2);
        });
      };
      var setCode = function(newCode) {
        if (newCode) {
          currentCode.set(newCode);
        }
      };
      var getCode = function() {
        return currentCode.get();
      };
      var add$4 = function(code, items) {
        var langData = data[code];
        if (!langData) {
          data[code] = langData = {};
        }
        each$j(items, function(translation, name2) {
          langData[name2.toLowerCase()] = translation;
        });
      };
      var translate = function(text) {
        var langData = getLanguageData().getOr({});
        var toString = function(obj) {
          if (isFunction(obj)) {
            return Object.prototype.toString.call(obj);
          }
          return !isEmpty2(obj) ? "" + obj : "";
        };
        var isEmpty2 = function(text2) {
          return text2 === "" || text2 === null || text2 === void 0;
        };
        var getLangData = function(text2) {
          var textstr = toString(text2);
          return get$9(langData, textstr.toLowerCase()).map(toString).getOr(textstr);
        };
        var removeContext = function(str) {
          return str.replace(/{context:\w+}$/, "");
        };
        if (isEmpty2(text)) {
          return "";
        }
        if (isRaw(text)) {
          return toString(text.raw);
        }
        if (isTokenised(text)) {
          var values_1 = text.slice(1);
          var substitued = getLangData(text[0]).replace(/\{([0-9]+)\}/g, function($1, $2) {
            return has$2(values_1, $2) ? toString(values_1[$2]) : $1;
          });
          return removeContext(substitued);
        }
        return removeContext(getLangData(text));
      };
      var isRtl$1 = function() {
        return getLanguageData().bind(function(items) {
          return get$9(items, "_dir");
        }).exists(function(dir2) {
          return dir2 === "rtl";
        });
      };
      var hasCode = function(code) {
        return has$2(data, code);
      };
      var I18n = {
        getData,
        setCode,
        getCode,
        add: add$4,
        translate,
        isRtl: isRtl$1,
        hasCode
      };
      var AddOnManager = function() {
        var items = [];
        var urls = {};
        var lookup = {};
        var _listeners = [];
        var runListeners = function(name2, state) {
          var matchedListeners = filter$4(_listeners, function(listener) {
            return listener.name === name2 && listener.state === state;
          });
          each$k(matchedListeners, function(listener) {
            return listener.callback();
          });
        };
        var get2 = function(name2) {
          if (lookup[name2]) {
            return lookup[name2].instance;
          }
          return void 0;
        };
        var dependencies = function(name2) {
          var result;
          if (lookup[name2]) {
            result = lookup[name2].dependencies;
          }
          return result || [];
        };
        var requireLangPack = function(name2, languages) {
          if (AddOnManager.languageLoad !== false) {
            waitFor(name2, function() {
              var language = I18n.getCode();
              var wrappedLanguages = "," + (languages || "") + ",";
              if (!language || languages && wrappedLanguages.indexOf("," + language + ",") === -1) {
                return;
              }
              ScriptLoader.ScriptLoader.add(urls[name2] + "/langs/" + language + ".js");
            }, "loaded");
          }
        };
        var add2 = function(id, addOn, dependencies2) {
          var addOnConstructor = addOn;
          items.push(addOnConstructor);
          lookup[id] = {
            instance: addOnConstructor,
            dependencies: dependencies2
          };
          runListeners(id, "added");
          return addOnConstructor;
        };
        var remove2 = function(name2) {
          delete urls[name2];
          delete lookup[name2];
        };
        var createUrl = function(baseUrl, dep) {
          if (typeof dep === "object") {
            return dep;
          }
          return typeof baseUrl === "string" ? {
            prefix: "",
            resource: dep,
            suffix: ""
          } : {
            prefix: baseUrl.prefix,
            resource: dep,
            suffix: baseUrl.suffix
          };
        };
        var addComponents = function(pluginName, scripts) {
          var pluginUrl = urls[pluginName];
          each$k(scripts, function(script) {
            ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script);
          });
        };
        var loadDependencies = function(name2, addOnUrl, success, scope) {
          var deps = dependencies(name2);
          each$k(deps, function(dep) {
            var newUrl = createUrl(addOnUrl, dep);
            load(newUrl.resource, newUrl, void 0, void 0);
          });
          if (success) {
            if (scope) {
              success.call(scope);
            } else {
              success.call(ScriptLoader);
            }
          }
        };
        var load = function(name2, addOnUrl, success, scope, failure) {
          if (urls[name2]) {
            return;
          }
          var urlString = typeof addOnUrl === "string" ? addOnUrl : addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
          if (urlString.indexOf("/") !== 0 && urlString.indexOf("://") === -1) {
            urlString = AddOnManager.baseURL + "/" + urlString;
          }
          urls[name2] = urlString.substring(0, urlString.lastIndexOf("/"));
          var done2 = function() {
            runListeners(name2, "loaded");
            loadDependencies(name2, addOnUrl, success, scope);
          };
          if (lookup[name2]) {
            done2();
          } else {
            ScriptLoader.ScriptLoader.add(urlString, done2, scope, failure);
          }
        };
        var waitFor = function(name2, callback, state) {
          if (state === void 0) {
            state = "added";
          }
          if (has$2(lookup, name2) && state === "added") {
            callback();
          } else if (has$2(urls, name2) && state === "loaded") {
            callback();
          } else {
            _listeners.push({
              name: name2,
              state,
              callback
            });
          }
        };
        return {
          items,
          urls,
          lookup,
          _listeners,
          get: get2,
          dependencies,
          requireLangPack,
          add: add2,
          remove: remove2,
          createUrl,
          addComponents,
          load,
          waitFor
        };
      };
      AddOnManager.languageLoad = true;
      AddOnManager.baseURL = "";
      AddOnManager.PluginManager = AddOnManager();
      AddOnManager.ThemeManager = AddOnManager();
      var singleton = function(doRevoke) {
        var subject = Cell(Optional.none());
        var revoke = function() {
          return subject.get().each(doRevoke);
        };
        var clear2 = function() {
          revoke();
          subject.set(Optional.none());
        };
        var isSet = function() {
          return subject.get().isSome();
        };
        var get2 = function() {
          return subject.get();
        };
        var set2 = function(s) {
          revoke();
          subject.set(Optional.some(s));
        };
        return {
          clear: clear2,
          isSet,
          get: get2,
          set: set2
        };
      };
      var value = function() {
        var subject = singleton(noop);
        var on2 = function(f) {
          return subject.get().each(f);
        };
        return __assign(__assign({}, subject), { on: on2 });
      };
      var first = function(fn, rate) {
        var timer = null;
        var cancel = function() {
          if (!isNull(timer)) {
            clearTimeout(timer);
            timer = null;
          }
        };
        var throttle = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          if (isNull(timer)) {
            timer = setTimeout(function() {
              timer = null;
              fn.apply(null, args);
            }, rate);
          }
        };
        return {
          cancel,
          throttle
        };
      };
      var last = function(fn, rate) {
        var timer = null;
        var cancel = function() {
          if (!isNull(timer)) {
            clearTimeout(timer);
            timer = null;
          }
        };
        var throttle = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          cancel();
          timer = setTimeout(function() {
            timer = null;
            fn.apply(null, args);
          }, rate);
        };
        return {
          cancel,
          throttle
        };
      };
      var read$4 = function(element, attr) {
        var value2 = get$6(element, attr);
        return value2 === void 0 || value2 === "" ? [] : value2.split(" ");
      };
      var add$3 = function(element, attr, id) {
        var old = read$4(element, attr);
        var nu2 = old.concat([id]);
        set$1(element, attr, nu2.join(" "));
        return true;
      };
      var remove$5 = function(element, attr, id) {
        var nu2 = filter$4(read$4(element, attr), function(v) {
          return v !== id;
        });
        if (nu2.length > 0) {
          set$1(element, attr, nu2.join(" "));
        } else {
          remove$6(element, attr);
        }
        return false;
      };
      var supports = function(element) {
        return element.dom.classList !== void 0;
      };
      var get$4 = function(element) {
        return read$4(element, "class");
      };
      var add$2 = function(element, clazz) {
        return add$3(element, "class", clazz);
      };
      var remove$4 = function(element, clazz) {
        return remove$5(element, "class", clazz);
      };
      var add$1 = function(element, clazz) {
        if (supports(element)) {
          element.dom.classList.add(clazz);
        } else {
          add$2(element, clazz);
        }
      };
      var cleanClass = function(element) {
        var classList = supports(element) ? element.dom.classList : get$4(element);
        if (classList.length === 0) {
          remove$6(element, "class");
        }
      };
      var remove$3 = function(element, clazz) {
        if (supports(element)) {
          var classList = element.dom.classList;
          classList.remove(clazz);
        } else {
          remove$4(element, clazz);
        }
        cleanClass(element);
      };
      var has = function(element, clazz) {
        return supports(element) && element.dom.classList.contains(clazz);
      };
      var descendants$1 = function(scope, predicate) {
        var result = [];
        each$k(children(scope), function(x) {
          if (predicate(x)) {
            result = result.concat([x]);
          }
          result = result.concat(descendants$1(x, predicate));
        });
        return result;
      };
      var descendants = function(scope, selector) {
        return all(selector, scope);
      };
      var annotation = constant("mce-annotation");
      var dataAnnotation = constant("data-mce-annotation");
      var dataAnnotationId = constant("data-mce-annotation-uid");
      var identify = function(editor, annotationName) {
        var rng = editor.selection.getRng();
        var start2 = SugarElement.fromDom(rng.startContainer);
        var root = SugarElement.fromDom(editor.getBody());
        var selector = annotationName.fold(function() {
          return "." + annotation();
        }, function(an) {
          return "[" + dataAnnotation() + '="' + an + '"]';
        });
        var newStart = child$1(start2, rng.startOffset).getOr(start2);
        var closest2 = closest$2(newStart, selector, function(n) {
          return eq(n, root);
        });
        var getAttr = function(c, property) {
          if (has$1(c, property)) {
            return Optional.some(get$6(c, property));
          } else {
            return Optional.none();
          }
        };
        return closest2.bind(function(c) {
          return getAttr(c, "" + dataAnnotationId()).bind(function(uid) {
            return getAttr(c, "" + dataAnnotation()).map(function(name2) {
              var elements = findMarkers(editor, uid);
              return {
                uid,
                name: name2,
                elements
              };
            });
          });
        });
      };
      var isAnnotation = function(elem) {
        return isElement$6(elem) && has(elem, annotation());
      };
      var findMarkers = function(editor, uid) {
        var body = SugarElement.fromDom(editor.getBody());
        return descendants(body, "[" + dataAnnotationId() + '="' + uid + '"]');
      };
      var findAll = function(editor, name2) {
        var body = SugarElement.fromDom(editor.getBody());
        var markers = descendants(body, "[" + dataAnnotation() + '="' + name2 + '"]');
        var directory = {};
        each$k(markers, function(m) {
          var uid = get$6(m, dataAnnotationId());
          var nodesAlready = get$9(directory, uid).getOr([]);
          directory[uid] = nodesAlready.concat([m]);
        });
        return directory;
      };
      var setup$n = function(editor, _registry) {
        var changeCallbacks = Cell({});
        var initData = function() {
          return {
            listeners: [],
            previous: value()
          };
        };
        var withCallbacks = function(name2, f) {
          updateCallbacks(name2, function(data2) {
            f(data2);
            return data2;
          });
        };
        var updateCallbacks = function(name2, f) {
          var callbackMap = changeCallbacks.get();
          var data2 = get$9(callbackMap, name2).getOrThunk(initData);
          var outputData = f(data2);
          callbackMap[name2] = outputData;
          changeCallbacks.set(callbackMap);
        };
        var fireCallbacks = function(name2, uid, elements) {
          withCallbacks(name2, function(data2) {
            each$k(data2.listeners, function(f) {
              return f(true, name2, {
                uid,
                nodes: map$3(elements, function(elem) {
                  return elem.dom;
                })
              });
            });
          });
        };
        var fireNoAnnotation = function(name2) {
          withCallbacks(name2, function(data2) {
            each$k(data2.listeners, function(f) {
              return f(false, name2);
            });
          });
        };
        var onNodeChange = last(function() {
          var callbackMap = changeCallbacks.get();
          var annotations = sort(keys(callbackMap));
          each$k(annotations, function(name2) {
            updateCallbacks(name2, function(data2) {
              var prev = data2.previous.get();
              identify(editor, Optional.some(name2)).fold(function() {
                if (prev.isSome()) {
                  fireNoAnnotation(name2);
                  data2.previous.clear();
                }
              }, function(_a) {
                var uid = _a.uid, name3 = _a.name, elements = _a.elements;
                if (!is$1(prev, uid)) {
                  fireCallbacks(name3, uid, elements);
                  data2.previous.set(uid);
                }
              });
              return {
                previous: data2.previous,
                listeners: data2.listeners
              };
            });
          });
        }, 30);
        editor.on("remove", function() {
          onNodeChange.cancel();
        });
        editor.on("NodeChange", function() {
          onNodeChange.throttle();
        });
        var addListener = function(name2, f) {
          updateCallbacks(name2, function(data2) {
            return {
              previous: data2.previous,
              listeners: data2.listeners.concat([f])
            };
          });
        };
        return { addListener };
      };
      var setup$m = function(editor, registry2) {
        var identifyParserNode = function(span) {
          return Optional.from(span.attr(dataAnnotation())).bind(registry2.lookup);
        };
        editor.on("init", function() {
          editor.serializer.addNodeFilter("span", function(spans) {
            each$k(spans, function(span) {
              identifyParserNode(span).each(function(settings) {
                if (settings.persistent === false) {
                  span.unwrap();
                }
              });
            });
          });
        });
      };
      var create$7 = function() {
        var annotations = {};
        var register2 = function(name2, settings) {
          annotations[name2] = {
            name: name2,
            settings
          };
        };
        var lookup = function(name2) {
          return get$9(annotations, name2).map(function(a) {
            return a.settings;
          });
        };
        return {
          register: register2,
          lookup
        };
      };
      var unique = 0;
      var generate = function(prefix) {
        var date = new Date();
        var time = date.getTime();
        var random = Math.floor(Math.random() * 1e9);
        unique++;
        return prefix + "_" + random + unique + String(time);
      };
      var add = function(element, classes) {
        each$k(classes, function(x) {
          add$1(element, x);
        });
      };
      var fromHtml = function(html, scope) {
        var doc2 = scope || document;
        var div = doc2.createElement("div");
        div.innerHTML = html;
        return children(SugarElement.fromDom(div));
      };
      var fromDom$1 = function(nodes) {
        return map$3(nodes, SugarElement.fromDom);
      };
      var get$3 = function(element) {
        return element.dom.innerHTML;
      };
      var set = function(element, content) {
        var owner2 = owner$1(element);
        var docDom = owner2.dom;
        var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
        var contentElements = fromHtml(content, docDom);
        append(fragment, contentElements);
        empty(element);
        append$1(element, fragment);
      };
      var clone$1 = function(original, isDeep) {
        return SugarElement.fromDom(original.dom.cloneNode(isDeep));
      };
      var shallow = function(original) {
        return clone$1(original, false);
      };
      var deep$1 = function(original) {
        return clone$1(original, true);
      };
      var TextWalker = function(startNode, rootNode, isBoundary) {
        if (isBoundary === void 0) {
          isBoundary = never;
        }
        var walker = new DomTreeWalker(startNode, rootNode);
        var walk2 = function(direction) {
          var next;
          do {
            next = walker[direction]();
          } while (next && !isText$7(next) && !isBoundary(next));
          return Optional.from(next).filter(isText$7);
        };
        return {
          current: function() {
            return Optional.from(walker.current()).filter(isText$7);
          },
          next: function() {
            return walk2("next");
          },
          prev: function() {
            return walk2("prev");
          },
          prev2: function() {
            return walk2("prev2");
          }
        };
      };
      var TextSeeker = function(dom2, isBoundary) {
        var isBlockBoundary = isBoundary ? isBoundary : function(node) {
          return dom2.isBlock(node) || isBr$5(node) || isContentEditableFalse$b(node);
        };
        var walk2 = function(node, offset, walker, process2) {
          if (isText$7(node)) {
            var newOffset = process2(node, offset, node.data);
            if (newOffset !== -1) {
              return Optional.some({
                container: node,
                offset: newOffset
              });
            }
          }
          return walker().bind(function(next) {
            return walk2(next.container, next.offset, walker, process2);
          });
        };
        var backwards = function(node, offset, process2, root) {
          var walker = TextWalker(node, root, isBlockBoundary);
          return walk2(node, offset, function() {
            return walker.prev().map(function(prev) {
              return {
                container: prev,
                offset: prev.length
              };
            });
          }, process2).getOrNull();
        };
        var forwards = function(node, offset, process2, root) {
          var walker = TextWalker(node, root, isBlockBoundary);
          return walk2(node, offset, function() {
            return walker.next().map(function(next) {
              return {
                container: next,
                offset: 0
              };
            });
          }, process2).getOrNull();
        };
        return {
          backwards,
          forwards
        };
      };
      var round$2 = Math.round;
      var clone = function(rect) {
        if (!rect) {
          return {
            left: 0,
            top: 0,
            bottom: 0,
            right: 0,
            width: 0,
            height: 0
          };
        }
        return {
          left: round$2(rect.left),
          top: round$2(rect.top),
          bottom: round$2(rect.bottom),
          right: round$2(rect.right),
          width: round$2(rect.width),
          height: round$2(rect.height)
        };
      };
      var collapse = function(rect, toStart) {
        rect = clone(rect);
        if (toStart) {
          rect.right = rect.left;
        } else {
          rect.left = rect.left + rect.width;
          rect.right = rect.left;
        }
        rect.width = 0;
        return rect;
      };
      var isEqual = function(rect1, rect2) {
        return rect1.left === rect2.left && rect1.top === rect2.top && rect1.bottom === rect2.bottom && rect1.right === rect2.right;
      };
      var isValidOverflow = function(overflowY, rect1, rect2) {
        return overflowY >= 0 && overflowY <= Math.min(rect1.height, rect2.height) / 2;
      };
      var isAbove$1 = function(rect1, rect2) {
        var halfHeight = Math.min(rect2.height / 2, rect1.height / 2);
        if (rect1.bottom - halfHeight < rect2.top) {
          return true;
        }
        if (rect1.top > rect2.bottom) {
          return false;
        }
        return isValidOverflow(rect2.top - rect1.bottom, rect1, rect2);
      };
      var isBelow$1 = function(rect1, rect2) {
        if (rect1.top > rect2.bottom) {
          return true;
        }
        if (rect1.bottom < rect2.top) {
          return false;
        }
        return isValidOverflow(rect2.bottom - rect1.top, rect1, rect2);
      };
      var containsXY = function(rect, clientX, clientY) {
        return clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom;
      };
      var clamp$2 = function(value2, min2, max2) {
        return Math.min(Math.max(value2, min2), max2);
      };
      var getSelectedNode = function(range2) {
        var startContainer = range2.startContainer, startOffset = range2.startOffset;
        if (startContainer.hasChildNodes() && range2.endOffset === startOffset + 1) {
          return startContainer.childNodes[startOffset];
        }
        return null;
      };
      var getNode$1 = function(container, offset) {
        if (isElement$5(container) && container.hasChildNodes()) {
          var childNodes = container.childNodes;
          var safeOffset = clamp$2(offset, 0, childNodes.length - 1);
          return childNodes[safeOffset];
        } else {
          return container;
        }
      };
      var getNodeUnsafe = function(container, offset) {
        if (offset < 0 && isElement$5(container) && container.hasChildNodes()) {
          return void 0;
        } else {
          return getNode$1(container, offset);
        }
      };
      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]");
      var isExtendingChar = function(ch) {
        return typeof ch === "string" && ch.charCodeAt(0) >= 768 && extendingChars.test(ch);
      };
      var or = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return function(x) {
          for (var i = 0; i < args.length; i++) {
            if (args[i](x)) {
              return true;
            }
          }
          return false;
        };
      };
      var and = function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        return function(x) {
          for (var i = 0; i < args.length; i++) {
            if (!args[i](x)) {
              return false;
            }
          }
          return true;
        };
      };
      var isElement$3 = isElement$5;
      var isCaretCandidate$2 = isCaretCandidate$3;
      var isBlock$1 = matchStyleValues("display", "block table");
      var isFloated = matchStyleValues("float", "left right");
      var isValidElementCaretCandidate = and(isElement$3, isCaretCandidate$2, not(isFloated));
      var isNotPre = not(matchStyleValues("white-space", "pre pre-line pre-wrap"));
      var isText$4 = isText$7;
      var isBr$2 = isBr$5;
      var nodeIndex$1 = DOMUtils.nodeIndex;
      var resolveIndex$1 = getNodeUnsafe;
      var createRange$1 = function(doc2) {
        return "createRange" in doc2 ? doc2.createRange() : DOMUtils.DOM.createRng();
      };
      var isWhiteSpace$1 = function(chr) {
        return chr && /[\r\n\t ]/.test(chr);
      };
      var isRange = function(rng) {
        return !!rng.setStart && !!rng.setEnd;
      };
      var isHiddenWhiteSpaceRange = function(range2) {
        var container = range2.startContainer;
        var offset = range2.startOffset;
        if (isWhiteSpace$1(range2.toString()) && isNotPre(container.parentNode) && isText$7(container)) {
          var text = container.data;
          if (isWhiteSpace$1(text[offset - 1]) || isWhiteSpace$1(text[offset + 1])) {
            return true;
          }
        }
        return false;
      };
      var getBrClientRect = function(brNode) {
        var doc2 = brNode.ownerDocument;
        var rng = createRange$1(doc2);
        var nbsp$1 = doc2.createTextNode(nbsp);
        var parentNode = brNode.parentNode;
        parentNode.insertBefore(nbsp$1, brNode);
        rng.setStart(nbsp$1, 0);
        rng.setEnd(nbsp$1, 1);
        var clientRect = clone(rng.getBoundingClientRect());
        parentNode.removeChild(nbsp$1);
        return clientRect;
      };
      var getBoundingClientRectWebKitText = function(rng) {
        var sc = rng.startContainer;
        var ec = rng.endContainer;
        var so = rng.startOffset;
        var eo = rng.endOffset;
        if (sc === ec && isText$7(ec) && so === 0 && eo === 1) {
          var newRng = rng.cloneRange();
          newRng.setEndAfter(ec);
          return getBoundingClientRect$1(newRng);
        } else {
          return null;
        }
      };
      var isZeroRect = function(r2) {
        return r2.left === 0 && r2.right === 0 && r2.top === 0 && r2.bottom === 0;
      };
      var getBoundingClientRect$1 = function(item) {
        var clientRect;
        var clientRects = item.getClientRects();
        if (clientRects.length > 0) {
          clientRect = clone(clientRects[0]);
        } else {
          clientRect = clone(item.getBoundingClientRect());
        }
        if (!isRange(item) && isBr$2(item) && isZeroRect(clientRect)) {
          return getBrClientRect(item);
        }
        if (isZeroRect(clientRect) && isRange(item)) {
          return getBoundingClientRectWebKitText(item);
        }
        return clientRect;
      };
      var collapseAndInflateWidth = function(clientRect, toStart) {
        var newClientRect = collapse(clientRect, toStart);
        newClientRect.width = 1;
        newClientRect.right = newClientRect.left + 1;
        return newClientRect;
      };
      var getCaretPositionClientRects = function(caretPosition) {
        var clientRects = [];
        var addUniqueAndValidRect = function(clientRect) {
          if (clientRect.height === 0) {
            return;
          }
          if (clientRects.length > 0) {
            if (isEqual(clientRect, clientRects[clientRects.length - 1])) {
              return;
            }
          }
          clientRects.push(clientRect);
        };
        var addCharacterOffset = function(container2, offset2) {
          var range2 = createRange$1(container2.ownerDocument);
          if (offset2 < container2.data.length) {
            if (isExtendingChar(container2.data[offset2])) {
              return clientRects;
            }
            if (isExtendingChar(container2.data[offset2 - 1])) {
              range2.setStart(container2, offset2);
              range2.setEnd(container2, offset2 + 1);
              if (!isHiddenWhiteSpaceRange(range2)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), false));
                return clientRects;
              }
            }
          }
          if (offset2 > 0) {
            range2.setStart(container2, offset2 - 1);
            range2.setEnd(container2, offset2);
            if (!isHiddenWhiteSpaceRange(range2)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), false));
            }
          }
          if (offset2 < container2.data.length) {
            range2.setStart(container2, offset2);
            range2.setEnd(container2, offset2 + 1);
            if (!isHiddenWhiteSpaceRange(range2)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(range2), true));
            }
          }
        };
        var container = caretPosition.container();
        var offset = caretPosition.offset();
        if (isText$4(container)) {
          addCharacterOffset(container, offset);
          return clientRects;
        }
        if (isElement$3(container)) {
          if (caretPosition.isAtEnd()) {
            var node = resolveIndex$1(container, offset);
            if (isText$4(node)) {
              addCharacterOffset(node, node.data.length);
            }
            if (isValidElementCaretCandidate(node) && !isBr$2(node)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
            }
          } else {
            var node = resolveIndex$1(container, offset);
            if (isText$4(node)) {
              addCharacterOffset(node, 0);
            }
            if (isValidElementCaretCandidate(node) && caretPosition.isAtEnd()) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), false));
              return clientRects;
            }
            var beforeNode = resolveIndex$1(caretPosition.container(), caretPosition.offset() - 1);
            if (isValidElementCaretCandidate(beforeNode) && !isBr$2(beforeNode)) {
              if (isBlock$1(beforeNode) || isBlock$1(node) || !isValidElementCaretCandidate(node)) {
                addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(beforeNode), false));
              }
            }
            if (isValidElementCaretCandidate(node)) {
              addUniqueAndValidRect(collapseAndInflateWidth(getBoundingClientRect$1(node), true));
            }
          }
        }
        return clientRects;
      };
      var CaretPosition = function(container, offset, clientRects) {
        var isAtStart = function() {
          if (isText$4(container)) {
            return offset === 0;
          }
          return offset === 0;
        };
        var isAtEnd = function() {
          if (isText$4(container)) {
            return offset >= container.data.length;
          }
          return offset >= container.childNodes.length;
        };
        var toRange = function() {
          var range2 = createRange$1(container.ownerDocument);
          range2.setStart(container, offset);
          range2.setEnd(container, offset);
          return range2;
        };
        var getClientRects2 = function() {
          if (!clientRects) {
            clientRects = getCaretPositionClientRects(CaretPosition(container, offset));
          }
          return clientRects;
        };
        var isVisible = function() {
          return getClientRects2().length > 0;
        };
        var isEqual2 = function(caretPosition) {
          return caretPosition && container === caretPosition.container() && offset === caretPosition.offset();
        };
        var getNode2 = function(before2) {
          return resolveIndex$1(container, before2 ? offset - 1 : offset);
        };
        return {
          container: constant(container),
          offset: constant(offset),
          toRange,
          getClientRects: getClientRects2,
          isVisible,
          isAtStart,
          isAtEnd,
          isEqual: isEqual2,
          getNode: getNode2
        };
      };
      CaretPosition.fromRangeStart = function(range2) {
        return CaretPosition(range2.startContainer, range2.startOffset);
      };
      CaretPosition.fromRangeEnd = function(range2) {
        return CaretPosition(range2.endContainer, range2.endOffset);
      };
      CaretPosition.after = function(node) {
        return CaretPosition(node.parentNode, nodeIndex$1(node) + 1);
      };
      CaretPosition.before = function(node) {
        return CaretPosition(node.parentNode, nodeIndex$1(node));
      };
      CaretPosition.isAbove = function(pos1, pos2) {
        return lift2(head(pos2.getClientRects()), last$2(pos1.getClientRects()), isAbove$1).getOr(false);
      };
      CaretPosition.isBelow = function(pos1, pos2) {
        return lift2(last$2(pos2.getClientRects()), head(pos1.getClientRects()), isBelow$1).getOr(false);
      };
      CaretPosition.isAtStart = function(pos) {
        return pos ? pos.isAtStart() : false;
      };
      CaretPosition.isAtEnd = function(pos) {
        return pos ? pos.isAtEnd() : false;
      };
      CaretPosition.isTextPosition = function(pos) {
        return pos ? isText$7(pos.container()) : false;
      };
      CaretPosition.isElementPosition = function(pos) {
        return CaretPosition.isTextPosition(pos) === false;
      };
      var trimEmptyTextNode$1 = function(dom2, node) {
        if (isText$7(node) && node.data.length === 0) {
          dom2.remove(node);
        }
      };
      var insertNode = function(dom2, rng, node) {
        rng.insertNode(node);
        trimEmptyTextNode$1(dom2, node.previousSibling);
        trimEmptyTextNode$1(dom2, node.nextSibling);
      };
      var insertFragment = function(dom2, rng, frag) {
        var firstChild2 = Optional.from(frag.firstChild);
        var lastChild2 = Optional.from(frag.lastChild);
        rng.insertNode(frag);
        firstChild2.each(function(child2) {
          return trimEmptyTextNode$1(dom2, child2.previousSibling);
        });
        lastChild2.each(function(child2) {
          return trimEmptyTextNode$1(dom2, child2.nextSibling);
        });
      };
      var rangeInsertNode = function(dom2, rng, node) {
        if (isDocumentFragment(node)) {
          insertFragment(dom2, rng, node);
        } else {
          insertNode(dom2, rng, node);
        }
      };
      var isText$3 = isText$7;
      var isBogus = isBogus$2;
      var nodeIndex = DOMUtils.nodeIndex;
      var normalizedParent = function(node) {
        var parentNode = node.parentNode;
        if (isBogus(parentNode)) {
          return normalizedParent(parentNode);
        }
        return parentNode;
      };
      var getChildNodes = function(node) {
        if (!node) {
          return [];
        }
        return reduce(node.childNodes, function(result, node2) {
          if (isBogus(node2) && node2.nodeName !== "BR") {
            result = result.concat(getChildNodes(node2));
          } else {
            result.push(node2);
          }
          return result;
        }, []);
      };
      var normalizedTextOffset = function(node, offset) {
        while (node = node.previousSibling) {
          if (!isText$3(node)) {
            break;
          }
          offset += node.data.length;
        }
        return offset;
      };
      var equal = function(a) {
        return function(b) {
          return a === b;
        };
      };
      var normalizedNodeIndex = function(node) {
        var nodes, index;
        nodes = getChildNodes(normalizedParent(node));
        index = findIndex$1(nodes, equal(node), node);
        nodes = nodes.slice(0, index + 1);
        var numTextFragments = reduce(nodes, function(result, node2, i) {
          if (isText$3(node2) && isText$3(nodes[i - 1])) {
            result++;
          }
          return result;
        }, 0);
        nodes = filter$2(nodes, matchNodeNames([node.nodeName]));
        index = findIndex$1(nodes, equal(node), node);
        return index - numTextFragments;
      };
      var createPathItem = function(node) {
        var name2;
        if (isText$3(node)) {
          name2 = "text()";
        } else {
          name2 = node.nodeName.toLowerCase();
        }
        return name2 + "[" + normalizedNodeIndex(node) + "]";
      };
      var parentsUntil$1 = function(root, node, predicate) {
        var parents2 = [];
        for (node = node.parentNode; node !== root; node = node.parentNode) {
          if (predicate && predicate(node)) {
            break;
          }
          parents2.push(node);
        }
        return parents2;
      };
      var create$6 = function(root, caretPosition) {
        var container, offset, path = [], outputOffset, childNodes, parents2;
        container = caretPosition.container();
        offset = caretPosition.offset();
        if (isText$3(container)) {
          outputOffset = normalizedTextOffset(container, offset);
        } else {
          childNodes = container.childNodes;
          if (offset >= childNodes.length) {
            outputOffset = "after";
            offset = childNodes.length - 1;
          } else {
            outputOffset = "before";
          }
          container = childNodes[offset];
        }
        path.push(createPathItem(container));
        parents2 = parentsUntil$1(root, container);
        parents2 = filter$2(parents2, not(isBogus$2));
        path = path.concat(map$1(parents2, function(node) {
          return createPathItem(node);
        }));
        return path.reverse().join("/") + "," + outputOffset;
      };
      var resolvePathItem = function(node, name2, index) {
        var nodes = getChildNodes(node);
        nodes = filter$2(nodes, function(node2, index2) {
          return !isText$3(node2) || !isText$3(nodes[index2 - 1]);
        });
        nodes = filter$2(nodes, matchNodeNames([name2]));
        return nodes[index];
      };
      var findTextPosition = function(container, offset) {
        var node = container, targetOffset = 0, dataLen;
        while (isText$3(node)) {
          dataLen = node.data.length;
          if (offset >= targetOffset && offset <= targetOffset + dataLen) {
            container = node;
            offset = offset - targetOffset;
            break;
          }
          if (!isText$3(node.nextSibling)) {
            container = node;
            offset = dataLen;
            break;
          }
          targetOffset += dataLen;
          node = node.nextSibling;
        }
        if (isText$3(container) && offset > container.data.length) {
          offset = container.data.length;
        }
        return CaretPosition(container, offset);
      };
      var resolve$2 = function(root, path) {
        var offset;
        if (!path) {
          return null;
        }
        var parts = path.split(",");
        var paths = parts[0].split("/");
        offset = parts.length > 1 ? parts[1] : "before";
        var container = reduce(paths, function(result, value2) {
          var match2 = /([\w\-\(\)]+)\[([0-9]+)\]/.exec(value2);
          if (!match2) {
            return null;
          }
          if (match2[1] === "text()") {
            match2[1] = "#text";
          }
          return resolvePathItem(result, match2[1], parseInt(match2[2], 10));
        }, root);
        if (!container) {
          return null;
        }
        if (!isText$3(container)) {
          if (offset === "after") {
            offset = nodeIndex(container) + 1;
          } else {
            offset = nodeIndex(container);
          }
          return CaretPosition(container.parentNode, offset);
        }
        return findTextPosition(container, parseInt(offset, 10));
      };
      var isContentEditableFalse$9 = isContentEditableFalse$b;
      var getNormalizedTextOffset = function(trim2, container, offset) {
        var node, trimmedOffset;
        trimmedOffset = trim2(container.data.slice(0, offset)).length;
        for (node = container.previousSibling; node && isText$7(node); node = node.previousSibling) {
          trimmedOffset += trim2(node.data).length;
        }
        return trimmedOffset;
      };
      var getPoint = function(dom2, trim2, normalized, rng, start2) {
        var container = rng[start2 ? "startContainer" : "endContainer"];
        var offset = rng[start2 ? "startOffset" : "endOffset"];
        var point = [];
        var childNodes, after2 = 0;
        var root = dom2.getRoot();
        if (isText$7(container)) {
          point.push(normalized ? getNormalizedTextOffset(trim2, container, offset) : offset);
        } else {
          childNodes = container.childNodes;
          if (offset >= childNodes.length && childNodes.length) {
            after2 = 1;
            offset = Math.max(0, childNodes.length - 1);
          }
          point.push(dom2.nodeIndex(childNodes[offset], normalized) + after2);
        }
        for (; container && container !== root; container = container.parentNode) {
          point.push(dom2.nodeIndex(container, normalized));
        }
        return point;
      };
      var getLocation = function(trim2, selection, normalized, rng) {
        var dom2 = selection.dom, bookmark = {};
        bookmark.start = getPoint(dom2, trim2, normalized, rng, true);
        if (!selection.isCollapsed()) {
          bookmark.end = getPoint(dom2, trim2, normalized, rng, false);
        }
        if (isRangeInCaretContainerBlock(rng)) {
          bookmark.isFakeCaret = true;
        }
        return bookmark;
      };
      var findIndex = function(dom2, name2, element) {
        var count2 = 0;
        Tools.each(dom2.select(name2), function(node) {
          if (node.getAttribute("data-mce-bogus") === "all") {
            return;
          }
          if (node === element) {
            return false;
          }
          count2++;
        });
        return count2;
      };
      var moveEndPoint$1 = function(rng, start2) {
        var container, offset, childNodes;
        var prefix = start2 ? "start" : "end";
        container = rng[prefix + "Container"];
        offset = rng[prefix + "Offset"];
        if (isElement$5(container) && container.nodeName === "TR") {
          childNodes = container.childNodes;
          container = childNodes[Math.min(start2 ? offset : offset - 1, childNodes.length - 1)];
          if (container) {
            offset = start2 ? 0 : container.childNodes.length;
            rng["set" + (start2 ? "Start" : "End")](container, offset);
          }
        }
      };
      var normalizeTableCellSelection = function(rng) {
        moveEndPoint$1(rng, true);
        moveEndPoint$1(rng, false);
        return rng;
      };
      var findSibling = function(node, offset) {
        var sibling2;
        if (isElement$5(node)) {
          node = getNode$1(node, offset);
          if (isContentEditableFalse$9(node)) {
            return node;
          }
        }
        if (isCaretContainer$2(node)) {
          if (isText$7(node) && isCaretContainerBlock$1(node)) {
            node = node.parentNode;
          }
          sibling2 = node.previousSibling;
          if (isContentEditableFalse$9(sibling2)) {
            return sibling2;
          }
          sibling2 = node.nextSibling;
          if (isContentEditableFalse$9(sibling2)) {
            return sibling2;
          }
        }
      };
      var findAdjacentContentEditableFalseElm = function(rng) {
        return findSibling(rng.startContainer, rng.startOffset) || findSibling(rng.endContainer, rng.endOffset);
      };
      var getOffsetBookmark = function(trim2, normalized, selection) {
        var element = selection.getNode();
        var name2 = element ? element.nodeName : null;
        var rng = selection.getRng();
        if (isContentEditableFalse$9(element) || name2 === "IMG") {
          return {
            name: name2,
            index: findIndex(selection.dom, name2, element)
          };
        }
        var sibling2 = findAdjacentContentEditableFalseElm(rng);
        if (sibling2) {
          name2 = sibling2.tagName;
          return {
            name: name2,
            index: findIndex(selection.dom, name2, sibling2)
          };
        }
        return getLocation(trim2, selection, normalized, rng);
      };
      var getCaretBookmark = function(selection) {
        var rng = selection.getRng();
        return {
          start: create$6(selection.dom.getRoot(), CaretPosition.fromRangeStart(rng)),
          end: create$6(selection.dom.getRoot(), CaretPosition.fromRangeEnd(rng))
        };
      };
      var getRangeBookmark = function(selection) {
        return { rng: selection.getRng() };
      };
      var createBookmarkSpan = function(dom2, id, filled) {
        var args = {
          "data-mce-type": "bookmark",
          id,
          "style": "overflow:hidden;line-height:0px"
        };
        return filled ? dom2.create("span", args, "&#xFEFF;") : dom2.create("span", args);
      };
      var getPersistentBookmark = function(selection, filled) {
        var dom2 = selection.dom;
        var rng = selection.getRng();
        var id = dom2.uniqueId();
        var collapsed = selection.isCollapsed();
        var element = selection.getNode();
        var name2 = element.nodeName;
        if (name2 === "IMG") {
          return {
            name: name2,
            index: findIndex(dom2, name2, element)
          };
        }
        var rng2 = normalizeTableCellSelection(rng.cloneRange());
        if (!collapsed) {
          rng2.collapse(false);
          var endBookmarkNode = createBookmarkSpan(dom2, id + "_end", filled);
          rangeInsertNode(dom2, rng2, endBookmarkNode);
        }
        rng = normalizeTableCellSelection(rng);
        rng.collapse(true);
        var startBookmarkNode = createBookmarkSpan(dom2, id + "_start", filled);
        rangeInsertNode(dom2, rng, startBookmarkNode);
        selection.moveToBookmark({
          id,
          keep: true
        });
        return { id };
      };
      var getBookmark$2 = function(selection, type2, normalized) {
        if (type2 === 2) {
          return getOffsetBookmark(trim$2, normalized, selection);
        } else if (type2 === 3) {
          return getCaretBookmark(selection);
        } else if (type2) {
          return getRangeBookmark(selection);
        } else {
          return getPersistentBookmark(selection, false);
        }
      };
      var getUndoBookmark = curry(getOffsetBookmark, identity, true);
      var DOM$9 = DOMUtils.DOM;
      var defaultPreviewStyles = "font-family font-size font-weight font-style text-decoration text-transform color background-color border border-radius outline text-shadow";
      var getBodySetting = function(editor, name2, defaultValue) {
        var value2 = editor.getParam(name2, defaultValue);
        if (value2.indexOf("=") !== -1) {
          var bodyObj = editor.getParam(name2, "", "hash");
          return get$9(bodyObj, editor.id).getOr(defaultValue);
        } else {
          return value2;
        }
      };
      var getIframeAttrs = function(editor) {
        return editor.getParam("iframe_attrs", {});
      };
      var getDocType = function(editor) {
        return editor.getParam("doctype", "<!DOCTYPE html>");
      };
      var getDocumentBaseUrl = function(editor) {
        return editor.getParam("document_base_url", "");
      };
      var getBodyId = function(editor) {
        return getBodySetting(editor, "body_id", "tinymce");
      };
      var getBodyClass = function(editor) {
        return getBodySetting(editor, "body_class", "");
      };
      var getContentSecurityPolicy = function(editor) {
        return editor.getParam("content_security_policy", "");
      };
      var shouldPutBrInPre$1 = function(editor) {
        return editor.getParam("br_in_pre", true);
      };
      var getForcedRootBlock = function(editor) {
        if (editor.getParam("force_p_newlines", false)) {
          return "p";
        }
        var block = editor.getParam("forced_root_block", "p");
        if (block === false) {
          return "";
        } else if (block === true) {
          return "p";
        } else {
          return block;
        }
      };
      var getForcedRootBlockAttrs = function(editor) {
        return editor.getParam("forced_root_block_attrs", {});
      };
      var getBrNewLineSelector = function(editor) {
        return editor.getParam("br_newline_selector", ".mce-toc h2,figcaption,caption");
      };
      var getNoNewLineSelector = function(editor) {
        return editor.getParam("no_newline_selector", "");
      };
      var shouldKeepStyles = function(editor) {
        return editor.getParam("keep_styles", true);
      };
      var shouldEndContainerOnEmptyBlock = function(editor) {
        return editor.getParam("end_container_on_empty_block", false);
      };
      var getFontStyleValues = function(editor) {
        return Tools.explode(editor.getParam("font_size_style_values", "xx-small,x-small,small,medium,large,x-large,xx-large"));
      };
      var getFontSizeClasses = function(editor) {
        return Tools.explode(editor.getParam("font_size_classes", ""));
      };
      var getImagesDataImgFilter = function(editor) {
        return editor.getParam("images_dataimg_filter", always, "function");
      };
      var isAutomaticUploadsEnabled = function(editor) {
        return editor.getParam("automatic_uploads", true, "boolean");
      };
      var shouldReuseFileName = function(editor) {
        return editor.getParam("images_reuse_filename", false, "boolean");
      };
      var shouldReplaceBlobUris = function(editor) {
        return editor.getParam("images_replace_blob_uris", true, "boolean");
      };
      var getIconPackName = function(editor) {
        return editor.getParam("icons", "", "string");
      };
      var getIconsUrl = function(editor) {
        return editor.getParam("icons_url", "", "string");
      };
      var getImageUploadUrl = function(editor) {
        return editor.getParam("images_upload_url", "", "string");
      };
      var getImageUploadBasePath = function(editor) {
        return editor.getParam("images_upload_base_path", "", "string");
      };
      var getImagesUploadCredentials = function(editor) {
        return editor.getParam("images_upload_credentials", false, "boolean");
      };
      var getImagesUploadHandler = function(editor) {
        return editor.getParam("images_upload_handler", null, "function");
      };
      var shouldUseContentCssCors = function(editor) {
        return editor.getParam("content_css_cors", false, "boolean");
      };
      var getReferrerPolicy = function(editor) {
        return editor.getParam("referrer_policy", "", "string");
      };
      var getLanguageCode = function(editor) {
        return editor.getParam("language", "en", "string");
      };
      var getLanguageUrl = function(editor) {
        return editor.getParam("language_url", "", "string");
      };
      var shouldIndentUseMargin = function(editor) {
        return editor.getParam("indent_use_margin", false);
      };
      var getIndentation = function(editor) {
        return editor.getParam("indentation", "40px", "string");
      };
      var getContentCss = function(editor) {
        var contentCss = editor.getParam("content_css");
        if (isString$1(contentCss)) {
          return map$3(contentCss.split(","), trim$4);
        } else if (isArray$1(contentCss)) {
          return contentCss;
        } else if (contentCss === false || editor.inline) {
          return [];
        } else {
          return ["default"];
        }
      };
      var getFontCss = function(editor) {
        var fontCss = editor.getParam("font_css", []);
        return isArray$1(fontCss) ? fontCss : map$3(fontCss.split(","), trim$4);
      };
      var getDirectionality = function(editor) {
        return editor.getParam("directionality", I18n.isRtl() ? "rtl" : void 0);
      };
      var getInlineBoundarySelector = function(editor) {
        return editor.getParam("inline_boundaries_selector", "a[href],code,.mce-annotation", "string");
      };
      var getObjectResizing = function(editor) {
        var selector = editor.getParam("object_resizing");
        if (selector === false || Env.iOS) {
          return false;
        } else {
          return isString$1(selector) ? selector : "table,img,figure.image,div,video,iframe";
        }
      };
      var getResizeImgProportional = function(editor) {
        return editor.getParam("resize_img_proportional", true, "boolean");
      };
      var getPlaceholder = function(editor) {
        return editor.getParam("placeholder", DOM$9.getAttrib(editor.getElement(), "placeholder"), "string");
      };
      var getEventRoot = function(editor) {
        return editor.getParam("event_root");
      };
      var getServiceMessage = function(editor) {
        return editor.getParam("service_message");
      };
      var getTheme = function(editor) {
        return editor.getParam("theme");
      };
      var shouldValidate = function(editor) {
        return editor.getParam("validate");
      };
      var isInlineBoundariesEnabled = function(editor) {
        return editor.getParam("inline_boundaries") !== false;
      };
      var getFormats = function(editor) {
        return editor.getParam("formats");
      };
      var getPreviewStyles = function(editor) {
        var style = editor.getParam("preview_styles", defaultPreviewStyles);
        if (isString$1(style)) {
          return style;
        } else {
          return "";
        }
      };
      var canFormatEmptyLines = function(editor) {
        return editor.getParam("format_empty_lines", false, "boolean");
      };
      var getCustomUiSelector = function(editor) {
        return editor.getParam("custom_ui_selector", "", "string");
      };
      var getThemeUrl = function(editor) {
        return editor.getParam("theme_url");
      };
      var isInline = function(editor) {
        return editor.getParam("inline");
      };
      var hasHiddenInput = function(editor) {
        return editor.getParam("hidden_input");
      };
      var shouldPatchSubmit = function(editor) {
        return editor.getParam("submit_patch");
      };
      var isEncodingXml = function(editor) {
        return editor.getParam("encoding") === "xml";
      };
      var shouldAddFormSubmitTrigger = function(editor) {
        return editor.getParam("add_form_submit_trigger");
      };
      var shouldAddUnloadTrigger = function(editor) {
        return editor.getParam("add_unload_trigger");
      };
      var hasForcedRootBlock = function(editor) {
        return getForcedRootBlock(editor) !== "";
      };
      var getCustomUndoRedoLevels = function(editor) {
        return editor.getParam("custom_undo_redo_levels", 0, "number");
      };
      var shouldDisableNodeChange = function(editor) {
        return editor.getParam("disable_nodechange");
      };
      var isReadOnly$1 = function(editor) {
        return editor.getParam("readonly");
      };
      var hasContentCssCors = function(editor) {
        return editor.getParam("content_css_cors");
      };
      var getPlugins = function(editor) {
        return editor.getParam("plugins", "", "string");
      };
      var getExternalPlugins$1 = function(editor) {
        return editor.getParam("external_plugins");
      };
      var shouldBlockUnsupportedDrop = function(editor) {
        return editor.getParam("block_unsupported_drop", true, "boolean");
      };
      var isVisualAidsEnabled = function(editor) {
        return editor.getParam("visual", true, "boolean");
      };
      var getVisualAidsTableClass = function(editor) {
        return editor.getParam("visual_table_class", "mce-item-table", "string");
      };
      var getVisualAidsAnchorClass = function(editor) {
        return editor.getParam("visual_anchor_class", "mce-item-anchor", "string");
      };
      var getIframeAriaText = function(editor) {
        return editor.getParam("iframe_aria_text", "Rich Text Area. Press ALT-0 for help.", "string");
      };
      var isElement$2 = isElement$5;
      var isText$2 = isText$7;
      var removeNode$1 = function(node) {
        var parentNode = node.parentNode;
        if (parentNode) {
          parentNode.removeChild(node);
        }
      };
      var trimCount = function(text) {
        var trimmedText = trim$2(text);
        return {
          count: text.length - trimmedText.length,
          text: trimmedText
        };
      };
      var deleteZwspChars = function(caretContainer) {
        var idx;
        while ((idx = caretContainer.data.lastIndexOf(ZWSP$1)) !== -1) {
          caretContainer.deleteData(idx, 1);
        }
      };
      var removeUnchanged = function(caretContainer, pos) {
        remove$2(caretContainer);
        return pos;
      };
      var removeTextAndReposition = function(caretContainer, pos) {
        var before2 = trimCount(caretContainer.data.substr(0, pos.offset()));
        var after2 = trimCount(caretContainer.data.substr(pos.offset()));
        var text = before2.text + after2.text;
        if (text.length > 0) {
          deleteZwspChars(caretContainer);
          return CaretPosition(caretContainer, pos.offset() - before2.count);
        } else {
          return pos;
        }
      };
      var removeElementAndReposition = function(caretContainer, pos) {
        var parentNode = pos.container();
        var newPosition = indexOf$2(from(parentNode.childNodes), caretContainer).map(function(index) {
          return index < pos.offset() ? CaretPosition(parentNode, pos.offset() - 1) : pos;
        }).getOr(pos);
        remove$2(caretContainer);
        return newPosition;
      };
      var removeTextCaretContainer = function(caretContainer, pos) {
        return isText$2(caretContainer) && pos.container() === caretContainer ? removeTextAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
      };
      var removeElementCaretContainer = function(caretContainer, pos) {
        return pos.container() === caretContainer.parentNode ? removeElementAndReposition(caretContainer, pos) : removeUnchanged(caretContainer, pos);
      };
      var removeAndReposition = function(container, pos) {
        return CaretPosition.isTextPosition(pos) ? removeTextCaretContainer(container, pos) : removeElementCaretContainer(container, pos);
      };
      var remove$2 = function(caretContainerNode) {
        if (isElement$2(caretContainerNode) && isCaretContainer$2(caretContainerNode)) {
          if (hasContent(caretContainerNode)) {
            caretContainerNode.removeAttribute("data-mce-caret");
          } else {
            removeNode$1(caretContainerNode);
          }
        }
        if (isText$2(caretContainerNode)) {
          deleteZwspChars(caretContainerNode);
          if (caretContainerNode.data.length === 0) {
            removeNode$1(caretContainerNode);
          }
        }
      };
      var browser$2 = detect().browser;
      var isContentEditableFalse$8 = isContentEditableFalse$b;
      var isMedia$1 = isMedia$2;
      var isTableCell$3 = isTableCell$5;
      var inlineFakeCaretSelector = "*[contentEditable=false],video,audio,embed,object";
      var getAbsoluteClientRect = function(root, element, before2) {
        var clientRect = collapse(element.getBoundingClientRect(), before2);
        var scrollX;
        var scrollY;
        if (root.tagName === "BODY") {
          var docElm = root.ownerDocument.documentElement;
          scrollX = root.scrollLeft || docElm.scrollLeft;
          scrollY = root.scrollTop || docElm.scrollTop;
        } else {
          var rootRect = root.getBoundingClientRect();
          scrollX = root.scrollLeft - rootRect.left;
          scrollY = root.scrollTop - rootRect.top;
        }
        clientRect.left += scrollX;
        clientRect.right += scrollX;
        clientRect.top += scrollY;
        clientRect.bottom += scrollY;
        clientRect.width = 1;
        var margin = element.offsetWidth - element.clientWidth;
        if (margin > 0) {
          if (before2) {
            margin *= -1;
          }
          clientRect.left += margin;
          clientRect.right += margin;
        }
        return clientRect;
      };
      var trimInlineCaretContainers = function(root) {
        var fakeCaretTargetNodes = descendants(SugarElement.fromDom(root), inlineFakeCaretSelector);
        for (var i = 0; i < fakeCaretTargetNodes.length; i++) {
          var node = fakeCaretTargetNodes[i].dom;
          var sibling2 = node.previousSibling;
          if (endsWithCaretContainer$1(sibling2)) {
            var data2 = sibling2.data;
            if (data2.length === 1) {
              sibling2.parentNode.removeChild(sibling2);
            } else {
              sibling2.deleteData(data2.length - 1, 1);
            }
          }
          sibling2 = node.nextSibling;
          if (startsWithCaretContainer$1(sibling2)) {
            var data2 = sibling2.data;
            if (data2.length === 1) {
              sibling2.parentNode.removeChild(sibling2);
            } else {
              sibling2.deleteData(0, 1);
            }
          }
        }
      };
      var FakeCaret = function(editor, root, isBlock2, hasFocus2) {
        var lastVisualCaret = value();
        var cursorInterval;
        var caretContainerNode;
        var rootBlock = getForcedRootBlock(editor);
        var caretBlock = rootBlock.length > 0 ? rootBlock : "p";
        var show = function(before2, element) {
          var rng;
          hide();
          if (isTableCell$3(element)) {
            return null;
          }
          if (isBlock2(element)) {
            caretContainerNode = insertBlock$1(caretBlock, element, before2);
            var clientRect = getAbsoluteClientRect(root, element, before2);
            DomQuery(caretContainerNode).css("top", clientRect.top);
            var caret = DomQuery('<div class="mce-visual-caret" data-mce-bogus="all"></div>').css(__assign({}, clientRect)).appendTo(root)[0];
            lastVisualCaret.set({
              caret,
              element,
              before: before2
            });
            if (before2) {
              DomQuery(caret).addClass("mce-visual-caret-before");
            }
            startBlink();
            rng = element.ownerDocument.createRange();
            rng.setStart(caretContainerNode, 0);
            rng.setEnd(caretContainerNode, 0);
          } else {
            caretContainerNode = insertInline$1(element, before2);
            rng = element.ownerDocument.createRange();
            if (isInlineFakeCaretTarget(caretContainerNode.nextSibling)) {
              rng.setStart(caretContainerNode, 0);
              rng.setEnd(caretContainerNode, 0);
            } else {
              rng.setStart(caretContainerNode, 1);
              rng.setEnd(caretContainerNode, 1);
            }
            return rng;
          }
          return rng;
        };
        var hide = function() {
          trimInlineCaretContainers(root);
          if (caretContainerNode) {
            remove$2(caretContainerNode);
            caretContainerNode = null;
          }
          lastVisualCaret.on(function(caretState) {
            DomQuery(caretState.caret).remove();
            lastVisualCaret.clear();
          });
          if (cursorInterval) {
            Delay.clearInterval(cursorInterval);
            cursorInterval = void 0;
          }
        };
        var startBlink = function() {
          cursorInterval = Delay.setInterval(function() {
            if (hasFocus2()) {
              DomQuery("div.mce-visual-caret", root).toggleClass("mce-visual-caret-hidden");
            } else {
              DomQuery("div.mce-visual-caret", root).addClass("mce-visual-caret-hidden");
            }
          }, 500);
        };
        var reposition2 = function() {
          lastVisualCaret.on(function(caretState) {
            var clientRect = getAbsoluteClientRect(root, caretState.element, caretState.before);
            DomQuery(caretState.caret).css(__assign({}, clientRect));
          });
        };
        var destroy2 = function() {
          return Delay.clearInterval(cursorInterval);
        };
        var getCss = function() {
          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;}";
        };
        return {
          show,
          hide,
          getCss,
          reposition: reposition2,
          destroy: destroy2
        };
      };
      var isFakeCaretTableBrowser = function() {
        return browser$2.isIE() || browser$2.isEdge() || browser$2.isFirefox();
      };
      var isInlineFakeCaretTarget = function(node) {
        return isContentEditableFalse$8(node) || isMedia$1(node);
      };
      var isFakeCaretTarget = function(node) {
        return isInlineFakeCaretTarget(node) || isTable$3(node) && isFakeCaretTableBrowser();
      };
      var isContentEditableFalse$7 = isContentEditableFalse$b;
      var isMedia = isMedia$2;
      var isBlockLike = matchStyleValues("display", "block table table-cell table-caption list-item");
      var isCaretContainer = isCaretContainer$2;
      var isCaretContainerBlock = isCaretContainerBlock$1;
      var isElement$1 = isElement$5;
      var isCaretCandidate$1 = isCaretCandidate$3;
      var isForwards = function(direction) {
        return direction > 0;
      };
      var isBackwards = function(direction) {
        return direction < 0;
      };
      var skipCaretContainers = function(walk2, shallow2) {
        var node;
        while (node = walk2(shallow2)) {
          if (!isCaretContainerBlock(node)) {
            return node;
          }
        }
        return null;
      };
      var findNode$1 = function(node, direction, predicateFn, rootNode, shallow2) {
        var walker = new DomTreeWalker(node, rootNode);
        var isCefOrCaretContainer = isContentEditableFalse$7(node) || isCaretContainerBlock(node);
        if (isBackwards(direction)) {
          if (isCefOrCaretContainer) {
            node = skipCaretContainers(walker.prev.bind(walker), true);
            if (predicateFn(node)) {
              return node;
            }
          }
          while (node = skipCaretContainers(walker.prev.bind(walker), shallow2)) {
            if (predicateFn(node)) {
              return node;
            }
          }
        }
        if (isForwards(direction)) {
          if (isCefOrCaretContainer) {
            node = skipCaretContainers(walker.next.bind(walker), true);
            if (predicateFn(node)) {
              return node;
            }
          }
          while (node = skipCaretContainers(walker.next.bind(walker), shallow2)) {
            if (predicateFn(node)) {
              return node;
            }
          }
        }
        return null;
      };
      var getParentBlock$2 = function(node, rootNode) {
        while (node && node !== rootNode) {
          if (isBlockLike(node)) {
            return node;
          }
          node = node.parentNode;
        }
        return null;
      };
      var isInSameBlock = function(caretPosition1, caretPosition2, rootNode) {
        return getParentBlock$2(caretPosition1.container(), rootNode) === getParentBlock$2(caretPosition2.container(), rootNode);
      };
      var getChildNodeAtRelativeOffset = function(relativeOffset, caretPosition) {
        if (!caretPosition) {
          return null;
        }
        var container = caretPosition.container();
        var offset = caretPosition.offset();
        if (!isElement$1(container)) {
          return null;
        }
        return container.childNodes[offset + relativeOffset];
      };
      var beforeAfter = function(before2, node) {
        var range2 = node.ownerDocument.createRange();
        if (before2) {
          range2.setStartBefore(node);
          range2.setEndBefore(node);
        } else {
          range2.setStartAfter(node);
          range2.setEndAfter(node);
        }
        return range2;
      };
      var isNodesInSameBlock = function(root, node1, node2) {
        return getParentBlock$2(node1, root) === getParentBlock$2(node2, root);
      };
      var lean = function(left, root, node) {
        var siblingName = left ? "previousSibling" : "nextSibling";
        while (node && node !== root) {
          var sibling2 = node[siblingName];
          if (isCaretContainer(sibling2)) {
            sibling2 = sibling2[siblingName];
          }
          if (isContentEditableFalse$7(sibling2) || isMedia(sibling2)) {
            if (isNodesInSameBlock(root, sibling2, node)) {
              return sibling2;
            }
            break;
          }
          if (isCaretCandidate$1(sibling2)) {
            break;
          }
          node = node.parentNode;
        }
        return null;
      };
      var before$2 = curry(beforeAfter, true);
      var after$2 = curry(beforeAfter, false);
      var normalizeRange = function(direction, root, range2) {
        var node;
        var leanLeft = curry(lean, true, root);
        var leanRight2 = curry(lean, false, root);
        var container = range2.startContainer;
        var offset = range2.startOffset;
        if (isCaretContainerBlock$1(container)) {
          if (!isElement$1(container)) {
            container = container.parentNode;
          }
          var location_1 = container.getAttribute("data-mce-caret");
          if (location_1 === "before") {
            node = container.nextSibling;
            if (isFakeCaretTarget(node)) {
              return before$2(node);
            }
          }
          if (location_1 === "after") {
            node = container.previousSibling;
            if (isFakeCaretTarget(node)) {
              return after$2(node);
            }
          }
        }
        if (!range2.collapsed) {
          return range2;
        }
        if (isText$7(container)) {
          if (isCaretContainer(container)) {
            if (direction === 1) {
              node = leanRight2(container);
              if (node) {
                return before$2(node);
              }
              node = leanLeft(container);
              if (node) {
                return after$2(node);
              }
            }
            if (direction === -1) {
              node = leanLeft(container);
              if (node) {
                return after$2(node);
              }
              node = leanRight2(container);
              if (node) {
                return before$2(node);
              }
            }
            return range2;
          }
          if (endsWithCaretContainer$1(container) && offset >= container.data.length - 1) {
            if (direction === 1) {
              node = leanRight2(container);
              if (node) {
                return before$2(node);
              }
            }
            return range2;
          }
          if (startsWithCaretContainer$1(container) && offset <= 1) {
            if (direction === -1) {
              node = leanLeft(container);
              if (node) {
                return after$2(node);
              }
            }
            return range2;
          }
          if (offset === container.data.length) {
            node = leanRight2(container);
            if (node) {
              return before$2(node);
            }
            return range2;
          }
          if (offset === 0) {
            node = leanLeft(container);
            if (node) {
              return after$2(node);
            }
            return range2;
          }
        }
        return range2;
      };
      var getRelativeCefElm = function(forward, caretPosition) {
        return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, caretPosition)).filter(isContentEditableFalse$7);
      };
      var getNormalizedRangeEndPoint = function(direction, root, range2) {
        var normalizedRange = normalizeRange(direction, root, range2);
        if (direction === -1) {
          return CaretPosition.fromRangeStart(normalizedRange);
        }
        return CaretPosition.fromRangeEnd(normalizedRange);
      };
      var getElementFromPosition = function(pos) {
        return Optional.from(pos.getNode()).map(SugarElement.fromDom);
      };
      var getElementFromPrevPosition = function(pos) {
        return Optional.from(pos.getNode(true)).map(SugarElement.fromDom);
      };
      var getVisualCaretPosition = function(walkFn, caretPosition) {
        while (caretPosition = walkFn(caretPosition)) {
          if (caretPosition.isVisible()) {
            return caretPosition;
          }
        }
        return caretPosition;
      };
      var isMoveInsideSameBlock = function(from2, to2) {
        var inSameBlock = isInSameBlock(from2, to2);
        if (!inSameBlock && isBr$5(from2.getNode())) {
          return true;
        }
        return inSameBlock;
      };
      var HDirection;
      (function(HDirection2) {
        HDirection2[HDirection2["Backwards"] = -1] = "Backwards";
        HDirection2[HDirection2["Forwards"] = 1] = "Forwards";
      })(HDirection || (HDirection = {}));
      var isContentEditableFalse$6 = isContentEditableFalse$b;
      var isText$1 = isText$7;
      var isElement = isElement$5;
      var isBr$1 = isBr$5;
      var isCaretCandidate = isCaretCandidate$3;
      var isAtomic = isAtomic$1;
      var isEditableCaretCandidate = isEditableCaretCandidate$1;
      var getParents$3 = function(node, root) {
        var parents2 = [];
        while (node && node !== root) {
          parents2.push(node);
          node = node.parentNode;
        }
        return parents2;
      };
      var nodeAtIndex = function(container, offset) {
        if (container.hasChildNodes() && offset < container.childNodes.length) {
          return container.childNodes[offset];
        }
        return null;
      };
      var getCaretCandidatePosition = function(direction, node) {
        if (isForwards(direction)) {
          if (isCaretCandidate(node.previousSibling) && !isText$1(node.previousSibling)) {
            return CaretPosition.before(node);
          }
          if (isText$1(node)) {
            return CaretPosition(node, 0);
          }
        }
        if (isBackwards(direction)) {
          if (isCaretCandidate(node.nextSibling) && !isText$1(node.nextSibling)) {
            return CaretPosition.after(node);
          }
          if (isText$1(node)) {
            return CaretPosition(node, node.data.length);
          }
        }
        if (isBackwards(direction)) {
          if (isBr$1(node)) {
            return CaretPosition.before(node);
          }
          return CaretPosition.after(node);
        }
        return CaretPosition.before(node);
      };
      var moveForwardFromBr = function(root, nextNode) {
        var nextSibling2 = nextNode.nextSibling;
        if (nextSibling2 && isCaretCandidate(nextSibling2)) {
          if (isText$1(nextSibling2)) {
            return CaretPosition(nextSibling2, 0);
          } else {
            return CaretPosition.before(nextSibling2);
          }
        } else {
          return findCaretPosition$1(HDirection.Forwards, CaretPosition.after(nextNode), root);
        }
      };
      var findCaretPosition$1 = function(direction, startPos, root) {
        var node;
        var nextNode;
        var innerNode;
        var caretPosition;
        if (!isElement(root) || !startPos) {
          return null;
        }
        if (startPos.isEqual(CaretPosition.after(root)) && root.lastChild) {
          caretPosition = CaretPosition.after(root.lastChild);
          if (isBackwards(direction) && isCaretCandidate(root.lastChild) && isElement(root.lastChild)) {
            return isBr$1(root.lastChild) ? CaretPosition.before(root.lastChild) : caretPosition;
          }
        } else {
          caretPosition = startPos;
        }
        var container = caretPosition.container();
        var offset = caretPosition.offset();
        if (isText$1(container)) {
          if (isBackwards(direction) && offset > 0) {
            return CaretPosition(container, --offset);
          }
          if (isForwards(direction) && offset < container.length) {
            return CaretPosition(container, ++offset);
          }
          node = container;
        } else {
          if (isBackwards(direction) && offset > 0) {
            nextNode = nodeAtIndex(container, offset - 1);
            if (isCaretCandidate(nextNode)) {
              if (!isAtomic(nextNode)) {
                innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
                if (innerNode) {
                  if (isText$1(innerNode)) {
                    return CaretPosition(innerNode, innerNode.data.length);
                  }
                  return CaretPosition.after(innerNode);
                }
              }
              if (isText$1(nextNode)) {
                return CaretPosition(nextNode, nextNode.data.length);
              }
              return CaretPosition.before(nextNode);
            }
          }
          if (isForwards(direction) && offset < container.childNodes.length) {
            nextNode = nodeAtIndex(container, offset);
            if (isCaretCandidate(nextNode)) {
              if (isBr$1(nextNode)) {
                return moveForwardFromBr(root, nextNode);
              }
              if (!isAtomic(nextNode)) {
                innerNode = findNode$1(nextNode, direction, isEditableCaretCandidate, nextNode);
                if (innerNode) {
                  if (isText$1(innerNode)) {
                    return CaretPosition(innerNode, 0);
                  }
                  return CaretPosition.before(innerNode);
                }
              }
              if (isText$1(nextNode)) {
                return CaretPosition(nextNode, 0);
              }
              return CaretPosition.after(nextNode);
            }
          }
          node = nextNode ? nextNode : caretPosition.getNode();
        }
        if (isForwards(direction) && caretPosition.isAtEnd() || isBackwards(direction) && caretPosition.isAtStart()) {
          node = findNode$1(node, direction, always, root, true);
          if (isEditableCaretCandidate(node, root)) {
            return getCaretCandidatePosition(direction, node);
          }
        }
        nextNode = findNode$1(node, direction, isEditableCaretCandidate, root);
        var rootContentEditableFalseElm = last$1(filter$4(getParents$3(container, root), isContentEditableFalse$6));
        if (rootContentEditableFalseElm && (!nextNode || !rootContentEditableFalseElm.contains(nextNode))) {
          if (isForwards(direction)) {
            caretPosition = CaretPosition.after(rootContentEditableFalseElm);
          } else {
            caretPosition = CaretPosition.before(rootContentEditableFalseElm);
          }
          return caretPosition;
        }
        if (nextNode) {
          return getCaretCandidatePosition(direction, nextNode);
        }
        return null;
      };
      var CaretWalker = function(root) {
        return {
          next: function(caretPosition) {
            return findCaretPosition$1(HDirection.Forwards, caretPosition, root);
          },
          prev: function(caretPosition) {
            return findCaretPosition$1(HDirection.Backwards, caretPosition, root);
          }
        };
      };
      var walkToPositionIn = function(forward, root, start2) {
        var position = forward ? CaretPosition.before(start2) : CaretPosition.after(start2);
        return fromPosition(forward, root, position);
      };
      var afterElement = function(node) {
        return isBr$5(node) ? CaretPosition.before(node) : CaretPosition.after(node);
      };
      var isBeforeOrStart = function(position) {
        if (CaretPosition.isTextPosition(position)) {
          return position.offset() === 0;
        } else {
          return isCaretCandidate$3(position.getNode());
        }
      };
      var isAfterOrEnd = function(position) {
        if (CaretPosition.isTextPosition(position)) {
          var container = position.container();
          return position.offset() === container.data.length;
        } else {
          return isCaretCandidate$3(position.getNode(true));
        }
      };
      var isBeforeAfterSameElement = function(from2, to2) {
        return !CaretPosition.isTextPosition(from2) && !CaretPosition.isTextPosition(to2) && from2.getNode() === to2.getNode(true);
      };
      var isAtBr = function(position) {
        return !CaretPosition.isTextPosition(position) && isBr$5(position.getNode());
      };
      var shouldSkipPosition = function(forward, from2, to2) {
        if (forward) {
          return !isBeforeAfterSameElement(from2, to2) && !isAtBr(from2) && isAfterOrEnd(from2) && isBeforeOrStart(to2);
        } else {
          return !isBeforeAfterSameElement(to2, from2) && isBeforeOrStart(from2) && isAfterOrEnd(to2);
        }
      };
      var fromPosition = function(forward, root, pos) {
        var walker = CaretWalker(root);
        return Optional.from(forward ? walker.next(pos) : walker.prev(pos));
      };
      var navigate = function(forward, root, from2) {
        return fromPosition(forward, root, from2).bind(function(to2) {
          if (isInSameBlock(from2, to2, root) && shouldSkipPosition(forward, from2, to2)) {
            return fromPosition(forward, root, to2);
          } else {
            return Optional.some(to2);
          }
        });
      };
      var navigateIgnore = function(forward, root, from2, ignoreFilter) {
        return navigate(forward, root, from2).bind(function(pos) {
          return ignoreFilter(pos) ? navigateIgnore(forward, root, pos, ignoreFilter) : Optional.some(pos);
        });
      };
      var positionIn = function(forward, element) {
        var startNode = forward ? element.firstChild : element.lastChild;
        if (isText$7(startNode)) {
          return Optional.some(CaretPosition(startNode, forward ? 0 : startNode.data.length));
        } else if (startNode) {
          if (isCaretCandidate$3(startNode)) {
            return Optional.some(forward ? CaretPosition.before(startNode) : afterElement(startNode));
          } else {
            return walkToPositionIn(forward, element, startNode);
          }
        } else {
          return Optional.none();
        }
      };
      var nextPosition = curry(fromPosition, true);
      var prevPosition = curry(fromPosition, false);
      var firstPositionIn = curry(positionIn, true);
      var lastPositionIn = curry(positionIn, false);
      var CARET_ID$1 = "_mce_caret";
      var isCaretNode = function(node) {
        return isElement$5(node) && node.id === CARET_ID$1;
      };
      var getParentCaretContainer = function(body, node) {
        while (node && node !== body) {
          if (node.id === CARET_ID$1) {
            return node;
          }
          node = node.parentNode;
        }
        return null;
      };
      var isStringPathBookmark = function(bookmark) {
        return isString$1(bookmark.start);
      };
      var isRangeBookmark = function(bookmark) {
        return has$2(bookmark, "rng");
      };
      var isIdBookmark = function(bookmark) {
        return has$2(bookmark, "id");
      };
      var isIndexBookmark = function(bookmark) {
        return has$2(bookmark, "name");
      };
      var isPathBookmark = function(bookmark) {
        return Tools.isArray(bookmark.start);
      };
      var addBogus = function(dom2, node) {
        if (isElement$5(node) && dom2.isBlock(node) && !node.innerHTML && !Env.ie) {
          node.innerHTML = '<br data-mce-bogus="1" />';
        }
        return node;
      };
      var resolveCaretPositionBookmark = function(dom2, bookmark) {
        var pos;
        var rng = dom2.createRng();
        pos = resolve$2(dom2.getRoot(), bookmark.start);
        rng.setStart(pos.container(), pos.offset());
        pos = resolve$2(dom2.getRoot(), bookmark.end);
        rng.setEnd(pos.container(), pos.offset());
        return rng;
      };
      var insertZwsp = function(node, rng) {
        var textNode = node.ownerDocument.createTextNode(ZWSP$1);
        node.appendChild(textNode);
        rng.setStart(textNode, 0);
        rng.setEnd(textNode, 0);
      };
      var isEmpty$1 = function(node) {
        return node.hasChildNodes() === false;
      };
      var tryFindRangePosition = function(node, rng) {
        return lastPositionIn(node).fold(never, function(pos) {
          rng.setStart(pos.container(), pos.offset());
          rng.setEnd(pos.container(), pos.offset());
          return true;
        });
      };
      var padEmptyCaretContainer = function(root, node, rng) {
        if (isEmpty$1(node) && getParentCaretContainer(root, node)) {
          insertZwsp(node, rng);
          return true;
        } else {
          return false;
        }
      };
      var setEndPoint = function(dom2, start2, bookmark, rng) {
        var point = bookmark[start2 ? "start" : "end"];
        var i, node, offset, children2;
        var root = dom2.getRoot();
        if (point) {
          offset = point[0];
          for (node = root, i = point.length - 1; i >= 1; i--) {
            children2 = node.childNodes;
            if (padEmptyCaretContainer(root, node, rng)) {
              return true;
            }
            if (point[i] > children2.length - 1) {
              if (padEmptyCaretContainer(root, node, rng)) {
                return true;
              }
              return tryFindRangePosition(node, rng);
            }
            node = children2[point[i]];
          }
          if (node.nodeType === 3) {
            offset = Math.min(point[0], node.nodeValue.length);
          }
          if (node.nodeType === 1) {
            offset = Math.min(point[0], node.childNodes.length);
          }
          if (start2) {
            rng.setStart(node, offset);
          } else {
            rng.setEnd(node, offset);
          }
        }
        return true;
      };
      var isValidTextNode = function(node) {
        return isText$7(node) && node.data.length > 0;
      };
      var restoreEndPoint = function(dom2, suffix, bookmark) {
        var marker = dom2.get(bookmark.id + "_" + suffix), node, idx, next, prev;
        var keep = bookmark.keep;
        var container, offset;
        if (marker) {
          node = marker.parentNode;
          if (suffix === "start") {
            if (!keep) {
              idx = dom2.nodeIndex(marker);
            } else {
              if (marker.hasChildNodes()) {
                node = marker.firstChild;
                idx = 1;
              } else if (isValidTextNode(marker.nextSibling)) {
                node = marker.nextSibling;
                idx = 0;
              } else if (isValidTextNode(marker.previousSibling)) {
                node = marker.previousSibling;
                idx = marker.previousSibling.data.length;
              } else {
                node = marker.parentNode;
                idx = dom2.nodeIndex(marker) + 1;
              }
            }
            container = node;
            offset = idx;
          } else {
            if (!keep) {
              idx = dom2.nodeIndex(marker);
            } else {
              if (marker.hasChildNodes()) {
                node = marker.firstChild;
                idx = 1;
              } else if (isValidTextNode(marker.previousSibling)) {
                node = marker.previousSibling;
                idx = marker.previousSibling.data.length;
              } else {
                node = marker.parentNode;
                idx = dom2.nodeIndex(marker);
              }
            }
            container = node;
            offset = idx;
          }
          if (!keep) {
            prev = marker.previousSibling;
            next = marker.nextSibling;
            Tools.each(Tools.grep(marker.childNodes), function(node2) {
              if (isText$7(node2)) {
                node2.nodeValue = node2.nodeValue.replace(/\uFEFF/g, "");
              }
            });
            while (marker = dom2.get(bookmark.id + "_" + suffix)) {
              dom2.remove(marker, true);
            }
            if (prev && next && prev.nodeType === next.nodeType && isText$7(prev) && !Env.opera) {
              idx = prev.nodeValue.length;
              prev.appendData(next.nodeValue);
              dom2.remove(next);
              container = prev;
              offset = idx;
            }
          }
          return Optional.some(CaretPosition(container, offset));
        } else {
          return Optional.none();
        }
      };
      var resolvePaths = function(dom2, bookmark) {
        var rng = dom2.createRng();
        if (setEndPoint(dom2, true, bookmark, rng) && setEndPoint(dom2, false, bookmark, rng)) {
          return Optional.some(rng);
        } else {
          return Optional.none();
        }
      };
      var resolveId = function(dom2, bookmark) {
        var startPos = restoreEndPoint(dom2, "start", bookmark);
        var endPos = restoreEndPoint(dom2, "end", bookmark);
        return lift2(startPos, endPos.or(startPos), function(spos, epos) {
          var rng = dom2.createRng();
          rng.setStart(addBogus(dom2, spos.container()), spos.offset());
          rng.setEnd(addBogus(dom2, epos.container()), epos.offset());
          return rng;
        });
      };
      var resolveIndex = function(dom2, bookmark) {
        return Optional.from(dom2.select(bookmark.name)[bookmark.index]).map(function(elm) {
          var rng = dom2.createRng();
          rng.selectNode(elm);
          return rng;
        });
      };
      var resolve$1 = function(selection, bookmark) {
        var dom2 = selection.dom;
        if (bookmark) {
          if (isPathBookmark(bookmark)) {
            return resolvePaths(dom2, bookmark);
          } else if (isStringPathBookmark(bookmark)) {
            return Optional.some(resolveCaretPositionBookmark(dom2, bookmark));
          } else if (isIdBookmark(bookmark)) {
            return resolveId(dom2, bookmark);
          } else if (isIndexBookmark(bookmark)) {
            return resolveIndex(dom2, bookmark);
          } else if (isRangeBookmark(bookmark)) {
            return Optional.some(bookmark.rng);
          }
        }
        return Optional.none();
      };
      var getBookmark$1 = function(selection, type2, normalized) {
        return getBookmark$2(selection, type2, normalized);
      };
      var moveToBookmark = function(selection, bookmark) {
        resolve$1(selection, bookmark).each(function(rng) {
          selection.setRng(rng);
        });
      };
      var isBookmarkNode$1 = function(node) {
        return isElement$5(node) && node.tagName === "SPAN" && node.getAttribute("data-mce-type") === "bookmark";
      };
      var is = function(expected) {
        return function(actual) {
          return expected === actual;
        };
      };
      var isNbsp = is(nbsp);
      var isWhiteSpace = function(chr) {
        return chr !== "" && " \f\n\r	\v".indexOf(chr) !== -1;
      };
      var isContent = function(chr) {
        return !isWhiteSpace(chr) && !isNbsp(chr);
      };
      var isNode = function(node) {
        return !!node.nodeType;
      };
      var isInlineBlock = function(node) {
        return node && /^(IMG)$/.test(node.nodeName);
      };
      var moveStart = function(dom2, selection, rng) {
        var offset = rng.startOffset;
        var container = rng.startContainer;
        if (container === rng.endContainer) {
          if (isInlineBlock(container.childNodes[offset])) {
            return;
          }
        }
        if (isElement$5(container)) {
          var nodes = container.childNodes;
          var walker = void 0;
          if (offset < nodes.length) {
            container = nodes[offset];
            walker = new DomTreeWalker(container, dom2.getParent(container, dom2.isBlock));
          } else {
            container = nodes[nodes.length - 1];
            walker = new DomTreeWalker(container, dom2.getParent(container, dom2.isBlock));
            walker.next(true);
          }
          for (var node = walker.current(); node; node = walker.next()) {
            if (isText$7(node) && !isWhiteSpaceNode$1(node)) {
              rng.setStart(node, 0);
              selection.setRng(rng);
              return;
            }
          }
        }
      };
      var getNonWhiteSpaceSibling = function(node, next, inc) {
        if (node) {
          var nextName = next ? "nextSibling" : "previousSibling";
          for (node = inc ? node : node[nextName]; node; node = node[nextName]) {
            if (isElement$5(node) || !isWhiteSpaceNode$1(node)) {
              return node;
            }
          }
        }
      };
      var isTextBlock$1 = function(editor, name2) {
        if (isNode(name2)) {
          name2 = name2.nodeName;
        }
        return !!editor.schema.getTextBlockElements()[name2.toLowerCase()];
      };
      var isValid = function(ed, parent2, child2) {
        return ed.schema.isValidChild(parent2, child2);
      };
      var isWhiteSpaceNode$1 = function(node, allowSpaces) {
        if (allowSpaces === void 0) {
          allowSpaces = false;
        }
        if (isNonNullable(node) && isText$7(node)) {
          var data2 = allowSpaces ? node.data.replace(/ /g, "\xA0") : node.data;
          return isWhitespaceText(data2);
        } else {
          return false;
        }
      };
      var isEmptyTextNode$1 = function(node) {
        return isNonNullable(node) && isText$7(node) && node.length === 0;
      };
      var replaceVars = function(value2, vars) {
        if (isFunction(value2)) {
          value2 = value2(vars);
        } else if (isNonNullable(vars)) {
          value2 = value2.replace(/%(\w+)/g, function(str, name2) {
            return vars[name2] || str;
          });
        }
        return value2;
      };
      var isEq$5 = function(str1, str2) {
        str1 = str1 || "";
        str2 = str2 || "";
        str1 = "" + (str1.nodeName || str1);
        str2 = "" + (str2.nodeName || str2);
        return str1.toLowerCase() === str2.toLowerCase();
      };
      var normalizeStyleValue = function(dom2, value2, name2) {
        if (name2 === "color" || name2 === "backgroundColor") {
          value2 = dom2.toHex(value2);
        }
        if (name2 === "fontWeight" && value2 === 700) {
          value2 = "bold";
        }
        if (name2 === "fontFamily") {
          value2 = value2.replace(/[\'\"]/g, "").replace(/,\s+/g, ",");
        }
        return "" + value2;
      };
      var getStyle = function(dom2, node, name2) {
        return normalizeStyleValue(dom2, dom2.getStyle(node, name2), name2);
      };
      var getTextDecoration = function(dom2, node) {
        var decoration;
        dom2.getParent(node, function(n) {
          decoration = dom2.getStyle(n, "text-decoration");
          return decoration && decoration !== "none";
        });
        return decoration;
      };
      var getParents$2 = function(dom2, node, selector) {
        return dom2.getParents(node, selector, dom2.getRoot());
      };
      var isVariableFormatName = function(editor, formatName) {
        var hasVariableValues = function(format) {
          var isVariableValue = function(val) {
            return val.length > 1 && val.charAt(0) === "%";
          };
          return exists([
            "styles",
            "attributes"
          ], function(key) {
            return get$9(format, key).exists(function(field) {
              var fieldValues = isArray$1(field) ? field : values(field);
              return exists(fieldValues, isVariableValue);
            });
          });
        };
        return exists(editor.formatter.get(formatName), hasVariableValues);
      };
      var areSimilarFormats = function(editor, formatName, otherFormatName) {
        var validKeys = [
          "inline",
          "block",
          "selector",
          "attributes",
          "styles",
          "classes"
        ];
        var filterObj = function(format) {
          return filter$3(format, function(_, key) {
            return exists(validKeys, function(validKey) {
              return validKey === key;
            });
          });
        };
        return exists(editor.formatter.get(formatName), function(fmt1) {
          var filteredFmt1 = filterObj(fmt1);
          return exists(editor.formatter.get(otherFormatName), function(fmt2) {
            var filteredFmt2 = filterObj(fmt2);
            return equal$1(filteredFmt1, filteredFmt2);
          });
        });
      };
      var isBlockFormat = function(format) {
        return hasNonNullableKey(format, "block");
      };
      var isSelectorFormat = function(format) {
        return hasNonNullableKey(format, "selector");
      };
      var isInlineFormat = function(format) {
        return hasNonNullableKey(format, "inline");
      };
      var isMixedFormat = function(format) {
        return isSelectorFormat(format) && isInlineFormat(format) && is$1(get$9(format, "mixed"), true);
      };
      var shouldExpandToSelector = function(format) {
        return isSelectorFormat(format) && format.expand !== false && !isInlineFormat(format);
      };
      var isBookmarkNode = isBookmarkNode$1;
      var getParents$1 = getParents$2;
      var isWhiteSpaceNode = isWhiteSpaceNode$1;
      var isTextBlock = isTextBlock$1;
      var isBogusBr = function(node) {
        return isBr$5(node) && node.getAttribute("data-mce-bogus") && !node.nextSibling;
      };
      var findParentContentEditable = function(dom2, node) {
        var parent2 = node;
        while (parent2) {
          if (isElement$5(parent2) && dom2.getContentEditable(parent2)) {
            return dom2.getContentEditable(parent2) === "false" ? parent2 : node;
          }
          parent2 = parent2.parentNode;
        }
        return node;
      };
      var walkText = function(start2, node, offset, predicate) {
        var str = node.data;
        for (var i = offset; start2 ? i >= 0 : i < str.length; start2 ? i-- : i++) {
          if (predicate(str.charAt(i))) {
            return start2 ? i + 1 : i;
          }
        }
        return -1;
      };
      var findSpace = function(start2, node, offset) {
        return walkText(start2, node, offset, function(c) {
          return isNbsp(c) || isWhiteSpace(c);
        });
      };
      var findContent = function(start2, node, offset) {
        return walkText(start2, node, offset, isContent);
      };
      var findWordEndPoint = function(dom2, body, container, offset, start2, includeTrailingSpaces) {
        var lastTextNode;
        var rootNode = dom2.getParent(container, dom2.isBlock) || body;
        var walk2 = function(container2, offset2, pred) {
          var textSeeker = TextSeeker(dom2);
          var walker = start2 ? textSeeker.backwards : textSeeker.forwards;
          return Optional.from(walker(container2, offset2, function(text, textOffset) {
            if (isBookmarkNode(text.parentNode)) {
              return -1;
            } else {
              lastTextNode = text;
              return pred(start2, text, textOffset);
            }
          }, rootNode));
        };
        var spaceResult = walk2(container, offset, findSpace);
        return spaceResult.bind(function(result) {
          return includeTrailingSpaces ? walk2(result.container, result.offset + (start2 ? -1 : 0), findContent) : Optional.some(result);
        }).orThunk(function() {
          return lastTextNode ? Optional.some({
            container: lastTextNode,
            offset: start2 ? 0 : lastTextNode.length
          }) : Optional.none();
        });
      };
      var findSelectorEndPoint = function(dom2, formatList, rng, container, siblingName) {
        if (isText$7(container) && isEmpty$3(container.data) && container[siblingName]) {
          container = container[siblingName];
        }
        var parents2 = getParents$1(dom2, container);
        for (var i = 0; i < parents2.length; i++) {
          for (var y = 0; y < formatList.length; y++) {
            var curFormat = formatList[y];
            if (isNonNullable(curFormat.collapsed) && curFormat.collapsed !== rng.collapsed) {
              continue;
            }
            if (isSelectorFormat(curFormat) && dom2.is(parents2[i], curFormat.selector)) {
              return parents2[i];
            }
          }
        }
        return container;
      };
      var findBlockEndPoint = function(editor, formatList, container, siblingName) {
        var node = container;
        var dom2 = editor.dom;
        var root = dom2.getRoot();
        var format = formatList[0];
        if (isBlockFormat(format)) {
          node = format.wrapper ? null : dom2.getParent(container, format.block, root);
        }
        if (!node) {
          var scopeRoot = dom2.getParent(container, "LI,TD,TH");
          node = dom2.getParent(isText$7(container) ? container.parentNode : container, function(node2) {
            return node2 !== root && isTextBlock(editor, node2);
          }, scopeRoot);
        }
        if (node && isBlockFormat(format) && format.wrapper) {
          node = getParents$1(dom2, node, "ul,ol").reverse()[0] || node;
        }
        if (!node) {
          node = container;
          while (node[siblingName] && !dom2.isBlock(node[siblingName])) {
            node = node[siblingName];
            if (isEq$5(node, "br")) {
              break;
            }
          }
        }
        return node || container;
      };
      var isAtBlockBoundary$1 = function(dom2, root, container, siblingName) {
        var parent2 = container.parentNode;
        if (isNonNullable(container[siblingName])) {
          return false;
        } else if (parent2 === root || isNullable(parent2) || dom2.isBlock(parent2)) {
          return true;
        } else {
          return isAtBlockBoundary$1(dom2, root, parent2, siblingName);
        }
      };
      var findParentContainer = function(dom2, formatList, container, offset, start2) {
        var parent2 = container;
        var siblingName = start2 ? "previousSibling" : "nextSibling";
        var root = dom2.getRoot();
        if (isText$7(container) && !isWhiteSpaceNode(container)) {
          if (start2 ? offset > 0 : offset < container.data.length) {
            return container;
          }
        }
        while (true) {
          if (!formatList[0].block_expand && dom2.isBlock(parent2)) {
            return parent2;
          }
          for (var sibling2 = parent2[siblingName]; sibling2; sibling2 = sibling2[siblingName]) {
            var allowSpaces = isText$7(sibling2) && !isAtBlockBoundary$1(dom2, root, sibling2, siblingName);
            if (!isBookmarkNode(sibling2) && !isBogusBr(sibling2) && !isWhiteSpaceNode(sibling2, allowSpaces)) {
              return parent2;
            }
          }
          if (parent2 === root || parent2.parentNode === root) {
            container = parent2;
            break;
          }
          parent2 = parent2.parentNode;
        }
        return container;
      };
      var isSelfOrParentBookmark = function(container) {
        return isBookmarkNode(container.parentNode) || isBookmarkNode(container);
      };
      var expandRng = function(editor, rng, formatList, includeTrailingSpace) {
        if (includeTrailingSpace === void 0) {
          includeTrailingSpace = false;
        }
        var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
        var dom2 = editor.dom;
        var format = formatList[0];
        if (isElement$5(startContainer) && startContainer.hasChildNodes()) {
          startContainer = getNode$1(startContainer, startOffset);
          if (isText$7(startContainer)) {
            startOffset = 0;
          }
        }
        if (isElement$5(endContainer) && endContainer.hasChildNodes()) {
          endContainer = getNode$1(endContainer, rng.collapsed ? endOffset : endOffset - 1);
          if (isText$7(endContainer)) {
            endOffset = endContainer.nodeValue.length;
          }
        }
        startContainer = findParentContentEditable(dom2, startContainer);
        endContainer = findParentContentEditable(dom2, endContainer);
        if (isSelfOrParentBookmark(startContainer)) {
          startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
          if (rng.collapsed) {
            startContainer = startContainer.previousSibling || startContainer;
          } else {
            startContainer = startContainer.nextSibling || startContainer;
          }
          if (isText$7(startContainer)) {
            startOffset = rng.collapsed ? startContainer.length : 0;
          }
        }
        if (isSelfOrParentBookmark(endContainer)) {
          endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
          if (rng.collapsed) {
            endContainer = endContainer.nextSibling || endContainer;
          } else {
            endContainer = endContainer.previousSibling || endContainer;
          }
          if (isText$7(endContainer)) {
            endOffset = rng.collapsed ? 0 : endContainer.length;
          }
        }
        if (rng.collapsed) {
          var startPoint = findWordEndPoint(dom2, editor.getBody(), startContainer, startOffset, true, includeTrailingSpace);
          startPoint.each(function(_a) {
            var container = _a.container, offset = _a.offset;
            startContainer = container;
            startOffset = offset;
          });
          var endPoint = findWordEndPoint(dom2, editor.getBody(), endContainer, endOffset, false, includeTrailingSpace);
          endPoint.each(function(_a) {
            var container = _a.container, offset = _a.offset;
            endContainer = container;
            endOffset = offset;
          });
        }
        if (isInlineFormat(format) || format.block_expand) {
          if (!isInlineFormat(format) || (!isText$7(startContainer) || startOffset === 0)) {
            startContainer = findParentContainer(dom2, formatList, startContainer, startOffset, true);
          }
          if (!isInlineFormat(format) || (!isText$7(endContainer) || endOffset === endContainer.nodeValue.length)) {
            endContainer = findParentContainer(dom2, formatList, endContainer, endOffset, false);
          }
        }
        if (shouldExpandToSelector(format)) {
          startContainer = findSelectorEndPoint(dom2, formatList, rng, startContainer, "previousSibling");
          endContainer = findSelectorEndPoint(dom2, formatList, rng, endContainer, "nextSibling");
        }
        if (isBlockFormat(format) || isSelectorFormat(format)) {
          startContainer = findBlockEndPoint(editor, formatList, startContainer, "previousSibling");
          endContainer = findBlockEndPoint(editor, formatList, endContainer, "nextSibling");
          if (isBlockFormat(format)) {
            if (!dom2.isBlock(startContainer)) {
              startContainer = findParentContainer(dom2, formatList, startContainer, startOffset, true);
            }
            if (!dom2.isBlock(endContainer)) {
              endContainer = findParentContainer(dom2, formatList, endContainer, endOffset, false);
            }
          }
        }
        if (isElement$5(startContainer)) {
          startOffset = dom2.nodeIndex(startContainer);
          startContainer = startContainer.parentNode;
        }
        if (isElement$5(endContainer)) {
          endOffset = dom2.nodeIndex(endContainer) + 1;
          endContainer = endContainer.parentNode;
        }
        return {
          startContainer,
          startOffset,
          endContainer,
          endOffset
        };
      };
      var walk$2 = function(dom2, rng, callback) {
        var startOffset = rng.startOffset;
        var startContainer = getNode$1(rng.startContainer, startOffset);
        var endOffset = rng.endOffset;
        var endContainer = getNode$1(rng.endContainer, endOffset - 1);
        var exclude = function(nodes) {
          var firstNode = nodes[0];
          if (isText$7(firstNode) && firstNode === startContainer && startOffset >= firstNode.data.length) {
            nodes.splice(0, 1);
          }
          var lastNode = nodes[nodes.length - 1];
          if (endOffset === 0 && nodes.length > 0 && lastNode === endContainer && isText$7(lastNode)) {
            nodes.splice(nodes.length - 1, 1);
          }
          return nodes;
        };
        var collectSiblings = function(node, name2, endNode) {
          var siblings3 = [];
          for (; node && node !== endNode; node = node[name2]) {
            siblings3.push(node);
          }
          return siblings3;
        };
        var findEndPoint = function(node, root) {
          return dom2.getParent(node, function(node2) {
            return node2.parentNode === root;
          }, root);
        };
        var walkBoundary = function(startNode, endNode, next) {
          var siblingName = next ? "nextSibling" : "previousSibling";
          for (var node = startNode, parent_1 = node.parentNode; node && node !== endNode; node = parent_1) {
            parent_1 = node.parentNode;
            var siblings_1 = collectSiblings(node === startNode ? node : node[siblingName], siblingName);
            if (siblings_1.length) {
              if (!next) {
                siblings_1.reverse();
              }
              callback(exclude(siblings_1));
            }
          }
        };
        if (startContainer === endContainer) {
          return callback(exclude([startContainer]));
        }
        var ancestor2 = dom2.findCommonAncestor(startContainer, endContainer);
        if (dom2.isChildOf(startContainer, endContainer)) {
          return walkBoundary(startContainer, ancestor2, true);
        }
        if (dom2.isChildOf(endContainer, startContainer)) {
          return walkBoundary(endContainer, ancestor2);
        }
        var startPoint = findEndPoint(startContainer, ancestor2) || startContainer;
        var endPoint = findEndPoint(endContainer, ancestor2) || endContainer;
        walkBoundary(startContainer, startPoint, true);
        var siblings2 = collectSiblings(startPoint === startContainer ? startPoint : startPoint.nextSibling, "nextSibling", endPoint === endContainer ? endPoint.nextSibling : endPoint);
        if (siblings2.length) {
          callback(exclude(siblings2));
        }
        walkBoundary(endContainer, endPoint);
      };
      var getRanges = function(selection) {
        var ranges = [];
        if (selection) {
          for (var i = 0; i < selection.rangeCount; i++) {
            ranges.push(selection.getRangeAt(i));
          }
        }
        return ranges;
      };
      var getSelectedNodes = function(ranges) {
        return bind(ranges, function(range2) {
          var node = getSelectedNode(range2);
          return node ? [SugarElement.fromDom(node)] : [];
        });
      };
      var hasMultipleRanges = function(selection) {
        return getRanges(selection).length > 1;
      };
      var getCellsFromRanges = function(ranges) {
        return filter$4(getSelectedNodes(ranges), isTableCell$4);
      };
      var getCellsFromElement = function(elm) {
        return descendants(elm, "td[data-mce-selected],th[data-mce-selected]");
      };
      var getCellsFromElementOrRanges = function(ranges, element) {
        var selectedCells = getCellsFromElement(element);
        return selectedCells.length > 0 ? selectedCells : getCellsFromRanges(ranges);
      };
      var getCellsFromEditor = function(editor) {
        return getCellsFromElementOrRanges(getRanges(editor.selection.getSel()), SugarElement.fromDom(editor.getBody()));
      };
      var getClosestTable = function(cell, isRoot) {
        return ancestor$2(cell, "table", isRoot);
      };
      var getStartNode = function(rng) {
        var sc = rng.startContainer, so = rng.startOffset;
        if (isText$7(sc)) {
          return so === 0 ? Optional.some(SugarElement.fromDom(sc)) : Optional.none();
        } else {
          return Optional.from(sc.childNodes[so]).map(SugarElement.fromDom);
        }
      };
      var getEndNode = function(rng) {
        var ec = rng.endContainer, eo = rng.endOffset;
        if (isText$7(ec)) {
          return eo === ec.data.length ? Optional.some(SugarElement.fromDom(ec)) : Optional.none();
        } else {
          return Optional.from(ec.childNodes[eo - 1]).map(SugarElement.fromDom);
        }
      };
      var getFirstChildren = function(node) {
        return firstChild(node).fold(constant([node]), function(child2) {
          return [node].concat(getFirstChildren(child2));
        });
      };
      var getLastChildren$1 = function(node) {
        return lastChild(node).fold(constant([node]), function(child2) {
          if (name(child2) === "br") {
            return prevSibling(child2).map(function(sibling2) {
              return [node].concat(getLastChildren$1(sibling2));
            }).getOr([]);
          } else {
            return [node].concat(getLastChildren$1(child2));
          }
        });
      };
      var hasAllContentsSelected = function(elm, rng) {
        return lift2(getStartNode(rng), getEndNode(rng), function(startNode, endNode) {
          var start2 = find$3(getFirstChildren(elm), curry(eq, startNode));
          var end2 = find$3(getLastChildren$1(elm), curry(eq, endNode));
          return start2.isSome() && end2.isSome();
        }).getOr(false);
      };
      var moveEndPoint = function(dom2, rng, node, start2) {
        var root = node, walker = new DomTreeWalker(node, root);
        var moveCaretBeforeOnEnterElementsMap = filter$3(dom2.schema.getMoveCaretBeforeOnEnterElements(), function(_, name2) {
          return !contains$3([
            "td",
            "th",
            "table"
          ], name2.toLowerCase());
        });
        do {
          if (isText$7(node) && Tools.trim(node.nodeValue).length !== 0) {
            if (start2) {
              rng.setStart(node, 0);
            } else {
              rng.setEnd(node, node.nodeValue.length);
            }
            return;
          }
          if (moveCaretBeforeOnEnterElementsMap[node.nodeName]) {
            if (start2) {
              rng.setStartBefore(node);
            } else {
              if (node.nodeName === "BR") {
                rng.setEndBefore(node);
              } else {
                rng.setEndAfter(node);
              }
            }
            return;
          }
        } while (node = start2 ? walker.next() : walker.prev());
        if (root.nodeName === "BODY") {
          if (start2) {
            rng.setStart(root, 0);
          } else {
            rng.setEnd(root, root.childNodes.length);
          }
        }
      };
      var hasAnyRanges = function(editor) {
        var sel = editor.selection.getSel();
        return sel && sel.rangeCount > 0;
      };
      var runOnRanges = function(editor, executor) {
        var fakeSelectionNodes = getCellsFromEditor(editor);
        if (fakeSelectionNodes.length > 0) {
          each$k(fakeSelectionNodes, function(elem) {
            var node = elem.dom;
            var fakeNodeRng = editor.dom.createRng();
            fakeNodeRng.setStartBefore(node);
            fakeNodeRng.setEndAfter(node);
            executor(fakeNodeRng, true);
          });
        } else {
          executor(editor.selection.getRng(), false);
        }
      };
      var preserve = function(selection, fillBookmark, executor) {
        var bookmark = getPersistentBookmark(selection, fillBookmark);
        executor(bookmark);
        selection.moveToBookmark(bookmark);
      };
      var NodeValue = function(is2, name2) {
        var get2 = function(element) {
          if (!is2(element)) {
            throw new Error("Can only get " + name2 + " value of a " + name2 + " node");
          }
          return getOption(element).getOr("");
        };
        var getOption = function(element) {
          return is2(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
        };
        var set2 = function(element, value2) {
          if (!is2(element)) {
            throw new Error("Can only set raw " + name2 + " value of a " + name2 + " node");
          }
          element.dom.nodeValue = value2;
        };
        return {
          get: get2,
          getOption,
          set: set2
        };
      };
      var api$1 = NodeValue(isText$8, "text");
      var get$2 = function(element) {
        return api$1.get(element);
      };
      var isZeroWidth = function(elem) {
        return isText$8(elem) && get$2(elem) === ZWSP$1;
      };
      var context = function(editor, elem, wrapName, nodeName) {
        return parent(elem).fold(function() {
          return "skipping";
        }, function(parent2) {
          if (nodeName === "br" || isZeroWidth(elem)) {
            return "valid";
          } else if (isAnnotation(elem)) {
            return "existing";
          } else if (isCaretNode(elem.dom)) {
            return "caret";
          } else if (!isValid(editor, wrapName, nodeName) || !isValid(editor, name(parent2), wrapName)) {
            return "invalid-child";
          } else {
            return "valid";
          }
        });
      };
      var applyWordGrab = function(editor, rng) {
        var r2 = expandRng(editor, rng, [{ inline: "span" }]);
        rng.setStart(r2.startContainer, r2.startOffset);
        rng.setEnd(r2.endContainer, r2.endOffset);
        editor.selection.setRng(rng);
      };
      var makeAnnotation = function(eDoc, _a, annotationName, decorate) {
        var _b = _a.uid, uid = _b === void 0 ? generate("mce-annotation") : _b, data2 = __rest(_a, ["uid"]);
        var master = SugarElement.fromTag("span", eDoc);
        add$1(master, annotation());
        set$1(master, "" + dataAnnotationId(), uid);
        set$1(master, "" + dataAnnotation(), annotationName);
        var _c = decorate(uid, data2), _d = _c.attributes, attributes2 = _d === void 0 ? {} : _d, _e = _c.classes, classes = _e === void 0 ? [] : _e;
        setAll$1(master, attributes2);
        add(master, classes);
        return master;
      };
      var annotate = function(editor, rng, annotationName, decorate, data2) {
        var newWrappers = [];
        var master = makeAnnotation(editor.getDoc(), data2, annotationName, decorate);
        var wrapper = value();
        var finishWrapper = function() {
          wrapper.clear();
        };
        var getOrOpenWrapper = function() {
          return wrapper.get().getOrThunk(function() {
            var nu2 = shallow(master);
            newWrappers.push(nu2);
            wrapper.set(nu2);
            return nu2;
          });
        };
        var processElements = function(elems) {
          each$k(elems, processElement);
        };
        var processElement = function(elem) {
          var ctx = context(editor, elem, "span", name(elem));
          switch (ctx) {
            case "invalid-child": {
              finishWrapper();
              var children$1 = children(elem);
              processElements(children$1);
              finishWrapper();
              break;
            }
            case "valid": {
              var w = getOrOpenWrapper();
              wrap$3(elem, w);
              break;
            }
          }
        };
        var processNodes = function(nodes) {
          var elems = map$3(nodes, SugarElement.fromDom);
          processElements(elems);
        };
        walk$2(editor.dom, rng, function(nodes) {
          finishWrapper();
          processNodes(nodes);
        });
        return newWrappers;
      };
      var annotateWithBookmark = function(editor, name2, settings, data2) {
        editor.undoManager.transact(function() {
          var selection = editor.selection;
          var initialRng = selection.getRng();
          var hasFakeSelection = getCellsFromEditor(editor).length > 0;
          if (initialRng.collapsed && !hasFakeSelection) {
            applyWordGrab(editor, initialRng);
          }
          if (selection.getRng().collapsed && !hasFakeSelection) {
            var wrapper = makeAnnotation(editor.getDoc(), data2, name2, settings.decorate);
            set(wrapper, nbsp);
            selection.getRng().insertNode(wrapper.dom);
            selection.select(wrapper.dom);
          } else {
            preserve(selection, false, function() {
              runOnRanges(editor, function(selectionRng) {
                annotate(editor, selectionRng, name2, settings.decorate, data2);
              });
            });
          }
        });
      };
      var Annotator = function(editor) {
        var registry2 = create$7();
        setup$m(editor, registry2);
        var changes = setup$n(editor);
        return {
          register: function(name2, settings) {
            registry2.register(name2, settings);
          },
          annotate: function(name2, data2) {
            registry2.lookup(name2).each(function(settings) {
              annotateWithBookmark(editor, name2, settings, data2);
            });
          },
          annotationChanged: function(name2, callback) {
            changes.addListener(name2, callback);
          },
          remove: function(name2) {
            identify(editor, Optional.some(name2)).each(function(_a) {
              var elements = _a.elements;
              each$k(elements, unwrap);
            });
          },
          getAll: function(name2) {
            var directory = findAll(editor, name2);
            return map$2(directory, function(elems) {
              return map$3(elems, function(elem) {
                return elem.dom;
              });
            });
          }
        };
      };
      var BookmarkManager = function(selection) {
        return {
          getBookmark: curry(getBookmark$1, selection),
          moveToBookmark: curry(moveToBookmark, selection)
        };
      };
      BookmarkManager.isBookmarkNode = isBookmarkNode$1;
      var getContentEditableRoot$1 = function(root, node) {
        while (node && node !== root) {
          if (isContentEditableTrue$4(node) || isContentEditableFalse$b(node)) {
            return node;
          }
          node = node.parentNode;
        }
        return null;
      };
      var isXYWithinRange = function(clientX, clientY, range2) {
        if (range2.collapsed) {
          return false;
        }
        if (Env.browser.isIE() && range2.startOffset === range2.endOffset - 1 && range2.startContainer === range2.endContainer) {
          var elm = range2.startContainer.childNodes[range2.startOffset];
          if (isElement$5(elm)) {
            return exists(elm.getClientRects(), function(rect) {
              return containsXY(rect, clientX, clientY);
            });
          }
        }
        return exists(range2.getClientRects(), function(rect) {
          return containsXY(rect, clientX, clientY);
        });
      };
      var firePreProcess = function(editor, args) {
        return editor.fire("PreProcess", args);
      };
      var firePostProcess = function(editor, args) {
        return editor.fire("PostProcess", args);
      };
      var fireRemove = function(editor) {
        return editor.fire("remove");
      };
      var fireDetach = function(editor) {
        return editor.fire("detach");
      };
      var fireSwitchMode = function(editor, mode) {
        return editor.fire("SwitchMode", { mode });
      };
      var fireObjectResizeStart = function(editor, target, width, height, origin) {
        editor.fire("ObjectResizeStart", {
          target,
          width,
          height,
          origin
        });
      };
      var fireObjectResized = function(editor, target, width, height, origin) {
        editor.fire("ObjectResized", {
          target,
          width,
          height,
          origin
        });
      };
      var firePreInit = function(editor) {
        return editor.fire("PreInit");
      };
      var firePostRender = function(editor) {
        return editor.fire("PostRender");
      };
      var fireInit = function(editor) {
        return editor.fire("Init");
      };
      var firePlaceholderToggle = function(editor, state) {
        return editor.fire("PlaceholderToggle", { state });
      };
      var fireError = function(editor, errorType, error2) {
        return editor.fire(errorType, error2);
      };
      var fireFormatApply = function(editor, format, node, vars) {
        return editor.fire("FormatApply", {
          format,
          node,
          vars
        });
      };
      var fireFormatRemove = function(editor, format, node, vars) {
        return editor.fire("FormatRemove", {
          format,
          node,
          vars
        });
      };
      var VK = {
        BACKSPACE: 8,
        DELETE: 46,
        DOWN: 40,
        ENTER: 13,
        ESC: 27,
        LEFT: 37,
        RIGHT: 39,
        SPACEBAR: 32,
        TAB: 9,
        UP: 38,
        PAGE_UP: 33,
        PAGE_DOWN: 34,
        END: 35,
        HOME: 36,
        modifierPressed: function(e) {
          return e.shiftKey || e.ctrlKey || e.altKey || VK.metaKeyPressed(e);
        },
        metaKeyPressed: function(e) {
          return Env.mac ? e.metaKey : e.ctrlKey && !e.altKey;
        }
      };
      var isContentEditableFalse$5 = isContentEditableFalse$b;
      var ControlSelection = function(selection, editor) {
        var elementSelectionAttr = "data-mce-selected";
        var dom2 = editor.dom, each2 = Tools.each;
        var selectedElm, selectedElmGhost, resizeHelper, selectedHandle, resizeBackdrop;
        var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
        var width, height;
        var editableDoc = editor.getDoc(), rootDocument = document;
        var abs = Math.abs, round2 = Math.round, rootElement = editor.getBody();
        var startScrollWidth, startScrollHeight;
        var resizeHandles = {
          nw: [
            0,
            0,
            -1,
            -1
          ],
          ne: [
            1,
            0,
            1,
            -1
          ],
          se: [
            1,
            1,
            1,
            1
          ],
          sw: [
            0,
            1,
            -1,
            1
          ]
        };
        var isImage = function(elm) {
          return elm && (elm.nodeName === "IMG" || editor.dom.is(elm, "figure.image"));
        };
        var isMedia2 = function(elm) {
          return isMedia$2(elm) || dom2.hasClass(elm, "mce-preview-object");
        };
        var isEventOnImageOutsideRange = function(evt, range2) {
          if (evt.type === "longpress" || evt.type.indexOf("touch") === 0) {
            var touch = evt.touches[0];
            return isImage(evt.target) && !isXYWithinRange(touch.clientX, touch.clientY, range2);
          } else {
            return isImage(evt.target) && !isXYWithinRange(evt.clientX, evt.clientY, range2);
          }
        };
        var contextMenuSelectImage = function(evt) {
          var target = evt.target;
          if (isEventOnImageOutsideRange(evt, editor.selection.getRng()) && !evt.isDefaultPrevented()) {
            editor.selection.select(target);
          }
        };
        var getResizeTargets = function(elm) {
          if (dom2.is(elm, "figure.image")) {
            return [elm.querySelector("img")];
          } else if (dom2.hasClass(elm, "mce-preview-object") && isNonNullable(elm.firstElementChild)) {
            return [
              elm,
              elm.firstElementChild
            ];
          } else {
            return [elm];
          }
        };
        var isResizable = function(elm) {
          var selector = getObjectResizing(editor);
          if (!selector) {
            return false;
          }
          if (elm.getAttribute("data-mce-resize") === "false") {
            return false;
          }
          if (elm === editor.getBody()) {
            return false;
          }
          if (dom2.hasClass(elm, "mce-preview-object")) {
            return is$2(SugarElement.fromDom(elm.firstElementChild), selector);
          } else {
            return is$2(SugarElement.fromDom(elm), selector);
          }
        };
        var createGhostElement = function(elm) {
          if (isMedia2(elm)) {
            return dom2.create("img", { src: Env.transparentSrc });
          } else {
            return elm.cloneNode(true);
          }
        };
        var setSizeProp = function(element, name2, value2) {
          if (isNonNullable(value2)) {
            var targets = getResizeTargets(element);
            each$k(targets, function(target) {
              if (target.style[name2] || !editor.schema.isValid(target.nodeName.toLowerCase(), name2)) {
                dom2.setStyle(target, name2, value2);
              } else {
                dom2.setAttrib(target, name2, "" + value2);
              }
            });
          }
        };
        var setGhostElmSize = function(ghostElm, width2, height2) {
          setSizeProp(ghostElm, "width", width2);
          setSizeProp(ghostElm, "height", height2);
        };
        var resizeGhostElement = function(e) {
          var deltaX, deltaY, proportional;
          var resizeHelperX, resizeHelperY;
          deltaX = e.screenX - startX;
          deltaY = e.screenY - startY;
          width = deltaX * selectedHandle[2] + startW;
          height = deltaY * selectedHandle[3] + startH;
          width = width < 5 ? 5 : width;
          height = height < 5 ? 5 : height;
          if ((isImage(selectedElm) || isMedia2(selectedElm)) && getResizeImgProportional(editor) !== false) {
            proportional = !VK.modifierPressed(e);
          } else {
            proportional = VK.modifierPressed(e);
          }
          if (proportional) {
            if (abs(deltaX) > abs(deltaY)) {
              height = round2(width * ratio);
              width = round2(height / ratio);
            } else {
              width = round2(height / ratio);
              height = round2(width * ratio);
            }
          }
          setGhostElmSize(selectedElmGhost, width, height);
          resizeHelperX = selectedHandle.startPos.x + deltaX;
          resizeHelperY = selectedHandle.startPos.y + deltaY;
          resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
          resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
          dom2.setStyles(resizeHelper, {
            left: resizeHelperX,
            top: resizeHelperY,
            display: "block"
          });
          resizeHelper.innerHTML = width + " &times; " + height;
          if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
            dom2.setStyle(selectedElmGhost, "left", selectedElmX + (startW - width));
          }
          if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
            dom2.setStyle(selectedElmGhost, "top", selectedElmY + (startH - height));
          }
          deltaX = rootElement.scrollWidth - startScrollWidth;
          deltaY = rootElement.scrollHeight - startScrollHeight;
          if (deltaX + deltaY !== 0) {
            dom2.setStyles(resizeHelper, {
              left: resizeHelperX - deltaX,
              top: resizeHelperY - deltaY
            });
          }
          if (!resizeStarted) {
            fireObjectResizeStart(editor, selectedElm, startW, startH, "corner-" + selectedHandle.name);
            resizeStarted = true;
          }
        };
        var endGhostResize = function() {
          var wasResizeStarted = resizeStarted;
          resizeStarted = false;
          if (wasResizeStarted) {
            setSizeProp(selectedElm, "width", width);
            setSizeProp(selectedElm, "height", height);
          }
          dom2.unbind(editableDoc, "mousemove", resizeGhostElement);
          dom2.unbind(editableDoc, "mouseup", endGhostResize);
          if (rootDocument !== editableDoc) {
            dom2.unbind(rootDocument, "mousemove", resizeGhostElement);
            dom2.unbind(rootDocument, "mouseup", endGhostResize);
          }
          dom2.remove(selectedElmGhost);
          dom2.remove(resizeHelper);
          dom2.remove(resizeBackdrop);
          showResizeRect(selectedElm);
          if (wasResizeStarted) {
            fireObjectResized(editor, selectedElm, width, height, "corner-" + selectedHandle.name);
            dom2.setAttrib(selectedElm, "style", dom2.getAttrib(selectedElm, "style"));
          }
          editor.nodeChanged();
        };
        var showResizeRect = function(targetElm) {
          unbindResizeHandleEvents();
          var position = dom2.getPos(targetElm, rootElement);
          var selectedElmX2 = position.x;
          var selectedElmY2 = position.y;
          var rect = targetElm.getBoundingClientRect();
          var targetWidth = rect.width || rect.right - rect.left;
          var targetHeight = rect.height || rect.bottom - rect.top;
          if (selectedElm !== targetElm) {
            hideResizeRect();
            selectedElm = targetElm;
            width = height = 0;
          }
          var e = editor.fire("ObjectSelected", { target: targetElm });
          var selectedValue = dom2.getAttrib(selectedElm, elementSelectionAttr, "1");
          if (isResizable(targetElm) && !e.isDefaultPrevented()) {
            each2(resizeHandles, function(handle2, name2) {
              var handleElm;
              var startDrag = function(e2) {
                var target = getResizeTargets(selectedElm)[0];
                startX = e2.screenX;
                startY = e2.screenY;
                startW = target.clientWidth;
                startH = target.clientHeight;
                ratio = startH / startW;
                selectedHandle = handle2;
                selectedHandle.name = name2;
                selectedHandle.startPos = {
                  x: targetWidth * handle2[0] + selectedElmX2,
                  y: targetHeight * handle2[1] + selectedElmY2
                };
                startScrollWidth = rootElement.scrollWidth;
                startScrollHeight = rootElement.scrollHeight;
                resizeBackdrop = dom2.add(rootElement, "div", {
                  "class": "mce-resize-backdrop",
                  "data-mce-bogus": "all"
                });
                dom2.setStyles(resizeBackdrop, {
                  position: "fixed",
                  left: "0",
                  top: "0",
                  width: "100%",
                  height: "100%"
                });
                selectedElmGhost = createGhostElement(selectedElm);
                dom2.addClass(selectedElmGhost, "mce-clonedresizable");
                dom2.setAttrib(selectedElmGhost, "data-mce-bogus", "all");
                selectedElmGhost.contentEditable = "false";
                dom2.setStyles(selectedElmGhost, {
                  left: selectedElmX2,
                  top: selectedElmY2,
                  margin: 0
                });
                setGhostElmSize(selectedElmGhost, targetWidth, targetHeight);
                selectedElmGhost.removeAttribute(elementSelectionAttr);
                rootElement.appendChild(selectedElmGhost);
                dom2.bind(editableDoc, "mousemove", resizeGhostElement);
                dom2.bind(editableDoc, "mouseup", endGhostResize);
                if (rootDocument !== editableDoc) {
                  dom2.bind(rootDocument, "mousemove", resizeGhostElement);
                  dom2.bind(rootDocument, "mouseup", endGhostResize);
                }
                resizeHelper = dom2.add(rootElement, "div", {
                  "class": "mce-resize-helper",
                  "data-mce-bogus": "all"
                }, startW + " &times; " + startH);
              };
              handleElm = dom2.get("mceResizeHandle" + name2);
              if (handleElm) {
                dom2.remove(handleElm);
              }
              handleElm = dom2.add(rootElement, "div", {
                "id": "mceResizeHandle" + name2,
                "data-mce-bogus": "all",
                "class": "mce-resizehandle",
                "unselectable": true,
                "style": "cursor:" + name2 + "-resize; margin:0; padding:0"
              });
              if (Env.ie === 11) {
                handleElm.contentEditable = false;
              }
              dom2.bind(handleElm, "mousedown", function(e2) {
                e2.stopImmediatePropagation();
                e2.preventDefault();
                startDrag(e2);
              });
              handle2.elm = handleElm;
              dom2.setStyles(handleElm, {
                left: targetWidth * handle2[0] + selectedElmX2 - handleElm.offsetWidth / 2,
                top: targetHeight * handle2[1] + selectedElmY2 - handleElm.offsetHeight / 2
              });
            });
          } else {
            hideResizeRect();
          }
          if (!dom2.getAttrib(selectedElm, elementSelectionAttr)) {
            selectedElm.setAttribute(elementSelectionAttr, selectedValue);
          }
        };
        var hideResizeRect = function() {
          unbindResizeHandleEvents();
          if (selectedElm) {
            selectedElm.removeAttribute(elementSelectionAttr);
          }
          each$j(resizeHandles, function(value2, name2) {
            var handleElm = dom2.get("mceResizeHandle" + name2);
            if (handleElm) {
              dom2.unbind(handleElm);
              dom2.remove(handleElm);
            }
          });
        };
        var updateResizeRect = function(e) {
          var startElm, controlElm;
          var isChildOrEqual = function(node, parent2) {
            if (node) {
              do {
                if (node === parent2) {
                  return true;
                }
              } while (node = node.parentNode);
            }
          };
          if (resizeStarted || editor.removed) {
            return;
          }
          each2(dom2.select("img[data-mce-selected],hr[data-mce-selected]"), function(img) {
            img.removeAttribute(elementSelectionAttr);
          });
          controlElm = e.type === "mousedown" ? e.target : selection.getNode();
          controlElm = dom2.$(controlElm).closest("table,img,figure.image,hr,video,span.mce-preview-object")[0];
          if (isChildOrEqual(controlElm, rootElement)) {
            disableGeckoResize();
            startElm = selection.getStart(true);
            if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
              showResizeRect(controlElm);
              return;
            }
          }
          hideResizeRect();
        };
        var isWithinContentEditableFalse = function(elm) {
          return isContentEditableFalse$5(getContentEditableRoot$1(editor.getBody(), elm));
        };
        var unbindResizeHandleEvents = function() {
          each$j(resizeHandles, function(handle2) {
            if (handle2.elm) {
              dom2.unbind(handle2.elm);
              delete handle2.elm;
            }
          });
        };
        var disableGeckoResize = function() {
          try {
            editor.getDoc().execCommand("enableObjectResizing", false, "false");
          } catch (ex) {
          }
        };
        editor.on("init", function() {
          disableGeckoResize();
          if (Env.browser.isIE() || Env.browser.isEdge()) {
            editor.on("mousedown click", function(e) {
              var target = e.target, nodeName = target.nodeName;
              if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName) && !isWithinContentEditableFalse(target)) {
                if (e.button !== 2) {
                  editor.selection.select(target, nodeName === "TABLE");
                }
                if (e.type === "mousedown") {
                  editor.nodeChanged();
                }
              }
            });
            var handleMSControlSelect_1 = function(e) {
              var delayedSelect = function(node) {
                Delay.setEditorTimeout(editor, function() {
                  return editor.selection.select(node);
                });
              };
              if (isWithinContentEditableFalse(e.target) || isMedia$2(e.target)) {
                e.preventDefault();
                delayedSelect(e.target);
                return;
              }
              if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
                e.preventDefault();
                if (e.target.tagName === "IMG") {
                  delayedSelect(e.target);
                }
              }
            };
            dom2.bind(rootElement, "mscontrolselect", handleMSControlSelect_1);
            editor.on("remove", function() {
              return dom2.unbind(rootElement, "mscontrolselect", handleMSControlSelect_1);
            });
          }
          var throttledUpdateResizeRect = Delay.throttle(function(e) {
            if (!editor.composing) {
              updateResizeRect(e);
            }
          });
          editor.on("nodechange ResizeEditor ResizeWindow ResizeContent drop FullscreenStateChanged", throttledUpdateResizeRect);
          editor.on("keyup compositionend", function(e) {
            if (selectedElm && selectedElm.nodeName === "TABLE") {
              throttledUpdateResizeRect(e);
            }
          });
          editor.on("hide blur", hideResizeRect);
          editor.on("contextmenu longpress", contextMenuSelectImage, true);
        });
        editor.on("remove", unbindResizeHandleEvents);
        var destroy2 = function() {
          selectedElm = selectedElmGhost = resizeBackdrop = null;
        };
        return {
          isResizable,
          showResizeRect,
          hideResizeRect,
          updateResizeRect,
          destroy: destroy2
        };
      };
      var hasCeProperty = function(node) {
        return isContentEditableTrue$4(node) || isContentEditableFalse$b(node);
      };
      var findParent$1 = function(node, rootNode, predicate) {
        while (node && node !== rootNode) {
          if (predicate(node)) {
            return node;
          }
          node = node.parentNode;
        }
        return null;
      };
      var findClosestIeRange = function(clientX, clientY, doc2) {
        var rects;
        var element = doc2.elementFromPoint(clientX, clientY);
        var rng = doc2.body.createTextRange();
        if (!element || element.tagName === "HTML") {
          element = doc2.body;
        }
        rng.moveToElementText(element);
        rects = Tools.toArray(rng.getClientRects());
        rects = rects.sort(function(a, b) {
          a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
          b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
          return a - b;
        });
        if (rects.length > 0) {
          clientY = (rects[0].bottom + rects[0].top) / 2;
          try {
            rng.moveToPoint(clientX, clientY);
            rng.collapse(true);
            return rng;
          } catch (ex) {
          }
        }
        return null;
      };
      var moveOutOfContentEditableFalse = function(rng, rootNode) {
        var parentElement = rng && rng.parentElement ? rng.parentElement() : null;
        return isContentEditableFalse$b(findParent$1(parentElement, rootNode, hasCeProperty)) ? null : rng;
      };
      var fromPoint = function(clientX, clientY, doc2) {
        var rng, point;
        var pointDoc = doc2;
        if (pointDoc.caretPositionFromPoint) {
          point = pointDoc.caretPositionFromPoint(clientX, clientY);
          if (point) {
            rng = doc2.createRange();
            rng.setStart(point.offsetNode, point.offset);
            rng.collapse(true);
          }
        } else if (pointDoc.caretRangeFromPoint) {
          rng = pointDoc.caretRangeFromPoint(clientX, clientY);
        } else if (pointDoc.body.createTextRange) {
          rng = pointDoc.body.createTextRange();
          try {
            rng.moveToPoint(clientX, clientY);
            rng.collapse(true);
          } catch (ex) {
            rng = findClosestIeRange(clientX, clientY, doc2);
          }
          return moveOutOfContentEditableFalse(rng, doc2.body);
        }
        return rng;
      };
      var isEq$4 = function(rng1, rng2) {
        return rng1 && rng2 && (rng1.startContainer === rng2.startContainer && rng1.startOffset === rng2.startOffset) && (rng1.endContainer === rng2.endContainer && rng1.endOffset === rng2.endOffset);
      };
      var findParent = function(node, rootNode, predicate) {
        while (node && node !== rootNode) {
          if (predicate(node)) {
            return node;
          }
          node = node.parentNode;
        }
        return null;
      };
      var hasParent$1 = function(node, rootNode, predicate) {
        return findParent(node, rootNode, predicate) !== null;
      };
      var hasParentWithName = function(node, rootNode, name2) {
        return hasParent$1(node, rootNode, function(node2) {
          return node2.nodeName === name2;
        });
      };
      var isTable = function(node) {
        return node && node.nodeName === "TABLE";
      };
      var isTableCell$2 = function(node) {
        return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
      };
      var isCeFalseCaretContainer = function(node, rootNode) {
        return isCaretContainer$2(node) && hasParent$1(node, rootNode, isCaretNode) === false;
      };
      var hasBrBeforeAfter = function(dom2, node, left) {
        var walker = new DomTreeWalker(node, dom2.getParent(node.parentNode, dom2.isBlock) || dom2.getRoot());
        while (node = walker[left ? "prev" : "next"]()) {
          if (isBr$5(node)) {
            return true;
          }
        }
      };
      var isPrevNode = function(node, name2) {
        return node.previousSibling && node.previousSibling.nodeName === name2;
      };
      var hasContentEditableFalseParent = function(body, node) {
        while (node && node !== body) {
          if (isContentEditableFalse$b(node)) {
            return true;
          }
          node = node.parentNode;
        }
        return false;
      };
      var findTextNodeRelative = function(dom2, isAfterNode, collapsed, left, startNode) {
        var lastInlineElement;
        var body = dom2.getRoot();
        var node;
        var nonEmptyElementsMap = dom2.schema.getNonEmptyElements();
        var parentBlockContainer = dom2.getParent(startNode.parentNode, dom2.isBlock) || body;
        if (left && isBr$5(startNode) && isAfterNode && dom2.isEmpty(parentBlockContainer)) {
          return Optional.some(CaretPosition(startNode.parentNode, dom2.nodeIndex(startNode)));
        }
        var walker = new DomTreeWalker(startNode, parentBlockContainer);
        while (node = walker[left ? "prev" : "next"]()) {
          if (dom2.getContentEditableParent(node) === "false" || isCeFalseCaretContainer(node, body)) {
            return Optional.none();
          }
          if (isText$7(node) && node.nodeValue.length > 0) {
            if (hasParentWithName(node, body, "A") === false) {
              return Optional.some(CaretPosition(node, left ? node.nodeValue.length : 0));
            }
            return Optional.none();
          }
          if (dom2.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
            return Optional.none();
          }
          lastInlineElement = node;
        }
        if (collapsed && lastInlineElement) {
          return Optional.some(CaretPosition(lastInlineElement, 0));
        }
        return Optional.none();
      };
      var normalizeEndPoint = function(dom2, collapsed, start2, rng) {
        var container, offset;
        var body = dom2.getRoot();
        var node;
        var directionLeft, normalized = false;
        container = rng[(start2 ? "start" : "end") + "Container"];
        offset = rng[(start2 ? "start" : "end") + "Offset"];
        var isAfterNode = isElement$5(container) && offset === container.childNodes.length;
        var nonEmptyElementsMap = dom2.schema.getNonEmptyElements();
        directionLeft = start2;
        if (isCaretContainer$2(container)) {
          return Optional.none();
        }
        if (isElement$5(container) && offset > container.childNodes.length - 1) {
          directionLeft = false;
        }
        if (isDocument$1(container)) {
          container = body;
          offset = 0;
        }
        if (container === body) {
          if (directionLeft) {
            node = container.childNodes[offset > 0 ? offset - 1 : 0];
            if (node) {
              if (isCaretContainer$2(node)) {
                return Optional.none();
              }
              if (nonEmptyElementsMap[node.nodeName] || isTable(node)) {
                return Optional.none();
              }
            }
          }
          if (container.hasChildNodes()) {
            offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
            container = container.childNodes[offset];
            offset = isText$7(container) && isAfterNode ? container.data.length : 0;
            if (!collapsed && container === body.lastChild && isTable(container)) {
              return Optional.none();
            }
            if (hasContentEditableFalseParent(body, container) || isCaretContainer$2(container)) {
              return Optional.none();
            }
            if (container.hasChildNodes() && isTable(container) === false) {
              node = container;
              var walker = new DomTreeWalker(container, body);
              do {
                if (isContentEditableFalse$b(node) || isCaretContainer$2(node)) {
                  normalized = false;
                  break;
                }
                if (isText$7(node) && node.nodeValue.length > 0) {
                  offset = directionLeft ? 0 : node.nodeValue.length;
                  container = node;
                  normalized = true;
                  break;
                }
                if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell$2(node)) {
                  offset = dom2.nodeIndex(node);
                  container = node.parentNode;
                  if (!directionLeft) {
                    offset++;
                  }
                  normalized = true;
                  break;
                }
              } while (node = directionLeft ? walker.next() : walker.prev());
            }
          }
        }
        if (collapsed) {
          if (isText$7(container) && offset === 0) {
            findTextNodeRelative(dom2, isAfterNode, collapsed, true, container).each(function(pos) {
              container = pos.container();
              offset = pos.offset();
              normalized = true;
            });
          }
          if (isElement$5(container)) {
            node = container.childNodes[offset];
            if (!node) {
              node = container.childNodes[offset - 1];
            }
            if (node && isBr$5(node) && !isPrevNode(node, "A") && !hasBrBeforeAfter(dom2, node, false) && !hasBrBeforeAfter(dom2, node, true)) {
              findTextNodeRelative(dom2, isAfterNode, collapsed, true, node).each(function(pos) {
                container = pos.container();
                offset = pos.offset();
                normalized = true;
              });
            }
          }
        }
        if (directionLeft && !collapsed && isText$7(container) && offset === container.nodeValue.length) {
          findTextNodeRelative(dom2, isAfterNode, collapsed, false, container).each(function(pos) {
            container = pos.container();
            offset = pos.offset();
            normalized = true;
          });
        }
        return normalized ? Optional.some(CaretPosition(container, offset)) : Optional.none();
      };
      var normalize$2 = function(dom2, rng) {
        var collapsed = rng.collapsed, normRng = rng.cloneRange();
        var startPos = CaretPosition.fromRangeStart(rng);
        normalizeEndPoint(dom2, collapsed, true, normRng).each(function(pos) {
          if (!collapsed || !CaretPosition.isAbove(startPos, pos)) {
            normRng.setStart(pos.container(), pos.offset());
          }
        });
        if (!collapsed) {
          normalizeEndPoint(dom2, collapsed, false, normRng).each(function(pos) {
            normRng.setEnd(pos.container(), pos.offset());
          });
        }
        if (collapsed) {
          normRng.collapse(true);
        }
        return isEq$4(rng, normRng) ? Optional.none() : Optional.some(normRng);
      };
      var splitText = function(node, offset) {
        return node.splitText(offset);
      };
      var split = function(rng) {
        var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset;
        if (startContainer === endContainer && isText$7(startContainer)) {
          if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
            endContainer = splitText(startContainer, startOffset);
            startContainer = endContainer.previousSibling;
            if (endOffset > startOffset) {
              endOffset = endOffset - startOffset;
              startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
              endOffset = endContainer.nodeValue.length;
              startOffset = 0;
            } else {
              endOffset = 0;
            }
          }
        } else {
          if (isText$7(startContainer) && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
            startContainer = splitText(startContainer, startOffset);
            startOffset = 0;
          }
          if (isText$7(endContainer) && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
            endContainer = splitText(endContainer, endOffset).previousSibling;
            endOffset = endContainer.nodeValue.length;
          }
        }
        return {
          startContainer,
          startOffset,
          endContainer,
          endOffset
        };
      };
      var RangeUtils = function(dom2) {
        var walk2 = function(rng, callback) {
          return walk$2(dom2, rng, callback);
        };
        var split$12 = split;
        var normalize2 = function(rng) {
          return normalize$2(dom2, rng).fold(never, function(normalizedRng) {
            rng.setStart(normalizedRng.startContainer, normalizedRng.startOffset);
            rng.setEnd(normalizedRng.endContainer, normalizedRng.endOffset);
            return true;
          });
        };
        return {
          walk: walk2,
          split: split$12,
          normalize: normalize2
        };
      };
      RangeUtils.compareRanges = isEq$4;
      RangeUtils.getCaretRangeFromPoint = fromPoint;
      RangeUtils.getSelectedNode = getSelectedNode;
      RangeUtils.getNode = getNode$1;
      var Dimension = function(name2, getOffset) {
        var set2 = function(element, h) {
          if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
            throw new Error(name2 + ".set accepts only positive integer values. Value was " + h);
          }
          var dom2 = element.dom;
          if (isSupported(dom2)) {
            dom2.style[name2] = h + "px";
          }
        };
        var get2 = function(element) {
          var r2 = getOffset(element);
          if (r2 <= 0 || r2 === null) {
            var css = get$5(element, name2);
            return parseFloat(css) || 0;
          }
          return r2;
        };
        var getOuter = get2;
        var aggregate = function(element, properties) {
          return foldl(properties, function(acc, property) {
            var val = get$5(element, property);
            var value2 = val === void 0 ? 0 : parseInt(val, 10);
            return isNaN(value2) ? acc : acc + value2;
          }, 0);
        };
        var max2 = function(element, value2, properties) {
          var cumulativeInclusions = aggregate(element, properties);
          var absoluteMax = value2 > cumulativeInclusions ? value2 - cumulativeInclusions : 0;
          return absoluteMax;
        };
        return {
          set: set2,
          get: get2,
          getOuter,
          aggregate,
          max: max2
        };
      };
      var api = Dimension("height", function(element) {
        var dom2 = element.dom;
        return inBody(element) ? dom2.getBoundingClientRect().height : dom2.offsetHeight;
      });
      var get$1 = function(element) {
        return api.get(element);
      };
      var walkUp = function(navigation, doc2) {
        var frame = navigation.view(doc2);
        return frame.fold(constant([]), function(f) {
          var parent2 = navigation.owner(f);
          var rest = walkUp(navigation, parent2);
          return [f].concat(rest);
        });
      };
      var pathTo = function(element, navigation) {
        var d = navigation.owner(element);
        return walkUp(navigation, d);
      };
      var view = function(doc2) {
        var _a;
        var element = doc2.dom === document ? Optional.none() : Optional.from((_a = doc2.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
        return element.map(SugarElement.fromDom);
      };
      var owner = function(element) {
        return documentOrOwner(element);
      };
      var Navigation = Object.freeze({
        __proto__: null,
        view,
        owner
      });
      var find$1 = function(element) {
        var doc2 = SugarElement.fromDom(document);
        var scroll = get$8(doc2);
        var frames = pathTo(element, Navigation);
        var offset = viewport(element);
        var r2 = foldr(frames, function(b, a) {
          var loc = viewport(a);
          return {
            left: b.left + loc.left,
            top: b.top + loc.top
          };
        }, {
          left: 0,
          top: 0
        });
        return SugarPosition(r2.left + offset.left + scroll.left, r2.top + offset.top + scroll.top);
      };
      var excludeFromDescend = function(element) {
        return name(element) === "textarea";
      };
      var fireScrollIntoViewEvent = function(editor, data2) {
        var scrollEvent = editor.fire("ScrollIntoView", data2);
        return scrollEvent.isDefaultPrevented();
      };
      var fireAfterScrollIntoViewEvent = function(editor, data2) {
        editor.fire("AfterScrollIntoView", data2);
      };
      var descend = function(element, offset) {
        var children$1 = children(element);
        if (children$1.length === 0 || excludeFromDescend(element)) {
          return {
            element,
            offset
          };
        } else if (offset < children$1.length && !excludeFromDescend(children$1[offset])) {
          return {
            element: children$1[offset],
            offset: 0
          };
        } else {
          var last2 = children$1[children$1.length - 1];
          if (excludeFromDescend(last2)) {
            return {
              element,
              offset
            };
          } else {
            if (name(last2) === "img") {
              return {
                element: last2,
                offset: 1
              };
            } else if (isText$8(last2)) {
              return {
                element: last2,
                offset: get$2(last2).length
              };
            } else {
              return {
                element: last2,
                offset: children(last2).length
              };
            }
          }
        }
      };
      var markerInfo = function(element, cleanupFun) {
        var pos = absolute(element);
        var height = get$1(element);
        return {
          element,
          bottom: pos.top + height,
          height,
          pos,
          cleanup: cleanupFun
        };
      };
      var createMarker = function(element, offset) {
        var startPoint = descend(element, offset);
        var span = SugarElement.fromHtml('<span data-mce-bogus="all" style="display: inline-block;">' + ZWSP$1 + "</span>");
        before$4(startPoint.element, span);
        return markerInfo(span, function() {
          return remove$7(span);
        });
      };
      var elementMarker = function(element) {
        return markerInfo(SugarElement.fromDom(element), noop);
      };
      var withMarker = function(editor, f, rng, alignToTop) {
        preserveWith(editor, function(_s, _e) {
          return applyWithMarker(editor, f, rng, alignToTop);
        }, rng);
      };
      var withScrollEvents = function(editor, doc2, f, marker, alignToTop) {
        var data2 = {
          elm: marker.element.dom,
          alignToTop
        };
        if (fireScrollIntoViewEvent(editor, data2)) {
          return;
        }
        var scrollTop = get$8(doc2).top;
        f(doc2, scrollTop, marker, alignToTop);
        fireAfterScrollIntoViewEvent(editor, data2);
      };
      var applyWithMarker = function(editor, f, rng, alignToTop) {
        var body = SugarElement.fromDom(editor.getBody());
        var doc2 = SugarElement.fromDom(editor.getDoc());
        reflow(body);
        var marker = createMarker(SugarElement.fromDom(rng.startContainer), rng.startOffset);
        withScrollEvents(editor, doc2, f, marker, alignToTop);
        marker.cleanup();
      };
      var withElement = function(editor, element, f, alignToTop) {
        var doc2 = SugarElement.fromDom(editor.getDoc());
        withScrollEvents(editor, doc2, f, elementMarker(element), alignToTop);
      };
      var preserveWith = function(editor, f, rng) {
        var startElement = rng.startContainer;
        var startOffset = rng.startOffset;
        var endElement = rng.endContainer;
        var endOffset = rng.endOffset;
        f(SugarElement.fromDom(startElement), SugarElement.fromDom(endElement));
        var newRng = editor.dom.createRng();
        newRng.setStart(startElement, startOffset);
        newRng.setEnd(endElement, endOffset);
        editor.selection.setRng(rng);
      };
      var scrollToMarker = function(marker, viewHeight, alignToTop, doc2) {
        var pos = marker.pos;
        if (alignToTop) {
          to(pos.left, pos.top, doc2);
        } else {
          var y = pos.top - viewHeight + marker.height;
          to(pos.left, y, doc2);
        }
      };
      var intoWindowIfNeeded = function(doc2, scrollTop, viewHeight, marker, alignToTop) {
        var viewportBottom = viewHeight + scrollTop;
        var markerTop = marker.pos.top;
        var markerBottom = marker.bottom;
        var largerThanViewport = markerBottom - markerTop >= viewHeight;
        if (markerTop < scrollTop) {
          scrollToMarker(marker, viewHeight, alignToTop !== false, doc2);
        } else if (markerTop > viewportBottom) {
          var align = largerThanViewport ? alignToTop !== false : alignToTop === true;
          scrollToMarker(marker, viewHeight, align, doc2);
        } else if (markerBottom > viewportBottom && !largerThanViewport) {
          scrollToMarker(marker, viewHeight, alignToTop === true, doc2);
        }
      };
      var intoWindow = function(doc2, scrollTop, marker, alignToTop) {
        var viewHeight = doc2.dom.defaultView.innerHeight;
        intoWindowIfNeeded(doc2, scrollTop, viewHeight, marker, alignToTop);
      };
      var intoFrame = function(doc2, scrollTop, marker, alignToTop) {
        var frameViewHeight = doc2.dom.defaultView.innerHeight;
        intoWindowIfNeeded(doc2, scrollTop, frameViewHeight, marker, alignToTop);
        var op = find$1(marker.element);
        var viewportBounds = getBounds(window);
        if (op.top < viewportBounds.y) {
          intoView(marker.element, alignToTop !== false);
        } else if (op.top > viewportBounds.bottom) {
          intoView(marker.element, alignToTop === true);
        }
      };
      var rangeIntoWindow = function(editor, rng, alignToTop) {
        return withMarker(editor, intoWindow, rng, alignToTop);
      };
      var elementIntoWindow = function(editor, element, alignToTop) {
        return withElement(editor, element, intoWindow, alignToTop);
      };
      var rangeIntoFrame = function(editor, rng, alignToTop) {
        return withMarker(editor, intoFrame, rng, alignToTop);
      };
      var elementIntoFrame = function(editor, element, alignToTop) {
        return withElement(editor, element, intoFrame, alignToTop);
      };
      var scrollElementIntoView = function(editor, element, alignToTop) {
        var scroller = editor.inline ? elementIntoWindow : elementIntoFrame;
        scroller(editor, element, alignToTop);
      };
      var scrollRangeIntoView = function(editor, rng, alignToTop) {
        var scroller = editor.inline ? rangeIntoWindow : rangeIntoFrame;
        scroller(editor, rng, alignToTop);
      };
      var getDocument = function() {
        return SugarElement.fromDom(document);
      };
      var focus$1 = function(element) {
        return element.dom.focus();
      };
      var hasFocus$1 = function(element) {
        var root = getRootNode(element).dom;
        return element.dom === root.activeElement;
      };
      var active = function(root) {
        if (root === void 0) {
          root = getDocument();
        }
        return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
      };
      var search = function(element) {
        return active(getRootNode(element)).filter(function(e) {
          return element.dom.contains(e.dom);
        });
      };
      var create$5 = function(start2, soffset, finish, foffset) {
        return {
          start: start2,
          soffset,
          finish,
          foffset
        };
      };
      var SimRange = { create: create$5 };
      var adt$1 = Adt.generate([
        { before: ["element"] },
        {
          on: [
            "element",
            "offset"
          ]
        },
        { after: ["element"] }
      ]);
      var cata = function(subject, onBefore, onOn, onAfter) {
        return subject.fold(onBefore, onOn, onAfter);
      };
      var getStart$2 = function(situ) {
        return situ.fold(identity, identity, identity);
      };
      var before$1 = adt$1.before;
      var on = adt$1.on;
      var after$1 = adt$1.after;
      var Situ = {
        before: before$1,
        on,
        after: after$1,
        cata,
        getStart: getStart$2
      };
      var adt = Adt.generate([
        { domRange: ["rng"] },
        {
          relative: [
            "startSitu",
            "finishSitu"
          ]
        },
        {
          exact: [
            "start",
            "soffset",
            "finish",
            "foffset"
          ]
        }
      ]);
      var exactFromRange = function(simRange) {
        return adt.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
      };
      var getStart$1 = function(selection) {
        return selection.match({
          domRange: function(rng) {
            return SugarElement.fromDom(rng.startContainer);
          },
          relative: function(startSitu, _finishSitu) {
            return Situ.getStart(startSitu);
          },
          exact: function(start2, _soffset, _finish, _foffset) {
            return start2;
          }
        });
      };
      var domRange = adt.domRange;
      var relative = adt.relative;
      var exact = adt.exact;
      var getWin = function(selection) {
        var start2 = getStart$1(selection);
        return defaultView(start2);
      };
      var range = SimRange.create;
      var SimSelection = {
        domRange,
        relative,
        exact,
        exactFromRange,
        getWin,
        range
      };
      var browser$1 = detect().browser;
      var clamp$1 = function(offset, element) {
        var max2 = isText$8(element) ? get$2(element).length : children(element).length + 1;
        if (offset > max2) {
          return max2;
        } else if (offset < 0) {
          return 0;
        }
        return offset;
      };
      var normalizeRng = function(rng) {
        return SimSelection.range(rng.start, clamp$1(rng.soffset, rng.start), rng.finish, clamp$1(rng.foffset, rng.finish));
      };
      var isOrContains = function(root, elm) {
        return !isRestrictedNode(elm.dom) && (contains$1(root, elm) || eq(root, elm));
      };
      var isRngInRoot = function(root) {
        return function(rng) {
          return isOrContains(root, rng.start) && isOrContains(root, rng.finish);
        };
      };
      var shouldStore = function(editor) {
        return editor.inline === true || browser$1.isIE();
      };
      var nativeRangeToSelectionRange = function(r2) {
        return SimSelection.range(SugarElement.fromDom(r2.startContainer), r2.startOffset, SugarElement.fromDom(r2.endContainer), r2.endOffset);
      };
      var readRange = function(win) {
        var selection = win.getSelection();
        var rng = !selection || selection.rangeCount === 0 ? Optional.none() : Optional.from(selection.getRangeAt(0));
        return rng.map(nativeRangeToSelectionRange);
      };
      var getBookmark = function(root) {
        var win = defaultView(root);
        return readRange(win.dom).filter(isRngInRoot(root));
      };
      var validate = function(root, bookmark) {
        return Optional.from(bookmark).filter(isRngInRoot(root)).map(normalizeRng);
      };
      var bookmarkToNativeRng = function(bookmark) {
        var rng = document.createRange();
        try {
          rng.setStart(bookmark.start.dom, bookmark.soffset);
          rng.setEnd(bookmark.finish.dom, bookmark.foffset);
          return Optional.some(rng);
        } catch (_) {
          return Optional.none();
        }
      };
      var store = function(editor) {
        var newBookmark = shouldStore(editor) ? getBookmark(SugarElement.fromDom(editor.getBody())) : Optional.none();
        editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
      };
      var storeNative = function(editor, rng) {
        var root = SugarElement.fromDom(editor.getBody());
        var range2 = shouldStore(editor) ? Optional.from(rng) : Optional.none();
        var newBookmark = range2.map(nativeRangeToSelectionRange).filter(isRngInRoot(root));
        editor.bookmark = newBookmark.isSome() ? newBookmark : editor.bookmark;
      };
      var getRng = function(editor) {
        var bookmark = editor.bookmark ? editor.bookmark : Optional.none();
        return bookmark.bind(function(x) {
          return validate(SugarElement.fromDom(editor.getBody()), x);
        }).bind(bookmarkToNativeRng);
      };
      var restore = function(editor) {
        getRng(editor).each(function(rng) {
          return editor.selection.setRng(rng);
        });
      };
      var isEditorUIElement$1 = function(elm) {
        var className = elm.className.toString();
        return className.indexOf("tox-") !== -1 || className.indexOf("mce-") !== -1;
      };
      var FocusManager = { isEditorUIElement: isEditorUIElement$1 };
      var isManualNodeChange = function(e) {
        return e.type === "nodechange" && e.selectionChange;
      };
      var registerPageMouseUp = function(editor, throttledStore) {
        var mouseUpPage = function() {
          throttledStore.throttle();
        };
        DOMUtils.DOM.bind(document, "mouseup", mouseUpPage);
        editor.on("remove", function() {
          DOMUtils.DOM.unbind(document, "mouseup", mouseUpPage);
        });
      };
      var registerFocusOut = function(editor) {
        editor.on("focusout", function() {
          store(editor);
        });
      };
      var registerMouseUp = function(editor, throttledStore) {
        editor.on("mouseup touchend", function(_e) {
          throttledStore.throttle();
        });
      };
      var registerEditorEvents = function(editor, throttledStore) {
        var browser2 = detect().browser;
        if (browser2.isIE()) {
          registerFocusOut(editor);
        } else {
          registerMouseUp(editor, throttledStore);
        }
        editor.on("keyup NodeChange", function(e) {
          if (!isManualNodeChange(e)) {
            store(editor);
          }
        });
      };
      var register$3 = function(editor) {
        var throttledStore = first(function() {
          store(editor);
        }, 0);
        editor.on("init", function() {
          if (editor.inline) {
            registerPageMouseUp(editor, throttledStore);
          }
          registerEditorEvents(editor, throttledStore);
        });
        editor.on("remove", function() {
          throttledStore.cancel();
        });
      };
      var documentFocusInHandler;
      var DOM$8 = DOMUtils.DOM;
      var isEditorUIElement = function(elm) {
        return FocusManager.isEditorUIElement(elm);
      };
      var isEditorContentAreaElement = function(elm) {
        var classList = elm.classList;
        if (classList !== void 0) {
          return classList.contains("tox-edit-area") || classList.contains("tox-edit-area__iframe") || classList.contains("mce-content-body");
        } else {
          return false;
        }
      };
      var isUIElement = function(editor, elm) {
        var customSelector = getCustomUiSelector(editor);
        var parent2 = DOM$8.getParent(elm, function(elm2) {
          return isEditorUIElement(elm2) || (customSelector ? editor.dom.is(elm2, customSelector) : false);
        });
        return parent2 !== null;
      };
      var getActiveElement = function(editor) {
        try {
          var root = getRootNode(SugarElement.fromDom(editor.getElement()));
          return active(root).fold(function() {
            return document.body;
          }, function(x) {
            return x.dom;
          });
        } catch (ex) {
          return document.body;
        }
      };
      var registerEvents$1 = function(editorManager, e) {
        var editor = e.editor;
        register$3(editor);
        editor.on("focusin", function() {
          var focusedEditor = editorManager.focusedEditor;
          if (focusedEditor !== editor) {
            if (focusedEditor) {
              focusedEditor.fire("blur", { focusedEditor: editor });
            }
            editorManager.setActive(editor);
            editorManager.focusedEditor = editor;
            editor.fire("focus", { blurredEditor: focusedEditor });
            editor.focus(true);
          }
        });
        editor.on("focusout", function() {
          Delay.setEditorTimeout(editor, function() {
            var focusedEditor = editorManager.focusedEditor;
            if (!isUIElement(editor, getActiveElement(editor)) && focusedEditor === editor) {
              editor.fire("blur", { focusedEditor: null });
              editorManager.focusedEditor = null;
            }
          });
        });
        if (!documentFocusInHandler) {
          documentFocusInHandler = function(e2) {
            var activeEditor = editorManager.activeEditor;
            if (activeEditor) {
              getOriginalEventTarget(e2).each(function(target) {
                if (target.ownerDocument === document) {
                  if (target !== document.body && !isUIElement(activeEditor, target) && editorManager.focusedEditor === activeEditor) {
                    activeEditor.fire("blur", { focusedEditor: null });
                    editorManager.focusedEditor = null;
                  }
                }
              });
            }
          };
          DOM$8.bind(document, "focusin", documentFocusInHandler);
        }
      };
      var unregisterDocumentEvents = function(editorManager, e) {
        if (editorManager.focusedEditor === e.editor) {
          editorManager.focusedEditor = null;
        }
        if (!editorManager.activeEditor) {
          DOM$8.unbind(document, "focusin", documentFocusInHandler);
          documentFocusInHandler = null;
        }
      };
      var setup$l = function(editorManager) {
        editorManager.on("AddEditor", curry(registerEvents$1, editorManager));
        editorManager.on("RemoveEditor", curry(unregisterDocumentEvents, editorManager));
      };
      var getContentEditableHost = function(editor, node) {
        return editor.dom.getParent(node, function(node2) {
          return editor.dom.getContentEditable(node2) === "true";
        });
      };
      var getCollapsedNode = function(rng) {
        return rng.collapsed ? Optional.from(getNode$1(rng.startContainer, rng.startOffset)).map(SugarElement.fromDom) : Optional.none();
      };
      var getFocusInElement = function(root, rng) {
        return getCollapsedNode(rng).bind(function(node) {
          if (isTableSection(node)) {
            return Optional.some(node);
          } else if (contains$1(root, node) === false) {
            return Optional.some(root);
          } else {
            return Optional.none();
          }
        });
      };
      var normalizeSelection$1 = function(editor, rng) {
        getFocusInElement(SugarElement.fromDom(editor.getBody()), rng).bind(function(elm) {
          return firstPositionIn(elm.dom);
        }).fold(function() {
          editor.selection.normalize();
          return;
        }, function(caretPos) {
          return editor.selection.setRng(caretPos.toRange());
        });
      };
      var focusBody = function(body) {
        if (body.setActive) {
          try {
            body.setActive();
          } catch (ex) {
            body.focus();
          }
        } else {
          body.focus();
        }
      };
      var hasElementFocus = function(elm) {
        return hasFocus$1(elm) || search(elm).isSome();
      };
      var hasIframeFocus = function(editor) {
        return editor.iframeElement && hasFocus$1(SugarElement.fromDom(editor.iframeElement));
      };
      var hasInlineFocus = function(editor) {
        var rawBody = editor.getBody();
        return rawBody && hasElementFocus(SugarElement.fromDom(rawBody));
      };
      var hasUiFocus = function(editor) {
        var dos = getRootNode(SugarElement.fromDom(editor.getElement()));
        return active(dos).filter(function(elem) {
          return !isEditorContentAreaElement(elem.dom) && isUIElement(editor, elem.dom);
        }).isSome();
      };
      var hasFocus = function(editor) {
        return editor.inline ? hasInlineFocus(editor) : hasIframeFocus(editor);
      };
      var hasEditorOrUiFocus = function(editor) {
        return hasFocus(editor) || hasUiFocus(editor);
      };
      var focusEditor = function(editor) {
        var selection = editor.selection;
        var body = editor.getBody();
        var rng = selection.getRng();
        editor.quirks.refreshContentEditable();
        if (editor.bookmark !== void 0 && hasFocus(editor) === false) {
          getRng(editor).each(function(bookmarkRng) {
            editor.selection.setRng(bookmarkRng);
            rng = bookmarkRng;
          });
        }
        var contentEditableHost = getContentEditableHost(editor, selection.getNode());
        if (editor.$.contains(body, contentEditableHost)) {
          focusBody(contentEditableHost);
          normalizeSelection$1(editor, rng);
          activateEditor(editor);
          return;
        }
        if (!editor.inline) {
          if (!Env.opera) {
            focusBody(body);
          }
          editor.getWin().focus();
        }
        if (Env.gecko || editor.inline) {
          focusBody(body);
          normalizeSelection$1(editor, rng);
        }
        activateEditor(editor);
      };
      var activateEditor = function(editor) {
        return editor.editorManager.setActive(editor);
      };
      var focus = function(editor, skipFocus) {
        if (editor.removed) {
          return;
        }
        if (skipFocus) {
          activateEditor(editor);
        } else {
          focusEditor(editor);
        }
      };
      var getEndpointElement = function(root, rng, start2, real, resolve2) {
        var container = start2 ? rng.startContainer : rng.endContainer;
        var offset = start2 ? rng.startOffset : rng.endOffset;
        return Optional.from(container).map(SugarElement.fromDom).map(function(elm) {
          return !real || !rng.collapsed ? child$1(elm, resolve2(elm, offset)).getOr(elm) : elm;
        }).bind(function(elm) {
          return isElement$6(elm) ? Optional.some(elm) : parent(elm).filter(isElement$6);
        }).map(function(elm) {
          return elm.dom;
        }).getOr(root);
      };
      var getStart = function(root, rng, real) {
        return getEndpointElement(root, rng, true, real, function(elm, offset) {
          return Math.min(childNodesCount(elm), offset);
        });
      };
      var getEnd = function(root, rng, real) {
        return getEndpointElement(root, rng, false, real, function(elm, offset) {
          return offset > 0 ? offset - 1 : offset;
        });
      };
      var skipEmptyTextNodes = function(node, forwards) {
        var orig = node;
        while (node && isText$7(node) && node.length === 0) {
          node = forwards ? node.nextSibling : node.previousSibling;
        }
        return node || orig;
      };
      var getNode = function(root, rng) {
        var elm, startContainer, endContainer;
        if (!rng) {
          return root;
        }
        startContainer = rng.startContainer;
        endContainer = rng.endContainer;
        var startOffset = rng.startOffset;
        var endOffset = rng.endOffset;
        elm = rng.commonAncestorContainer;
        if (!rng.collapsed) {
          if (startContainer === endContainer) {
            if (endOffset - startOffset < 2) {
              if (startContainer.hasChildNodes()) {
                elm = startContainer.childNodes[startOffset];
              }
            }
          }
          if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
            if (startContainer.length === startOffset) {
              startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
            } else {
              startContainer = startContainer.parentNode;
            }
            if (endOffset === 0) {
              endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
            } else {
              endContainer = endContainer.parentNode;
            }
            if (startContainer && startContainer === endContainer) {
              return startContainer;
            }
          }
        }
        if (elm && elm.nodeType === 3) {
          return elm.parentNode;
        }
        return elm;
      };
      var getSelectedBlocks = function(dom2, rng, startElm, endElm) {
        var node;
        var selectedBlocks = [];
        var root = dom2.getRoot();
        startElm = dom2.getParent(startElm || getStart(root, rng, rng.collapsed), dom2.isBlock);
        endElm = dom2.getParent(endElm || getEnd(root, rng, rng.collapsed), dom2.isBlock);
        if (startElm && startElm !== root) {
          selectedBlocks.push(startElm);
        }
        if (startElm && endElm && startElm !== endElm) {
          node = startElm;
          var walker = new DomTreeWalker(startElm, root);
          while ((node = walker.next()) && node !== endElm) {
            if (dom2.isBlock(node)) {
              selectedBlocks.push(node);
            }
          }
        }
        if (endElm && startElm !== endElm && endElm !== root) {
          selectedBlocks.push(endElm);
        }
        return selectedBlocks;
      };
      var select = function(dom2, node, content) {
        return Optional.from(node).map(function(node2) {
          var idx = dom2.nodeIndex(node2);
          var rng = dom2.createRng();
          rng.setStart(node2.parentNode, idx);
          rng.setEnd(node2.parentNode, idx + 1);
          if (content) {
            moveEndPoint(dom2, rng, node2, true);
            moveEndPoint(dom2, rng, node2, false);
          }
          return rng;
        });
      };
      var processRanges = function(editor, ranges) {
        return map$3(ranges, function(range2) {
          var evt = editor.fire("GetSelectionRange", { range: range2 });
          return evt.range !== range2 ? evt.range : range2;
        });
      };
      var typeLookup = {
        "#text": 3,
        "#comment": 8,
        "#cdata": 4,
        "#pi": 7,
        "#doctype": 10,
        "#document-fragment": 11
      };
      var walk$1 = function(node, root, prev) {
        var startName = prev ? "lastChild" : "firstChild";
        var siblingName = prev ? "prev" : "next";
        if (node[startName]) {
          return node[startName];
        }
        if (node !== root) {
          var sibling2 = node[siblingName];
          if (sibling2) {
            return sibling2;
          }
          for (var parent_1 = node.parent; parent_1 && parent_1 !== root; parent_1 = parent_1.parent) {
            sibling2 = parent_1[siblingName];
            if (sibling2) {
              return sibling2;
            }
          }
        }
      };
      var isEmptyTextNode = function(node) {
        if (!isWhitespaceText(node.value)) {
          return false;
        }
        var parentNode = node.parent;
        if (parentNode && (parentNode.name !== "span" || parentNode.attr("style")) && /^[ ]+$/.test(node.value)) {
          return false;
        }
        return true;
      };
      var isNonEmptyElement = function(node) {
        var isNamedAnchor2 = node.name === "a" && !node.attr("href") && node.attr("id");
        return node.attr("name") || node.attr("id") && !node.firstChild || node.attr("data-mce-bookmark") || isNamedAnchor2;
      };
      var AstNode = function() {
        function AstNode2(name2, type2) {
          this.name = name2;
          this.type = type2;
          if (type2 === 1) {
            this.attributes = [];
            this.attributes.map = {};
          }
        }
        AstNode2.create = function(name2, attrs) {
          var node = new AstNode2(name2, typeLookup[name2] || 1);
          if (attrs) {
            each$j(attrs, function(value2, attrName) {
              node.attr(attrName, value2);
            });
          }
          return node;
        };
        AstNode2.prototype.replace = function(node) {
          var self2 = this;
          if (node.parent) {
            node.remove();
          }
          self2.insert(node, self2);
          self2.remove();
          return self2;
        };
        AstNode2.prototype.attr = function(name2, value2) {
          var self2 = this;
          var attrs;
          if (typeof name2 !== "string") {
            if (name2 !== void 0 && name2 !== null) {
              each$j(name2, function(value3, key) {
                self2.attr(key, value3);
              });
            }
            return self2;
          }
          if (attrs = self2.attributes) {
            if (value2 !== void 0) {
              if (value2 === null) {
                if (name2 in attrs.map) {
                  delete attrs.map[name2];
                  var i = attrs.length;
                  while (i--) {
                    if (attrs[i].name === name2) {
                      attrs.splice(i, 1);
                      return self2;
                    }
                  }
                }
                return self2;
              }
              if (name2 in attrs.map) {
                var i = attrs.length;
                while (i--) {
                  if (attrs[i].name === name2) {
                    attrs[i].value = value2;
                    break;
                  }
                }
              } else {
                attrs.push({
                  name: name2,
                  value: value2
                });
              }
              attrs.map[name2] = value2;
              return self2;
            }
            return attrs.map[name2];
          }
        };
        AstNode2.prototype.clone = function() {
          var self2 = this;
          var clone2 = new AstNode2(self2.name, self2.type);
          var selfAttrs;
          if (selfAttrs = self2.attributes) {
            var cloneAttrs = [];
            cloneAttrs.map = {};
            for (var i = 0, l = selfAttrs.length; i < l; i++) {
              var selfAttr = selfAttrs[i];
              if (selfAttr.name !== "id") {
                cloneAttrs[cloneAttrs.length] = {
                  name: selfAttr.name,
                  value: selfAttr.value
                };
                cloneAttrs.map[selfAttr.name] = selfAttr.value;
              }
            }
            clone2.attributes = cloneAttrs;
          }
          clone2.value = self2.value;
          clone2.shortEnded = self2.shortEnded;
          return clone2;
        };
        AstNode2.prototype.wrap = function(wrapper) {
          var self2 = this;
          self2.parent.insert(wrapper, self2);
          wrapper.append(self2);
          return self2;
        };
        AstNode2.prototype.unwrap = function() {
          var self2 = this;
          for (var node = self2.firstChild; node; ) {
            var next = node.next;
            self2.insert(node, self2, true);
            node = next;
          }
          self2.remove();
        };
        AstNode2.prototype.remove = function() {
          var self2 = this, parent2 = self2.parent, next = self2.next, prev = self2.prev;
          if (parent2) {
            if (parent2.firstChild === self2) {
              parent2.firstChild = next;
              if (next) {
                next.prev = null;
              }
            } else {
              prev.next = next;
            }
            if (parent2.lastChild === self2) {
              parent2.lastChild = prev;
              if (prev) {
                prev.next = null;
              }
            } else {
              next.prev = prev;
            }
            self2.parent = self2.next = self2.prev = null;
          }
          return self2;
        };
        AstNode2.prototype.append = function(node) {
          var self2 = this;
          if (node.parent) {
            node.remove();
          }
          var last2 = self2.lastChild;
          if (last2) {
            last2.next = node;
            node.prev = last2;
            self2.lastChild = node;
          } else {
            self2.lastChild = self2.firstChild = node;
          }
          node.parent = self2;
          return node;
        };
        AstNode2.prototype.insert = function(node, refNode, before2) {
          if (node.parent) {
            node.remove();
          }
          var parent2 = refNode.parent || this;
          if (before2) {
            if (refNode === parent2.firstChild) {
              parent2.firstChild = node;
            } else {
              refNode.prev.next = node;
            }
            node.prev = refNode.prev;
            node.next = refNode;
            refNode.prev = node;
          } else {
            if (refNode === parent2.lastChild) {
              parent2.lastChild = node;
            } else {
              refNode.next.prev = node;
            }
            node.next = refNode.next;
            node.prev = refNode;
            refNode.next = node;
          }
          node.parent = parent2;
          return node;
        };
        AstNode2.prototype.getAll = function(name2) {
          var self2 = this;
          var collection = [];
          for (var node = self2.firstChild; node; node = walk$1(node, self2)) {
            if (node.name === name2) {
              collection.push(node);
            }
          }
          return collection;
        };
        AstNode2.prototype.children = function() {
          var self2 = this;
          var collection = [];
          for (var node = self2.firstChild; node; node = node.next) {
            collection.push(node);
          }
          return collection;
        };
        AstNode2.prototype.empty = function() {
          var self2 = this;
          if (self2.firstChild) {
            var nodes = [];
            for (var node = self2.firstChild; node; node = walk$1(node, self2)) {
              nodes.push(node);
            }
            var i = nodes.length;
            while (i--) {
              var node = nodes[i];
              node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
            }
          }
          self2.firstChild = self2.lastChild = null;
          return self2;
        };
        AstNode2.prototype.isEmpty = function(elements, whitespace2, predicate) {
          if (whitespace2 === void 0) {
            whitespace2 = {};
          }
          var self2 = this;
          var node = self2.firstChild;
          if (isNonEmptyElement(self2)) {
            return false;
          }
          if (node) {
            do {
              if (node.type === 1) {
                if (node.attr("data-mce-bogus")) {
                  continue;
                }
                if (elements[node.name]) {
                  return false;
                }
                if (isNonEmptyElement(node)) {
                  return false;
                }
              }
              if (node.type === 8) {
                return false;
              }
              if (node.type === 3 && !isEmptyTextNode(node)) {
                return false;
              }
              if (node.type === 3 && node.parent && whitespace2[node.parent.name] && isWhitespaceText(node.value)) {
                return false;
              }
              if (predicate && predicate(node)) {
                return false;
              }
            } while (node = walk$1(node, self2));
          }
          return true;
        };
        AstNode2.prototype.walk = function(prev) {
          return walk$1(this, null, prev);
        };
        return AstNode2;
      }();
      var extractBase64DataUris = function(html) {
        var dataImageUri = /data:[^;<"'\s]+;base64,([a-z0-9\+\/=\s]+)/gi;
        var chunks = [];
        var uris = {};
        var prefix = generate("img");
        var matches2;
        var index = 0;
        var count2 = 0;
        while (matches2 = dataImageUri.exec(html)) {
          var uri = matches2[0];
          var imageId = prefix + "_" + count2++;
          uris[imageId] = uri;
          if (index < matches2.index) {
            chunks.push(html.substr(index, matches2.index - index));
          }
          chunks.push(imageId);
          index = matches2.index + uri.length;
        }
        var re = new RegExp(prefix + "_[0-9]+", "g");
        if (index === 0) {
          return {
            prefix,
            uris,
            html,
            re
          };
        } else {
          if (index < html.length) {
            chunks.push(html.substr(index));
          }
          return {
            prefix,
            uris,
            html: chunks.join(""),
            re
          };
        }
      };
      var restoreDataUris = function(html, result) {
        return html.replace(result.re, function(imageId) {
          return get$9(result.uris, imageId).getOr(imageId);
        });
      };
      var parseDataUri$1 = function(uri) {
        var matches2 = /data:([^;]+);base64,([a-z0-9\+\/=\s]+)/i.exec(uri);
        if (matches2) {
          return Optional.some({
            type: matches2[1],
            data: decodeURIComponent(matches2[2])
          });
        } else {
          return Optional.none();
        }
      };
      var each$d = Tools.each, trim = Tools.trim;
      var queryParts = "source protocol authority userInfo user password host port relative path directory file query anchor".split(" ");
      var DEFAULT_PORTS = {
        ftp: 21,
        http: 80,
        https: 443,
        mailto: 25
      };
      var safeSvgDataUrlElements = [
        "img",
        "video"
      ];
      var blockSvgDataUris = function(allowSvgDataUrls, tagName) {
        if (isNonNullable(allowSvgDataUrls)) {
          return !allowSvgDataUrls;
        } else {
          return isNonNullable(tagName) ? !contains$3(safeSvgDataUrlElements, tagName) : true;
        }
      };
      var isInvalidUri = function(settings, uri, tagName) {
        if (settings.allow_html_data_urls) {
          return false;
        } else if (/^data:image\//i.test(uri)) {
          return blockSvgDataUris(settings.allow_svg_data_urls, tagName) && /^data:image\/svg\+xml/i.test(uri);
        } else {
          return /^data:/i.test(uri);
        }
      };
      var URI = function() {
        function URI2(url, settings) {
          url = trim(url);
          this.settings = settings || {};
          var baseUri = this.settings.base_uri;
          var self2 = this;
          if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
            self2.source = url;
            return;
          }
          var isProtocolRelative = url.indexOf("//") === 0;
          if (url.indexOf("/") === 0 && !isProtocolRelative) {
            url = (baseUri ? baseUri.protocol || "http" : "http") + "://mce_host" + url;
          }
          if (!/^[\w\-]*:?\/\//.test(url)) {
            var baseUrl = this.settings.base_uri ? this.settings.base_uri.path : new URI2(document.location.href).directory;
            if (this.settings.base_uri && this.settings.base_uri.protocol == "") {
              url = "//mce_host" + self2.toAbsPath(baseUrl, url);
            } else {
              var match2 = /([^#?]*)([#?]?.*)/.exec(url);
              url = (baseUri && baseUri.protocol || "http") + "://mce_host" + self2.toAbsPath(baseUrl, match2[1]) + match2[2];
            }
          }
          url = url.replace(/@@/g, "(mce_at)");
          var urlMatch = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?(\[[a-zA-Z0-9:.%]+\]|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
          each$d(queryParts, function(v, i) {
            var part = urlMatch[i];
            if (part) {
              part = part.replace(/\(mce_at\)/g, "@@");
            }
            self2[v] = part;
          });
          if (baseUri) {
            if (!self2.protocol) {
              self2.protocol = baseUri.protocol;
            }
            if (!self2.userInfo) {
              self2.userInfo = baseUri.userInfo;
            }
            if (!self2.port && self2.host === "mce_host") {
              self2.port = baseUri.port;
            }
            if (!self2.host || self2.host === "mce_host") {
              self2.host = baseUri.host;
            }
            self2.source = "";
          }
          if (isProtocolRelative) {
            self2.protocol = "";
          }
        }
        URI2.parseDataUri = function(uri) {
          var type2;
          var uriComponents = decodeURIComponent(uri).split(",");
          var matches2 = /data:([^;]+)/.exec(uriComponents[0]);
          if (matches2) {
            type2 = matches2[1];
          }
          return {
            type: type2,
            data: uriComponents[1]
          };
        };
        URI2.isDomSafe = function(uri, context2, options) {
          if (options === void 0) {
            options = {};
          }
          if (options.allow_script_urls) {
            return true;
          } else {
            var decodedUri = Entities.decode(uri).replace(/[\s\u0000-\u001F]+/g, "");
            try {
              decodedUri = decodeURIComponent(decodedUri);
            } catch (ex) {
              decodedUri = unescape(decodedUri);
            }
            if (/((java|vb)script|mhtml):/i.test(decodedUri)) {
              return false;
            }
            return !isInvalidUri(options, decodedUri, context2);
          }
        };
        URI2.getDocumentBaseUrl = function(loc) {
          var baseUrl;
          if (loc.protocol.indexOf("http") !== 0 && loc.protocol !== "file:") {
            baseUrl = loc.href;
          } else {
            baseUrl = loc.protocol + "//" + loc.host + loc.pathname;
          }
          if (/^[^:]+:\/\/\/?[^\/]+\//.test(baseUrl)) {
            baseUrl = baseUrl.replace(/[\?#].*$/, "").replace(/[\/\\][^\/]+$/, "");
            if (!/[\/\\]$/.test(baseUrl)) {
              baseUrl += "/";
            }
          }
          return baseUrl;
        };
        URI2.prototype.setPath = function(path) {
          var pathMatch = /^(.*?)\/?(\w+)?$/.exec(path);
          this.path = pathMatch[0];
          this.directory = pathMatch[1];
          this.file = pathMatch[2];
          this.source = "";
          this.getURI();
        };
        URI2.prototype.toRelative = function(uri) {
          var output;
          if (uri === "./") {
            return uri;
          }
          var relativeUri = new URI2(uri, { base_uri: this });
          if (relativeUri.host !== "mce_host" && this.host !== relativeUri.host && relativeUri.host || this.port !== relativeUri.port || this.protocol !== relativeUri.protocol && relativeUri.protocol !== "") {
            return relativeUri.getURI();
          }
          var tu = this.getURI(), uu = relativeUri.getURI();
          if (tu === uu || tu.charAt(tu.length - 1) === "/" && tu.substr(0, tu.length - 1) === uu) {
            return tu;
          }
          output = this.toRelPath(this.path, relativeUri.path);
          if (relativeUri.query) {
            output += "?" + relativeUri.query;
          }
          if (relativeUri.anchor) {
            output += "#" + relativeUri.anchor;
          }
          return output;
        };
        URI2.prototype.toAbsolute = function(uri, noHost) {
          var absoluteUri = new URI2(uri, { base_uri: this });
          return absoluteUri.getURI(noHost && this.isSameOrigin(absoluteUri));
        };
        URI2.prototype.isSameOrigin = function(uri) {
          if (this.host == uri.host && this.protocol == uri.protocol) {
            if (this.port == uri.port) {
              return true;
            }
            var defaultPort = DEFAULT_PORTS[this.protocol];
            if (defaultPort && (this.port || defaultPort) == (uri.port || defaultPort)) {
              return true;
            }
          }
          return false;
        };
        URI2.prototype.toRelPath = function(base, path) {
          var breakPoint = 0, out = "", i, l;
          var normalizedBase = base.substring(0, base.lastIndexOf("/")).split("/");
          var items = path.split("/");
          if (normalizedBase.length >= items.length) {
            for (i = 0, l = normalizedBase.length; i < l; i++) {
              if (i >= items.length || normalizedBase[i] !== items[i]) {
                breakPoint = i + 1;
                break;
              }
            }
          }
          if (normalizedBase.length < items.length) {
            for (i = 0, l = items.length; i < l; i++) {
              if (i >= normalizedBase.length || normalizedBase[i] !== items[i]) {
                breakPoint = i + 1;
                break;
              }
            }
          }
          if (breakPoint === 1) {
            return path;
          }
          for (i = 0, l = normalizedBase.length - (breakPoint - 1); i < l; i++) {
            out += "../";
          }
          for (i = breakPoint - 1, l = items.length; i < l; i++) {
            if (i !== breakPoint - 1) {
              out += "/" + items[i];
            } else {
              out += items[i];
            }
          }
          return out;
        };
        URI2.prototype.toAbsPath = function(base, path) {
          var i, nb = 0, o = [], outPath;
          var tr = /\/$/.test(path) ? "/" : "";
          var normalizedBase = base.split("/");
          var normalizedPath = path.split("/");
          each$d(normalizedBase, function(k) {
            if (k) {
              o.push(k);
            }
          });
          normalizedBase = o;
          for (i = normalizedPath.length - 1, o = []; i >= 0; i--) {
            if (normalizedPath[i].length === 0 || normalizedPath[i] === ".") {
              continue;
            }
            if (normalizedPath[i] === "..") {
              nb++;
              continue;
            }
            if (nb > 0) {
              nb--;
              continue;
            }
            o.push(normalizedPath[i]);
          }
          i = normalizedBase.length - nb;
          if (i <= 0) {
            outPath = reverse(o).join("/");
          } else {
            outPath = normalizedBase.slice(0, i).join("/") + "/" + reverse(o).join("/");
          }
          if (outPath.indexOf("/") !== 0) {
            outPath = "/" + outPath;
          }
          if (tr && outPath.lastIndexOf("/") !== outPath.length - 1) {
            outPath += tr;
          }
          return outPath;
        };
        URI2.prototype.getURI = function(noProtoHost) {
          if (noProtoHost === void 0) {
            noProtoHost = false;
          }
          var s;
          if (!this.source || noProtoHost) {
            s = "";
            if (!noProtoHost) {
              if (this.protocol) {
                s += this.protocol + "://";
              } else {
                s += "//";
              }
              if (this.userInfo) {
                s += this.userInfo + "@";
              }
              if (this.host) {
                s += this.host;
              }
              if (this.port) {
                s += ":" + this.port;
              }
            }
            if (this.path) {
              s += this.path;
            }
            if (this.query) {
              s += "?" + this.query;
            }
            if (this.anchor) {
              s += "#" + this.anchor;
            }
            this.source = s;
          }
          return this.source;
        };
        return URI2;
      }();
      var filteredClobberElements = Tools.makeMap("button,fieldset,form,iframe,img,image,input,object,output,select,textarea");
      var isValidPrefixAttrName = function(name2) {
        return name2.indexOf("data-") === 0 || name2.indexOf("aria-") === 0;
      };
      var findMatchingEndTagIndex = function(schema, html, startIndex) {
        var startTagRegExp = /<([!?\/])?([A-Za-z0-9\-_:.]+)/g;
        var endTagRegExp = /(?:\s(?:[^'">]+(?:"[^"]*"|'[^']*'))*[^"'>]*(?:"[^">]*|'[^'>]*)?|\s*|\/)>/g;
        var shortEndedElements = schema.getShortEndedElements();
        var count2 = 1, index = startIndex;
        while (count2 !== 0) {
          startTagRegExp.lastIndex = index;
          while (true) {
            var startMatch = startTagRegExp.exec(html);
            if (startMatch === null) {
              return index;
            } else if (startMatch[1] === "!") {
              if (startsWith(startMatch[2], "--")) {
                index = findCommentEndIndex(html, false, startMatch.index + "!--".length);
              } else {
                index = findCommentEndIndex(html, true, startMatch.index + 1);
              }
              break;
            } else {
              endTagRegExp.lastIndex = startTagRegExp.lastIndex;
              var endMatch = endTagRegExp.exec(html);
              if (isNull(endMatch) || endMatch.index !== startTagRegExp.lastIndex) {
                continue;
              }
              if (startMatch[1] === "/") {
                count2 -= 1;
              } else if (!has$2(shortEndedElements, startMatch[2])) {
                count2 += 1;
              }
              index = startTagRegExp.lastIndex + endMatch[0].length;
              break;
            }
          }
        }
        return index;
      };
      var isConditionalComment = function(html, startIndex) {
        return /^\s*\[if [\w\W]+\]>.*<!\[endif\](--!?)?>/.test(html.substr(startIndex));
      };
      var findCommentEndIndex = function(html, isBogus2, startIndex) {
        if (startIndex === void 0) {
          startIndex = 0;
        }
        var lcHtml = html.toLowerCase();
        if (lcHtml.indexOf("[if ", startIndex) !== -1 && isConditionalComment(lcHtml, startIndex)) {
          var endIfIndex = lcHtml.indexOf("[endif]", startIndex);
          return lcHtml.indexOf(">", endIfIndex);
        } else {
          if (isBogus2) {
            var endIndex = lcHtml.indexOf(">", startIndex);
            return endIndex !== -1 ? endIndex : lcHtml.length;
          } else {
            var endCommentRegexp = /--!?>/g;
            endCommentRegexp.lastIndex = startIndex;
            var match2 = endCommentRegexp.exec(html);
            return match2 ? match2.index + match2[0].length : lcHtml.length;
          }
        }
      };
      var checkBogusAttribute = function(regExp, attrString) {
        var matches2 = regExp.exec(attrString);
        if (matches2) {
          var name_1 = matches2[1];
          var value2 = matches2[2];
          return typeof name_1 === "string" && name_1.toLowerCase() === "data-mce-bogus" ? value2 : null;
        } else {
          return null;
        }
      };
      var SaxParser = function(settings, schema) {
        var _a;
        if (schema === void 0) {
          schema = Schema();
        }
        settings = settings || {};
        var doc2 = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
        var form = doc2.createElement("form");
        if (settings.fix_self_closing !== false) {
          settings.fix_self_closing = true;
        }
        var comment = settings.comment ? settings.comment : noop;
        var cdata = settings.cdata ? settings.cdata : noop;
        var text = settings.text ? settings.text : noop;
        var start2 = settings.start ? settings.start : noop;
        var end2 = settings.end ? settings.end : noop;
        var pi = settings.pi ? settings.pi : noop;
        var doctype = settings.doctype ? settings.doctype : noop;
        var parseInternal = function(base64Extract, format) {
          if (format === void 0) {
            format = "html";
          }
          var html = base64Extract.html;
          var matches2, index = 0, value2, endRegExp;
          var stack = [];
          var attrList, i, textData, name2;
          var isInternalElement, isShortEnded;
          var elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
          var attributesRequired, attributesDefault, attributesForced;
          var anyAttributesRequired, attrValue, idCount = 0;
          var decode2 = Entities.decode;
          var filteredUrlAttrs = Tools.makeMap("src,href,data,background,action,formaction,poster,xlink:href");
          var parsingMode = format === "html" ? 0 : 1;
          var processEndTag = function(name3) {
            var pos, i2;
            pos = stack.length;
            while (pos--) {
              if (stack[pos].name === name3) {
                break;
              }
            }
            if (pos >= 0) {
              for (i2 = stack.length - 1; i2 >= pos; i2--) {
                name3 = stack[i2];
                if (name3.valid) {
                  end2(name3.name);
                }
              }
              stack.length = pos;
            }
          };
          var processText = function(value3, raw) {
            return text(restoreDataUris(value3, base64Extract), raw);
          };
          var processComment = function(value3) {
            if (value3 === "") {
              return;
            }
            if (value3.charAt(0) === ">") {
              value3 = " " + value3;
            }
            if (!settings.allow_conditional_comments && value3.substr(0, 3).toLowerCase() === "[if") {
              value3 = " " + value3;
            }
            comment(restoreDataUris(value3, base64Extract));
          };
          var processAttr = function(value3) {
            return restoreDataUris(value3, base64Extract);
          };
          var processMalformedComment = function(value3, startIndex) {
            var startTag = value3 || "";
            var isBogus2 = !startsWith(startTag, "--");
            var endIndex = findCommentEndIndex(html, isBogus2, startIndex);
            value3 = html.substr(startIndex, endIndex - startIndex);
            processComment(isBogus2 ? startTag + value3 : value3);
            return endIndex + 1;
          };
          var parseAttribute = function(tagName, name3, value3, val2, val3) {
            name3 = name3.toLowerCase();
            value3 = processAttr(name3 in fillAttrsMap ? name3 : decode2(value3 || val2 || val3 || ""));
            if (validate2 && !isInternalElement && isValidPrefixAttrName(name3) === false) {
              var attrRule = validAttributesMap[name3];
              if (!attrRule && validAttributePatterns) {
                var i_1 = validAttributePatterns.length;
                while (i_1--) {
                  attrRule = validAttributePatterns[i_1];
                  if (attrRule.pattern.test(name3)) {
                    break;
                  }
                }
                if (i_1 === -1) {
                  attrRule = null;
                }
              }
              if (!attrRule) {
                return;
              }
              if (attrRule.validValues && !(value3 in attrRule.validValues)) {
                return;
              }
            }
            var isNameOrId = name3 === "name" || name3 === "id";
            if (isNameOrId && tagName in filteredClobberElements && (value3 in doc2 || value3 in form)) {
              return;
            }
            if (filteredUrlAttrs[name3] && !URI.isDomSafe(value3, tagName, settings)) {
              return;
            }
            if (isInternalElement && (name3 in filteredUrlAttrs || name3.indexOf("on") === 0)) {
              return;
            }
            attrList.map[name3] = value3;
            attrList.push({
              name: name3,
              value: value3
            });
          };
          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");
          var attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
          var shortEndedElements = schema.getShortEndedElements();
          var selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
          var fillAttrsMap = schema.getBoolAttrs();
          var validate2 = settings.validate;
          var removeInternalElements = settings.remove_internals;
          var fixSelfClosing = settings.fix_self_closing;
          var specialElements = schema.getSpecialElements();
          var processHtml = html + ">";
          while (matches2 = tokenRegExp.exec(processHtml)) {
            var matchText = matches2[0];
            if (index < matches2.index) {
              processText(decode2(html.substr(index, matches2.index - index)));
            }
            if (value2 = matches2[7]) {
              value2 = value2.toLowerCase();
              if (value2.charAt(0) === ":") {
                value2 = value2.substr(1);
              }
              processEndTag(value2);
            } else if (value2 = matches2[8]) {
              if (matches2.index + matchText.length > html.length) {
                processText(decode2(html.substr(matches2.index)));
                index = matches2.index + matchText.length;
                continue;
              }
              value2 = value2.toLowerCase();
              if (value2.charAt(0) === ":") {
                value2 = value2.substr(1);
              }
              isShortEnded = value2 in shortEndedElements;
              if (fixSelfClosing && selfClosing[value2] && stack.length > 0 && stack[stack.length - 1].name === value2) {
                processEndTag(value2);
              }
              var bogusValue = checkBogusAttribute(attrRegExp, matches2[9]);
              if (bogusValue !== null) {
                if (bogusValue === "all") {
                  index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
                  tokenRegExp.lastIndex = index;
                  continue;
                }
                isValidElement = false;
              }
              if (!validate2 || (elementRule = schema.getElementRule(value2))) {
                isValidElement = true;
                if (validate2) {
                  validAttributesMap = elementRule.attributes;
                  validAttributePatterns = elementRule.attributePatterns;
                }
                if (attribsValue = matches2[9]) {
                  isInternalElement = attribsValue.indexOf("data-mce-type") !== -1;
                  if (isInternalElement && removeInternalElements) {
                    isValidElement = false;
                  }
                  attrList = [];
                  attrList.map = {};
                  attribsValue.replace(attrRegExp, function(match2, name3, val, val2, val3) {
                    parseAttribute(value2, name3, val, val2, val3);
                    return "";
                  });
                } else {
                  attrList = [];
                  attrList.map = {};
                }
                if (validate2 && !isInternalElement) {
                  attributesRequired = elementRule.attributesRequired;
                  attributesDefault = elementRule.attributesDefault;
                  attributesForced = elementRule.attributesForced;
                  anyAttributesRequired = elementRule.removeEmptyAttrs;
                  if (anyAttributesRequired && !attrList.length) {
                    isValidElement = false;
                  }
                  if (attributesForced) {
                    i = attributesForced.length;
                    while (i--) {
                      attr = attributesForced[i];
                      name2 = attr.name;
                      attrValue = attr.value;
                      if (attrValue === "{$uid}") {
                        attrValue = "mce_" + idCount++;
                      }
                      attrList.map[name2] = attrValue;
                      attrList.push({
                        name: name2,
                        value: attrValue
                      });
                    }
                  }
                  if (attributesDefault) {
                    i = attributesDefault.length;
                    while (i--) {
                      attr = attributesDefault[i];
                      name2 = attr.name;
                      if (!(name2 in attrList.map)) {
                        attrValue = attr.value;
                        if (attrValue === "{$uid}") {
                          attrValue = "mce_" + idCount++;
                        }
                        attrList.map[name2] = attrValue;
                        attrList.push({
                          name: name2,
                          value: attrValue
                        });
                      }
                    }
                  }
                  if (attributesRequired) {
                    i = attributesRequired.length;
                    while (i--) {
                      if (attributesRequired[i] in attrList.map) {
                        break;
                      }
                    }
                    if (i === -1) {
                      isValidElement = false;
                    }
                  }
                  if (attr = attrList.map["data-mce-bogus"]) {
                    if (attr === "all") {
                      index = findMatchingEndTagIndex(schema, html, tokenRegExp.lastIndex);
                      tokenRegExp.lastIndex = index;
                      continue;
                    }
                    isValidElement = false;
                  }
                }
                if (isValidElement) {
                  start2(value2, attrList, isShortEnded);
                }
              } else {
                isValidElement = false;
              }
              if (endRegExp = specialElements[value2]) {
                endRegExp.lastIndex = index = matches2.index + matchText.length;
                if (matches2 = endRegExp.exec(html)) {
                  if (isValidElement) {
                    textData = html.substr(index, matches2.index - index);
                  }
                  index = matches2.index + matches2[0].length;
                } else {
                  textData = html.substr(index);
                  index = html.length;
                }
                if (isValidElement) {
                  if (textData.length > 0) {
                    processText(textData, true);
                  }
                  end2(value2);
                }
                tokenRegExp.lastIndex = index;
                continue;
              }
              if (!isShortEnded) {
                if (!attribsValue || attribsValue.indexOf("/") !== attribsValue.length - 1) {
                  stack.push({
                    name: value2,
                    valid: isValidElement
                  });
                } else if (isValidElement) {
                  end2(value2);
                }
              }
            } else if (value2 = matches2[1]) {
              processComment(value2);
            } else if (value2 = matches2[2]) {
              var isValidCdataSection = parsingMode === 1 || settings.preserve_cdata || stack.length > 0 && schema.isValidChild(stack[stack.length - 1].name, "#cdata");
              if (isValidCdataSection) {
                cdata(value2);
              } else {
                index = processMalformedComment("", matches2.index + 2);
                tokenRegExp.lastIndex = index;
                continue;
              }
            } else if (value2 = matches2[3]) {
              doctype(value2);
            } else if ((value2 = matches2[4]) || matchText === "<!") {
              index = processMalformedComment(value2, matches2.index + matchText.length);
              tokenRegExp.lastIndex = index;
              continue;
            } else if (value2 = matches2[5]) {
              if (parsingMode === 1) {
                pi(value2, matches2[6]);
              } else {
                index = processMalformedComment("?", matches2.index + 2);
                tokenRegExp.lastIndex = index;
                continue;
              }
            }
            index = matches2.index + matchText.length;
          }
          if (index < html.length) {
            processText(decode2(html.substr(index)));
          }
          for (i = stack.length - 1; i >= 0; i--) {
            value2 = stack[i];
            if (value2.valid) {
              end2(value2.name);
            }
          }
        };
        var parse = function(html, format) {
          if (format === void 0) {
            format = "html";
          }
          parseInternal(extractBase64DataUris(html), format);
        };
        return { parse };
      };
      SaxParser.findEndTag = findMatchingEndTagIndex;
      var trimHtml = function(tempAttrs, html) {
        var trimContentRegExp = new RegExp(["\\s?(" + tempAttrs.join("|") + ')="[^"]+"'].join("|"), "gi");
        return html.replace(trimContentRegExp, "");
      };
      var trimInternal = function(serializer, html) {
        var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
        var schema = serializer.schema;
        var content = trimHtml(serializer.getTempAttrs(), html);
        var shortEndedElements = schema.getShortEndedElements();
        var matches2;
        while (matches2 = bogusAllRegExp.exec(content)) {
          var index = bogusAllRegExp.lastIndex;
          var matchLength = matches2[0].length;
          var endTagIndex = void 0;
          if (shortEndedElements[matches2[1]]) {
            endTagIndex = index;
          } else {
            endTagIndex = SaxParser.findEndTag(schema, content, index);
          }
          content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
          bogusAllRegExp.lastIndex = index - matchLength;
        }
        return trim$2(content);
      };
      var trimExternal = trimInternal;
      var trimEmptyContents = function(editor, html) {
        var blockName = getForcedRootBlock(editor);
        var emptyRegExp = new RegExp("^(<" + blockName + "[^>]*>(&nbsp;|&#160;|\\s|\xA0|<br \\/>|)<\\/" + blockName + ">[\r\n]*|<br \\/>[\r\n]*)$");
        return html.replace(emptyRegExp, "");
      };
      var setupArgs$3 = function(args, format) {
        return __assign(__assign({}, args), {
          format,
          get: true,
          getInner: true
        });
      };
      var getContentFromBody = function(editor, args, format, body) {
        var defaultedArgs = setupArgs$3(args, format);
        var updatedArgs = args.no_events ? defaultedArgs : editor.fire("BeforeGetContent", defaultedArgs);
        var content;
        if (updatedArgs.format === "raw") {
          content = Tools.trim(trimExternal(editor.serializer, body.innerHTML));
        } else if (updatedArgs.format === "text") {
          content = editor.dom.isEmpty(body) ? "" : trim$2(body.innerText || body.textContent);
        } else if (updatedArgs.format === "tree") {
          content = editor.serializer.serialize(body, updatedArgs);
        } else {
          content = trimEmptyContents(editor, editor.serializer.serialize(body, updatedArgs));
        }
        if (!contains$3([
          "text",
          "tree"
        ], updatedArgs.format) && !isWsPreserveElement(SugarElement.fromDom(body))) {
          updatedArgs.content = Tools.trim(content);
        } else {
          updatedArgs.content = content;
        }
        if (updatedArgs.no_events) {
          return updatedArgs.content;
        } else {
          return editor.fire("GetContent", updatedArgs).content;
        }
      };
      var getContentInternal = function(editor, args, format) {
        return Optional.from(editor.getBody()).fold(constant(args.format === "tree" ? new AstNode("body", 11) : ""), function(body) {
          return getContentFromBody(editor, args, format, body);
        });
      };
      var each$c = Tools.each;
      var ElementUtils = function(dom2) {
        var compare = function(node1, node2) {
          if (node1.nodeName !== node2.nodeName) {
            return false;
          }
          var getAttribs = function(node) {
            var attribs = {};
            each$c(dom2.getAttribs(node), function(attr) {
              var name2 = attr.nodeName.toLowerCase();
              if (name2.indexOf("_") !== 0 && name2 !== "style" && name2.indexOf("data-") !== 0) {
                attribs[name2] = dom2.getAttrib(node, name2);
              }
            });
            return attribs;
          };
          var compareObjects = function(obj1, obj2) {
            var value2, name2;
            for (name2 in obj1) {
              if (has$2(obj1, name2)) {
                value2 = obj2[name2];
                if (typeof value2 === "undefined") {
                  return false;
                }
                if (obj1[name2] !== value2) {
                  return false;
                }
                delete obj2[name2];
              }
            }
            for (name2 in obj2) {
              if (has$2(obj2, name2)) {
                return false;
              }
            }
            return true;
          };
          if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
            return false;
          }
          if (!compareObjects(dom2.parseStyle(dom2.getAttrib(node1, "style")), dom2.parseStyle(dom2.getAttrib(node2, "style")))) {
            return false;
          }
          return !isBookmarkNode$1(node1) && !isBookmarkNode$1(node2);
        };
        return { compare };
      };
      var makeMap$1 = Tools.makeMap;
      var Writer = function(settings) {
        var html = [];
        settings = settings || {};
        var indent = settings.indent;
        var indentBefore = makeMap$1(settings.indent_before || "");
        var indentAfter = makeMap$1(settings.indent_after || "");
        var encode = Entities.getEncodeFunc(settings.entity_encoding || "raw", settings.entities);
        var htmlOutput = settings.element_format === "html";
        return {
          start: function(name2, attrs, empty2) {
            var i, l, attr, value2;
            if (indent && indentBefore[name2] && html.length > 0) {
              value2 = html[html.length - 1];
              if (value2.length > 0 && value2 !== "\n") {
                html.push("\n");
              }
            }
            html.push("<", name2);
            if (attrs) {
              for (i = 0, l = attrs.length; i < l; i++) {
                attr = attrs[i];
                html.push(" ", attr.name, '="', encode(attr.value, true), '"');
              }
            }
            if (!empty2 || htmlOutput) {
              html[html.length] = ">";
            } else {
              html[html.length] = " />";
            }
            if (empty2 && indent && indentAfter[name2] && html.length > 0) {
              value2 = html[html.length - 1];
              if (value2.length > 0 && value2 !== "\n") {
                html.push("\n");
              }
            }
          },
          end: function(name2) {
            var value2;
            html.push("</", name2, ">");
            if (indent && indentAfter[name2] && html.length > 0) {
              value2 = html[html.length - 1];
              if (value2.length > 0 && value2 !== "\n") {
                html.push("\n");
              }
            }
          },
          text: function(text, raw) {
            if (text.length > 0) {
              html[html.length] = raw ? text : encode(text);
            }
          },
          cdata: function(text) {
            html.push("<![CDATA[", text, "]]>");
          },
          comment: function(text) {
            html.push("<!--", text, "-->");
          },
          pi: function(name2, text) {
            if (text) {
              html.push("<?", name2, " ", encode(text), "?>");
            } else {
              html.push("<?", name2, "?>");
            }
            if (indent) {
              html.push("\n");
            }
          },
          doctype: function(text) {
            html.push("<!DOCTYPE", text, ">", indent ? "\n" : "");
          },
          reset: function() {
            html.length = 0;
          },
          getContent: function() {
            return html.join("").replace(/\n$/, "");
          }
        };
      };
      var HtmlSerializer = function(settings, schema) {
        if (schema === void 0) {
          schema = Schema();
        }
        var writer = Writer(settings);
        settings = settings || {};
        settings.validate = "validate" in settings ? settings.validate : true;
        var serialize2 = function(node) {
          var validate2 = settings.validate;
          var handlers = {
            3: function(node2) {
              writer.text(node2.value, node2.raw);
            },
            8: function(node2) {
              writer.comment(node2.value);
            },
            7: function(node2) {
              writer.pi(node2.name, node2.value);
            },
            10: function(node2) {
              writer.doctype(node2.value);
            },
            4: function(node2) {
              writer.cdata(node2.value);
            },
            11: function(node2) {
              if (node2 = node2.firstChild) {
                do {
                  walk2(node2);
                } while (node2 = node2.next);
              }
            }
          };
          writer.reset();
          var walk2 = function(node2) {
            var handler = handlers[node2.type];
            if (!handler) {
              var name_1 = node2.name;
              var isEmpty2 = node2.shortEnded;
              var attrs = node2.attributes;
              if (validate2 && attrs && attrs.length > 1) {
                var sortedAttrs = [];
                sortedAttrs.map = {};
                var elementRule = schema.getElementRule(node2.name);
                if (elementRule) {
                  for (var i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
                    var attrName = elementRule.attributesOrder[i];
                    if (attrName in attrs.map) {
                      var attrValue = attrs.map[attrName];
                      sortedAttrs.map[attrName] = attrValue;
                      sortedAttrs.push({
                        name: attrName,
                        value: attrValue
                      });
                    }
                  }
                  for (var i = 0, l = attrs.length; i < l; i++) {
                    var attrName = attrs[i].name;
                    if (!(attrName in sortedAttrs.map)) {
                      var attrValue = attrs.map[attrName];
                      sortedAttrs.map[attrName] = attrValue;
                      sortedAttrs.push({
                        name: attrName,
                        value: attrValue
                      });
                    }
                  }
                  attrs = sortedAttrs;
                }
              }
              writer.start(node2.name, attrs, isEmpty2);
              if (!isEmpty2) {
                if (node2 = node2.firstChild) {
                  do {
                    walk2(node2);
                  } while (node2 = node2.next);
                }
                writer.end(name_1);
              }
            } else {
              handler(node2);
            }
          };
          if (node.type === 1 && !settings.inner) {
            walk2(node);
          } else {
            handlers[11](node);
          }
          return writer.getContent();
        };
        return { serialize: serialize2 };
      };
      var nonInheritableStyles = /* @__PURE__ */ new Set();
      (function() {
        var nonInheritableStylesArr = [
          "margin",
          "margin-left",
          "margin-right",
          "margin-top",
          "margin-bottom",
          "padding",
          "padding-left",
          "padding-right",
          "padding-top",
          "padding-bottom",
          "border",
          "border-width",
          "border-style",
          "border-color",
          "background",
          "background-attachment",
          "background-clip",
          "background-color",
          "background-image",
          "background-origin",
          "background-position",
          "background-repeat",
          "background-size",
          "float",
          "position",
          "left",
          "right",
          "top",
          "bottom",
          "z-index",
          "display",
          "transform",
          "width",
          "max-width",
          "min-width",
          "height",
          "max-height",
          "min-height",
          "overflow",
          "overflow-x",
          "overflow-y",
          "text-overflow",
          "vertical-align",
          "transition",
          "transition-delay",
          "transition-duration",
          "transition-property",
          "transition-timing-function"
        ];
        each$k(nonInheritableStylesArr, function(style) {
          nonInheritableStyles.add(style);
        });
      })();
      var shorthandStyleProps = [
        "font",
        "text-decoration",
        "text-emphasis"
      ];
      var getStyleProps = function(dom2, node) {
        return keys(dom2.parseStyle(dom2.getAttrib(node, "style")));
      };
      var isNonInheritableStyle = function(style) {
        return nonInheritableStyles.has(style);
      };
      var hasInheritableStyles = function(dom2, node) {
        return forall(getStyleProps(dom2, node), function(style) {
          return !isNonInheritableStyle(style);
        });
      };
      var getLonghandStyleProps = function(styles) {
        return filter$4(styles, function(style) {
          return exists(shorthandStyleProps, function(prop) {
            return startsWith(style, prop);
          });
        });
      };
      var hasStyleConflict = function(dom2, node, parentNode) {
        var nodeStyleProps = getStyleProps(dom2, node);
        var parentNodeStyleProps = getStyleProps(dom2, parentNode);
        var valueMismatch = function(prop) {
          var nodeValue = dom2.getStyle(node, prop);
          var parentValue = dom2.getStyle(parentNode, prop);
          return isNotEmpty(nodeValue) && isNotEmpty(parentValue) && nodeValue !== parentValue;
        };
        return exists(nodeStyleProps, function(nodeStyleProp) {
          var propExists = function(props) {
            return exists(props, function(prop) {
              return prop === nodeStyleProp;
            });
          };
          if (!propExists(parentNodeStyleProps) && propExists(shorthandStyleProps)) {
            var longhandProps = getLonghandStyleProps(parentNodeStyleProps);
            return exists(longhandProps, valueMismatch);
          } else {
            return valueMismatch(nodeStyleProp);
          }
        });
      };
      var isChar = function(forward, predicate, pos) {
        return Optional.from(pos.container()).filter(isText$7).exists(function(text) {
          var delta = forward ? 0 : -1;
          return predicate(text.data.charAt(pos.offset() + delta));
        });
      };
      var isBeforeSpace = curry(isChar, true, isWhiteSpace);
      var isAfterSpace = curry(isChar, false, isWhiteSpace);
      var isEmptyText = function(pos) {
        var container = pos.container();
        return isText$7(container) && (container.data.length === 0 || isZwsp(container.data) && BookmarkManager.isBookmarkNode(container.parentNode));
      };
      var matchesElementPosition = function(before2, predicate) {
        return function(pos) {
          return Optional.from(getChildNodeAtRelativeOffset(before2 ? 0 : -1, pos)).filter(predicate).isSome();
        };
      };
      var isImageBlock = function(node) {
        return isImg(node) && get$5(SugarElement.fromDom(node), "display") === "block";
      };
      var isCefNode = function(node) {
        return isContentEditableFalse$b(node) && !isBogusAll$1(node);
      };
      var isBeforeImageBlock = matchesElementPosition(true, isImageBlock);
      var isAfterImageBlock = matchesElementPosition(false, isImageBlock);
      var isBeforeMedia = matchesElementPosition(true, isMedia$2);
      var isAfterMedia = matchesElementPosition(false, isMedia$2);
      var isBeforeTable = matchesElementPosition(true, isTable$3);
      var isAfterTable = matchesElementPosition(false, isTable$3);
      var isBeforeContentEditableFalse = matchesElementPosition(true, isCefNode);
      var isAfterContentEditableFalse = matchesElementPosition(false, isCefNode);
      var getLastChildren = function(elm) {
        var children2 = [];
        var rawNode = elm.dom;
        while (rawNode) {
          children2.push(SugarElement.fromDom(rawNode));
          rawNode = rawNode.lastChild;
        }
        return children2;
      };
      var removeTrailingBr = function(elm) {
        var allBrs = descendants(elm, "br");
        var brs = filter$4(getLastChildren(elm).slice(-1), isBr$4);
        if (allBrs.length === brs.length) {
          each$k(brs, remove$7);
        }
      };
      var fillWithPaddingBr = function(elm) {
        empty(elm);
        append$1(elm, SugarElement.fromHtml('<br data-mce-bogus="1">'));
      };
      var trimBlockTrailingBr = function(elm) {
        lastChild(elm).each(function(lastChild2) {
          prevSibling(lastChild2).each(function(lastChildPrevSibling) {
            if (isBlock$2(elm) && isBr$4(lastChild2) && isBlock$2(lastChildPrevSibling)) {
              remove$7(lastChild2);
            }
          });
        });
      };
      var dropLast = function(xs) {
        return xs.slice(0, -1);
      };
      var parentsUntil = function(start2, root, predicate) {
        if (contains$1(root, start2)) {
          return dropLast(parents$1(start2, function(elm) {
            return predicate(elm) || eq(elm, root);
          }));
        } else {
          return [];
        }
      };
      var parents = function(start2, root) {
        return parentsUntil(start2, root, never);
      };
      var parentsAndSelf = function(start2, root) {
        return [start2].concat(parents(start2, root));
      };
      var navigateIgnoreEmptyTextNodes = function(forward, root, from2) {
        return navigateIgnore(forward, root, from2, isEmptyText);
      };
      var getClosestBlock$1 = function(root, pos) {
        return find$3(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
      };
      var isAtBeforeAfterBlockBoundary = function(forward, root, pos) {
        return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function(newPos) {
          return getClosestBlock$1(root, pos).fold(function() {
            return isInSameBlock(newPos, pos, root.dom) === false;
          }, function(fromBlock) {
            return isInSameBlock(newPos, pos, root.dom) === false && contains$1(fromBlock, SugarElement.fromDom(newPos.container()));
          });
        });
      };
      var isAtBlockBoundary = function(forward, root, pos) {
        return getClosestBlock$1(root, pos).fold(function() {
          return navigateIgnoreEmptyTextNodes(forward, root.dom, pos).forall(function(newPos) {
            return isInSameBlock(newPos, pos, root.dom) === false;
          });
        }, function(parent2) {
          return navigateIgnoreEmptyTextNodes(forward, parent2.dom, pos).isNone();
        });
      };
      var isAtStartOfBlock = curry(isAtBlockBoundary, false);
      var isAtEndOfBlock = curry(isAtBlockBoundary, true);
      var isBeforeBlock = curry(isAtBeforeAfterBlockBoundary, false);
      var isAfterBlock = curry(isAtBeforeAfterBlockBoundary, true);
      var isBr = function(pos) {
        return getElementFromPosition(pos).exists(isBr$4);
      };
      var findBr = function(forward, root, pos) {
        var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
        var scope = head(parentBlocks).getOr(root);
        return fromPosition(forward, scope.dom, pos).filter(isBr);
      };
      var isBeforeBr$1 = function(root, pos) {
        return getElementFromPosition(pos).exists(isBr$4) || findBr(true, root, pos).isSome();
      };
      var isAfterBr = function(root, pos) {
        return getElementFromPrevPosition(pos).exists(isBr$4) || findBr(false, root, pos).isSome();
      };
      var findPreviousBr = curry(findBr, false);
      var findNextBr = curry(findBr, true);
      var isInMiddleOfText = function(pos) {
        return CaretPosition.isTextPosition(pos) && !pos.isAtStart() && !pos.isAtEnd();
      };
      var getClosestBlock = function(root, pos) {
        var parentBlocks = filter$4(parentsAndSelf(SugarElement.fromDom(pos.container()), root), isBlock$2);
        return head(parentBlocks).getOr(root);
      };
      var hasSpaceBefore = function(root, pos) {
        if (isInMiddleOfText(pos)) {
          return isAfterSpace(pos);
        } else {
          return isAfterSpace(pos) || prevPosition(getClosestBlock(root, pos).dom, pos).exists(isAfterSpace);
        }
      };
      var hasSpaceAfter = function(root, pos) {
        if (isInMiddleOfText(pos)) {
          return isBeforeSpace(pos);
        } else {
          return isBeforeSpace(pos) || nextPosition(getClosestBlock(root, pos).dom, pos).exists(isBeforeSpace);
        }
      };
      var isPreValue = function(value2) {
        return contains$3([
          "pre",
          "pre-wrap"
        ], value2);
      };
      var isInPre = function(pos) {
        return getElementFromPosition(pos).bind(function(elm) {
          return closest$3(elm, isElement$6);
        }).exists(function(elm) {
          return isPreValue(get$5(elm, "white-space"));
        });
      };
      var isAtBeginningOfBody = function(root, pos) {
        return prevPosition(root.dom, pos).isNone();
      };
      var isAtEndOfBody = function(root, pos) {
        return nextPosition(root.dom, pos).isNone();
      };
      var isAtLineBoundary = function(root, pos) {
        return isAtBeginningOfBody(root, pos) || isAtEndOfBody(root, pos) || isAtStartOfBlock(root, pos) || isAtEndOfBlock(root, pos) || isAfterBr(root, pos) || isBeforeBr$1(root, pos);
      };
      var needsToHaveNbsp = function(root, pos) {
        if (isInPre(pos)) {
          return false;
        } else {
          return isAtLineBoundary(root, pos) || hasSpaceBefore(root, pos) || hasSpaceAfter(root, pos);
        }
      };
      var needsToBeNbspLeft = function(root, pos) {
        if (isInPre(pos)) {
          return false;
        } else {
          return isAtStartOfBlock(root, pos) || isBeforeBlock(root, pos) || isAfterBr(root, pos) || hasSpaceBefore(root, pos);
        }
      };
      var leanRight = function(pos) {
        var container = pos.container();
        var offset = pos.offset();
        if (isText$7(container) && offset < container.data.length) {
          return CaretPosition(container, offset + 1);
        } else {
          return pos;
        }
      };
      var needsToBeNbspRight = function(root, pos) {
        if (isInPre(pos)) {
          return false;
        } else {
          return isAtEndOfBlock(root, pos) || isAfterBlock(root, pos) || isBeforeBr$1(root, pos) || hasSpaceAfter(root, pos);
        }
      };
      var needsToBeNbsp = function(root, pos) {
        return needsToBeNbspLeft(root, pos) || needsToBeNbspRight(root, leanRight(pos));
      };
      var isNbspAt = function(text, offset) {
        return isNbsp(text.charAt(offset));
      };
      var hasNbsp = function(pos) {
        var container = pos.container();
        return isText$7(container) && contains$2(container.data, nbsp);
      };
      var normalizeNbspMiddle = function(text) {
        var chars = text.split("");
        return map$3(chars, function(chr, i) {
          if (isNbsp(chr) && i > 0 && i < chars.length - 1 && isContent(chars[i - 1]) && isContent(chars[i + 1])) {
            return " ";
          } else {
            return chr;
          }
        }).join("");
      };
      var normalizeNbspAtStart = function(root, node) {
        var text = node.data;
        var firstPos = CaretPosition(node, 0);
        if (isNbspAt(text, 0) && !needsToBeNbsp(root, firstPos)) {
          node.data = " " + text.slice(1);
          return true;
        } else {
          return false;
        }
      };
      var normalizeNbspInMiddleOfTextNode = function(node) {
        var text = node.data;
        var newText = normalizeNbspMiddle(text);
        if (newText !== text) {
          node.data = newText;
          return true;
        } else {
          return false;
        }
      };
      var normalizeNbspAtEnd = function(root, node) {
        var text = node.data;
        var lastPos = CaretPosition(node, text.length - 1);
        if (isNbspAt(text, text.length - 1) && !needsToBeNbsp(root, lastPos)) {
          node.data = text.slice(0, -1) + " ";
          return true;
        } else {
          return false;
        }
      };
      var normalizeNbsps = function(root, pos) {
        return Optional.some(pos).filter(hasNbsp).bind(function(pos2) {
          var container = pos2.container();
          var normalized = normalizeNbspAtStart(root, container) || normalizeNbspInMiddleOfTextNode(container) || normalizeNbspAtEnd(root, container);
          return normalized ? Optional.some(pos2) : Optional.none();
        });
      };
      var normalizeNbspsInEditor = function(editor) {
        var root = SugarElement.fromDom(editor.getBody());
        if (editor.selection.isCollapsed()) {
          normalizeNbsps(root, CaretPosition.fromRangeStart(editor.selection.getRng())).each(function(pos) {
            editor.selection.setRng(pos.toRange());
          });
        }
      };
      var normalizeContent = function(content, isStartOfContent, isEndOfContent) {
        var result = foldl(content, function(acc, c) {
          if (isWhiteSpace(c) || isNbsp(c)) {
            if (acc.previousCharIsSpace || acc.str === "" && isStartOfContent || acc.str.length === content.length - 1 && isEndOfContent) {
              return {
                previousCharIsSpace: false,
                str: acc.str + nbsp
              };
            } else {
              return {
                previousCharIsSpace: true,
                str: acc.str + " "
              };
            }
          } else {
            return {
              previousCharIsSpace: false,
              str: acc.str + c
            };
          }
        }, {
          previousCharIsSpace: false,
          str: ""
        });
        return result.str;
      };
      var normalize$1 = function(node, offset, count2) {
        if (count2 === 0) {
          return;
        }
        var elm = SugarElement.fromDom(node);
        var root = ancestor$3(elm, isBlock$2).getOr(elm);
        var whitespace2 = node.data.slice(offset, offset + count2);
        var isEndOfContent = offset + count2 >= node.data.length && needsToBeNbspRight(root, CaretPosition(node, node.data.length));
        var isStartOfContent = offset === 0 && needsToBeNbspLeft(root, CaretPosition(node, 0));
        node.replaceData(offset, count2, normalizeContent(whitespace2, isStartOfContent, isEndOfContent));
      };
      var normalizeWhitespaceAfter = function(node, offset) {
        var content = node.data.slice(offset);
        var whitespaceCount = content.length - lTrim(content).length;
        normalize$1(node, offset, whitespaceCount);
      };
      var normalizeWhitespaceBefore = function(node, offset) {
        var content = node.data.slice(0, offset);
        var whitespaceCount = content.length - rTrim(content).length;
        normalize$1(node, offset - whitespaceCount, whitespaceCount);
      };
      var mergeTextNodes = function(prevNode, nextNode, normalizeWhitespace, mergeToPrev) {
        if (mergeToPrev === void 0) {
          mergeToPrev = true;
        }
        var whitespaceOffset = rTrim(prevNode.data).length;
        var newNode = mergeToPrev ? prevNode : nextNode;
        var removeNode2 = mergeToPrev ? nextNode : prevNode;
        if (mergeToPrev) {
          newNode.appendData(removeNode2.data);
        } else {
          newNode.insertData(0, removeNode2.data);
        }
        remove$7(SugarElement.fromDom(removeNode2));
        if (normalizeWhitespace) {
          normalizeWhitespaceAfter(newNode, whitespaceOffset);
        }
        return newNode;
      };
      var needsReposition = function(pos, elm) {
        var container = pos.container();
        var offset = pos.offset();
        return CaretPosition.isTextPosition(pos) === false && container === elm.parentNode && offset > CaretPosition.before(elm).offset();
      };
      var reposition = function(elm, pos) {
        return needsReposition(pos, elm) ? CaretPosition(pos.container(), pos.offset() - 1) : pos;
      };
      var beforeOrStartOf = function(node) {
        return isText$7(node) ? CaretPosition(node, 0) : CaretPosition.before(node);
      };
      var afterOrEndOf = function(node) {
        return isText$7(node) ? CaretPosition(node, node.data.length) : CaretPosition.after(node);
      };
      var getPreviousSiblingCaretPosition = function(elm) {
        if (isCaretCandidate$3(elm.previousSibling)) {
          return Optional.some(afterOrEndOf(elm.previousSibling));
        } else {
          return elm.previousSibling ? lastPositionIn(elm.previousSibling) : Optional.none();
        }
      };
      var getNextSiblingCaretPosition = function(elm) {
        if (isCaretCandidate$3(elm.nextSibling)) {
          return Optional.some(beforeOrStartOf(elm.nextSibling));
        } else {
          return elm.nextSibling ? firstPositionIn(elm.nextSibling) : Optional.none();
        }
      };
      var findCaretPositionBackwardsFromElm = function(rootElement, elm) {
        var startPosition = CaretPosition.before(elm.previousSibling ? elm.previousSibling : elm.parentNode);
        return prevPosition(rootElement, startPosition).fold(function() {
          return nextPosition(rootElement, CaretPosition.after(elm));
        }, Optional.some);
      };
      var findCaretPositionForwardsFromElm = function(rootElement, elm) {
        return nextPosition(rootElement, CaretPosition.after(elm)).fold(function() {
          return prevPosition(rootElement, CaretPosition.before(elm));
        }, Optional.some);
      };
      var findCaretPositionBackwards = function(rootElement, elm) {
        return getPreviousSiblingCaretPosition(elm).orThunk(function() {
          return getNextSiblingCaretPosition(elm);
        }).orThunk(function() {
          return findCaretPositionBackwardsFromElm(rootElement, elm);
        });
      };
      var findCaretPositionForward = function(rootElement, elm) {
        return getNextSiblingCaretPosition(elm).orThunk(function() {
          return getPreviousSiblingCaretPosition(elm);
        }).orThunk(function() {
          return findCaretPositionForwardsFromElm(rootElement, elm);
        });
      };
      var findCaretPosition = function(forward, rootElement, elm) {
        return forward ? findCaretPositionForward(rootElement, elm) : findCaretPositionBackwards(rootElement, elm);
      };
      var findCaretPosOutsideElmAfterDelete = function(forward, rootElement, elm) {
        return findCaretPosition(forward, rootElement, elm).map(curry(reposition, elm));
      };
      var setSelection$1 = function(editor, forward, pos) {
        pos.fold(function() {
          editor.focus();
        }, function(pos2) {
          editor.selection.setRng(pos2.toRange(), forward);
        });
      };
      var eqRawNode = function(rawNode) {
        return function(elm) {
          return elm.dom === rawNode;
        };
      };
      var isBlock = function(editor, elm) {
        return elm && has$2(editor.schema.getBlockElements(), name(elm));
      };
      var paddEmptyBlock = function(elm) {
        if (isEmpty$2(elm)) {
          var br = SugarElement.fromHtml('<br data-mce-bogus="1">');
          empty(elm);
          append$1(elm, br);
          return Optional.some(CaretPosition.before(br.dom));
        } else {
          return Optional.none();
        }
      };
      var deleteNormalized = function(elm, afterDeletePosOpt, normalizeWhitespace) {
        var prevTextOpt = prevSibling(elm).filter(isText$8);
        var nextTextOpt = nextSibling(elm).filter(isText$8);
        remove$7(elm);
        return lift3(prevTextOpt, nextTextOpt, afterDeletePosOpt, function(prev, next, pos) {
          var prevNode = prev.dom, nextNode = next.dom;
          var offset = prevNode.data.length;
          mergeTextNodes(prevNode, nextNode, normalizeWhitespace);
          return pos.container() === nextNode ? CaretPosition(prevNode, offset) : pos;
        }).orThunk(function() {
          if (normalizeWhitespace) {
            prevTextOpt.each(function(elm2) {
              return normalizeWhitespaceBefore(elm2.dom, elm2.dom.length);
            });
            nextTextOpt.each(function(elm2) {
              return normalizeWhitespaceAfter(elm2.dom, 0);
            });
          }
          return afterDeletePosOpt;
        });
      };
      var isInlineElement = function(editor, element) {
        return has$2(editor.schema.getTextInlineElements(), name(element));
      };
      var deleteElement$2 = function(editor, forward, elm, moveCaret2) {
        if (moveCaret2 === void 0) {
          moveCaret2 = true;
        }
        var afterDeletePos = findCaretPosOutsideElmAfterDelete(forward, editor.getBody(), elm.dom);
        var parentBlock = ancestor$3(elm, curry(isBlock, editor), eqRawNode(editor.getBody()));
        var normalizedAfterDeletePos = deleteNormalized(elm, afterDeletePos, isInlineElement(editor, elm));
        if (editor.dom.isEmpty(editor.getBody())) {
          editor.setContent("");
          editor.selection.setCursorLocation();
        } else {
          parentBlock.bind(paddEmptyBlock).fold(function() {
            if (moveCaret2) {
              setSelection$1(editor, forward, normalizedAfterDeletePos);
            }
          }, function(paddPos) {
            if (moveCaret2) {
              setSelection$1(editor, forward, Optional.some(paddPos));
            }
          });
        }
      };
      var isRootFromElement = function(root) {
        return function(cur) {
          return eq(root, cur);
        };
      };
      var getTableCells = function(table) {
        return descendants(table, "td,th");
      };
      var getTableDetailsFromRange = function(rng, isRoot) {
        var getTable2 = function(node) {
          return getClosestTable(SugarElement.fromDom(node), isRoot);
        };
        var startTable = getTable2(rng.startContainer);
        var endTable = getTable2(rng.endContainer);
        var isStartInTable = startTable.isSome();
        var isEndInTable = endTable.isSome();
        var isSameTable = lift2(startTable, endTable, eq).getOr(false);
        var isMultiTable = !isSameTable && isStartInTable && isEndInTable;
        return {
          startTable,
          endTable,
          isStartInTable,
          isEndInTable,
          isSameTable,
          isMultiTable
        };
      };
      var tableCellRng = function(start2, end2) {
        return {
          start: start2,
          end: end2
        };
      };
      var tableSelection = function(rng, table, cells) {
        return {
          rng,
          table,
          cells
        };
      };
      var deleteAction = Adt.generate([
        {
          singleCellTable: [
            "rng",
            "cell"
          ]
        },
        { fullTable: ["table"] },
        {
          partialTable: [
            "cells",
            "outsideDetails"
          ]
        },
        {
          multiTable: [
            "startTableCells",
            "endTableCells",
            "betweenRng"
          ]
        }
      ]);
      var getClosestCell$1 = function(container, isRoot) {
        return closest$2(SugarElement.fromDom(container), "td,th", isRoot);
      };
      var isExpandedCellRng = function(cellRng) {
        return !eq(cellRng.start, cellRng.end);
      };
      var getTableFromCellRng = function(cellRng, isRoot) {
        return getClosestTable(cellRng.start, isRoot).bind(function(startParentTable) {
          return getClosestTable(cellRng.end, isRoot).bind(function(endParentTable) {
            return someIf(eq(startParentTable, endParentTable), startParentTable);
          });
        });
      };
      var isSingleCellTable = function(cellRng, isRoot) {
        return !isExpandedCellRng(cellRng) && getTableFromCellRng(cellRng, isRoot).exists(function(table) {
          var rows = table.dom.rows;
          return rows.length === 1 && rows[0].cells.length === 1;
        });
      };
      var getCellRng = function(rng, isRoot) {
        var startCell = getClosestCell$1(rng.startContainer, isRoot);
        var endCell = getClosestCell$1(rng.endContainer, isRoot);
        return lift2(startCell, endCell, tableCellRng);
      };
      var getCellRangeFromStartTable = function(isRoot) {
        return function(startCell) {
          return getClosestTable(startCell, isRoot).bind(function(table) {
            return last$2(getTableCells(table)).map(function(endCell) {
              return tableCellRng(startCell, endCell);
            });
          });
        };
      };
      var getCellRangeFromEndTable = function(isRoot) {
        return function(endCell) {
          return getClosestTable(endCell, isRoot).bind(function(table) {
            return head(getTableCells(table)).map(function(startCell) {
              return tableCellRng(startCell, endCell);
            });
          });
        };
      };
      var getTableSelectionFromCellRng = function(isRoot) {
        return function(cellRng) {
          return getTableFromCellRng(cellRng, isRoot).map(function(table) {
            return tableSelection(cellRng, table, getTableCells(table));
          });
        };
      };
      var getTableSelections = function(cellRng, selectionDetails, rng, isRoot) {
        if (rng.collapsed || !cellRng.forall(isExpandedCellRng)) {
          return Optional.none();
        } else if (selectionDetails.isSameTable) {
          var sameTableSelection = cellRng.bind(getTableSelectionFromCellRng(isRoot));
          return Optional.some({
            start: sameTableSelection,
            end: sameTableSelection
          });
        } else {
          var startCell = getClosestCell$1(rng.startContainer, isRoot);
          var endCell = getClosestCell$1(rng.endContainer, isRoot);
          var startTableSelection = startCell.bind(getCellRangeFromStartTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
          var endTableSelection = endCell.bind(getCellRangeFromEndTable(isRoot)).bind(getTableSelectionFromCellRng(isRoot));
          return Optional.some({
            start: startTableSelection,
            end: endTableSelection
          });
        }
      };
      var getCellIndex = function(cells, cell) {
        return findIndex$2(cells, function(x) {
          return eq(x, cell);
        });
      };
      var getSelectedCells = function(tableSelection2) {
        return lift2(getCellIndex(tableSelection2.cells, tableSelection2.rng.start), getCellIndex(tableSelection2.cells, tableSelection2.rng.end), function(startIndex, endIndex) {
          return tableSelection2.cells.slice(startIndex, endIndex + 1);
        });
      };
      var isSingleCellTableContentSelected = function(optCellRng, rng, isRoot) {
        return optCellRng.exists(function(cellRng) {
          return isSingleCellTable(cellRng, isRoot) && hasAllContentsSelected(cellRng.start, rng);
        });
      };
      var unselectCells = function(rng, selectionDetails) {
        var startTable = selectionDetails.startTable, endTable = selectionDetails.endTable;
        var otherContentRng = rng.cloneRange();
        startTable.each(function(table) {
          return otherContentRng.setStartAfter(table.dom);
        });
        endTable.each(function(table) {
          return otherContentRng.setEndBefore(table.dom);
        });
        return otherContentRng;
      };
      var handleSingleTable = function(cellRng, selectionDetails, rng, isRoot) {
        return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function(_a) {
          var start2 = _a.start, end2 = _a.end;
          return start2.or(end2);
        }).bind(function(tableSelection2) {
          var isSameTable = selectionDetails.isSameTable;
          var selectedCells = getSelectedCells(tableSelection2).getOr([]);
          if (isSameTable && tableSelection2.cells.length === selectedCells.length) {
            return Optional.some(deleteAction.fullTable(tableSelection2.table));
          } else if (selectedCells.length > 0) {
            if (isSameTable) {
              return Optional.some(deleteAction.partialTable(selectedCells, Optional.none()));
            } else {
              var otherContentRng = unselectCells(rng, selectionDetails);
              return Optional.some(deleteAction.partialTable(selectedCells, Optional.some(__assign(__assign({}, selectionDetails), { rng: otherContentRng }))));
            }
          } else {
            return Optional.none();
          }
        });
      };
      var handleMultiTable = function(cellRng, selectionDetails, rng, isRoot) {
        return getTableSelections(cellRng, selectionDetails, rng, isRoot).bind(function(_a) {
          var start2 = _a.start, end2 = _a.end;
          var startTableSelectedCells = start2.bind(getSelectedCells).getOr([]);
          var endTableSelectedCells = end2.bind(getSelectedCells).getOr([]);
          if (startTableSelectedCells.length > 0 && endTableSelectedCells.length > 0) {
            var otherContentRng = unselectCells(rng, selectionDetails);
            return Optional.some(deleteAction.multiTable(startTableSelectedCells, endTableSelectedCells, otherContentRng));
          } else {
            return Optional.none();
          }
        });
      };
      var getActionFromRange = function(root, rng) {
        var isRoot = isRootFromElement(root);
        var optCellRng = getCellRng(rng, isRoot);
        var selectionDetails = getTableDetailsFromRange(rng, isRoot);
        if (isSingleCellTableContentSelected(optCellRng, rng, isRoot)) {
          return optCellRng.map(function(cellRng) {
            return deleteAction.singleCellTable(rng, cellRng.start);
          });
        } else if (selectionDetails.isMultiTable) {
          return handleMultiTable(optCellRng, selectionDetails, rng, isRoot);
        } else {
          return handleSingleTable(optCellRng, selectionDetails, rng, isRoot);
        }
      };
      var freefallRtl = function(root) {
        var child2 = isComment$1(root) ? prevSibling(root) : lastChild(root);
        return child2.bind(freefallRtl).orThunk(function() {
          return Optional.some(root);
        });
      };
      var cleanCells = function(cells) {
        return each$k(cells, function(cell) {
          remove$6(cell, "contenteditable");
          fillWithPaddingBr(cell);
        });
      };
      var getOutsideBlock = function(editor, container) {
        return Optional.from(editor.dom.getParent(container, editor.dom.isBlock)).map(SugarElement.fromDom);
      };
      var handleEmptyBlock = function(editor, startInTable, emptyBlock2) {
        emptyBlock2.each(function(block) {
          if (startInTable) {
            remove$7(block);
          } else {
            fillWithPaddingBr(block);
            editor.selection.setCursorLocation(block.dom, 0);
          }
        });
      };
      var deleteContentInsideCell = function(editor, cell, rng, isFirstCellInSelection) {
        var insideTableRng = rng.cloneRange();
        if (isFirstCellInSelection) {
          insideTableRng.setStart(rng.startContainer, rng.startOffset);
          insideTableRng.setEndAfter(cell.dom.lastChild);
        } else {
          insideTableRng.setStartBefore(cell.dom.firstChild);
          insideTableRng.setEnd(rng.endContainer, rng.endOffset);
        }
        deleteCellContents(editor, insideTableRng, cell, false);
      };
      var collapseAndRestoreCellSelection = function(editor) {
        var selectedCells = getCellsFromEditor(editor);
        var selectedNode = SugarElement.fromDom(editor.selection.getNode());
        if (isTableCell$5(selectedNode.dom) && isEmpty$2(selectedNode)) {
          editor.selection.setCursorLocation(selectedNode.dom, 0);
        } else {
          editor.selection.collapse(true);
        }
        if (selectedCells.length > 1 && exists(selectedCells, function(cell) {
          return eq(cell, selectedNode);
        })) {
          set$1(selectedNode, "data-mce-selected", "1");
        }
      };
      var emptySingleTableCells = function(editor, cells, outsideDetails) {
        var editorRng = editor.selection.getRng();
        var cellsToClean = outsideDetails.bind(function(_a) {
          var rng = _a.rng, isStartInTable = _a.isStartInTable;
          var outsideBlock = getOutsideBlock(editor, isStartInTable ? rng.endContainer : rng.startContainer);
          rng.deleteContents();
          handleEmptyBlock(editor, isStartInTable, outsideBlock.filter(isEmpty$2));
          var endPointCell = isStartInTable ? cells[0] : cells[cells.length - 1];
          deleteContentInsideCell(editor, endPointCell, editorRng, isStartInTable);
          if (!isEmpty$2(endPointCell)) {
            return Optional.some(isStartInTable ? cells.slice(1) : cells.slice(0, -1));
          } else {
            return Optional.none();
          }
        }).getOr(cells);
        cleanCells(cellsToClean);
        collapseAndRestoreCellSelection(editor);
        return true;
      };
      var emptyMultiTableCells = function(editor, startTableCells, endTableCells, betweenRng) {
        var rng = editor.selection.getRng();
        var startCell = startTableCells[0];
        var endCell = endTableCells[endTableCells.length - 1];
        deleteContentInsideCell(editor, startCell, rng, true);
        deleteContentInsideCell(editor, endCell, rng, false);
        var startTableCellsToClean = isEmpty$2(startCell) ? startTableCells : startTableCells.slice(1);
        var endTableCellsToClean = isEmpty$2(endCell) ? endTableCells : endTableCells.slice(0, -1);
        cleanCells(startTableCellsToClean.concat(endTableCellsToClean));
        betweenRng.deleteContents();
        collapseAndRestoreCellSelection(editor);
        return true;
      };
      var deleteCellContents = function(editor, rng, cell, moveSelection2) {
        if (moveSelection2 === void 0) {
          moveSelection2 = true;
        }
        rng.deleteContents();
        var lastNode = freefallRtl(cell).getOr(cell);
        var lastBlock = SugarElement.fromDom(editor.dom.getParent(lastNode.dom, editor.dom.isBlock));
        if (isEmpty$2(lastBlock)) {
          fillWithPaddingBr(lastBlock);
          if (moveSelection2) {
            editor.selection.setCursorLocation(lastBlock.dom, 0);
          }
        }
        if (!eq(cell, lastBlock)) {
          var additionalCleanupNodes = is$1(parent(lastBlock), cell) ? [] : siblings(lastBlock);
          each$k(additionalCleanupNodes.concat(children(cell)), function(node) {
            if (!eq(node, lastBlock) && !contains$1(node, lastBlock) && isEmpty$2(node)) {
              remove$7(node);
            }
          });
        }
        return true;
      };
      var deleteTableElement = function(editor, table) {
        deleteElement$2(editor, false, table);
        return true;
      };
      var deleteCellRange = function(editor, rootElm, rng) {
        return getActionFromRange(rootElm, rng).map(function(action2) {
          return action2.fold(curry(deleteCellContents, editor), curry(deleteTableElement, editor), curry(emptySingleTableCells, editor), curry(emptyMultiTableCells, editor));
        });
      };
      var deleteCaptionRange = function(editor, caption) {
        return emptyElement(editor, caption);
      };
      var deleteTableRange = function(editor, rootElm, rng, startElm) {
        return getParentCaption(rootElm, startElm).fold(function() {
          return deleteCellRange(editor, rootElm, rng);
        }, function(caption) {
          return deleteCaptionRange(editor, caption);
        }).getOr(false);
      };
      var deleteRange$2 = function(editor, startElm, selectedCells) {
        var rootNode = SugarElement.fromDom(editor.getBody());
        var rng = editor.selection.getRng();
        return selectedCells.length !== 0 ? emptySingleTableCells(editor, selectedCells, Optional.none()) : deleteTableRange(editor, rootNode, rng, startElm);
      };
      var getParentCell = function(rootElm, elm) {
        return find$3(parentsAndSelf(elm, rootElm), isTableCell$4);
      };
      var getParentCaption = function(rootElm, elm) {
        return find$3(parentsAndSelf(elm, rootElm), isTag("caption"));
      };
      var deleteBetweenCells = function(editor, rootElm, forward, fromCell, from2) {
        return navigate(forward, editor.getBody(), from2).bind(function(to2) {
          return getParentCell(rootElm, SugarElement.fromDom(to2.getNode())).map(function(toCell) {
            return eq(toCell, fromCell) === false;
          });
        });
      };
      var emptyElement = function(editor, elm) {
        fillWithPaddingBr(elm);
        editor.selection.setCursorLocation(elm.dom, 0);
        return Optional.some(true);
      };
      var isDeleteOfLastCharPos = function(fromCaption, forward, from2, to2) {
        return firstPositionIn(fromCaption.dom).bind(function(first2) {
          return lastPositionIn(fromCaption.dom).map(function(last2) {
            return forward ? from2.isEqual(first2) && to2.isEqual(last2) : from2.isEqual(last2) && to2.isEqual(first2);
          });
        }).getOr(true);
      };
      var emptyCaretCaption = function(editor, elm) {
        return emptyElement(editor, elm);
      };
      var validateCaretCaption = function(rootElm, fromCaption, to2) {
        return getParentCaption(rootElm, SugarElement.fromDom(to2.getNode())).map(function(toCaption) {
          return eq(toCaption, fromCaption) === false;
        });
      };
      var deleteCaretInsideCaption = function(editor, rootElm, forward, fromCaption, from2) {
        return navigate(forward, editor.getBody(), from2).bind(function(to2) {
          return isDeleteOfLastCharPos(fromCaption, forward, from2, to2) ? emptyCaretCaption(editor, fromCaption) : validateCaretCaption(rootElm, fromCaption, to2);
        }).or(Optional.some(true));
      };
      var deleteCaretCells = function(editor, forward, rootElm, startElm) {
        var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
        return getParentCell(rootElm, startElm).bind(function(fromCell) {
          return isEmpty$2(fromCell) ? emptyElement(editor, fromCell) : deleteBetweenCells(editor, rootElm, forward, fromCell, from2);
        }).getOr(false);
      };
      var deleteCaretCaption = function(editor, forward, rootElm, fromCaption) {
        var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
        return isEmpty$2(fromCaption) ? emptyElement(editor, fromCaption) : deleteCaretInsideCaption(editor, rootElm, forward, fromCaption, from2);
      };
      var isNearTable = function(forward, pos) {
        return forward ? isBeforeTable(pos) : isAfterTable(pos);
      };
      var isBeforeOrAfterTable = function(editor, forward) {
        var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
        return isNearTable(forward, fromPos) || fromPosition(forward, editor.getBody(), fromPos).exists(function(pos) {
          return isNearTable(forward, pos);
        });
      };
      var deleteCaret$3 = function(editor, forward, startElm) {
        var rootElm = SugarElement.fromDom(editor.getBody());
        return getParentCaption(rootElm, startElm).fold(function() {
          return deleteCaretCells(editor, forward, rootElm, startElm) || isBeforeOrAfterTable(editor, forward);
        }, function(fromCaption) {
          return deleteCaretCaption(editor, forward, rootElm, fromCaption).getOr(false);
        });
      };
      var backspaceDelete$9 = function(editor, forward) {
        var startElm = SugarElement.fromDom(editor.selection.getStart(true));
        var cells = getCellsFromEditor(editor);
        return editor.selection.isCollapsed() && cells.length === 0 ? deleteCaret$3(editor, forward, startElm) : deleteRange$2(editor, startElm, cells);
      };
      var createRange = function(sc, so, ec, eo) {
        var rng = document.createRange();
        rng.setStart(sc, so);
        rng.setEnd(ec, eo);
        return rng;
      };
      var normalizeBlockSelectionRange = function(rng) {
        var startPos = CaretPosition.fromRangeStart(rng);
        var endPos = CaretPosition.fromRangeEnd(rng);
        var rootNode = rng.commonAncestorContainer;
        return fromPosition(false, rootNode, endPos).map(function(newEndPos) {
          if (!isInSameBlock(startPos, endPos, rootNode) && isInSameBlock(startPos, newEndPos, rootNode)) {
            return createRange(startPos.container(), startPos.offset(), newEndPos.container(), newEndPos.offset());
          } else {
            return rng;
          }
        }).getOr(rng);
      };
      var normalize = function(rng) {
        return rng.collapsed ? rng : normalizeBlockSelectionRange(rng);
      };
      var hasOnlyOneChild$1 = function(node) {
        return node.firstChild && node.firstChild === node.lastChild;
      };
      var isPaddingNode = function(node) {
        return node.name === "br" || node.value === nbsp;
      };
      var isPaddedEmptyBlock = function(schema, node) {
        var blockElements = schema.getBlockElements();
        return blockElements[node.name] && hasOnlyOneChild$1(node) && isPaddingNode(node.firstChild);
      };
      var isEmptyFragmentElement = function(schema, node) {
        var nonEmptyElements = schema.getNonEmptyElements();
        return node && (node.isEmpty(nonEmptyElements) || isPaddedEmptyBlock(schema, node));
      };
      var isListFragment = function(schema, fragment) {
        var firstChild2 = fragment.firstChild;
        var lastChild2 = fragment.lastChild;
        if (firstChild2 && firstChild2.name === "meta") {
          firstChild2 = firstChild2.next;
        }
        if (lastChild2 && lastChild2.attr("id") === "mce_marker") {
          lastChild2 = lastChild2.prev;
        }
        if (isEmptyFragmentElement(schema, lastChild2)) {
          lastChild2 = lastChild2.prev;
        }
        if (!firstChild2 || firstChild2 !== lastChild2) {
          return false;
        }
        return firstChild2.name === "ul" || firstChild2.name === "ol";
      };
      var cleanupDomFragment = function(domFragment) {
        var firstChild2 = domFragment.firstChild;
        var lastChild2 = domFragment.lastChild;
        if (firstChild2 && firstChild2.nodeName === "META") {
          firstChild2.parentNode.removeChild(firstChild2);
        }
        if (lastChild2 && lastChild2.id === "mce_marker") {
          lastChild2.parentNode.removeChild(lastChild2);
        }
        return domFragment;
      };
      var toDomFragment = function(dom2, serializer, fragment) {
        var html = serializer.serialize(fragment);
        var domFragment = dom2.createFragment(html);
        return cleanupDomFragment(domFragment);
      };
      var listItems = function(elm) {
        return filter$4(elm.childNodes, function(child2) {
          return child2.nodeName === "LI";
        });
      };
      var isPadding = function(node) {
        return node.data === nbsp || isBr$5(node);
      };
      var isListItemPadded = function(node) {
        return node && node.firstChild && node.firstChild === node.lastChild && isPadding(node.firstChild);
      };
      var isEmptyOrPadded = function(elm) {
        return !elm.firstChild || isListItemPadded(elm);
      };
      var trimListItems = function(elms) {
        return elms.length > 0 && isEmptyOrPadded(elms[elms.length - 1]) ? elms.slice(0, -1) : elms;
      };
      var getParentLi = function(dom2, node) {
        var parentBlock = dom2.getParent(node, dom2.isBlock);
        return parentBlock && parentBlock.nodeName === "LI" ? parentBlock : null;
      };
      var isParentBlockLi = function(dom2, node) {
        return !!getParentLi(dom2, node);
      };
      var getSplit = function(parentNode, rng) {
        var beforeRng = rng.cloneRange();
        var afterRng = rng.cloneRange();
        beforeRng.setStartBefore(parentNode);
        afterRng.setEndAfter(parentNode);
        return [
          beforeRng.cloneContents(),
          afterRng.cloneContents()
        ];
      };
      var findFirstIn = function(node, rootNode) {
        var caretPos = CaretPosition.before(node);
        var caretWalker = CaretWalker(rootNode);
        var newCaretPos = caretWalker.next(caretPos);
        return newCaretPos ? newCaretPos.toRange() : null;
      };
      var findLastOf = function(node, rootNode) {
        var caretPos = CaretPosition.after(node);
        var caretWalker = CaretWalker(rootNode);
        var newCaretPos = caretWalker.prev(caretPos);
        return newCaretPos ? newCaretPos.toRange() : null;
      };
      var insertMiddle = function(target, elms, rootNode, rng) {
        var parts = getSplit(target, rng);
        var parentElm = target.parentNode;
        parentElm.insertBefore(parts[0], target);
        Tools.each(elms, function(li) {
          parentElm.insertBefore(li, target);
        });
        parentElm.insertBefore(parts[1], target);
        parentElm.removeChild(target);
        return findLastOf(elms[elms.length - 1], rootNode);
      };
      var insertBefore$1 = function(target, elms, rootNode) {
        var parentElm = target.parentNode;
        Tools.each(elms, function(elm) {
          parentElm.insertBefore(elm, target);
        });
        return findFirstIn(target, rootNode);
      };
      var insertAfter$1 = function(target, elms, rootNode, dom2) {
        dom2.insertAfter(elms.reverse(), target);
        return findLastOf(elms[0], rootNode);
      };
      var insertAtCaret$1 = function(serializer, dom2, rng, fragment) {
        var domFragment = toDomFragment(dom2, serializer, fragment);
        var liTarget = getParentLi(dom2, rng.startContainer);
        var liElms = trimListItems(listItems(domFragment.firstChild));
        var BEGINNING = 1, END = 2;
        var rootNode = dom2.getRoot();
        var isAt = function(location) {
          var caretPos = CaretPosition.fromRangeStart(rng);
          var caretWalker = CaretWalker(dom2.getRoot());
          var newPos = location === BEGINNING ? caretWalker.prev(caretPos) : caretWalker.next(caretPos);
          return newPos ? getParentLi(dom2, newPos.getNode()) !== liTarget : true;
        };
        if (isAt(BEGINNING)) {
          return insertBefore$1(liTarget, liElms, rootNode);
        } else if (isAt(END)) {
          return insertAfter$1(liTarget, liElms, rootNode, dom2);
        }
        return insertMiddle(liTarget, liElms, rootNode, rng);
      };
      var trimOrPadLeftRight = function(dom2, rng, html) {
        var root = SugarElement.fromDom(dom2.getRoot());
        if (needsToBeNbspLeft(root, CaretPosition.fromRangeStart(rng))) {
          html = html.replace(/^ /, "&nbsp;");
        } else {
          html = html.replace(/^&nbsp;/, " ");
        }
        if (needsToBeNbspRight(root, CaretPosition.fromRangeEnd(rng))) {
          html = html.replace(/(&nbsp;| )(<br( \/)>)?$/, "&nbsp;");
        } else {
          html = html.replace(/&nbsp;(<br( \/)?>)?$/, " ");
        }
        return html;
      };
      var isTableCell$1 = isTableCell$5;
      var isTableCellContentSelected = function(dom2, rng, cell) {
        if (cell !== null) {
          var endCell = dom2.getParent(rng.endContainer, isTableCell$1);
          return cell === endCell && hasAllContentsSelected(SugarElement.fromDom(cell), rng);
        } else {
          return false;
        }
      };
      var validInsertion = function(editor, value2, parentNode) {
        if (parentNode.getAttribute("data-mce-bogus") === "all") {
          parentNode.parentNode.insertBefore(editor.dom.createFragment(value2), parentNode);
        } else {
          var node = parentNode.firstChild;
          var node2 = parentNode.lastChild;
          if (!node || node === node2 && node.nodeName === "BR") {
            editor.dom.setHTML(parentNode, value2);
          } else {
            editor.selection.setContent(value2);
          }
        }
      };
      var trimBrsFromTableCell = function(dom2, elm) {
        Optional.from(dom2.getParent(elm, "td,th")).map(SugarElement.fromDom).each(trimBlockTrailingBr);
      };
      var reduceInlineTextElements = function(editor, merge2) {
        var textInlineElements = editor.schema.getTextInlineElements();
        var dom2 = editor.dom;
        if (merge2) {
          var root_1 = editor.getBody();
          var elementUtils_1 = ElementUtils(dom2);
          Tools.each(dom2.select("*[data-mce-fragment]"), function(node) {
            var isInline2 = isNonNullable(textInlineElements[node.nodeName.toLowerCase()]);
            if (isInline2 && hasInheritableStyles(dom2, node)) {
              for (var parentNode = node.parentNode; isNonNullable(parentNode) && parentNode !== root_1; parentNode = parentNode.parentNode) {
                var styleConflict = hasStyleConflict(dom2, node, parentNode);
                if (styleConflict) {
                  break;
                }
                if (elementUtils_1.compare(parentNode, node)) {
                  dom2.remove(node, true);
                  break;
                }
              }
            }
          });
        }
      };
      var markFragmentElements = function(fragment) {
        var node = fragment;
        while (node = node.walk()) {
          if (node.type === 1) {
            node.attr("data-mce-fragment", "1");
          }
        }
      };
      var unmarkFragmentElements = function(elm) {
        Tools.each(elm.getElementsByTagName("*"), function(elm2) {
          elm2.removeAttribute("data-mce-fragment");
        });
      };
      var isPartOfFragment = function(node) {
        return !!node.getAttribute("data-mce-fragment");
      };
      var canHaveChildren = function(editor, node) {
        return node && !editor.schema.getShortEndedElements()[node.nodeName];
      };
      var moveSelectionToMarker = function(editor, marker) {
        var nextRng;
        var dom2 = editor.dom;
        var selection = editor.selection;
        if (!marker) {
          return;
        }
        selection.scrollIntoView(marker);
        var parentEditableElm = getContentEditableRoot$1(editor.getBody(), marker);
        if (dom2.getContentEditable(parentEditableElm) === "false") {
          dom2.remove(marker);
          selection.select(parentEditableElm);
          return;
        }
        var rng = dom2.createRng();
        var node = marker.previousSibling;
        if (isText$7(node)) {
          rng.setStart(node, node.nodeValue.length);
          if (!Env.ie) {
            var node2 = marker.nextSibling;
            if (isText$7(node2)) {
              node.appendData(node2.data);
              node2.parentNode.removeChild(node2);
            }
          }
        } else {
          rng.setStartBefore(marker);
          rng.setEndBefore(marker);
        }
        var findNextCaretRng = function(rng2) {
          var caretPos = CaretPosition.fromRangeStart(rng2);
          var caretWalker = CaretWalker(editor.getBody());
          caretPos = caretWalker.next(caretPos);
          if (caretPos) {
            return caretPos.toRange();
          }
        };
        var parentBlock = dom2.getParent(marker, dom2.isBlock);
        dom2.remove(marker);
        if (parentBlock && dom2.isEmpty(parentBlock)) {
          editor.$(parentBlock).empty();
          rng.setStart(parentBlock, 0);
          rng.setEnd(parentBlock, 0);
          if (!isTableCell$1(parentBlock) && !isPartOfFragment(parentBlock) && (nextRng = findNextCaretRng(rng))) {
            rng = nextRng;
            dom2.remove(parentBlock);
          } else {
            dom2.add(parentBlock, dom2.create("br", { "data-mce-bogus": "1" }));
          }
        }
        selection.setRng(rng);
      };
      var deleteSelectedContent = function(editor) {
        var dom2 = editor.dom;
        var rng = normalize(editor.selection.getRng());
        editor.selection.setRng(rng);
        var startCell = dom2.getParent(rng.startContainer, isTableCell$1);
        if (isTableCellContentSelected(dom2, rng, startCell)) {
          deleteCellContents(editor, rng, SugarElement.fromDom(startCell));
        } else {
          editor.getDoc().execCommand("Delete", false, null);
        }
      };
      var insertHtmlAtCaret = function(editor, value2, details) {
        var parentNode;
        var rng, node;
        var selection = editor.selection;
        var dom2 = editor.dom;
        if (/^ | $/.test(value2)) {
          value2 = trimOrPadLeftRight(dom2, selection.getRng(), value2);
        }
        var parser = editor.parser;
        var merge2 = details.merge;
        var serializer = HtmlSerializer({ validate: shouldValidate(editor) }, editor.schema);
        var bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>';
        var args = editor.fire("BeforeSetContent", {
          content: value2,
          format: "html",
          selection: true,
          paste: details.paste
        });
        if (args.isDefaultPrevented()) {
          editor.fire("SetContent", {
            content: args.content,
            format: "html",
            selection: true,
            paste: details.paste
          });
          return;
        }
        value2 = args.content;
        if (value2.indexOf("{$caret}") === -1) {
          value2 += "{$caret}";
        }
        value2 = value2.replace(/\{\$caret\}/, bookmarkHtml);
        rng = selection.getRng();
        var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
        var body = editor.getBody();
        if (caretElement === body && selection.isCollapsed()) {
          if (dom2.isBlock(body.firstChild) && canHaveChildren(editor, body.firstChild) && dom2.isEmpty(body.firstChild)) {
            rng = dom2.createRng();
            rng.setStart(body.firstChild, 0);
            rng.setEnd(body.firstChild, 0);
            selection.setRng(rng);
          }
        }
        if (!selection.isCollapsed()) {
          deleteSelectedContent(editor);
        }
        parentNode = selection.getNode();
        var parserArgs = {
          context: parentNode.nodeName.toLowerCase(),
          data: details.data,
          insert: true
        };
        var fragment = parser.parse(value2, parserArgs);
        if (details.paste === true && isListFragment(editor.schema, fragment) && isParentBlockLi(dom2, parentNode)) {
          rng = insertAtCaret$1(serializer, dom2, selection.getRng(), fragment);
          selection.setRng(rng);
          editor.fire("SetContent", args);
          return;
        }
        markFragmentElements(fragment);
        node = fragment.lastChild;
        if (node.attr("id") === "mce_marker") {
          var marker = node;
          for (node = node.prev; node; node = node.walk(true)) {
            if (node.type === 3 || !dom2.isBlock(node.name)) {
              if (editor.schema.isValidChild(node.parent.name, "span")) {
                node.parent.insert(marker, node, node.name === "br");
              }
              break;
            }
          }
        }
        editor._selectionOverrides.showBlockCaretContainer(parentNode);
        if (!parserArgs.invalid) {
          value2 = serializer.serialize(fragment);
          validInsertion(editor, value2, parentNode);
        } else {
          editor.selection.setContent(bookmarkHtml);
          parentNode = selection.getNode();
          var rootNode = editor.getBody();
          if (parentNode.nodeType === 9) {
            parentNode = node = rootNode;
          } else {
            node = parentNode;
          }
          while (node !== rootNode) {
            parentNode = node;
            node = node.parentNode;
          }
          value2 = parentNode === rootNode ? rootNode.innerHTML : dom2.getOuterHTML(parentNode);
          value2 = serializer.serialize(parser.parse(value2.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
            return serializer.serialize(fragment);
          })));
          if (parentNode === rootNode) {
            dom2.setHTML(rootNode, value2);
          } else {
            dom2.setOuterHTML(parentNode, value2);
          }
        }
        reduceInlineTextElements(editor, merge2);
        moveSelectionToMarker(editor, dom2.get("mce_marker"));
        unmarkFragmentElements(editor.getBody());
        trimBrsFromTableCell(dom2, selection.getStart());
        editor.fire("SetContent", args);
        editor.addVisual();
      };
      var traverse = function(node, fn) {
        fn(node);
        if (node.firstChild) {
          traverse(node.firstChild, fn);
        }
        if (node.next) {
          traverse(node.next, fn);
        }
      };
      var findMatchingNodes = function(nodeFilters, attributeFilters, node) {
        var nodeMatches = {};
        var attrMatches = {};
        var matches2 = [];
        if (node.firstChild) {
          traverse(node.firstChild, function(node2) {
            each$k(nodeFilters, function(filter2) {
              if (filter2.name === node2.name) {
                if (nodeMatches[filter2.name]) {
                  nodeMatches[filter2.name].nodes.push(node2);
                } else {
                  nodeMatches[filter2.name] = {
                    filter: filter2,
                    nodes: [node2]
                  };
                }
              }
            });
            each$k(attributeFilters, function(filter2) {
              if (typeof node2.attr(filter2.name) === "string") {
                if (attrMatches[filter2.name]) {
                  attrMatches[filter2.name].nodes.push(node2);
                } else {
                  attrMatches[filter2.name] = {
                    filter: filter2,
                    nodes: [node2]
                  };
                }
              }
            });
          });
        }
        for (var name_1 in nodeMatches) {
          if (has$2(nodeMatches, name_1)) {
            matches2.push(nodeMatches[name_1]);
          }
        }
        for (var name_2 in attrMatches) {
          if (has$2(attrMatches, name_2)) {
            matches2.push(attrMatches[name_2]);
          }
        }
        return matches2;
      };
      var filter$1 = function(nodeFilters, attributeFilters, node) {
        var matches2 = findMatchingNodes(nodeFilters, attributeFilters, node);
        each$k(matches2, function(match2) {
          each$k(match2.filter.callbacks, function(callback) {
            callback(match2.nodes, match2.filter.name, {});
          });
        });
      };
      var defaultFormat$1 = "html";
      var isTreeNode = function(content) {
        return content instanceof AstNode;
      };
      var moveSelection = function(editor) {
        if (hasFocus(editor)) {
          firstPositionIn(editor.getBody()).each(function(pos) {
            var node = pos.getNode();
            var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
            editor.selection.setRng(caretPos.toRange());
          });
        }
      };
      var setEditorHtml = function(editor, html, noSelection) {
        editor.dom.setHTML(editor.getBody(), html);
        if (noSelection !== true) {
          moveSelection(editor);
        }
      };
      var setContentString = function(editor, body, content, args) {
        if (content.length === 0 || /^\s+$/.test(content)) {
          var padd = '<br data-mce-bogus="1">';
          if (body.nodeName === "TABLE") {
            content = "<tr><td>" + padd + "</td></tr>";
          } else if (/^(UL|OL)$/.test(body.nodeName)) {
            content = "<li>" + padd + "</li>";
          }
          var forcedRootBlockName = getForcedRootBlock(editor);
          if (forcedRootBlockName && editor.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
            content = padd;
            content = editor.dom.createHTML(forcedRootBlockName, getForcedRootBlockAttrs(editor), content);
          } else if (!content) {
            content = '<br data-mce-bogus="1">';
          }
          setEditorHtml(editor, content, args.no_selection);
          editor.fire("SetContent", args);
        } else {
          if (args.format !== "raw") {
            content = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(editor.parser.parse(content, {
              isRootContent: true,
              insert: true
            }));
          }
          args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? content : Tools.trim(content);
          setEditorHtml(editor, args.content, args.no_selection);
          if (!args.no_events) {
            editor.fire("SetContent", args);
          }
        }
        return args.content;
      };
      var setContentTree = function(editor, body, content, args) {
        filter$1(editor.parser.getNodeFilters(), editor.parser.getAttributeFilters(), content);
        var html = HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(content);
        args.content = isWsPreserveElement(SugarElement.fromDom(body)) ? html : Tools.trim(html);
        setEditorHtml(editor, args.content, args.no_selection);
        if (!args.no_events) {
          editor.fire("SetContent", args);
        }
        return content;
      };
      var setupArgs$2 = function(args, content) {
        return __assign(__assign({ format: defaultFormat$1 }, args), {
          set: true,
          content: isTreeNode(content) ? "" : content
        });
      };
      var setContentInternal = function(editor, content, args) {
        var defaultedArgs = setupArgs$2(args, content);
        var updatedArgs = args.no_events ? defaultedArgs : editor.fire("BeforeSetContent", defaultedArgs);
        if (!isTreeNode(content)) {
          content = updatedArgs.content;
        }
        return Optional.from(editor.getBody()).fold(constant(content), function(body) {
          return isTreeNode(content) ? setContentTree(editor, body, content, updatedArgs) : setContentString(editor, body, content, updatedArgs);
        });
      };
      var sibling = function(scope, predicate) {
        return sibling$2(scope, predicate).isSome();
      };
      var ensureIsRoot = function(isRoot) {
        return isFunction(isRoot) ? isRoot : never;
      };
      var ancestor = function(scope, transform, isRoot) {
        var element = scope.dom;
        var stop2 = ensureIsRoot(isRoot);
        while (element.parentNode) {
          element = element.parentNode;
          var el = SugarElement.fromDom(element);
          var transformed = transform(el);
          if (transformed.isSome()) {
            return transformed;
          } else if (stop2(el)) {
            break;
          }
        }
        return Optional.none();
      };
      var closest$1 = function(scope, transform, isRoot) {
        var current = transform(scope);
        var stop2 = ensureIsRoot(isRoot);
        return current.orThunk(function() {
          return stop2(scope) ? Optional.none() : ancestor(scope, transform, stop2);
        });
      };
      var isEq$3 = isEq$5;
      var matchesUnInheritedFormatSelector = function(ed, node, name2) {
        var formatList = ed.formatter.get(name2);
        if (formatList) {
          for (var i = 0; i < formatList.length; i++) {
            var format = formatList[i];
            if (isSelectorFormat(format) && format.inherit === false && ed.dom.is(node, format.selector)) {
              return true;
            }
          }
        }
        return false;
      };
      var matchParents = function(editor, node, name2, vars, similar) {
        var root = editor.dom.getRoot();
        if (node === root) {
          return false;
        }
        node = editor.dom.getParent(node, function(node2) {
          if (matchesUnInheritedFormatSelector(editor, node2, name2)) {
            return true;
          }
          return node2.parentNode === root || !!matchNode(editor, node2, name2, vars, true);
        });
        return !!matchNode(editor, node, name2, vars, similar);
      };
      var matchName$1 = function(dom2, node, format) {
        if (isEq$3(node, format.inline)) {
          return true;
        }
        if (isEq$3(node, format.block)) {
          return true;
        }
        if (format.selector) {
          return node.nodeType === 1 && dom2.is(node, format.selector);
        }
      };
      var matchItems = function(dom2, node, format, itemName, similar, vars) {
        var items = format[itemName];
        if (isFunction(format.onmatch)) {
          return format.onmatch(node, format, itemName);
        }
        if (items) {
          if (isUndefined(items.length)) {
            for (var key in items) {
              if (has$2(items, key)) {
                var value2 = itemName === "attributes" ? dom2.getAttrib(node, key) : getStyle(dom2, node, key);
                var expectedValue = replaceVars(items[key], vars);
                var isEmptyValue = isNullable(value2) || isEmpty$3(value2);
                if (isEmptyValue && isNullable(expectedValue)) {
                  continue;
                }
                if (similar && isEmptyValue && !format.exact) {
                  return false;
                }
                if ((!similar || format.exact) && !isEq$3(value2, normalizeStyleValue(dom2, expectedValue, key))) {
                  return false;
                }
              }
            }
          } else {
            for (var i = 0; i < items.length; i++) {
              if (itemName === "attributes" ? dom2.getAttrib(node, items[i]) : getStyle(dom2, node, items[i])) {
                return true;
              }
            }
          }
        }
        return true;
      };
      var matchNode = function(ed, node, name2, vars, similar) {
        var formatList = ed.formatter.get(name2);
        var dom2 = ed.dom;
        if (formatList && node) {
          for (var i = 0; i < formatList.length; i++) {
            var format = formatList[i];
            if (matchName$1(ed.dom, node, format) && matchItems(dom2, node, format, "attributes", similar, vars) && matchItems(dom2, node, format, "styles", similar, vars)) {
              var classes = format.classes;
              if (classes) {
                for (var x = 0; x < classes.length; x++) {
                  if (!ed.dom.hasClass(node, replaceVars(classes[x], vars))) {
                    return;
                  }
                }
              }
              return format;
            }
          }
        }
      };
      var match$2 = function(editor, name2, vars, node, similar) {
        if (node) {
          return matchParents(editor, node, name2, vars, similar);
        }
        node = editor.selection.getNode();
        if (matchParents(editor, node, name2, vars, similar)) {
          return true;
        }
        var startNode = editor.selection.getStart();
        if (startNode !== node) {
          if (matchParents(editor, startNode, name2, vars, similar)) {
            return true;
          }
        }
        return false;
      };
      var matchAll = function(editor, names, vars) {
        var matchedFormatNames = [];
        var checkedMap = {};
        var startElement = editor.selection.getStart();
        editor.dom.getParent(startElement, function(node) {
          for (var i = 0; i < names.length; i++) {
            var name_1 = names[i];
            if (!checkedMap[name_1] && matchNode(editor, node, name_1, vars)) {
              checkedMap[name_1] = true;
              matchedFormatNames.push(name_1);
            }
          }
        }, editor.dom.getRoot());
        return matchedFormatNames;
      };
      var closest = function(editor, names) {
        var isRoot = function(elm) {
          return eq(elm, SugarElement.fromDom(editor.getBody()));
        };
        var match2 = function(elm, name2) {
          return matchNode(editor, elm.dom, name2) ? Optional.some(name2) : Optional.none();
        };
        return Optional.from(editor.selection.getStart(true)).bind(function(rawElm) {
          return closest$1(SugarElement.fromDom(rawElm), function(elm) {
            return findMap(names, function(name2) {
              return match2(elm, name2);
            });
          }, isRoot);
        }).getOrNull();
      };
      var canApply = function(editor, name2) {
        var formatList = editor.formatter.get(name2);
        var dom2 = editor.dom;
        if (formatList) {
          var startNode = editor.selection.getStart();
          var parents2 = getParents$2(dom2, startNode);
          for (var x = formatList.length - 1; x >= 0; x--) {
            var format = formatList[x];
            if (!isSelectorFormat(format) || isNonNullable(format.defaultBlock)) {
              return true;
            }
            for (var i = parents2.length - 1; i >= 0; i--) {
              if (dom2.is(parents2[i], format.selector)) {
                return true;
              }
            }
          }
        }
        return false;
      };
      var matchAllOnNode = function(editor, node, formatNames) {
        return foldl(formatNames, function(acc, name2) {
          var matchSimilar = isVariableFormatName(editor, name2);
          if (editor.formatter.matchNode(node, name2, {}, matchSimilar)) {
            return acc.concat([name2]);
          } else {
            return acc;
          }
        }, []);
      };
      var ZWSP = ZWSP$1, CARET_ID = "_mce_caret";
      var importNode = function(ownerDocument, node) {
        return ownerDocument.importNode(node, true);
      };
      var getEmptyCaretContainers = function(node) {
        var nodes = [];
        while (node) {
          if (node.nodeType === 3 && node.nodeValue !== ZWSP || node.childNodes.length > 1) {
            return [];
          }
          if (node.nodeType === 1) {
            nodes.push(node);
          }
          node = node.firstChild;
        }
        return nodes;
      };
      var isCaretContainerEmpty = function(node) {
        return getEmptyCaretContainers(node).length > 0;
      };
      var findFirstTextNode = function(node) {
        if (node) {
          var walker = new DomTreeWalker(node, node);
          for (node = walker.current(); node; node = walker.next()) {
            if (isText$7(node)) {
              return node;
            }
          }
        }
        return null;
      };
      var createCaretContainer = function(fill) {
        var caretContainer = SugarElement.fromTag("span");
        setAll$1(caretContainer, {
          "id": CARET_ID,
          "data-mce-bogus": "1",
          "data-mce-type": "format-caret"
        });
        if (fill) {
          append$1(caretContainer, SugarElement.fromText(ZWSP));
        }
        return caretContainer;
      };
      var trimZwspFromCaretContainer = function(caretContainerNode) {
        var textNode = findFirstTextNode(caretContainerNode);
        if (textNode && textNode.nodeValue.charAt(0) === ZWSP) {
          textNode.deleteData(0, 1);
        }
        return textNode;
      };
      var removeCaretContainerNode = function(editor, node, moveCaret2) {
        if (moveCaret2 === void 0) {
          moveCaret2 = true;
        }
        var dom2 = editor.dom, selection = editor.selection;
        if (isCaretContainerEmpty(node)) {
          deleteElement$2(editor, false, SugarElement.fromDom(node), moveCaret2);
        } else {
          var rng = selection.getRng();
          var block = dom2.getParent(node, dom2.isBlock);
          var startContainer = rng.startContainer;
          var startOffset = rng.startOffset;
          var endContainer = rng.endContainer;
          var endOffset = rng.endOffset;
          var textNode = trimZwspFromCaretContainer(node);
          dom2.remove(node, true);
          if (startContainer === textNode && startOffset > 0) {
            rng.setStart(textNode, startOffset - 1);
          }
          if (endContainer === textNode && endOffset > 0) {
            rng.setEnd(textNode, endOffset - 1);
          }
          if (block && dom2.isEmpty(block)) {
            fillWithPaddingBr(SugarElement.fromDom(block));
          }
          selection.setRng(rng);
        }
      };
      var removeCaretContainer = function(editor, node, moveCaret2) {
        if (moveCaret2 === void 0) {
          moveCaret2 = true;
        }
        var dom2 = editor.dom, selection = editor.selection;
        if (!node) {
          node = getParentCaretContainer(editor.getBody(), selection.getStart());
          if (!node) {
            while (node = dom2.get(CARET_ID)) {
              removeCaretContainerNode(editor, node, false);
            }
          }
        } else {
          removeCaretContainerNode(editor, node, moveCaret2);
        }
      };
      var insertCaretContainerNode = function(editor, caretContainer, formatNode) {
        var dom2 = editor.dom, block = dom2.getParent(formatNode, curry(isTextBlock$1, editor));
        if (block && dom2.isEmpty(block)) {
          formatNode.parentNode.replaceChild(caretContainer, formatNode);
        } else {
          removeTrailingBr(SugarElement.fromDom(formatNode));
          if (dom2.isEmpty(formatNode)) {
            formatNode.parentNode.replaceChild(caretContainer, formatNode);
          } else {
            dom2.insertAfter(caretContainer, formatNode);
          }
        }
      };
      var appendNode = function(parentNode, node) {
        parentNode.appendChild(node);
        return node;
      };
      var insertFormatNodesIntoCaretContainer = function(formatNodes, caretContainer) {
        var innerMostFormatNode = foldr(formatNodes, function(parentNode, formatNode) {
          return appendNode(parentNode, formatNode.cloneNode(false));
        }, caretContainer);
        return appendNode(innerMostFormatNode, innerMostFormatNode.ownerDocument.createTextNode(ZWSP));
      };
      var cleanFormatNode = function(editor, caretContainer, formatNode, name2, vars, similar) {
        var formatter = editor.formatter;
        var dom2 = editor.dom;
        var validFormats = filter$4(keys(formatter.get()), function(formatName) {
          return formatName !== name2 && !contains$2(formatName, "removeformat");
        });
        var matchedFormats = matchAllOnNode(editor, formatNode, validFormats);
        var uniqueFormats = filter$4(matchedFormats, function(fmtName) {
          return !areSimilarFormats(editor, fmtName, name2);
        });
        if (uniqueFormats.length > 0) {
          var clonedFormatNode = formatNode.cloneNode(false);
          dom2.add(caretContainer, clonedFormatNode);
          formatter.remove(name2, vars, clonedFormatNode, similar);
          dom2.remove(clonedFormatNode);
          return Optional.some(clonedFormatNode);
        } else {
          return Optional.none();
        }
      };
      var applyCaretFormat = function(editor, name2, vars) {
        var caretContainer, textNode;
        var selection = editor.selection;
        var selectionRng = selection.getRng();
        var offset = selectionRng.startOffset;
        var container = selectionRng.startContainer;
        var text = container.nodeValue;
        caretContainer = getParentCaretContainer(editor.getBody(), selection.getStart());
        if (caretContainer) {
          textNode = findFirstTextNode(caretContainer);
        }
        var wordcharRegex = /[^\s\u00a0\u00ad\u200b\ufeff]/;
        if (text && offset > 0 && offset < text.length && wordcharRegex.test(text.charAt(offset)) && wordcharRegex.test(text.charAt(offset - 1))) {
          var bookmark = selection.getBookmark();
          selectionRng.collapse(true);
          var rng = expandRng(editor, selectionRng, editor.formatter.get(name2));
          rng = split(rng);
          editor.formatter.apply(name2, vars, rng);
          selection.moveToBookmark(bookmark);
        } else {
          if (!caretContainer || textNode.nodeValue !== ZWSP) {
            caretContainer = importNode(editor.getDoc(), createCaretContainer(true).dom);
            textNode = caretContainer.firstChild;
            selectionRng.insertNode(caretContainer);
            offset = 1;
            editor.formatter.apply(name2, vars, caretContainer);
          } else {
            editor.formatter.apply(name2, vars, caretContainer);
          }
          selection.setCursorLocation(textNode, offset);
        }
      };
      var removeCaretFormat = function(editor, name2, vars, similar) {
        var dom2 = editor.dom;
        var selection = editor.selection;
        var hasContentAfter, node, formatNode;
        var parents2 = [];
        var rng = selection.getRng();
        var container = rng.startContainer;
        var offset = rng.startOffset;
        node = container;
        if (container.nodeType === 3) {
          if (offset !== container.nodeValue.length) {
            hasContentAfter = true;
          }
          node = node.parentNode;
        }
        while (node) {
          if (matchNode(editor, node, name2, vars, similar)) {
            formatNode = node;
            break;
          }
          if (node.nextSibling) {
            hasContentAfter = true;
          }
          parents2.push(node);
          node = node.parentNode;
        }
        if (!formatNode) {
          return;
        }
        if (hasContentAfter) {
          var bookmark = selection.getBookmark();
          rng.collapse(true);
          var expandedRng = expandRng(editor, rng, editor.formatter.get(name2), true);
          expandedRng = split(expandedRng);
          editor.formatter.remove(name2, vars, expandedRng, similar);
          selection.moveToBookmark(bookmark);
        } else {
          var caretContainer = getParentCaretContainer(editor.getBody(), formatNode);
          var newCaretContainer = createCaretContainer(false).dom;
          insertCaretContainerNode(editor, newCaretContainer, caretContainer !== null ? caretContainer : formatNode);
          var cleanedFormatNode = cleanFormatNode(editor, newCaretContainer, formatNode, name2, vars, similar);
          var caretTextNode = insertFormatNodesIntoCaretContainer(parents2.concat(cleanedFormatNode.toArray()), newCaretContainer);
          removeCaretContainerNode(editor, caretContainer, false);
          selection.setCursorLocation(caretTextNode, 1);
          if (dom2.isEmpty(formatNode)) {
            dom2.remove(formatNode);
          }
        }
      };
      var disableCaretContainer = function(editor, keyCode) {
        var selection = editor.selection, body = editor.getBody();
        removeCaretContainer(editor, null, false);
        if ((keyCode === 8 || keyCode === 46) && selection.isCollapsed() && selection.getStart().innerHTML === ZWSP) {
          removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
        }
        if (keyCode === 37 || keyCode === 39) {
          removeCaretContainer(editor, getParentCaretContainer(body, selection.getStart()));
        }
      };
      var setup$k = function(editor) {
        editor.on("mouseup keydown", function(e) {
          disableCaretContainer(editor, e.keyCode);
        });
      };
      var replaceWithCaretFormat = function(targetNode, formatNodes) {
        var caretContainer = createCaretContainer(false);
        var innerMost = insertFormatNodesIntoCaretContainer(formatNodes, caretContainer.dom);
        before$4(SugarElement.fromDom(targetNode), caretContainer);
        remove$7(SugarElement.fromDom(targetNode));
        return CaretPosition(innerMost, 0);
      };
      var isFormatElement = function(editor, element) {
        var inlineElements = editor.schema.getTextInlineElements();
        return has$2(inlineElements, name(element)) && !isCaretNode(element.dom) && !isBogus$2(element.dom);
      };
      var isEmptyCaretFormatElement = function(element) {
        return isCaretNode(element.dom) && isCaretContainerEmpty(element.dom);
      };
      var postProcessHooks = {};
      var filter = filter$2;
      var each$b = each$i;
      var addPostProcessHook = function(name2, hook) {
        var hooks = postProcessHooks[name2];
        if (!hooks) {
          postProcessHooks[name2] = [];
        }
        postProcessHooks[name2].push(hook);
      };
      var postProcess$1 = function(name2, editor) {
        each$b(postProcessHooks[name2], function(hook) {
          hook(editor);
        });
      };
      addPostProcessHook("pre", function(editor) {
        var rng = editor.selection.getRng();
        var blocks2;
        var hasPreSibling = function(pre) {
          return isPre(pre.previousSibling) && indexOf$1(blocks2, pre.previousSibling) !== -1;
        };
        var joinPre = function(pre1, pre2) {
          DomQuery(pre2).remove();
          DomQuery(pre1).append("<br><br>").append(pre2.childNodes);
        };
        var isPre = matchNodeNames(["pre"]);
        if (!rng.collapsed) {
          blocks2 = editor.selection.getSelectedBlocks();
          each$b(filter(filter(blocks2, isPre), hasPreSibling), function(pre) {
            joinPre(pre.previousSibling, pre);
          });
        }
      });
      var each$a = Tools.each;
      var isElementNode$1 = function(node) {
        return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
      };
      var findElementSibling = function(node, siblingName) {
        for (var sibling2 = node; sibling2; sibling2 = sibling2[siblingName]) {
          if (isText$7(sibling2) && isNotEmpty(sibling2.data)) {
            return node;
          }
          if (isElement$5(sibling2) && !isBookmarkNode$1(sibling2)) {
            return sibling2;
          }
        }
        return node;
      };
      var mergeSiblingsNodes = function(dom2, prev, next) {
        var elementUtils = ElementUtils(dom2);
        if (prev && next) {
          prev = findElementSibling(prev, "previousSibling");
          next = findElementSibling(next, "nextSibling");
          if (elementUtils.compare(prev, next)) {
            for (var sibling2 = prev.nextSibling; sibling2 && sibling2 !== next; ) {
              var tmpSibling = sibling2;
              sibling2 = sibling2.nextSibling;
              prev.appendChild(tmpSibling);
            }
            dom2.remove(next);
            Tools.each(Tools.grep(next.childNodes), function(node) {
              prev.appendChild(node);
            });
            return prev;
          }
        }
        return next;
      };
      var mergeSiblings = function(dom2, format, vars, node) {
        if (node && format.merge_siblings !== false) {
          var newNode = mergeSiblingsNodes(dom2, getNonWhiteSpaceSibling(node), node);
          mergeSiblingsNodes(dom2, newNode, getNonWhiteSpaceSibling(newNode, true));
        }
      };
      var clearChildStyles = function(dom2, format, node) {
        if (format.clear_child_styles) {
          var selector = format.links ? "*:not(a)" : "*";
          each$a(dom2.select(selector, node), function(node2) {
            if (isElementNode$1(node2)) {
              each$a(format.styles, function(value2, name2) {
                dom2.setStyle(node2, name2, "");
              });
            }
          });
        }
      };
      var processChildElements = function(node, filter2, process2) {
        each$a(node.childNodes, function(node2) {
          if (isElementNode$1(node2)) {
            if (filter2(node2)) {
              process2(node2);
            }
            if (node2.hasChildNodes()) {
              processChildElements(node2, filter2, process2);
            }
          }
        });
      };
      var unwrapEmptySpan = function(dom2, node) {
        if (node.nodeName === "SPAN" && dom2.getAttribs(node).length === 0) {
          dom2.remove(node, true);
        }
      };
      var hasStyle = function(dom2, name2) {
        return function(node) {
          return !!(node && getStyle(dom2, node, name2));
        };
      };
      var applyStyle = function(dom2, name2, value2) {
        return function(node) {
          dom2.setStyle(node, name2, value2);
          if (node.getAttribute("style") === "") {
            node.removeAttribute("style");
          }
          unwrapEmptySpan(dom2, node);
        };
      };
      var removeResult = Adt.generate([
        { keep: [] },
        { rename: ["name"] },
        { removed: [] }
      ]);
      var MCE_ATTR_RE = /^(src|href|style)$/;
      var each$9 = Tools.each;
      var isEq$2 = isEq$5;
      var isTableCellOrRow = function(node) {
        return /^(TR|TH|TD)$/.test(node.nodeName);
      };
      var isChildOfInlineParent = function(dom2, node, parent2) {
        return dom2.isChildOf(node, parent2) && node !== parent2 && !dom2.isBlock(parent2);
      };
      var getContainer = function(ed, rng, start2) {
        var container = rng[start2 ? "startContainer" : "endContainer"];
        var offset = rng[start2 ? "startOffset" : "endOffset"];
        if (isElement$5(container)) {
          var lastIdx = container.childNodes.length - 1;
          if (!start2 && offset) {
            offset--;
          }
          container = container.childNodes[offset > lastIdx ? lastIdx : offset];
        }
        if (isText$7(container) && start2 && offset >= container.nodeValue.length) {
          container = new DomTreeWalker(container, ed.getBody()).next() || container;
        }
        if (isText$7(container) && !start2 && offset === 0) {
          container = new DomTreeWalker(container, ed.getBody()).prev() || container;
        }
        return container;
      };
      var normalizeTableSelection = function(node, start2) {
        var prop = start2 ? "firstChild" : "lastChild";
        if (isTableCellOrRow(node) && node[prop]) {
          var childNode = node[prop];
          if (node.nodeName === "TR") {
            return childNode[prop] || childNode;
          } else {
            return childNode;
          }
        }
        return node;
      };
      var wrap$1 = function(dom2, node, name2, attrs) {
        var wrapper = dom2.create(name2, attrs);
        node.parentNode.insertBefore(wrapper, node);
        wrapper.appendChild(node);
        return wrapper;
      };
      var wrapWithSiblings = function(dom2, node, next, name2, attrs) {
        var start2 = SugarElement.fromDom(node);
        var wrapper = SugarElement.fromDom(dom2.create(name2, attrs));
        var siblings2 = next ? nextSiblings(start2) : prevSiblings(start2);
        append(wrapper, siblings2);
        if (next) {
          before$4(start2, wrapper);
          prepend(wrapper, start2);
        } else {
          after$3(start2, wrapper);
          append$1(wrapper, start2);
        }
        return wrapper.dom;
      };
      var matchName = function(dom2, node, format) {
        if (isInlineFormat(format) && isEq$2(node, format.inline)) {
          return true;
        }
        if (isBlockFormat(format) && isEq$2(node, format.block)) {
          return true;
        }
        if (isSelectorFormat(format)) {
          return isElement$5(node) && dom2.is(node, format.selector);
        }
      };
      var isColorFormatAndAnchor = function(node, format) {
        return format.links && node.nodeName === "A";
      };
      var find = function(dom2, node, next, inc) {
        var sibling2 = getNonWhiteSpaceSibling(node, next, inc);
        return isNullable(sibling2) || sibling2.nodeName === "BR" || dom2.isBlock(sibling2);
      };
      var removeNode = function(ed, node, format) {
        var parentNode = node.parentNode;
        var rootBlockElm;
        var dom2 = ed.dom, forcedRootBlock = getForcedRootBlock(ed);
        if (isBlockFormat(format)) {
          if (!forcedRootBlock) {
            if (dom2.isBlock(node) && !dom2.isBlock(parentNode)) {
              if (!find(dom2, node, false) && !find(dom2, node.firstChild, true, true)) {
                node.insertBefore(dom2.create("br"), node.firstChild);
              }
              if (!find(dom2, node, true) && !find(dom2, node.lastChild, false, true)) {
                node.appendChild(dom2.create("br"));
              }
            }
          } else {
            if (parentNode === dom2.getRoot()) {
              if (!format.list_block || !isEq$2(node, format.list_block)) {
                each$k(from(node.childNodes), function(node2) {
                  if (isValid(ed, forcedRootBlock, node2.nodeName.toLowerCase())) {
                    if (!rootBlockElm) {
                      rootBlockElm = wrap$1(dom2, node2, forcedRootBlock);
                      dom2.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
                    } else {
                      rootBlockElm.appendChild(node2);
                    }
                  } else {
                    rootBlockElm = null;
                  }
                });
              }
            }
          }
        }
        if (isMixedFormat(format) && !isEq$2(format.inline, node)) {
          return;
        }
        dom2.remove(node, true);
      };
      var removeFormatInternal = function(ed, format, vars, node, compareNode) {
        var stylesModified;
        var dom2 = ed.dom;
        if (!matchName(dom2, node, format) && !isColorFormatAndAnchor(node, format)) {
          return removeResult.keep();
        }
        var elm = node;
        if (isInlineFormat(format) && format.remove === "all" && isArray$1(format.preserve_attributes)) {
          var attrsToPreserve = filter$4(dom2.getAttribs(elm), function(attr) {
            return contains$3(format.preserve_attributes, attr.name.toLowerCase());
          });
          dom2.removeAllAttribs(elm);
          each$k(attrsToPreserve, function(attr) {
            return dom2.setAttrib(elm, attr.name, attr.value);
          });
          if (attrsToPreserve.length > 0) {
            return removeResult.rename("span");
          }
        }
        if (format.remove !== "all") {
          each$9(format.styles, function(value2, name2) {
            value2 = normalizeStyleValue(dom2, replaceVars(value2, vars), name2 + "");
            if (isNumber(name2)) {
              name2 = value2;
              compareNode = null;
            }
            if (format.remove_similar || (!compareNode || isEq$2(getStyle(dom2, compareNode, name2), value2))) {
              dom2.setStyle(elm, name2, "");
            }
            stylesModified = true;
          });
          if (stylesModified && dom2.getAttrib(elm, "style") === "") {
            elm.removeAttribute("style");
            elm.removeAttribute("data-mce-style");
          }
          each$9(format.attributes, function(value2, name2) {
            var valueOut;
            value2 = replaceVars(value2, vars);
            if (isNumber(name2)) {
              name2 = value2;
              compareNode = null;
            }
            if (format.remove_similar || (!compareNode || isEq$2(dom2.getAttrib(compareNode, name2), value2))) {
              if (name2 === "class") {
                value2 = dom2.getAttrib(elm, name2);
                if (value2) {
                  valueOut = "";
                  each$k(value2.split(/\s+/), function(cls) {
                    if (/mce\-\w+/.test(cls)) {
                      valueOut += (valueOut ? " " : "") + cls;
                    }
                  });
                  if (valueOut) {
                    dom2.setAttrib(elm, name2, valueOut);
                    return;
                  }
                }
              }
              if (MCE_ATTR_RE.test(name2)) {
                elm.removeAttribute("data-mce-" + name2);
              }
              if (name2 === "style" && matchNodeNames(["li"])(elm) && dom2.getStyle(elm, "list-style-type") === "none") {
                elm.removeAttribute(name2);
                dom2.setStyle(elm, "list-style-type", "none");
                return;
              }
              if (name2 === "class") {
                elm.removeAttribute("className");
              }
              elm.removeAttribute(name2);
            }
          });
          each$9(format.classes, function(value2) {
            value2 = replaceVars(value2, vars);
            if (!compareNode || dom2.hasClass(compareNode, value2)) {
              dom2.removeClass(elm, value2);
            }
          });
          var attrs = dom2.getAttribs(elm);
          for (var i = 0; i < attrs.length; i++) {
            var attrName = attrs[i].nodeName;
            if (attrName.indexOf("_") !== 0 && attrName.indexOf("data-") !== 0) {
              return removeResult.keep();
            }
          }
        }
        if (format.remove !== "none") {
          removeNode(ed, elm, format);
          return removeResult.removed();
        }
        return removeResult.keep();
      };
      var removeFormat$1 = function(ed, format, vars, node, compareNode) {
        return removeFormatInternal(ed, format, vars, node, compareNode).fold(never, function(newName) {
          ed.dom.rename(node, newName);
          return true;
        }, always);
      };
      var findFormatRoot = function(editor, container, name2, vars, similar) {
        var formatRoot;
        each$k(getParents$2(editor.dom, container.parentNode).reverse(), function(parent2) {
          if (!formatRoot && parent2.id !== "_start" && parent2.id !== "_end") {
            var format = matchNode(editor, parent2, name2, vars, similar);
            if (format && format.split !== false) {
              formatRoot = parent2;
            }
          }
        });
        return formatRoot;
      };
      var removeFormatFromClone = function(editor, format, vars, clone2) {
        return removeFormatInternal(editor, format, vars, clone2, clone2).fold(constant(clone2), function(newName) {
          var fragment = editor.dom.createFragment();
          fragment.appendChild(clone2);
          return editor.dom.rename(clone2, newName);
        }, constant(null));
      };
      var wrapAndSplit = function(editor, formatList, formatRoot, container, target, split2, format, vars) {
        var clone2, lastClone, firstClone;
        var dom2 = editor.dom;
        if (formatRoot) {
          var formatRootParent = formatRoot.parentNode;
          for (var parent_1 = container.parentNode; parent_1 && parent_1 !== formatRootParent; parent_1 = parent_1.parentNode) {
            clone2 = dom2.clone(parent_1, false);
            for (var i = 0; i < formatList.length; i++) {
              clone2 = removeFormatFromClone(editor, formatList[i], vars, clone2);
              if (clone2 === null) {
                break;
              }
            }
            if (clone2) {
              if (lastClone) {
                clone2.appendChild(lastClone);
              }
              if (!firstClone) {
                firstClone = clone2;
              }
              lastClone = clone2;
            }
          }
          if (split2 && (!format.mixed || !dom2.isBlock(formatRoot))) {
            container = dom2.split(formatRoot, container);
          }
          if (lastClone) {
            target.parentNode.insertBefore(lastClone, target);
            firstClone.appendChild(target);
            if (isInlineFormat(format)) {
              mergeSiblings(dom2, format, vars, lastClone);
            }
          }
        }
        return container;
      };
      var remove$1 = function(ed, name2, vars, node, similar) {
        var formatList = ed.formatter.get(name2);
        var format = formatList[0];
        var contentEditable = true;
        var dom2 = ed.dom;
        var selection = ed.selection;
        var splitToFormatRoot = function(container) {
          var formatRoot = findFormatRoot(ed, container, name2, vars, similar);
          return wrapAndSplit(ed, formatList, formatRoot, container, container, true, format, vars);
        };
        var isRemoveBookmarkNode = function(node2) {
          return isBookmarkNode$1(node2) && isElement$5(node2) && (node2.id === "_start" || node2.id === "_end");
        };
        var removeNodeFormat = function(node2) {
          return exists(formatList, function(fmt) {
            return removeFormat$1(ed, fmt, vars, node2, node2);
          });
        };
        var process2 = function(node2) {
          var lastContentEditable = true;
          var hasContentEditableState2 = false;
          if (isElement$5(node2) && dom2.getContentEditable(node2)) {
            lastContentEditable = contentEditable;
            contentEditable = dom2.getContentEditable(node2) === "true";
            hasContentEditableState2 = true;
          }
          var children2 = from(node2.childNodes);
          if (contentEditable && !hasContentEditableState2) {
            var removed = removeNodeFormat(node2);
            var currentNodeMatches = removed || exists(formatList, function(f) {
              return matchName$1(dom2, node2, f);
            });
            var parentNode = node2.parentNode;
            if (!currentNodeMatches && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
              removeNodeFormat(parentNode);
            }
          }
          if (format.deep) {
            if (children2.length) {
              for (var i2 = 0; i2 < children2.length; i2++) {
                process2(children2[i2]);
              }
              if (hasContentEditableState2) {
                contentEditable = lastContentEditable;
              }
            }
          }
          var textDecorations = [
            "underline",
            "line-through",
            "overline"
          ];
          each$k(textDecorations, function(decoration) {
            if (isElement$5(node2) && ed.dom.getStyle(node2, "text-decoration") === decoration && node2.parentNode && getTextDecoration(dom2, node2.parentNode) === decoration) {
              removeFormat$1(ed, {
                deep: false,
                exact: true,
                inline: "span",
                styles: { textDecoration: decoration }
              }, null, node2);
            }
          });
        };
        var unwrap2 = function(start2) {
          var node2 = dom2.get(start2 ? "_start" : "_end");
          var out = node2[start2 ? "firstChild" : "lastChild"];
          if (isRemoveBookmarkNode(out)) {
            out = out[start2 ? "firstChild" : "lastChild"];
          }
          if (isText$7(out) && out.data.length === 0) {
            out = start2 ? node2.previousSibling || node2.nextSibling : node2.nextSibling || node2.previousSibling;
          }
          dom2.remove(node2, true);
          return out;
        };
        var removeRngStyle = function(rng2) {
          var startContainer, endContainer;
          var expandedRng = expandRng(ed, rng2, formatList, rng2.collapsed);
          if (format.split) {
            expandedRng = split(expandedRng);
            startContainer = getContainer(ed, expandedRng, true);
            endContainer = getContainer(ed, expandedRng);
            if (startContainer !== endContainer) {
              startContainer = normalizeTableSelection(startContainer, true);
              endContainer = normalizeTableSelection(endContainer, false);
              if (isChildOfInlineParent(dom2, startContainer, endContainer)) {
                var marker = Optional.from(startContainer.firstChild).getOr(startContainer);
                splitToFormatRoot(wrapWithSiblings(dom2, marker, true, "span", {
                  "id": "_start",
                  "data-mce-type": "bookmark"
                }));
                unwrap2(true);
                return;
              }
              if (isChildOfInlineParent(dom2, endContainer, startContainer)) {
                var marker = Optional.from(endContainer.lastChild).getOr(endContainer);
                splitToFormatRoot(wrapWithSiblings(dom2, marker, false, "span", {
                  "id": "_end",
                  "data-mce-type": "bookmark"
                }));
                unwrap2(false);
                return;
              }
              startContainer = wrap$1(dom2, startContainer, "span", {
                "id": "_start",
                "data-mce-type": "bookmark"
              });
              endContainer = wrap$1(dom2, endContainer, "span", {
                "id": "_end",
                "data-mce-type": "bookmark"
              });
              var newRng = dom2.createRng();
              newRng.setStartAfter(startContainer);
              newRng.setEndBefore(endContainer);
              walk$2(dom2, newRng, function(nodes) {
                each$k(nodes, function(n) {
                  if (!isBookmarkNode$1(n) && !isBookmarkNode$1(n.parentNode)) {
                    splitToFormatRoot(n);
                  }
                });
              });
              splitToFormatRoot(startContainer);
              splitToFormatRoot(endContainer);
              startContainer = unwrap2(true);
              endContainer = unwrap2();
            } else {
              startContainer = endContainer = splitToFormatRoot(startContainer);
            }
            expandedRng.startContainer = startContainer.parentNode ? startContainer.parentNode : startContainer;
            expandedRng.startOffset = dom2.nodeIndex(startContainer);
            expandedRng.endContainer = endContainer.parentNode ? endContainer.parentNode : endContainer;
            expandedRng.endOffset = dom2.nodeIndex(endContainer) + 1;
          }
          walk$2(dom2, expandedRng, function(nodes) {
            each$k(nodes, process2);
          });
        };
        if (node) {
          if (isNode(node)) {
            var rng = dom2.createRng();
            rng.setStartBefore(node);
            rng.setEndAfter(node);
            removeRngStyle(rng);
          } else {
            removeRngStyle(node);
          }
          fireFormatRemove(ed, name2, node, vars);
          return;
        }
        if (dom2.getContentEditable(selection.getNode()) === "false") {
          node = selection.getNode();
          for (var i = 0; i < formatList.length; i++) {
            if (formatList[i].ceFalseOverride) {
              if (removeFormat$1(ed, formatList[i], vars, node, node)) {
                break;
              }
            }
          }
          fireFormatRemove(ed, name2, node, vars);
          return;
        }
        if (!selection.isCollapsed() || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
          preserve(selection, true, function() {
            runOnRanges(ed, removeRngStyle);
          });
          if (isInlineFormat(format) && match$2(ed, name2, vars, selection.getStart())) {
            moveStart(dom2, selection, selection.getRng());
          }
          ed.nodeChanged();
        } else {
          removeCaretFormat(ed, name2, vars, similar);
        }
        fireFormatRemove(ed, name2, node, vars);
      };
      var each$8 = Tools.each;
      var mergeTextDecorationsAndColor = function(dom2, format, vars, node) {
        var processTextDecorationsAndColor = function(n) {
          if (n.nodeType === 1 && n.parentNode && n.parentNode.nodeType === 1) {
            var textDecoration = getTextDecoration(dom2, n.parentNode);
            if (dom2.getStyle(n, "color") && textDecoration) {
              dom2.setStyle(n, "text-decoration", textDecoration);
            } else if (dom2.getStyle(n, "text-decoration") === textDecoration) {
              dom2.setStyle(n, "text-decoration", null);
            }
          }
        };
        if (format.styles && (format.styles.color || format.styles.textDecoration)) {
          Tools.walk(node, processTextDecorationsAndColor, "childNodes");
          processTextDecorationsAndColor(node);
        }
      };
      var mergeBackgroundColorAndFontSize = function(dom2, format, vars, node) {
        if (format.styles && format.styles.backgroundColor) {
          processChildElements(node, hasStyle(dom2, "fontSize"), applyStyle(dom2, "backgroundColor", replaceVars(format.styles.backgroundColor, vars)));
        }
      };
      var mergeSubSup = function(dom2, format, vars, node) {
        if (isInlineFormat(format) && (format.inline === "sub" || format.inline === "sup")) {
          processChildElements(node, hasStyle(dom2, "fontSize"), applyStyle(dom2, "fontSize", ""));
          dom2.remove(dom2.select(format.inline === "sup" ? "sub" : "sup", node), true);
        }
      };
      var mergeWithChildren = function(editor, formatList, vars, node) {
        each$8(formatList, function(format) {
          if (isInlineFormat(format)) {
            each$8(editor.dom.select(format.inline, node), function(child2) {
              if (!isElementNode$1(child2)) {
                return;
              }
              removeFormat$1(editor, format, vars, child2, format.exact ? child2 : null);
            });
          }
          clearChildStyles(editor.dom, format, node);
        });
      };
      var mergeWithParents = function(editor, format, name2, vars, node) {
        if (matchNode(editor, node.parentNode, name2, vars)) {
          if (removeFormat$1(editor, format, vars, node)) {
            return;
          }
        }
        if (format.merge_with_parents) {
          editor.dom.getParent(node.parentNode, function(parent2) {
            if (matchNode(editor, parent2, name2, vars)) {
              removeFormat$1(editor, format, vars, node);
              return true;
            }
          });
        }
      };
      var each$7 = Tools.each;
      var isElementNode = function(node) {
        return isElement$5(node) && !isBookmarkNode$1(node) && !isCaretNode(node) && !isBogus$2(node);
      };
      var canFormatBR = function(editor, format, node, parentName) {
        if (canFormatEmptyLines(editor) && isInlineFormat(format)) {
          var validBRParentElements = getTextRootBlockElements(editor.schema);
          var hasCaretNodeSibling = sibling(SugarElement.fromDom(node), function(sibling2) {
            return isCaretNode(sibling2.dom);
          });
          return hasNonNullableKey(validBRParentElements, parentName) && isEmpty$2(SugarElement.fromDom(node.parentNode), false) && !hasCaretNodeSibling;
        } else {
          return false;
        }
      };
      var applyFormat$1 = function(ed, name2, vars, node) {
        var formatList = ed.formatter.get(name2);
        var format = formatList[0];
        var isCollapsed = !node && ed.selection.isCollapsed();
        var dom2 = ed.dom;
        var selection = ed.selection;
        var setElementFormat = function(elm, fmt) {
          if (fmt === void 0) {
            fmt = format;
          }
          if (isFunction(fmt.onformat)) {
            fmt.onformat(elm, fmt, vars, node);
          }
          each$7(fmt.styles, function(value2, name3) {
            dom2.setStyle(elm, name3, replaceVars(value2, vars));
          });
          if (fmt.styles) {
            var styleVal = dom2.getAttrib(elm, "style");
            if (styleVal) {
              dom2.setAttrib(elm, "data-mce-style", styleVal);
            }
          }
          each$7(fmt.attributes, function(value2, name3) {
            dom2.setAttrib(elm, name3, replaceVars(value2, vars));
          });
          each$7(fmt.classes, function(value2) {
            value2 = replaceVars(value2, vars);
            if (!dom2.hasClass(elm, value2)) {
              dom2.addClass(elm, value2);
            }
          });
        };
        var applyNodeStyle = function(formatList2, node2) {
          var found = false;
          each$7(formatList2, function(format2) {
            if (!isSelectorFormat(format2)) {
              return false;
            }
            if (isNonNullable(format2.collapsed) && format2.collapsed !== isCollapsed) {
              return;
            }
            if (dom2.is(node2, format2.selector) && !isCaretNode(node2)) {
              setElementFormat(node2, format2);
              found = true;
              return false;
            }
          });
          return found;
        };
        var createWrapElement = function(wrapName) {
          if (isString$1(wrapName)) {
            var wrapElm = dom2.create(wrapName);
            setElementFormat(wrapElm);
            return wrapElm;
          } else {
            return null;
          }
        };
        var applyRngStyle = function(dom3, rng2, nodeSpecific) {
          var newWrappers = [];
          var contentEditable = true;
          var wrapName = format.inline || format.block;
          var wrapElm = createWrapElement(wrapName);
          walk$2(dom3, rng2, function(nodes) {
            var currentWrapElm;
            var process2 = function(node2) {
              var hasContentEditableState2 = false;
              var lastContentEditable = contentEditable;
              var nodeName = node2.nodeName.toLowerCase();
              var parentNode = node2.parentNode;
              var parentName = parentNode.nodeName.toLowerCase();
              if (isElement$5(node2) && dom3.getContentEditable(node2)) {
                lastContentEditable = contentEditable;
                contentEditable = dom3.getContentEditable(node2) === "true";
                hasContentEditableState2 = true;
              }
              if (isBr$5(node2) && !canFormatBR(ed, format, node2, parentName)) {
                currentWrapElm = null;
                if (isBlockFormat(format)) {
                  dom3.remove(node2);
                }
                return;
              }
              if (isBlockFormat(format) && format.wrapper && matchNode(ed, node2, name2, vars)) {
                currentWrapElm = null;
                return;
              }
              if (contentEditable && !hasContentEditableState2 && isBlockFormat(format) && !format.wrapper && isTextBlock$1(ed, nodeName) && isValid(ed, parentName, wrapName)) {
                var elm = dom3.rename(node2, wrapName);
                setElementFormat(elm);
                newWrappers.push(elm);
                currentWrapElm = null;
                return;
              }
              if (isSelectorFormat(format)) {
                var found = applyNodeStyle(formatList, node2);
                if (!found && isNonNullable(parentNode) && shouldExpandToSelector(format)) {
                  found = applyNodeStyle(formatList, parentNode);
                }
                if (!isInlineFormat(format) || found) {
                  currentWrapElm = null;
                  return;
                }
              }
              if (contentEditable && !hasContentEditableState2 && isValid(ed, wrapName, nodeName) && isValid(ed, parentName, wrapName) && !(!nodeSpecific && isText$7(node2) && isZwsp(node2.data)) && !isCaretNode(node2) && (!isInlineFormat(format) || !dom3.isBlock(node2))) {
                if (!currentWrapElm) {
                  currentWrapElm = dom3.clone(wrapElm, false);
                  node2.parentNode.insertBefore(currentWrapElm, node2);
                  newWrappers.push(currentWrapElm);
                }
                currentWrapElm.appendChild(node2);
              } else {
                currentWrapElm = null;
                each$k(from(node2.childNodes), process2);
                if (hasContentEditableState2) {
                  contentEditable = lastContentEditable;
                }
                currentWrapElm = null;
              }
            };
            each$k(nodes, process2);
          });
          if (format.links === true) {
            each$k(newWrappers, function(node2) {
              var process2 = function(node3) {
                if (node3.nodeName === "A") {
                  setElementFormat(node3, format);
                }
                each$k(from(node3.childNodes), process2);
              };
              process2(node2);
            });
          }
          each$k(newWrappers, function(node2) {
            var getChildCount = function(node3) {
              var count2 = 0;
              each$k(node3.childNodes, function(node4) {
                if (!isEmptyTextNode$1(node4) && !isBookmarkNode$1(node4)) {
                  count2++;
                }
              });
              return count2;
            };
            var mergeStyles = function(node3) {
              var childElement = find$3(node3.childNodes, isElementNode).filter(function(child2) {
                return matchName$1(dom3, child2, format);
              });
              return childElement.map(function(child2) {
                var clone2 = dom3.clone(child2, false);
                setElementFormat(clone2);
                dom3.replace(clone2, node3, true);
                dom3.remove(child2, true);
                return clone2;
              }).getOr(node3);
            };
            var childCount = getChildCount(node2);
            if ((newWrappers.length > 1 || !dom3.isBlock(node2)) && childCount === 0) {
              dom3.remove(node2, true);
              return;
            }
            if (isInlineFormat(format) || isBlockFormat(format) && format.wrapper) {
              if (!format.exact && childCount === 1) {
                node2 = mergeStyles(node2);
              }
              mergeWithChildren(ed, formatList, vars, node2);
              mergeWithParents(ed, format, name2, vars, node2);
              mergeBackgroundColorAndFontSize(dom3, format, vars, node2);
              mergeTextDecorationsAndColor(dom3, format, vars, node2);
              mergeSubSup(dom3, format, vars, node2);
              mergeSiblings(dom3, format, vars, node2);
            }
          });
        };
        if (dom2.getContentEditable(selection.getNode()) === "false") {
          node = selection.getNode();
          for (var i = 0, l = formatList.length; i < l; i++) {
            var formatItem = formatList[i];
            if (formatItem.ceFalseOverride && isSelectorFormat(formatItem) && dom2.is(node, formatItem.selector)) {
              setElementFormat(node, formatItem);
              break;
            }
          }
          fireFormatApply(ed, name2, node, vars);
          return;
        }
        if (format) {
          if (node) {
            if (isNode(node)) {
              if (!applyNodeStyle(formatList, node)) {
                var rng = dom2.createRng();
                rng.setStartBefore(node);
                rng.setEndAfter(node);
                applyRngStyle(dom2, expandRng(ed, rng, formatList), true);
              }
            } else {
              applyRngStyle(dom2, node, true);
            }
          } else {
            if (!isCollapsed || !isInlineFormat(format) || getCellsFromEditor(ed).length) {
              var curSelNode = selection.getNode();
              var firstFormat = formatList[0];
              if (!ed.settings.forced_root_block && firstFormat.defaultBlock && !dom2.getParent(curSelNode, dom2.isBlock)) {
                applyFormat$1(ed, firstFormat.defaultBlock);
              }
              selection.setRng(normalize(selection.getRng()));
              preserve(selection, true, function() {
                runOnRanges(ed, function(selectionRng, fake) {
                  var expandedRng = fake ? selectionRng : expandRng(ed, selectionRng, formatList);
                  applyRngStyle(dom2, expandedRng, false);
                });
              });
              moveStart(dom2, selection, selection.getRng());
              ed.nodeChanged();
            } else {
              applyCaretFormat(ed, name2, vars);
            }
          }
          postProcess$1(name2, ed);
        }
        fireFormatApply(ed, name2, node, vars);
      };
      var hasVars = function(value2) {
        return has$2(value2, "vars");
      };
      var setup$j = function(registeredFormatListeners, editor) {
        registeredFormatListeners.set({});
        editor.on("NodeChange", function(e) {
          updateAndFireChangeCallbacks(editor, e.element, registeredFormatListeners.get());
        });
        editor.on("FormatApply FormatRemove", function(e) {
          var element = Optional.from(e.node).map(function(nodeOrRange) {
            return isNode(nodeOrRange) ? nodeOrRange : nodeOrRange.startContainer;
          }).bind(function(node) {
            return isElement$5(node) ? Optional.some(node) : Optional.from(node.parentElement);
          }).getOrThunk(function() {
            return fallbackElement(editor);
          });
          updateAndFireChangeCallbacks(editor, element, registeredFormatListeners.get());
        });
      };
      var fallbackElement = function(editor) {
        return editor.selection.getStart();
      };
      var matchingNode = function(editor, parents2, format, similar, vars) {
        var isMatchingNode = function(node) {
          var matchingFormat = editor.formatter.matchNode(node, format, vars !== null && vars !== void 0 ? vars : {}, similar);
          return !isUndefined(matchingFormat);
        };
        var isUnableToMatch = function(node) {
          if (matchesUnInheritedFormatSelector(editor, node, format)) {
            return true;
          } else {
            if (!similar) {
              return isNonNullable(editor.formatter.matchNode(node, format, vars, true));
            } else {
              return false;
            }
          }
        };
        return findUntil$1(parents2, isMatchingNode, isUnableToMatch);
      };
      var getParents = function(editor, elm) {
        var element = elm !== null && elm !== void 0 ? elm : fallbackElement(editor);
        return filter$4(getParents$2(editor.dom, element), function(node) {
          return isElement$5(node) && !isBogus$2(node);
        });
      };
      var updateAndFireChangeCallbacks = function(editor, elm, registeredCallbacks) {
        var parents2 = getParents(editor, elm);
        each$j(registeredCallbacks, function(data2, format) {
          var runIfChanged = function(spec) {
            var match2 = matchingNode(editor, parents2, format, spec.similar, hasVars(spec) ? spec.vars : void 0);
            var isSet = match2.isSome();
            if (spec.state.get() !== isSet) {
              spec.state.set(isSet);
              var node_1 = match2.getOr(elm);
              if (hasVars(spec)) {
                spec.callback(isSet, {
                  node: node_1,
                  format,
                  parents: parents2
                });
              } else {
                each$k(spec.callbacks, function(callback) {
                  return callback(isSet, {
                    node: node_1,
                    format,
                    parents: parents2
                  });
                });
              }
            }
          };
          each$k([
            data2.withSimilar,
            data2.withoutSimilar
          ], runIfChanged);
          each$k(data2.withVars, runIfChanged);
        });
      };
      var addListeners = function(editor, registeredFormatListeners, formats, callback, similar, vars) {
        var formatChangeItems = registeredFormatListeners.get();
        each$k(formats.split(","), function(format) {
          var group = get$9(formatChangeItems, format).getOrThunk(function() {
            var base = {
              withSimilar: {
                state: Cell(false),
                similar: true,
                callbacks: []
              },
              withoutSimilar: {
                state: Cell(false),
                similar: false,
                callbacks: []
              },
              withVars: []
            };
            formatChangeItems[format] = base;
            return base;
          });
          var getCurrent = function() {
            var parents2 = getParents(editor);
            return matchingNode(editor, parents2, format, similar, vars).isSome();
          };
          if (isUndefined(vars)) {
            var toAppendTo = similar ? group.withSimilar : group.withoutSimilar;
            toAppendTo.callbacks.push(callback);
            if (toAppendTo.callbacks.length === 1) {
              toAppendTo.state.set(getCurrent());
            }
          } else {
            group.withVars.push({
              state: Cell(getCurrent()),
              similar,
              vars,
              callback
            });
          }
        });
        registeredFormatListeners.set(formatChangeItems);
      };
      var removeListeners = function(registeredFormatListeners, formats, callback) {
        var formatChangeItems = registeredFormatListeners.get();
        each$k(formats.split(","), function(format) {
          return get$9(formatChangeItems, format).each(function(group) {
            formatChangeItems[format] = {
              withSimilar: __assign(__assign({}, group.withSimilar), {
                callbacks: filter$4(group.withSimilar.callbacks, function(cb) {
                  return cb !== callback;
                })
              }),
              withoutSimilar: __assign(__assign({}, group.withoutSimilar), {
                callbacks: filter$4(group.withoutSimilar.callbacks, function(cb) {
                  return cb !== callback;
                })
              }),
              withVars: filter$4(group.withVars, function(item) {
                return item.callback !== callback;
              })
            };
          });
        });
        registeredFormatListeners.set(formatChangeItems);
      };
      var formatChangedInternal = function(editor, registeredFormatListeners, formats, callback, similar, vars) {
        if (registeredFormatListeners.get() === null) {
          setup$j(registeredFormatListeners, editor);
        }
        addListeners(editor, registeredFormatListeners, formats, callback, similar, vars);
        return {
          unbind: function() {
            return removeListeners(registeredFormatListeners, formats, callback);
          }
        };
      };
      var toggle = function(editor, name2, vars, node) {
        var fmt = editor.formatter.get(name2);
        if (match$2(editor, name2, vars, node) && (!("toggle" in fmt[0]) || fmt[0].toggle)) {
          remove$1(editor, name2, vars, node);
        } else {
          applyFormat$1(editor, name2, vars, node);
        }
      };
      var fromElements = function(elements, scope) {
        var doc2 = scope || document;
        var fragment = doc2.createDocumentFragment();
        each$k(elements, function(element) {
          fragment.appendChild(element.dom);
        });
        return SugarElement.fromDom(fragment);
      };
      var tableModel = function(element, width, rows) {
        return {
          element,
          width,
          rows
        };
      };
      var tableRow = function(element, cells) {
        return {
          element,
          cells
        };
      };
      var cellPosition = function(x, y) {
        return {
          x,
          y
        };
      };
      var getSpan = function(td, key) {
        var value2 = parseInt(get$6(td, key), 10);
        return isNaN(value2) ? 1 : value2;
      };
      var fillout = function(table, x, y, tr, td) {
        var rowspan = getSpan(td, "rowspan");
        var colspan = getSpan(td, "colspan");
        var rows = table.rows;
        for (var y2 = y; y2 < y + rowspan; y2++) {
          if (!rows[y2]) {
            rows[y2] = tableRow(deep$1(tr), []);
          }
          for (var x2 = x; x2 < x + colspan; x2++) {
            var cells = rows[y2].cells;
            cells[x2] = y2 === y && x2 === x ? td : shallow(td);
          }
        }
      };
      var cellExists = function(table, x, y) {
        var rows = table.rows;
        var cells = rows[y] ? rows[y].cells : [];
        return !!cells[x];
      };
      var skipCellsX = function(table, x, y) {
        while (cellExists(table, x, y)) {
          x++;
        }
        return x;
      };
      var getWidth = function(rows) {
        return foldl(rows, function(acc, row) {
          return row.cells.length > acc ? row.cells.length : acc;
        }, 0);
      };
      var findElementPos = function(table, element) {
        var rows = table.rows;
        for (var y = 0; y < rows.length; y++) {
          var cells = rows[y].cells;
          for (var x = 0; x < cells.length; x++) {
            if (eq(cells[x], element)) {
              return Optional.some(cellPosition(x, y));
            }
          }
        }
        return Optional.none();
      };
      var extractRows = function(table, sx, sy, ex, ey) {
        var newRows = [];
        var rows = table.rows;
        for (var y = sy; y <= ey; y++) {
          var cells = rows[y].cells;
          var slice2 = sx < ex ? cells.slice(sx, ex + 1) : cells.slice(ex, sx + 1);
          newRows.push(tableRow(rows[y].element, slice2));
        }
        return newRows;
      };
      var subTable = function(table, startPos, endPos) {
        var sx = startPos.x, sy = startPos.y;
        var ex = endPos.x, ey = endPos.y;
        var newRows = sy < ey ? extractRows(table, sx, sy, ex, ey) : extractRows(table, sx, ey, ex, sy);
        return tableModel(table.element, getWidth(newRows), newRows);
      };
      var createDomTable = function(table, rows) {
        var tableElement = shallow(table.element);
        var tableBody = SugarElement.fromTag("tbody");
        append(tableBody, rows);
        append$1(tableElement, tableBody);
        return tableElement;
      };
      var modelRowsToDomRows = function(table) {
        return map$3(table.rows, function(row) {
          var cells = map$3(row.cells, function(cell) {
            var td = deep$1(cell);
            remove$6(td, "colspan");
            remove$6(td, "rowspan");
            return td;
          });
          var tr = shallow(row.element);
          append(tr, cells);
          return tr;
        });
      };
      var fromDom = function(tableElm) {
        var table = tableModel(shallow(tableElm), 0, []);
        each$k(descendants(tableElm, "tr"), function(tr, y) {
          each$k(descendants(tr, "td,th"), function(td, x) {
            fillout(table, skipCellsX(table, x, y), y, tr, td);
          });
        });
        return tableModel(table.element, getWidth(table.rows), table.rows);
      };
      var toDom = function(table) {
        return createDomTable(table, modelRowsToDomRows(table));
      };
      var subsection = function(table, startElement, endElement) {
        return findElementPos(table, startElement).bind(function(startPos) {
          return findElementPos(table, endElement).map(function(endPos) {
            return subTable(table, startPos, endPos);
          });
        });
      };
      var findParentListContainer = function(parents2) {
        return find$3(parents2, function(elm) {
          return name(elm) === "ul" || name(elm) === "ol";
        });
      };
      var getFullySelectedListWrappers = function(parents2, rng) {
        return find$3(parents2, function(elm) {
          return name(elm) === "li" && hasAllContentsSelected(elm, rng);
        }).fold(constant([]), function(_li) {
          return findParentListContainer(parents2).map(function(listCont) {
            var listElm = SugarElement.fromTag(name(listCont));
            var listStyles = filter$3(getAllRaw(listCont), function(_style, name2) {
              return startsWith(name2, "list-style");
            });
            setAll(listElm, listStyles);
            return [
              SugarElement.fromTag("li"),
              listElm
            ];
          }).getOr([]);
        });
      };
      var wrap = function(innerElm, elms) {
        var wrapped = foldl(elms, function(acc, elm) {
          append$1(elm, acc);
          return elm;
        }, innerElm);
        return elms.length > 0 ? fromElements([wrapped]) : wrapped;
      };
      var directListWrappers = function(commonAnchorContainer) {
        if (isListItem(commonAnchorContainer)) {
          return parent(commonAnchorContainer).filter(isList).fold(constant([]), function(listElm) {
            return [
              commonAnchorContainer,
              listElm
            ];
          });
        } else {
          return isList(commonAnchorContainer) ? [commonAnchorContainer] : [];
        }
      };
      var getWrapElements = function(rootNode, rng) {
        var commonAnchorContainer = SugarElement.fromDom(rng.commonAncestorContainer);
        var parents2 = parentsAndSelf(commonAnchorContainer, rootNode);
        var wrapElements = filter$4(parents2, function(elm) {
          return isInline$1(elm) || isHeading(elm);
        });
        var listWrappers = getFullySelectedListWrappers(parents2, rng);
        var allWrappers = wrapElements.concat(listWrappers.length ? listWrappers : directListWrappers(commonAnchorContainer));
        return map$3(allWrappers, shallow);
      };
      var emptyFragment = function() {
        return fromElements([]);
      };
      var getFragmentFromRange = function(rootNode, rng) {
        return wrap(SugarElement.fromDom(rng.cloneContents()), getWrapElements(rootNode, rng));
      };
      var getParentTable = function(rootElm, cell) {
        return ancestor$2(cell, "table", curry(eq, rootElm));
      };
      var getTableFragment = function(rootNode, selectedTableCells) {
        return getParentTable(rootNode, selectedTableCells[0]).bind(function(tableElm) {
          var firstCell = selectedTableCells[0];
          var lastCell = selectedTableCells[selectedTableCells.length - 1];
          var fullTableModel = fromDom(tableElm);
          return subsection(fullTableModel, firstCell, lastCell).map(function(sectionedTableModel) {
            return fromElements([toDom(sectionedTableModel)]);
          });
        }).getOrThunk(emptyFragment);
      };
      var getSelectionFragment = function(rootNode, ranges) {
        return ranges.length > 0 && ranges[0].collapsed ? emptyFragment() : getFragmentFromRange(rootNode, ranges[0]);
      };
      var read$3 = function(rootNode, ranges) {
        var selectedCells = getCellsFromElementOrRanges(ranges, rootNode);
        return selectedCells.length > 0 ? getTableFragment(rootNode, selectedCells) : getSelectionFragment(rootNode, ranges);
      };
      var trimLeadingCollapsibleText = function(text) {
        return text.replace(/^[ \f\n\r\t\v]+/, "");
      };
      var isCollapsibleWhitespace = function(text, index) {
        return index >= 0 && index < text.length && isWhiteSpace(text.charAt(index));
      };
      var getInnerText = function(bin, shouldTrim) {
        var text = trim$2(bin.innerText);
        return shouldTrim ? trimLeadingCollapsibleText(text) : text;
      };
      var getContextNodeName = function(parentBlockOpt) {
        return parentBlockOpt.map(function(block) {
          return block.nodeName;
        }).getOr("div").toLowerCase();
      };
      var getTextContent = function(editor) {
        return Optional.from(editor.selection.getRng()).map(function(rng) {
          var parentBlockOpt = Optional.from(editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock));
          var body = editor.getBody();
          var contextNodeName = getContextNodeName(parentBlockOpt);
          var shouldTrimSpaces = Env.browser.isIE() && contextNodeName !== "pre";
          var bin = editor.dom.add(body, contextNodeName, {
            "data-mce-bogus": "all",
            "style": "overflow: hidden; opacity: 0;"
          }, rng.cloneContents());
          var text = getInnerText(bin, shouldTrimSpaces);
          var nonRenderedText = trim$2(bin.textContent);
          editor.dom.remove(bin);
          if (isCollapsibleWhitespace(nonRenderedText, 0) || isCollapsibleWhitespace(nonRenderedText, nonRenderedText.length - 1)) {
            var parentBlock = parentBlockOpt.getOr(body);
            var parentBlockText = getInnerText(parentBlock, shouldTrimSpaces);
            var textIndex = parentBlockText.indexOf(text);
            if (textIndex === -1) {
              return text;
            } else {
              var hasProceedingSpace = isCollapsibleWhitespace(parentBlockText, textIndex - 1);
              var hasTrailingSpace = isCollapsibleWhitespace(parentBlockText, textIndex + text.length);
              return (hasProceedingSpace ? " " : "") + text + (hasTrailingSpace ? " " : "");
            }
          } else {
            return text;
          }
        }).getOr("");
      };
      var getSerializedContent = function(editor, args) {
        var rng = editor.selection.getRng(), tmpElm = editor.dom.create("body");
        var sel = editor.selection.getSel();
        var ranges = processRanges(editor, getRanges(sel));
        var fragment = args.contextual ? read$3(SugarElement.fromDom(editor.getBody()), ranges).dom : rng.cloneContents();
        if (fragment) {
          tmpElm.appendChild(fragment);
        }
        return editor.selection.serializer.serialize(tmpElm, args);
      };
      var setupArgs$1 = function(args, format) {
        return __assign(__assign({}, args), {
          format,
          get: true,
          selection: true
        });
      };
      var getSelectedContentInternal = function(editor, format, args) {
        if (args === void 0) {
          args = {};
        }
        var defaultedArgs = setupArgs$1(args, format);
        var updatedArgs = editor.fire("BeforeGetContent", defaultedArgs);
        if (updatedArgs.isDefaultPrevented()) {
          editor.fire("GetContent", updatedArgs);
          return updatedArgs.content;
        }
        if (updatedArgs.format === "text") {
          return getTextContent(editor);
        } else {
          updatedArgs.getInner = true;
          var content = getSerializedContent(editor, updatedArgs);
          if (updatedArgs.format === "tree") {
            return content;
          } else {
            updatedArgs.content = editor.selection.isCollapsed() ? "" : content;
            editor.fire("GetContent", updatedArgs);
            return updatedArgs.content;
          }
        }
      };
      var KEEP = 0, INSERT = 1, DELETE = 2;
      var diff = function(left, right) {
        var size = left.length + right.length + 2;
        var vDown = new Array(size);
        var vUp = new Array(size);
        var snake = function(start2, end2, diag) {
          return {
            start: start2,
            end: end2,
            diag
          };
        };
        var buildScript = function(start1, end1, start2, end2, script2) {
          var middle = getMiddleSnake(start1, end1, start2, end2);
          if (middle === null || middle.start === end1 && middle.diag === end1 - end2 || middle.end === start1 && middle.diag === start1 - start2) {
            var i = start1;
            var j = start2;
            while (i < end1 || j < end2) {
              if (i < end1 && j < end2 && left[i] === right[j]) {
                script2.push([
                  KEEP,
                  left[i]
                ]);
                ++i;
                ++j;
              } else {
                if (end1 - start1 > end2 - start2) {
                  script2.push([
                    DELETE,
                    left[i]
                  ]);
                  ++i;
                } else {
                  script2.push([
                    INSERT,
                    right[j]
                  ]);
                  ++j;
                }
              }
            }
          } else {
            buildScript(start1, middle.start, start2, middle.start - middle.diag, script2);
            for (var i2 = middle.start; i2 < middle.end; ++i2) {
              script2.push([
                KEEP,
                left[i2]
              ]);
            }
            buildScript(middle.end, end1, middle.end - middle.diag, end2, script2);
          }
        };
        var buildSnake = function(start2, diag, end1, end2) {
          var end3 = start2;
          while (end3 - diag < end2 && end3 < end1 && left[end3] === right[end3 - diag]) {
            ++end3;
          }
          return snake(start2, end3, diag);
        };
        var getMiddleSnake = function(start1, end1, start2, end2) {
          var m = end1 - start1;
          var n = end2 - start2;
          if (m === 0 || n === 0) {
            return null;
          }
          var delta = m - n;
          var sum = n + m;
          var offset = (sum % 2 === 0 ? sum : sum + 1) / 2;
          vDown[1 + offset] = start1;
          vUp[1 + offset] = end1 + 1;
          var d, k, i, x, y;
          for (d = 0; d <= offset; ++d) {
            for (k = -d; k <= d; k += 2) {
              i = k + offset;
              if (k === -d || k !== d && vDown[i - 1] < vDown[i + 1]) {
                vDown[i] = vDown[i + 1];
              } else {
                vDown[i] = vDown[i - 1] + 1;
              }
              x = vDown[i];
              y = x - start1 + start2 - k;
              while (x < end1 && y < end2 && left[x] === right[y]) {
                vDown[i] = ++x;
                ++y;
              }
              if (delta % 2 !== 0 && delta - d <= k && k <= delta + d) {
                if (vUp[i - delta] <= vDown[i]) {
                  return buildSnake(vUp[i - delta], k + start1 - start2, end1, end2);
                }
              }
            }
            for (k = delta - d; k <= delta + d; k += 2) {
              i = k + offset - delta;
              if (k === delta - d || k !== delta + d && vUp[i + 1] <= vUp[i - 1]) {
                vUp[i] = vUp[i + 1] - 1;
              } else {
                vUp[i] = vUp[i - 1];
              }
              x = vUp[i] - 1;
              y = x - start1 + start2 - k;
              while (x >= start1 && y >= start2 && left[x] === right[y]) {
                vUp[i] = x--;
                y--;
              }
              if (delta % 2 === 0 && -d <= k && k <= d) {
                if (vUp[i] <= vDown[i + delta]) {
                  return buildSnake(vUp[i], k + start1 - start2, end1, end2);
                }
              }
            }
          }
        };
        var script = [];
        buildScript(0, left.length, 0, right.length, script);
        return script;
      };
      var getOuterHtml = function(elm) {
        if (isElement$5(elm)) {
          return elm.outerHTML;
        } else if (isText$7(elm)) {
          return Entities.encodeRaw(elm.data, false);
        } else if (isComment(elm)) {
          return "<!--" + elm.data + "-->";
        }
        return "";
      };
      var createFragment = function(html) {
        var node;
        var container = document.createElement("div");
        var frag = document.createDocumentFragment();
        if (html) {
          container.innerHTML = html;
        }
        while (node = container.firstChild) {
          frag.appendChild(node);
        }
        return frag;
      };
      var insertAt = function(elm, html, index) {
        var fragment = createFragment(html);
        if (elm.hasChildNodes() && index < elm.childNodes.length) {
          var target = elm.childNodes[index];
          target.parentNode.insertBefore(fragment, target);
        } else {
          elm.appendChild(fragment);
        }
      };
      var removeAt = function(elm, index) {
        if (elm.hasChildNodes() && index < elm.childNodes.length) {
          var target = elm.childNodes[index];
          target.parentNode.removeChild(target);
        }
      };
      var applyDiff = function(diff2, elm) {
        var index = 0;
        each$k(diff2, function(action2) {
          if (action2[0] === KEEP) {
            index++;
          } else if (action2[0] === INSERT) {
            insertAt(elm, action2[1], index);
            index++;
          } else if (action2[0] === DELETE) {
            removeAt(elm, index);
          }
        });
      };
      var read$2 = function(elm) {
        return filter$4(map$3(from(elm.childNodes), getOuterHtml), function(item) {
          return item.length > 0;
        });
      };
      var write = function(fragments, elm) {
        var currentFragments = map$3(from(elm.childNodes), getOuterHtml);
        applyDiff(diff(currentFragments, fragments), elm);
        return elm;
      };
      var lazyTempDocument = cached(function() {
        return document.implementation.createHTMLDocument("undo");
      });
      var hasIframes = function(html) {
        return html.indexOf("</iframe>") !== -1;
      };
      var createFragmentedLevel = function(fragments) {
        return {
          type: "fragmented",
          fragments,
          content: "",
          bookmark: null,
          beforeBookmark: null
        };
      };
      var createCompleteLevel = function(content) {
        return {
          type: "complete",
          fragments: null,
          content,
          bookmark: null,
          beforeBookmark: null
        };
      };
      var createFromEditor = function(editor) {
        var fragments = read$2(editor.getBody());
        var trimmedFragments = bind(fragments, function(html) {
          var trimmed = trimInternal(editor.serializer, html);
          return trimmed.length > 0 ? [trimmed] : [];
        });
        var content = trimmedFragments.join("");
        return hasIframes(content) ? createFragmentedLevel(trimmedFragments) : createCompleteLevel(content);
      };
      var applyToEditor = function(editor, level, before2) {
        var bookmark = before2 ? level.beforeBookmark : level.bookmark;
        if (level.type === "fragmented") {
          write(level.fragments, editor.getBody());
        } else {
          editor.setContent(level.content, {
            format: "raw",
            no_selection: isNonNullable(bookmark) && isPathBookmark(bookmark) ? !bookmark.isFakeCaret : true
          });
        }
        editor.selection.moveToBookmark(bookmark);
      };
      var getLevelContent = function(level) {
        return level.type === "fragmented" ? level.fragments.join("") : level.content;
      };
      var getCleanLevelContent = function(level) {
        var elm = SugarElement.fromTag("body", lazyTempDocument());
        set(elm, getLevelContent(level));
        each$k(descendants(elm, "*[data-mce-bogus]"), unwrap);
        return get$3(elm);
      };
      var hasEqualContent = function(level1, level2) {
        return getLevelContent(level1) === getLevelContent(level2);
      };
      var hasEqualCleanedContent = function(level1, level2) {
        return getCleanLevelContent(level1) === getCleanLevelContent(level2);
      };
      var isEq$1 = function(level1, level2) {
        if (!level1 || !level2) {
          return false;
        } else if (hasEqualContent(level1, level2)) {
          return true;
        } else {
          return hasEqualCleanedContent(level1, level2);
        }
      };
      var isUnlocked = function(locks) {
        return locks.get() === 0;
      };
      var setTyping = function(undoManager, typing, locks) {
        if (isUnlocked(locks)) {
          undoManager.typing = typing;
        }
      };
      var endTyping = function(undoManager, locks) {
        if (undoManager.typing) {
          setTyping(undoManager, false, locks);
          undoManager.add();
        }
      };
      var endTypingLevelIgnoreLocks = function(undoManager) {
        if (undoManager.typing) {
          undoManager.typing = false;
          undoManager.add();
        }
      };
      var beforeChange$1 = function(editor, locks, beforeBookmark) {
        if (isUnlocked(locks)) {
          beforeBookmark.set(getUndoBookmark(editor.selection));
        }
      };
      var addUndoLevel$1 = function(editor, undoManager, index, locks, beforeBookmark, level, event) {
        var currentLevel = createFromEditor(editor);
        level = level || {};
        level = Tools.extend(level, currentLevel);
        if (isUnlocked(locks) === false || editor.removed) {
          return null;
        }
        var lastLevel = undoManager.data[index.get()];
        if (editor.fire("BeforeAddUndo", {
          level,
          lastLevel,
          originalEvent: event
        }).isDefaultPrevented()) {
          return null;
        }
        if (lastLevel && isEq$1(lastLevel, level)) {
          return null;
        }
        if (undoManager.data[index.get()]) {
          beforeBookmark.get().each(function(bm) {
            undoManager.data[index.get()].beforeBookmark = bm;
          });
        }
        var customUndoRedoLevels = getCustomUndoRedoLevels(editor);
        if (customUndoRedoLevels) {
          if (undoManager.data.length > customUndoRedoLevels) {
            for (var i = 0; i < undoManager.data.length - 1; i++) {
              undoManager.data[i] = undoManager.data[i + 1];
            }
            undoManager.data.length--;
            index.set(undoManager.data.length);
          }
        }
        level.bookmark = getUndoBookmark(editor.selection);
        if (index.get() < undoManager.data.length - 1) {
          undoManager.data.length = index.get() + 1;
        }
        undoManager.data.push(level);
        index.set(undoManager.data.length - 1);
        var args = {
          level,
          lastLevel,
          originalEvent: event
        };
        if (index.get() > 0) {
          editor.setDirty(true);
          editor.fire("AddUndo", args);
          editor.fire("change", args);
        } else {
          editor.fire("AddUndo", args);
        }
        return level;
      };
      var clear$1 = function(editor, undoManager, index) {
        undoManager.data = [];
        index.set(0);
        undoManager.typing = false;
        editor.fire("ClearUndos");
      };
      var extra$1 = function(editor, undoManager, index, callback1, callback2) {
        if (undoManager.transact(callback1)) {
          var bookmark = undoManager.data[index.get()].bookmark;
          var lastLevel = undoManager.data[index.get() - 1];
          applyToEditor(editor, lastLevel, true);
          if (undoManager.transact(callback2)) {
            undoManager.data[index.get() - 1].beforeBookmark = bookmark;
          }
        }
      };
      var redo$1 = function(editor, index, data2) {
        var level;
        if (index.get() < data2.length - 1) {
          index.set(index.get() + 1);
          level = data2[index.get()];
          applyToEditor(editor, level, false);
          editor.setDirty(true);
          editor.fire("Redo", { level });
        }
        return level;
      };
      var undo$1 = function(editor, undoManager, locks, index) {
        var level;
        if (undoManager.typing) {
          undoManager.add();
          undoManager.typing = false;
          setTyping(undoManager, false, locks);
        }
        if (index.get() > 0) {
          index.set(index.get() - 1);
          level = undoManager.data[index.get()];
          applyToEditor(editor, level, true);
          editor.setDirty(true);
          editor.fire("Undo", { level });
        }
        return level;
      };
      var reset$1 = function(undoManager) {
        undoManager.clear();
        undoManager.add();
      };
      var hasUndo$1 = function(editor, undoManager, index) {
        return index.get() > 0 || undoManager.typing && undoManager.data[0] && !isEq$1(createFromEditor(editor), undoManager.data[0]);
      };
      var hasRedo$1 = function(undoManager, index) {
        return index.get() < undoManager.data.length - 1 && !undoManager.typing;
      };
      var transact$1 = function(undoManager, locks, callback) {
        endTyping(undoManager, locks);
        undoManager.beforeChange();
        undoManager.ignore(callback);
        return undoManager.add();
      };
      var ignore$1 = function(locks, callback) {
        try {
          locks.set(locks.get() + 1);
          callback();
        } finally {
          locks.set(locks.get() - 1);
        }
      };
      var addVisualInternal = function(editor, elm) {
        var dom2 = editor.dom;
        var scope = isNonNullable(elm) ? elm : editor.getBody();
        if (isUndefined(editor.hasVisual)) {
          editor.hasVisual = isVisualAidsEnabled(editor);
        }
        each$k(dom2.select("table,a", scope), function(matchedElm) {
          switch (matchedElm.nodeName) {
            case "TABLE":
              var cls = getVisualAidsTableClass(editor);
              var value2 = dom2.getAttrib(matchedElm, "border");
              if ((!value2 || value2 === "0") && editor.hasVisual) {
                dom2.addClass(matchedElm, cls);
              } else {
                dom2.removeClass(matchedElm, cls);
              }
              break;
            case "A":
              if (!dom2.getAttrib(matchedElm, "href")) {
                var value_1 = dom2.getAttrib(matchedElm, "name") || matchedElm.id;
                var cls_1 = getVisualAidsAnchorClass(editor);
                if (value_1 && editor.hasVisual) {
                  dom2.addClass(matchedElm, cls_1);
                } else {
                  dom2.removeClass(matchedElm, cls_1);
                }
              }
              break;
          }
        });
        editor.fire("VisualAid", {
          element: elm,
          hasVisual: editor.hasVisual
        });
      };
      var makePlainAdaptor = function(editor) {
        return {
          undoManager: {
            beforeChange: function(locks, beforeBookmark) {
              return beforeChange$1(editor, locks, beforeBookmark);
            },
            add: function(undoManager, index, locks, beforeBookmark, level, event) {
              return addUndoLevel$1(editor, undoManager, index, locks, beforeBookmark, level, event);
            },
            undo: function(undoManager, locks, index) {
              return undo$1(editor, undoManager, locks, index);
            },
            redo: function(index, data2) {
              return redo$1(editor, index, data2);
            },
            clear: function(undoManager, index) {
              return clear$1(editor, undoManager, index);
            },
            reset: function(undoManager) {
              return reset$1(undoManager);
            },
            hasUndo: function(undoManager, index) {
              return hasUndo$1(editor, undoManager, index);
            },
            hasRedo: function(undoManager, index) {
              return hasRedo$1(undoManager, index);
            },
            transact: function(undoManager, locks, callback) {
              return transact$1(undoManager, locks, callback);
            },
            ignore: function(locks, callback) {
              return ignore$1(locks, callback);
            },
            extra: function(undoManager, index, callback1, callback2) {
              return extra$1(editor, undoManager, index, callback1, callback2);
            }
          },
          formatter: {
            match: function(name2, vars, node, similar) {
              return match$2(editor, name2, vars, node, similar);
            },
            matchAll: function(names, vars) {
              return matchAll(editor, names, vars);
            },
            matchNode: function(node, name2, vars, similar) {
              return matchNode(editor, node, name2, vars, similar);
            },
            canApply: function(name2) {
              return canApply(editor, name2);
            },
            closest: function(names) {
              return closest(editor, names);
            },
            apply: function(name2, vars, node) {
              return applyFormat$1(editor, name2, vars, node);
            },
            remove: function(name2, vars, node, similar) {
              return remove$1(editor, name2, vars, node, similar);
            },
            toggle: function(name2, vars, node) {
              return toggle(editor, name2, vars, node);
            },
            formatChanged: function(registeredFormatListeners, formats, callback, similar, vars) {
              return formatChangedInternal(editor, registeredFormatListeners, formats, callback, similar, vars);
            }
          },
          editor: {
            getContent: function(args, format) {
              return getContentInternal(editor, args, format);
            },
            setContent: function(content, args) {
              return setContentInternal(editor, content, args);
            },
            insertContent: function(value2, details) {
              return insertHtmlAtCaret(editor, value2, details);
            },
            addVisual: function(elm) {
              return addVisualInternal(editor, elm);
            }
          },
          selection: {
            getContent: function(format, args) {
              return getSelectedContentInternal(editor, format, args);
            }
          },
          raw: {
            getModel: function() {
              return Optional.none();
            }
          }
        };
      };
      var makeRtcAdaptor = function(rtcEditor) {
        var defaultVars = function(vars) {
          return isObject(vars) ? vars : {};
        };
        var undoManager = rtcEditor.undoManager, formatter = rtcEditor.formatter, editor = rtcEditor.editor, selection = rtcEditor.selection, raw = rtcEditor.raw;
        return {
          undoManager: {
            beforeChange: undoManager.beforeChange,
            add: undoManager.add,
            undo: undoManager.undo,
            redo: undoManager.redo,
            clear: undoManager.clear,
            reset: undoManager.reset,
            hasUndo: undoManager.hasUndo,
            hasRedo: undoManager.hasRedo,
            transact: function(_undoManager, _locks, fn) {
              return undoManager.transact(fn);
            },
            ignore: function(_locks, callback) {
              return undoManager.ignore(callback);
            },
            extra: function(_undoManager, _index, callback1, callback2) {
              return undoManager.extra(callback1, callback2);
            }
          },
          formatter: {
            match: function(name2, vars, _node, similar) {
              return formatter.match(name2, defaultVars(vars), similar);
            },
            matchAll: formatter.matchAll,
            matchNode: formatter.matchNode,
            canApply: function(name2) {
              return formatter.canApply(name2);
            },
            closest: function(names) {
              return formatter.closest(names);
            },
            apply: function(name2, vars, _node) {
              return formatter.apply(name2, defaultVars(vars));
            },
            remove: function(name2, vars, _node, _similar) {
              return formatter.remove(name2, defaultVars(vars));
            },
            toggle: function(name2, vars, _node) {
              return formatter.toggle(name2, defaultVars(vars));
            },
            formatChanged: function(_rfl, formats, callback, similar, vars) {
              return formatter.formatChanged(formats, callback, similar, vars);
            }
          },
          editor: {
            getContent: function(args, _format) {
              return editor.getContent(args);
            },
            setContent: function(content, args) {
              return editor.setContent(content, args);
            },
            insertContent: function(content, _details) {
              return editor.insertContent(content);
            },
            addVisual: editor.addVisual
          },
          selection: {
            getContent: function(_format, args) {
              return selection.getContent(args);
            }
          },
          raw: {
            getModel: function() {
              return Optional.some(raw.getRawModel());
            }
          }
        };
      };
      var makeNoopAdaptor = function() {
        var nul = constant(null);
        var empty2 = constant("");
        return {
          undoManager: {
            beforeChange: noop,
            add: nul,
            undo: nul,
            redo: nul,
            clear: noop,
            reset: noop,
            hasUndo: never,
            hasRedo: never,
            transact: nul,
            ignore: noop,
            extra: noop
          },
          formatter: {
            match: never,
            matchAll: constant([]),
            matchNode: constant(void 0),
            canApply: never,
            closest: empty2,
            apply: noop,
            remove: noop,
            toggle: noop,
            formatChanged: constant({ unbind: noop })
          },
          editor: {
            getContent: empty2,
            setContent: empty2,
            insertContent: noop,
            addVisual: noop
          },
          selection: { getContent: empty2 },
          raw: { getModel: constant(Optional.none()) }
        };
      };
      var isRtc = function(editor) {
        return has$2(editor.plugins, "rtc");
      };
      var getRtcSetup = function(editor) {
        return get$9(editor.plugins, "rtc").bind(function(rtcPlugin) {
          return Optional.from(rtcPlugin.setup);
        });
      };
      var setup$i = function(editor) {
        var editorCast = editor;
        return getRtcSetup(editor).fold(function() {
          editorCast.rtcInstance = makePlainAdaptor(editor);
          return Optional.none();
        }, function(setup2) {
          editorCast.rtcInstance = makeNoopAdaptor();
          return Optional.some(function() {
            return setup2().then(function(rtcEditor) {
              editorCast.rtcInstance = makeRtcAdaptor(rtcEditor);
              return rtcEditor.rtc.isRemote;
            });
          });
        });
      };
      var getRtcInstanceWithFallback = function(editor) {
        return editor.rtcInstance ? editor.rtcInstance : makePlainAdaptor(editor);
      };
      var getRtcInstanceWithError = function(editor) {
        var rtcInstance = editor.rtcInstance;
        if (!rtcInstance) {
          throw new Error("Failed to get RTC instance not yet initialized.");
        } else {
          return rtcInstance;
        }
      };
      var beforeChange = function(editor, locks, beforeBookmark) {
        getRtcInstanceWithError(editor).undoManager.beforeChange(locks, beforeBookmark);
      };
      var addUndoLevel = function(editor, undoManager, index, locks, beforeBookmark, level, event) {
        return getRtcInstanceWithError(editor).undoManager.add(undoManager, index, locks, beforeBookmark, level, event);
      };
      var undo = function(editor, undoManager, locks, index) {
        return getRtcInstanceWithError(editor).undoManager.undo(undoManager, locks, index);
      };
      var redo = function(editor, index, data2) {
        return getRtcInstanceWithError(editor).undoManager.redo(index, data2);
      };
      var clear = function(editor, undoManager, index) {
        getRtcInstanceWithError(editor).undoManager.clear(undoManager, index);
      };
      var reset = function(editor, undoManager) {
        getRtcInstanceWithError(editor).undoManager.reset(undoManager);
      };
      var hasUndo = function(editor, undoManager, index) {
        return getRtcInstanceWithError(editor).undoManager.hasUndo(undoManager, index);
      };
      var hasRedo = function(editor, undoManager, index) {
        return getRtcInstanceWithError(editor).undoManager.hasRedo(undoManager, index);
      };
      var transact = function(editor, undoManager, locks, callback) {
        return getRtcInstanceWithError(editor).undoManager.transact(undoManager, locks, callback);
      };
      var ignore = function(editor, locks, callback) {
        getRtcInstanceWithError(editor).undoManager.ignore(locks, callback);
      };
      var extra = function(editor, undoManager, index, callback1, callback2) {
        getRtcInstanceWithError(editor).undoManager.extra(undoManager, index, callback1, callback2);
      };
      var matchFormat = function(editor, name2, vars, node, similar) {
        return getRtcInstanceWithError(editor).formatter.match(name2, vars, node, similar);
      };
      var matchAllFormats = function(editor, names, vars) {
        return getRtcInstanceWithError(editor).formatter.matchAll(names, vars);
      };
      var matchNodeFormat = function(editor, node, name2, vars, similar) {
        return getRtcInstanceWithError(editor).formatter.matchNode(node, name2, vars, similar);
      };
      var canApplyFormat = function(editor, name2) {
        return getRtcInstanceWithError(editor).formatter.canApply(name2);
      };
      var closestFormat = function(editor, names) {
        return getRtcInstanceWithError(editor).formatter.closest(names);
      };
      var applyFormat = function(editor, name2, vars, node) {
        getRtcInstanceWithError(editor).formatter.apply(name2, vars, node);
      };
      var removeFormat = function(editor, name2, vars, node, similar) {
        getRtcInstanceWithError(editor).formatter.remove(name2, vars, node, similar);
      };
      var toggleFormat = function(editor, name2, vars, node) {
        getRtcInstanceWithError(editor).formatter.toggle(name2, vars, node);
      };
      var formatChanged = function(editor, registeredFormatListeners, formats, callback, similar, vars) {
        return getRtcInstanceWithError(editor).formatter.formatChanged(registeredFormatListeners, formats, callback, similar, vars);
      };
      var getContent$2 = function(editor, args, format) {
        return getRtcInstanceWithFallback(editor).editor.getContent(args, format);
      };
      var setContent$2 = function(editor, content, args) {
        return getRtcInstanceWithFallback(editor).editor.setContent(content, args);
      };
      var insertContent = function(editor, value2, details) {
        return getRtcInstanceWithFallback(editor).editor.insertContent(value2, details);
      };
      var getSelectedContent = function(editor, format, args) {
        return getRtcInstanceWithError(editor).selection.getContent(format, args);
      };
      var addVisual$1 = function(editor, elm) {
        return getRtcInstanceWithError(editor).editor.addVisual(elm);
      };
      var getContent$1 = function(editor, args) {
        if (args === void 0) {
          args = {};
        }
        var format = args.format ? args.format : "html";
        return getSelectedContent(editor, format, args);
      };
      var removeEmpty = function(text) {
        if (text.dom.length === 0) {
          remove$7(text);
          return Optional.none();
        } else {
          return Optional.some(text);
        }
      };
      var walkPastBookmark = function(node, start2) {
        return node.filter(function(elm) {
          return BookmarkManager.isBookmarkNode(elm.dom);
        }).bind(start2 ? nextSibling : prevSibling);
      };
      var merge = function(outer, inner, rng, start2) {
        var outerElm = outer.dom;
        var innerElm = inner.dom;
        var oldLength = start2 ? outerElm.length : innerElm.length;
        if (start2) {
          mergeTextNodes(outerElm, innerElm, false, !start2);
          rng.setStart(innerElm, oldLength);
        } else {
          mergeTextNodes(innerElm, outerElm, false, !start2);
          rng.setEnd(innerElm, oldLength);
        }
      };
      var normalizeTextIfRequired = function(inner, start2) {
        parent(inner).each(function(root) {
          var text = inner.dom;
          if (start2 && needsToBeNbspLeft(root, CaretPosition(text, 0))) {
            normalizeWhitespaceAfter(text, 0);
          } else if (!start2 && needsToBeNbspRight(root, CaretPosition(text, text.length))) {
            normalizeWhitespaceBefore(text, text.length);
          }
        });
      };
      var mergeAndNormalizeText = function(outerNode, innerNode, rng, start2) {
        outerNode.bind(function(outer) {
          var normalizer = start2 ? normalizeWhitespaceBefore : normalizeWhitespaceAfter;
          normalizer(outer.dom, start2 ? outer.dom.length : 0);
          return innerNode.filter(isText$8).map(function(inner) {
            return merge(outer, inner, rng, start2);
          });
        }).orThunk(function() {
          var innerTextNode = walkPastBookmark(innerNode, start2).or(innerNode).filter(isText$8);
          return innerTextNode.map(function(inner) {
            return normalizeTextIfRequired(inner, start2);
          });
        });
      };
      var rngSetContent = function(rng, fragment) {
        var firstChild2 = Optional.from(fragment.firstChild).map(SugarElement.fromDom);
        var lastChild2 = Optional.from(fragment.lastChild).map(SugarElement.fromDom);
        rng.deleteContents();
        rng.insertNode(fragment);
        var prevText = firstChild2.bind(prevSibling).filter(isText$8).bind(removeEmpty);
        var nextText = lastChild2.bind(nextSibling).filter(isText$8).bind(removeEmpty);
        mergeAndNormalizeText(prevText, firstChild2, rng, true);
        mergeAndNormalizeText(nextText, lastChild2, rng, false);
        rng.collapse(false);
      };
      var setupArgs = function(args, content) {
        return __assign(__assign({ format: "html" }, args), {
          set: true,
          selection: true,
          content
        });
      };
      var cleanContent = function(editor, args) {
        if (args.format !== "raw") {
          var rng = editor.selection.getRng();
          var contextBlock = editor.dom.getParent(rng.commonAncestorContainer, editor.dom.isBlock);
          var contextArgs = contextBlock ? { context: contextBlock.nodeName.toLowerCase() } : {};
          var node = editor.parser.parse(args.content, __assign(__assign({
            isRootContent: true,
            forced_root_block: false
          }, contextArgs), args));
          return HtmlSerializer({ validate: editor.validate }, editor.schema).serialize(node);
        } else {
          return args.content;
        }
      };
      var setContent$1 = function(editor, content, args) {
        if (args === void 0) {
          args = {};
        }
        var defaultedArgs = setupArgs(args, content);
        var updatedArgs = defaultedArgs;
        if (!defaultedArgs.no_events) {
          var eventArgs = editor.fire("BeforeSetContent", defaultedArgs);
          if (eventArgs.isDefaultPrevented()) {
            editor.fire("SetContent", eventArgs);
            return;
          } else {
            updatedArgs = eventArgs;
          }
        }
        updatedArgs.content = cleanContent(editor, updatedArgs);
        var rng = editor.selection.getRng();
        rngSetContent(rng, rng.createContextualFragment(updatedArgs.content));
        editor.selection.setRng(rng);
        scrollRangeIntoView(editor, rng);
        if (!updatedArgs.no_events) {
          editor.fire("SetContent", updatedArgs);
        }
      };
      var deleteFromCallbackMap = function(callbackMap, selector, callback) {
        if (callbackMap && has$2(callbackMap, selector)) {
          var newCallbacks = filter$4(callbackMap[selector], function(cb) {
            return cb !== callback;
          });
          if (newCallbacks.length === 0) {
            delete callbackMap[selector];
          } else {
            callbackMap[selector] = newCallbacks;
          }
        }
      };
      function SelectorChanged(dom2, editor) {
        var selectorChangedData;
        var currentSelectors;
        var findMatchingNode = function(selector, nodes) {
          return find$3(nodes, function(node) {
            return dom2.is(node, selector);
          });
        };
        var getParents2 = function(elem) {
          return dom2.getParents(elem, null, dom2.getRoot());
        };
        return {
          selectorChangedWithUnbind: function(selector, callback) {
            if (!selectorChangedData) {
              selectorChangedData = {};
              currentSelectors = {};
              editor.on("NodeChange", function(e) {
                var node = e.element;
                var parents2 = getParents2(node);
                var matchedSelectors = {};
                Tools.each(selectorChangedData, function(callbacks, selector2) {
                  findMatchingNode(selector2, parents2).each(function(node2) {
                    if (!currentSelectors[selector2]) {
                      each$k(callbacks, function(callback2) {
                        callback2(true, {
                          node: node2,
                          selector: selector2,
                          parents: parents2
                        });
                      });
                      currentSelectors[selector2] = callbacks;
                    }
                    matchedSelectors[selector2] = callbacks;
                  });
                });
                Tools.each(currentSelectors, function(callbacks, selector2) {
                  if (!matchedSelectors[selector2]) {
                    delete currentSelectors[selector2];
                    Tools.each(callbacks, function(callback2) {
                      callback2(false, {
                        node,
                        selector: selector2,
                        parents: parents2
                      });
                    });
                  }
                });
              });
            }
            if (!selectorChangedData[selector]) {
              selectorChangedData[selector] = [];
            }
            selectorChangedData[selector].push(callback);
            findMatchingNode(selector, getParents2(editor.selection.getStart())).each(function() {
              currentSelectors[selector] = selectorChangedData[selector];
            });
            return {
              unbind: function() {
                deleteFromCallbackMap(selectorChangedData, selector, callback);
                deleteFromCallbackMap(currentSelectors, selector, callback);
              }
            };
          }
        };
      }
      var isNativeIeSelection = function(rng) {
        return !!rng.select;
      };
      var isAttachedToDom = function(node) {
        return !!(node && node.ownerDocument) && contains$1(SugarElement.fromDom(node.ownerDocument), SugarElement.fromDom(node));
      };
      var isValidRange = function(rng) {
        if (!rng) {
          return false;
        } else if (isNativeIeSelection(rng)) {
          return true;
        } else {
          return isAttachedToDom(rng.startContainer) && isAttachedToDom(rng.endContainer);
        }
      };
      var EditorSelection = function(dom2, win, serializer, editor) {
        var selectedRange;
        var explicitRange;
        var selectorChangedWithUnbind = SelectorChanged(dom2, editor).selectorChangedWithUnbind;
        var setCursorLocation = function(node, offset) {
          var rng = dom2.createRng();
          if (isNonNullable(node) && isNonNullable(offset)) {
            rng.setStart(node, offset);
            rng.setEnd(node, offset);
            setRng(rng);
            collapse2(false);
          } else {
            moveEndPoint(dom2, rng, editor.getBody(), true);
            setRng(rng);
          }
        };
        var getContent2 = function(args) {
          return getContent$1(editor, args);
        };
        var setContent2 = function(content, args) {
          return setContent$1(editor, content, args);
        };
        var getStart$12 = function(real) {
          return getStart(editor.getBody(), getRng$1(), real);
        };
        var getEnd$1 = function(real) {
          return getEnd(editor.getBody(), getRng$1(), real);
        };
        var getBookmark2 = function(type2, normalized) {
          return bookmarkManager.getBookmark(type2, normalized);
        };
        var moveToBookmark2 = function(bookmark) {
          return bookmarkManager.moveToBookmark(bookmark);
        };
        var select$12 = function(node, content) {
          select(dom2, node, content).each(setRng);
          return node;
        };
        var isCollapsed = function() {
          var rng = getRng$1(), sel = getSel();
          if (!rng || rng.item) {
            return false;
          }
          if (rng.compareEndPoints) {
            return rng.compareEndPoints("StartToEnd", rng) === 0;
          }
          return !sel || rng.collapsed;
        };
        var collapse2 = function(toStart) {
          var rng = getRng$1();
          rng.collapse(!!toStart);
          setRng(rng);
        };
        var getSel = function() {
          return win.getSelection ? win.getSelection() : win.document.selection;
        };
        var getRng$1 = function() {
          var selection, rng, elm;
          var tryCompareBoundaryPoints = function(how, sourceRange, destinationRange) {
            try {
              return sourceRange.compareBoundaryPoints(how, destinationRange);
            } catch (ex) {
              return -1;
            }
          };
          var doc2 = win.document;
          if (editor.bookmark !== void 0 && hasFocus(editor) === false) {
            var bookmark = getRng(editor);
            if (bookmark.isSome()) {
              return bookmark.map(function(r2) {
                return processRanges(editor, [r2])[0];
              }).getOr(doc2.createRange());
            }
          }
          try {
            if ((selection = getSel()) && !isRestrictedNode(selection.anchorNode)) {
              if (selection.rangeCount > 0) {
                rng = selection.getRangeAt(0);
              } else {
                rng = selection.createRange ? selection.createRange() : doc2.createRange();
              }
              rng = processRanges(editor, [rng])[0];
            }
          } catch (ex) {
          }
          if (!rng) {
            rng = doc2.createRange ? doc2.createRange() : doc2.body.createTextRange();
          }
          if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
            elm = dom2.getRoot();
            rng.setStart(elm, 0);
            rng.setEnd(elm, 0);
          }
          if (selectedRange && explicitRange) {
            if (tryCompareBoundaryPoints(rng.START_TO_START, rng, selectedRange) === 0 && tryCompareBoundaryPoints(rng.END_TO_END, rng, selectedRange) === 0) {
              rng = explicitRange;
            } else {
              selectedRange = null;
              explicitRange = null;
            }
          }
          return rng;
        };
        var setRng = function(rng, forward) {
          var node;
          if (!isValidRange(rng)) {
            return;
          }
          var ieRange = isNativeIeSelection(rng) ? rng : null;
          if (ieRange) {
            explicitRange = null;
            try {
              ieRange.select();
            } catch (ex) {
            }
            return;
          }
          var sel = getSel();
          var evt = editor.fire("SetSelectionRange", {
            range: rng,
            forward
          });
          rng = evt.range;
          if (sel) {
            explicitRange = rng;
            try {
              sel.removeAllRanges();
              sel.addRange(rng);
            } catch (ex) {
            }
            if (forward === false && sel.extend) {
              sel.collapse(rng.endContainer, rng.endOffset);
              sel.extend(rng.startContainer, rng.startOffset);
            }
            selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
          }
          if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) {
            if (rng.endOffset - rng.startOffset < 2) {
              if (rng.startContainer.hasChildNodes()) {
                node = rng.startContainer.childNodes[rng.startOffset];
                if (node && node.tagName === "IMG") {
                  sel.setBaseAndExtent(rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset);
                  if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) {
                    sel.setBaseAndExtent(node, 0, node, 1);
                  }
                }
              }
            }
          }
          editor.fire("AfterSetSelectionRange", {
            range: rng,
            forward
          });
        };
        var setNode = function(elm) {
          setContent2(dom2.getOuterHTML(elm));
          return elm;
        };
        var getNode$12 = function() {
          return getNode(editor.getBody(), getRng$1());
        };
        var getSelectedBlocks$1 = function(startElm, endElm) {
          return getSelectedBlocks(dom2, getRng$1(), startElm, endElm);
        };
        var isForward = function() {
          var sel = getSel();
          var anchorNode = sel === null || sel === void 0 ? void 0 : sel.anchorNode;
          var focusNode = sel === null || sel === void 0 ? void 0 : sel.focusNode;
          if (!sel || !anchorNode || !focusNode || isRestrictedNode(anchorNode) || isRestrictedNode(focusNode)) {
            return true;
          }
          var anchorRange = dom2.createRng();
          anchorRange.setStart(anchorNode, sel.anchorOffset);
          anchorRange.collapse(true);
          var focusRange = dom2.createRng();
          focusRange.setStart(focusNode, sel.focusOffset);
          focusRange.collapse(true);
          return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
        };
        var normalize2 = function() {
          var rng = getRng$1();
          var sel = getSel();
          if (!hasMultipleRanges(sel) && hasAnyRanges(editor)) {
            var normRng = normalize$2(dom2, rng);
            normRng.each(function(normRng2) {
              setRng(normRng2, isForward());
            });
            return normRng.getOr(rng);
          }
          return rng;
        };
        var selectorChanged = function(selector, callback) {
          selectorChangedWithUnbind(selector, callback);
          return exports2;
        };
        var getScrollContainer = function() {
          var scrollContainer;
          var node = dom2.getRoot();
          while (node && node.nodeName !== "BODY") {
            if (node.scrollHeight > node.clientHeight) {
              scrollContainer = node;
              break;
            }
            node = node.parentNode;
          }
          return scrollContainer;
        };
        var scrollIntoView = function(elm, alignToTop) {
          if (isNonNullable(elm)) {
            scrollElementIntoView(editor, elm, alignToTop);
          } else {
            scrollRangeIntoView(editor, getRng$1(), alignToTop);
          }
        };
        var placeCaretAt = function(clientX, clientY) {
          return setRng(fromPoint(clientX, clientY, editor.getDoc()));
        };
        var getBoundingClientRect2 = function() {
          var rng = getRng$1();
          return rng.collapsed ? CaretPosition.fromRangeStart(rng).getClientRects()[0] : rng.getBoundingClientRect();
        };
        var destroy2 = function() {
          win = selectedRange = explicitRange = null;
          controlSelection.destroy();
        };
        var exports2 = {
          bookmarkManager: null,
          controlSelection: null,
          dom: dom2,
          win,
          serializer,
          editor,
          collapse: collapse2,
          setCursorLocation,
          getContent: getContent2,
          setContent: setContent2,
          getBookmark: getBookmark2,
          moveToBookmark: moveToBookmark2,
          select: select$12,
          isCollapsed,
          isForward,
          setNode,
          getNode: getNode$12,
          getSel,
          setRng,
          getRng: getRng$1,
          getStart: getStart$12,
          getEnd: getEnd$1,
          getSelectedBlocks: getSelectedBlocks$1,
          normalize: normalize2,
          selectorChanged,
          selectorChangedWithUnbind,
          getScrollContainer,
          scrollIntoView,
          placeCaretAt,
          getBoundingClientRect: getBoundingClientRect2,
          destroy: destroy2
        };
        var bookmarkManager = BookmarkManager(exports2);
        var controlSelection = ControlSelection(exports2, editor);
        exports2.bookmarkManager = bookmarkManager;
        exports2.controlSelection = controlSelection;
        return exports2;
      };
      var removeAttrs = function(node, names) {
        each$k(names, function(name2) {
          node.attr(name2, null);
        });
      };
      var addFontToSpansFilter = function(domParser, styles, fontSizes) {
        domParser.addNodeFilter("font", function(nodes) {
          each$k(nodes, function(node) {
            var props = styles.parse(node.attr("style"));
            var color = node.attr("color");
            var face = node.attr("face");
            var size = node.attr("size");
            if (color) {
              props.color = color;
            }
            if (face) {
              props["font-family"] = face;
            }
            if (size) {
              props["font-size"] = fontSizes[parseInt(node.attr("size"), 10) - 1];
            }
            node.name = "span";
            node.attr("style", styles.serialize(props));
            removeAttrs(node, [
              "color",
              "face",
              "size"
            ]);
          });
        });
      };
      var addStrikeToSpanFilter = function(domParser, styles) {
        domParser.addNodeFilter("strike", function(nodes) {
          each$k(nodes, function(node) {
            var props = styles.parse(node.attr("style"));
            props["text-decoration"] = "line-through";
            node.name = "span";
            node.attr("style", styles.serialize(props));
          });
        });
      };
      var addFilters = function(domParser, settings) {
        var styles = Styles();
        if (settings.convert_fonts_to_spans) {
          addFontToSpansFilter(domParser, styles, Tools.explode(settings.font_size_legacy_values));
        }
        addStrikeToSpanFilter(domParser, styles);
      };
      var register$2 = function(domParser, settings) {
        if (settings.inline_styles) {
          addFilters(domParser, settings);
        }
      };
      var blobUriToBlob = function(url) {
        return new promiseObj(function(resolve2, reject) {
          var rejectWithError = function() {
            reject("Cannot convert " + url + " to Blob. Resource might not exist or is inaccessible.");
          };
          try {
            var xhr_1 = new XMLHttpRequest();
            xhr_1.open("GET", url, true);
            xhr_1.responseType = "blob";
            xhr_1.onload = function() {
              if (xhr_1.status === 200) {
                resolve2(xhr_1.response);
              } else {
                rejectWithError();
              }
            };
            xhr_1.onerror = rejectWithError;
            xhr_1.send();
          } catch (ex) {
            rejectWithError();
          }
        });
      };
      var parseDataUri = function(uri) {
        var type2;
        var uriParts = decodeURIComponent(uri).split(",");
        var matches2 = /data:([^;]+)/.exec(uriParts[0]);
        if (matches2) {
          type2 = matches2[1];
        }
        return {
          type: type2,
          data: uriParts[1]
        };
      };
      var buildBlob = function(type2, data2) {
        var str;
        try {
          str = atob(data2);
        } catch (e) {
          return Optional.none();
        }
        var arr2 = new Uint8Array(str.length);
        for (var i = 0; i < arr2.length; i++) {
          arr2[i] = str.charCodeAt(i);
        }
        return Optional.some(new Blob([arr2], { type: type2 }));
      };
      var dataUriToBlob = function(uri) {
        return new promiseObj(function(resolve2) {
          var _a = parseDataUri(uri), type2 = _a.type, data2 = _a.data;
          buildBlob(type2, data2).fold(function() {
            return resolve2(new Blob([]));
          }, resolve2);
        });
      };
      var uriToBlob = function(url) {
        if (url.indexOf("blob:") === 0) {
          return blobUriToBlob(url);
        }
        if (url.indexOf("data:") === 0) {
          return dataUriToBlob(url);
        }
        return null;
      };
      var blobToDataUri = function(blob) {
        return new promiseObj(function(resolve2) {
          var reader = new FileReader();
          reader.onloadend = function() {
            resolve2(reader.result);
          };
          reader.readAsDataURL(blob);
        });
      };
      var count$1 = 0;
      var uniqueId = function(prefix) {
        return (prefix || "blobid") + count$1++;
      };
      var imageToBlobInfo = function(blobCache, img, resolve2, reject) {
        var base64, blobInfo;
        if (img.src.indexOf("blob:") === 0) {
          blobInfo = blobCache.getByUri(img.src);
          if (blobInfo) {
            resolve2({
              image: img,
              blobInfo
            });
          } else {
            uriToBlob(img.src).then(function(blob) {
              blobToDataUri(blob).then(function(dataUri) {
                base64 = parseDataUri(dataUri).data;
                blobInfo = blobCache.create(uniqueId(), blob, base64);
                blobCache.add(blobInfo);
                resolve2({
                  image: img,
                  blobInfo
                });
              });
            }, function(err) {
              reject(err);
            });
          }
          return;
        }
        var _a = parseDataUri(img.src), data2 = _a.data, type2 = _a.type;
        base64 = data2;
        blobInfo = blobCache.getByData(base64, type2);
        if (blobInfo) {
          resolve2({
            image: img,
            blobInfo
          });
        } else {
          uriToBlob(img.src).then(function(blob) {
            blobInfo = blobCache.create(uniqueId(), blob, base64);
            blobCache.add(blobInfo);
            resolve2({
              image: img,
              blobInfo
            });
          }, function(err) {
            reject(err);
          });
        }
      };
      var getAllImages = function(elm) {
        return elm ? from(elm.getElementsByTagName("img")) : [];
      };
      var ImageScanner = function(uploadStatus, blobCache) {
        var cachedPromises = {};
        var findAll2 = function(elm, predicate) {
          if (!predicate) {
            predicate = always;
          }
          var images = filter$4(getAllImages(elm), function(img) {
            var src = img.src;
            if (!Env.fileApi) {
              return false;
            }
            if (img.hasAttribute("data-mce-bogus")) {
              return false;
            }
            if (img.hasAttribute("data-mce-placeholder")) {
              return false;
            }
            if (!src || src === Env.transparentSrc) {
              return false;
            }
            if (src.indexOf("blob:") === 0) {
              return !uploadStatus.isUploaded(src) && predicate(img);
            }
            if (src.indexOf("data:") === 0) {
              return predicate(img);
            }
            return false;
          });
          var promises = map$3(images, function(img) {
            if (cachedPromises[img.src] !== void 0) {
              return new promiseObj(function(resolve2) {
                cachedPromises[img.src].then(function(imageInfo) {
                  if (typeof imageInfo === "string") {
                    return imageInfo;
                  }
                  resolve2({
                    image: img,
                    blobInfo: imageInfo.blobInfo
                  });
                });
              });
            }
            var newPromise = new promiseObj(function(resolve2, reject) {
              imageToBlobInfo(blobCache, img, resolve2, reject);
            }).then(function(result) {
              delete cachedPromises[result.image.src];
              return result;
            }).catch(function(error2) {
              delete cachedPromises[img.src];
              return error2;
            });
            cachedPromises[img.src] = newPromise;
            return newPromise;
          });
          return promiseObj.all(promises);
        };
        return { findAll: findAll2 };
      };
      var paddEmptyNode = function(settings, args, blockElements, node) {
        var brPreferred = settings.padd_empty_with_br || args.insert;
        if (brPreferred && blockElements[node.name]) {
          node.empty().append(new AstNode("br", 1)).shortEnded = true;
        } else {
          node.empty().append(new AstNode("#text", 3)).value = nbsp;
        }
      };
      var isPaddedWithNbsp = function(node) {
        return hasOnlyChild(node, "#text") && node.firstChild.value === nbsp;
      };
      var hasOnlyChild = function(node, name2) {
        return node && node.firstChild && node.firstChild === node.lastChild && node.firstChild.name === name2;
      };
      var isPadded = function(schema, node) {
        var rule = schema.getElementRule(node.name);
        return rule && rule.paddEmpty;
      };
      var isEmpty = function(schema, nonEmptyElements, whitespaceElements, node) {
        return node.isEmpty(nonEmptyElements, whitespaceElements, function(node2) {
          return isPadded(schema, node2);
        });
      };
      var isLineBreakNode = function(node, blockElements) {
        return node && (has$2(blockElements, node.name) || node.name === "br");
      };
      var isBogusImage = function(img) {
        return isNonNullable(img.attr("data-mce-bogus"));
      };
      var isInternalImageSource = function(img) {
        return img.attr("src") === Env.transparentSrc || isNonNullable(img.attr("data-mce-placeholder"));
      };
      var isValidDataImg = function(img, settings) {
        if (settings.images_dataimg_filter) {
          var imgElem_1 = new Image();
          imgElem_1.src = img.attr("src");
          each$j(img.attributes.map, function(value2, key) {
            imgElem_1.setAttribute(key, value2);
          });
          return settings.images_dataimg_filter(imgElem_1);
        } else {
          return true;
        }
      };
      var registerBase64ImageFilter = function(parser, settings) {
        var blobCache = settings.blob_cache;
        var processImage = function(img) {
          var inputSrc = img.attr("src");
          if (isInternalImageSource(img) || isBogusImage(img)) {
            return;
          }
          parseDataUri$1(inputSrc).filter(function() {
            return isValidDataImg(img, settings);
          }).bind(function(_a) {
            var type2 = _a.type, data2 = _a.data;
            return Optional.from(blobCache.getByData(data2, type2)).orThunk(function() {
              return buildBlob(type2, data2).map(function(blob) {
                var blobInfo = blobCache.create(uniqueId(), blob, data2);
                blobCache.add(blobInfo);
                return blobInfo;
              });
            });
          }).each(function(blobInfo) {
            img.attr("src", blobInfo.blobUri());
          });
        };
        if (blobCache) {
          parser.addAttributeFilter("src", function(nodes) {
            return each$k(nodes, processImage);
          });
        }
      };
      var register$1 = function(parser, settings) {
        var schema = parser.schema;
        if (settings.remove_trailing_brs) {
          parser.addNodeFilter("br", function(nodes, _, args) {
            var i;
            var l = nodes.length;
            var node;
            var blockElements = Tools.extend({}, schema.getBlockElements());
            var nonEmptyElements = schema.getNonEmptyElements();
            var parent2, lastParent, prev, prevName;
            var whiteSpaceElements = schema.getWhiteSpaceElements();
            var elementRule, textNode;
            blockElements.body = 1;
            for (i = 0; i < l; i++) {
              node = nodes[i];
              parent2 = node.parent;
              if (blockElements[node.parent.name] && node === parent2.lastChild) {
                prev = node.prev;
                while (prev) {
                  prevName = prev.name;
                  if (prevName !== "span" || prev.attr("data-mce-type") !== "bookmark") {
                    if (prevName === "br") {
                      node = null;
                    }
                    break;
                  }
                  prev = prev.prev;
                }
                if (node) {
                  node.remove();
                  if (isEmpty(schema, nonEmptyElements, whiteSpaceElements, parent2)) {
                    elementRule = schema.getElementRule(parent2.name);
                    if (elementRule) {
                      if (elementRule.removeEmpty) {
                        parent2.remove();
                      } else if (elementRule.paddEmpty) {
                        paddEmptyNode(settings, args, blockElements, parent2);
                      }
                    }
                  }
                }
              } else {
                lastParent = node;
                while (parent2 && parent2.firstChild === lastParent && parent2.lastChild === lastParent) {
                  lastParent = parent2;
                  if (blockElements[parent2.name]) {
                    break;
                  }
                  parent2 = parent2.parent;
                }
                if (lastParent === parent2 && settings.padd_empty_with_br !== true) {
                  textNode = new AstNode("#text", 3);
                  textNode.value = nbsp;
                  node.replace(textNode);
                }
              }
            }
          });
        }
        parser.addAttributeFilter("href", function(nodes) {
          var i = nodes.length;
          var appendRel = function(rel) {
            var parts = rel.split(" ").filter(function(p) {
              return p.length > 0;
            });
            return parts.concat(["noopener"]).sort().join(" ");
          };
          var addNoOpener = function(rel) {
            var newRel = rel ? Tools.trim(rel) : "";
            if (!/\b(noopener)\b/g.test(newRel)) {
              return appendRel(newRel);
            } else {
              return newRel;
            }
          };
          if (!settings.allow_unsafe_link_target) {
            while (i--) {
              var node = nodes[i];
              if (node.name === "a" && node.attr("target") === "_blank") {
                node.attr("rel", addNoOpener(node.attr("rel")));
              }
            }
          }
        });
        if (!settings.allow_html_in_named_anchor) {
          parser.addAttributeFilter("id,name", function(nodes) {
            var i = nodes.length, sibling2, prevSibling2, parent2, node;
            while (i--) {
              node = nodes[i];
              if (node.name === "a" && node.firstChild && !node.attr("href")) {
                parent2 = node.parent;
                sibling2 = node.lastChild;
                do {
                  prevSibling2 = sibling2.prev;
                  parent2.insert(sibling2, node);
                  sibling2 = prevSibling2;
                } while (sibling2);
              }
            }
          });
        }
        if (settings.fix_list_elements) {
          parser.addNodeFilter("ul,ol", function(nodes) {
            var i = nodes.length, node, parentNode;
            while (i--) {
              node = nodes[i];
              parentNode = node.parent;
              if (parentNode.name === "ul" || parentNode.name === "ol") {
                if (node.prev && node.prev.name === "li") {
                  node.prev.append(node);
                } else {
                  var li = new AstNode("li", 1);
                  li.attr("style", "list-style-type: none");
                  node.wrap(li);
                }
              }
            }
          });
        }
        if (settings.validate && schema.getValidClasses()) {
          parser.addAttributeFilter("class", function(nodes) {
            var validClasses = schema.getValidClasses();
            var i = nodes.length;
            while (i--) {
              var node = nodes[i];
              var classList = node.attr("class").split(" ");
              var classValue = "";
              for (var ci = 0; ci < classList.length; ci++) {
                var className = classList[ci];
                var valid = false;
                var validClassesMap = validClasses["*"];
                if (validClassesMap && validClassesMap[className]) {
                  valid = true;
                }
                validClassesMap = validClasses[node.name];
                if (!valid && validClassesMap && validClassesMap[className]) {
                  valid = true;
                }
                if (valid) {
                  if (classValue) {
                    classValue += " ";
                  }
                  classValue += className;
                }
              }
              if (!classValue.length) {
                classValue = null;
              }
              node.attr("class", classValue);
            }
          });
        }
        registerBase64ImageFilter(parser, settings);
      };
      var makeMap = Tools.makeMap, each$6 = Tools.each, explode$2 = Tools.explode, extend$4 = Tools.extend;
      var DomParser = function(settings, schema) {
        if (schema === void 0) {
          schema = Schema();
        }
        var nodeFilters = {};
        var attributeFilters = [];
        var matchedNodes = {};
        var matchedAttributes = {};
        settings = settings || {};
        settings.validate = "validate" in settings ? settings.validate : true;
        settings.root_name = settings.root_name || "body";
        var fixInvalidChildren = function(nodes) {
          var nonSplitableElements = makeMap("tr,td,th,tbody,thead,tfoot,table");
          var nonEmptyElements = schema.getNonEmptyElements();
          var whitespaceElements = schema.getWhiteSpaceElements();
          var textBlockElements = schema.getTextBlockElements();
          var specialElements = schema.getSpecialElements();
          var removeOrUnwrapInvalidNode = function(node2, originalNodeParent) {
            if (originalNodeParent === void 0) {
              originalNodeParent = node2.parent;
            }
            if (specialElements[node2.name]) {
              node2.empty().remove();
            } else {
              var children2 = node2.children();
              for (var _i = 0, children_1 = children2; _i < children_1.length; _i++) {
                var childNode2 = children_1[_i];
                if (!schema.isValidChild(originalNodeParent.name, childNode2.name)) {
                  removeOrUnwrapInvalidNode(childNode2, originalNodeParent);
                }
              }
              node2.unwrap();
            }
          };
          for (var ni = 0; ni < nodes.length; ni++) {
            var node = nodes[ni];
            var parent_1 = void 0, newParent = void 0, tempNode = void 0;
            if (!node.parent || node.fixed) {
              continue;
            }
            if (textBlockElements[node.name] && node.parent.name === "li") {
              var sibling2 = node.next;
              while (sibling2) {
                if (textBlockElements[sibling2.name]) {
                  sibling2.name = "li";
                  sibling2.fixed = true;
                  node.parent.insert(sibling2, node.parent);
                } else {
                  break;
                }
                sibling2 = sibling2.next;
              }
              node.unwrap();
              continue;
            }
            var parents2 = [node];
            for (parent_1 = node.parent; parent_1 && !schema.isValidChild(parent_1.name, node.name) && !nonSplitableElements[parent_1.name]; parent_1 = parent_1.parent) {
              parents2.push(parent_1);
            }
            if (parent_1 && parents2.length > 1) {
              if (schema.isValidChild(parent_1.name, node.name)) {
                parents2.reverse();
                newParent = filterNode(parents2[0].clone());
                var currentNode = newParent;
                for (var i = 0; i < parents2.length - 1; i++) {
                  if (schema.isValidChild(currentNode.name, parents2[i].name)) {
                    tempNode = filterNode(parents2[i].clone());
                    currentNode.append(tempNode);
                  } else {
                    tempNode = currentNode;
                  }
                  for (var childNode = parents2[i].firstChild; childNode && childNode !== parents2[i + 1]; ) {
                    var nextNode = childNode.next;
                    tempNode.append(childNode);
                    childNode = nextNode;
                  }
                  currentNode = tempNode;
                }
                if (!isEmpty(schema, nonEmptyElements, whitespaceElements, newParent)) {
                  parent_1.insert(newParent, parents2[0], true);
                  parent_1.insert(node, newParent);
                } else {
                  parent_1.insert(node, parents2[0], true);
                }
                parent_1 = parents2[0];
                if (isEmpty(schema, nonEmptyElements, whitespaceElements, parent_1) || hasOnlyChild(parent_1, "br")) {
                  parent_1.empty().remove();
                }
              } else {
                removeOrUnwrapInvalidNode(node);
              }
            } else if (node.parent) {
              if (node.name === "li") {
                var sibling2 = node.prev;
                if (sibling2 && (sibling2.name === "ul" || sibling2.name === "ol")) {
                  sibling2.append(node);
                  continue;
                }
                sibling2 = node.next;
                if (sibling2 && (sibling2.name === "ul" || sibling2.name === "ol")) {
                  sibling2.insert(node, sibling2.firstChild, true);
                  continue;
                }
                node.wrap(filterNode(new AstNode("ul", 1)));
                continue;
              }
              if (schema.isValidChild(node.parent.name, "div") && schema.isValidChild("div", node.name)) {
                node.wrap(filterNode(new AstNode("div", 1)));
              } else {
                removeOrUnwrapInvalidNode(node);
              }
            }
          }
        };
        var filterNode = function(node) {
          var name2 = node.name;
          if (name2 in nodeFilters) {
            var list = matchedNodes[name2];
            if (list) {
              list.push(node);
            } else {
              matchedNodes[name2] = [node];
            }
          }
          var i = attributeFilters.length;
          while (i--) {
            var attrName = attributeFilters[i].name;
            if (attrName in node.attributes.map) {
              var list = matchedAttributes[attrName];
              if (list) {
                list.push(node);
              } else {
                matchedAttributes[attrName] = [node];
              }
            }
          }
          return node;
        };
        var addNodeFilter = function(name2, callback) {
          each$6(explode$2(name2), function(name3) {
            var list = nodeFilters[name3];
            if (!list) {
              nodeFilters[name3] = list = [];
            }
            list.push(callback);
          });
        };
        var getNodeFilters = function() {
          var out = [];
          for (var name_1 in nodeFilters) {
            if (has$2(nodeFilters, name_1)) {
              out.push({
                name: name_1,
                callbacks: nodeFilters[name_1]
              });
            }
          }
          return out;
        };
        var addAttributeFilter = function(name2, callback) {
          each$6(explode$2(name2), function(name3) {
            var i;
            for (i = 0; i < attributeFilters.length; i++) {
              if (attributeFilters[i].name === name3) {
                attributeFilters[i].callbacks.push(callback);
                return;
              }
            }
            attributeFilters.push({
              name: name3,
              callbacks: [callback]
            });
          });
        };
        var getAttributeFilters = function() {
          return [].concat(attributeFilters);
        };
        var parse = function(html, args) {
          var nodes, i, l, fi, fl, list, name2;
          var invalidChildren = [];
          var node;
          var getRootBlockName = function(name3) {
            if (name3 === false) {
              return "";
            } else if (name3 === true) {
              return "p";
            } else {
              return name3;
            }
          };
          args = args || {};
          matchedNodes = {};
          matchedAttributes = {};
          var blockElements = extend$4(makeMap("script,style,head,html,body,title,meta,param"), schema.getBlockElements());
          var textRootBlockElements = getTextRootBlockElements(schema);
          var nonEmptyElements = schema.getNonEmptyElements();
          var children2 = schema.children;
          var validate2 = settings.validate;
          var forcedRootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
          var rootBlockName = getRootBlockName(forcedRootBlockName);
          var whiteSpaceElements = schema.getWhiteSpaceElements();
          var startWhiteSpaceRegExp = /^[ \t\r\n]+/;
          var endWhiteSpaceRegExp = /[ \t\r\n]+$/;
          var allWhiteSpaceRegExp = /[ \t\r\n]+/g;
          var isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
          var isInWhiteSpacePreservedElement = has$2(whiteSpaceElements, args.context) || has$2(whiteSpaceElements, settings.root_name);
          var addRootBlocks2 = function() {
            var node2 = rootNode.firstChild, rootBlockNode = null;
            var trim2 = function(rootBlock) {
              if (rootBlock) {
                node2 = rootBlock.firstChild;
                if (node2 && node2.type === 3) {
                  node2.value = node2.value.replace(startWhiteSpaceRegExp, "");
                }
                node2 = rootBlock.lastChild;
                if (node2 && node2.type === 3) {
                  node2.value = node2.value.replace(endWhiteSpaceRegExp, "");
                }
              }
            };
            if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
              return;
            }
            while (node2) {
              var next = node2.next;
              if (node2.type === 3 || node2.type === 1 && node2.name !== "p" && !blockElements[node2.name] && !node2.attr("data-mce-type")) {
                if (!rootBlockNode) {
                  rootBlockNode = createNode(rootBlockName, 1);
                  rootBlockNode.attr(settings.forced_root_block_attrs);
                  rootNode.insert(rootBlockNode, node2);
                  rootBlockNode.append(node2);
                } else {
                  rootBlockNode.append(node2);
                }
              } else {
                trim2(rootBlockNode);
                rootBlockNode = null;
              }
              node2 = next;
            }
            trim2(rootBlockNode);
          };
          var createNode = function(name3, type2) {
            var node2 = new AstNode(name3, type2);
            var list2;
            if (name3 in nodeFilters) {
              list2 = matchedNodes[name3];
              if (list2) {
                list2.push(node2);
              } else {
                matchedNodes[name3] = [node2];
              }
            }
            return node2;
          };
          var removeWhitespaceBefore = function(node2) {
            var blockElements2 = schema.getBlockElements();
            for (var textNode = node2.prev; textNode && textNode.type === 3; ) {
              var textVal = textNode.value.replace(endWhiteSpaceRegExp, "");
              if (textVal.length > 0) {
                textNode.value = textVal;
                return;
              }
              var textNodeNext = textNode.next;
              if (textNodeNext) {
                if (textNodeNext.type === 3 && textNodeNext.value.length) {
                  textNode = textNode.prev;
                  continue;
                }
                if (!blockElements2[textNodeNext.name] && textNodeNext.name !== "script" && textNodeNext.name !== "style") {
                  textNode = textNode.prev;
                  continue;
                }
              }
              var sibling2 = textNode.prev;
              textNode.remove();
              textNode = sibling2;
            }
          };
          var cloneAndExcludeBlocks = function(input) {
            var output = {};
            for (var name_2 in input) {
              if (name_2 !== "li" && name_2 !== "p") {
                output[name_2] = input[name_2];
              }
            }
            return output;
          };
          var isTextRootBlockEmpty = function(node2) {
            var tempNode = node2;
            while (isNonNullable(tempNode)) {
              if (tempNode.name in textRootBlockElements) {
                return isEmpty(schema, nonEmptyElements, whiteSpaceElements, tempNode);
              } else {
                tempNode = tempNode.parent;
              }
            }
            return false;
          };
          var parser = SaxParser({
            validate: validate2,
            document: settings.document,
            allow_html_data_urls: settings.allow_html_data_urls,
            allow_svg_data_urls: settings.allow_svg_data_urls,
            allow_script_urls: settings.allow_script_urls,
            allow_conditional_comments: settings.allow_conditional_comments,
            preserve_cdata: settings.preserve_cdata,
            self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
            cdata: function(text) {
              node.append(createNode("#cdata", 4)).value = text;
            },
            text: function(text, raw) {
              var textNode;
              if (!isInWhiteSpacePreservedElement) {
                text = text.replace(allWhiteSpaceRegExp, " ");
                if (isLineBreakNode(node.lastChild, blockElements)) {
                  text = text.replace(startWhiteSpaceRegExp, "");
                }
              }
              if (text.length !== 0) {
                textNode = createNode("#text", 3);
                textNode.raw = !!raw;
                node.append(textNode).value = text;
              }
            },
            comment: function(text) {
              node.append(createNode("#comment", 8)).value = text;
            },
            pi: function(name3, text) {
              node.append(createNode(name3, 7)).value = text;
              removeWhitespaceBefore(node);
            },
            doctype: function(text) {
              var newNode = node.append(createNode("#doctype", 10));
              newNode.value = text;
              removeWhitespaceBefore(node);
            },
            start: function(name3, attrs, empty2) {
              var elementRule = validate2 ? schema.getElementRule(name3) : {};
              if (elementRule) {
                var newNode = createNode(elementRule.outputName || name3, 1);
                newNode.attributes = attrs;
                newNode.shortEnded = empty2;
                node.append(newNode);
                var parent_2 = children2[node.name];
                if (parent_2 && children2[newNode.name] && !parent_2[newNode.name]) {
                  invalidChildren.push(newNode);
                }
                var attrFiltersLen = attributeFilters.length;
                while (attrFiltersLen--) {
                  var attrName = attributeFilters[attrFiltersLen].name;
                  if (attrName in attrs.map) {
                    list = matchedAttributes[attrName];
                    if (list) {
                      list.push(newNode);
                    } else {
                      matchedAttributes[attrName] = [newNode];
                    }
                  }
                }
                if (blockElements[name3]) {
                  removeWhitespaceBefore(newNode);
                }
                if (!empty2) {
                  node = newNode;
                }
                if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name3]) {
                  isInWhiteSpacePreservedElement = true;
                }
              }
            },
            end: function(name3) {
              var textNode, text, sibling2;
              var elementRule = validate2 ? schema.getElementRule(name3) : {};
              if (elementRule) {
                if (blockElements[name3]) {
                  if (!isInWhiteSpacePreservedElement) {
                    textNode = node.firstChild;
                    if (textNode && textNode.type === 3) {
                      text = textNode.value.replace(startWhiteSpaceRegExp, "");
                      if (text.length > 0) {
                        textNode.value = text;
                        textNode = textNode.next;
                      } else {
                        sibling2 = textNode.next;
                        textNode.remove();
                        textNode = sibling2;
                        while (textNode && textNode.type === 3) {
                          text = textNode.value;
                          sibling2 = textNode.next;
                          if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                            textNode.remove();
                            textNode = sibling2;
                          }
                          textNode = sibling2;
                        }
                      }
                    }
                    textNode = node.lastChild;
                    if (textNode && textNode.type === 3) {
                      text = textNode.value.replace(endWhiteSpaceRegExp, "");
                      if (text.length > 0) {
                        textNode.value = text;
                        textNode = textNode.prev;
                      } else {
                        sibling2 = textNode.prev;
                        textNode.remove();
                        textNode = sibling2;
                        while (textNode && textNode.type === 3) {
                          text = textNode.value;
                          sibling2 = textNode.prev;
                          if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
                            textNode.remove();
                            textNode = sibling2;
                          }
                          textNode = sibling2;
                        }
                      }
                    }
                  }
                }
                if (isInWhiteSpacePreservedElement && whiteSpaceElements[name3]) {
                  isInWhiteSpacePreservedElement = false;
                }
                var isNodeEmpty = isEmpty(schema, nonEmptyElements, whiteSpaceElements, node);
                var parentNode = node.parent;
                if (elementRule.paddInEmptyBlock && isNodeEmpty && isTextRootBlockEmpty(node)) {
                  paddEmptyNode(settings, args, blockElements, node);
                } else if (elementRule.removeEmpty && isNodeEmpty) {
                  if (blockElements[node.name]) {
                    node.empty().remove();
                  } else {
                    node.unwrap();
                  }
                } else if (elementRule.paddEmpty && (isPaddedWithNbsp(node) || isNodeEmpty)) {
                  paddEmptyNode(settings, args, blockElements, node);
                }
                node = parentNode;
              }
            }
          }, schema);
          var rootNode = node = new AstNode(args.context || settings.root_name, 11);
          parser.parse(html, args.format);
          if (validate2 && invalidChildren.length) {
            if (!args.context) {
              fixInvalidChildren(invalidChildren);
            } else {
              args.invalid = true;
            }
          }
          if (rootBlockName && (rootNode.name === "body" || args.isRootContent)) {
            addRootBlocks2();
          }
          if (!args.invalid) {
            for (name2 in matchedNodes) {
              if (!has$2(matchedNodes, name2)) {
                continue;
              }
              list = nodeFilters[name2];
              nodes = matchedNodes[name2];
              fi = nodes.length;
              while (fi--) {
                if (!nodes[fi].parent) {
                  nodes.splice(fi, 1);
                }
              }
              for (i = 0, l = list.length; i < l; i++) {
                list[i](nodes, name2, args);
              }
            }
            for (i = 0, l = attributeFilters.length; i < l; i++) {
              list = attributeFilters[i];
              if (list.name in matchedAttributes) {
                nodes = matchedAttributes[list.name];
                fi = nodes.length;
                while (fi--) {
                  if (!nodes[fi].parent) {
                    nodes.splice(fi, 1);
                  }
                }
                for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
                  list.callbacks[fi](nodes, list.name, args);
                }
              }
            }
          }
          return rootNode;
        };
        var exports2 = {
          schema,
          addAttributeFilter,
          getAttributeFilters,
          addNodeFilter,
          getNodeFilters,
          filterNode,
          parse
        };
        register$1(exports2, settings);
        register$2(exports2, settings);
        return exports2;
      };
      var register = function(htmlParser, settings, dom2) {
        htmlParser.addAttributeFilter("data-mce-tabindex", function(nodes, name2) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            node.attr("tabindex", node.attr("data-mce-tabindex"));
            node.attr(name2, null);
          }
        });
        htmlParser.addAttributeFilter("src,href,style", function(nodes, name2) {
          var internalName = "data-mce-" + name2;
          var urlConverter = settings.url_converter;
          var urlConverterScope = settings.url_converter_scope;
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            var value2 = node.attr(internalName);
            if (value2 !== void 0) {
              node.attr(name2, value2.length > 0 ? value2 : null);
              node.attr(internalName, null);
            } else {
              value2 = node.attr(name2);
              if (name2 === "style") {
                value2 = dom2.serializeStyle(dom2.parseStyle(value2), node.name);
              } else if (urlConverter) {
                value2 = urlConverter.call(urlConverterScope, value2, name2, node.name);
              }
              node.attr(name2, value2.length > 0 ? value2 : null);
            }
          }
        });
        htmlParser.addAttributeFilter("class", function(nodes) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            var value2 = node.attr("class");
            if (value2) {
              value2 = node.attr("class").replace(/(?:^|\s)mce-item-\w+(?!\S)/g, "");
              node.attr("class", value2.length > 0 ? value2 : null);
            }
          }
        });
        htmlParser.addAttributeFilter("data-mce-type", function(nodes, name2, args) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            if (node.attr("data-mce-type") === "bookmark" && !args.cleanup) {
              var hasChildren = Optional.from(node.firstChild).exists(function(firstChild2) {
                return !isZwsp(firstChild2.value);
              });
              if (hasChildren) {
                node.unwrap();
              } else {
                node.remove();
              }
            }
          }
        });
        htmlParser.addNodeFilter("noscript", function(nodes) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i].firstChild;
            if (node) {
              node.value = Entities.decode(node.value);
            }
          }
        });
        htmlParser.addNodeFilter("script,style", function(nodes, name2) {
          var trim2 = function(value3) {
            return value3.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, "");
          };
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            var value2 = node.firstChild ? node.firstChild.value : "";
            if (name2 === "script") {
              var type2 = node.attr("type");
              if (type2) {
                node.attr("type", type2 === "mce-no/type" ? null : type2.replace(/^mce\-/, ""));
              }
              if (settings.element_format === "xhtml" && value2.length > 0) {
                node.firstChild.value = "// <![CDATA[\n" + trim2(value2) + "\n// ]]>";
              }
            } else {
              if (settings.element_format === "xhtml" && value2.length > 0) {
                node.firstChild.value = "<!--\n" + trim2(value2) + "\n-->";
              }
            }
          }
        });
        htmlParser.addNodeFilter("#comment", function(nodes) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            if (settings.preserve_cdata && node.value.indexOf("[CDATA[") === 0) {
              node.name = "#cdata";
              node.type = 4;
              node.value = dom2.decode(node.value.replace(/^\[CDATA\[|\]\]$/g, ""));
            } else if (node.value.indexOf("mce:protected ") === 0) {
              node.name = "#text";
              node.type = 3;
              node.raw = true;
              node.value = unescape(node.value).substr(14);
            }
          }
        });
        htmlParser.addNodeFilter("xml:namespace,input", function(nodes, name2) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            if (node.type === 7) {
              node.remove();
            } else if (node.type === 1) {
              if (name2 === "input" && !node.attr("type")) {
                node.attr("type", "text");
              }
            }
          }
        });
        htmlParser.addAttributeFilter("data-mce-type", function(nodes) {
          each$k(nodes, function(node) {
            if (node.attr("data-mce-type") === "format-caret") {
              if (node.isEmpty(htmlParser.schema.getNonEmptyElements())) {
                node.remove();
              } else {
                node.unwrap();
              }
            }
          });
        });
        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, name2) {
          var i = nodes.length;
          while (i--) {
            nodes[i].attr(name2, null);
          }
        });
      };
      var trimTrailingBr = function(rootNode) {
        var isBr2 = function(node) {
          return node && node.name === "br";
        };
        var brNode1 = rootNode.lastChild;
        if (isBr2(brNode1)) {
          var brNode2 = brNode1.prev;
          if (isBr2(brNode2)) {
            brNode1.remove();
            brNode2.remove();
          }
        }
      };
      var preProcess = function(editor, node, args) {
        var oldDoc;
        var dom2 = editor.dom;
        var clonedNode = node.cloneNode(true);
        var impl = document.implementation;
        if (impl.createHTMLDocument) {
          var doc_1 = impl.createHTMLDocument("");
          Tools.each(clonedNode.nodeName === "BODY" ? clonedNode.childNodes : [clonedNode], function(node2) {
            doc_1.body.appendChild(doc_1.importNode(node2, true));
          });
          if (clonedNode.nodeName !== "BODY") {
            clonedNode = doc_1.body.firstChild;
          } else {
            clonedNode = doc_1.body;
          }
          oldDoc = dom2.doc;
          dom2.doc = doc_1;
        }
        firePreProcess(editor, __assign(__assign({}, args), { node: clonedNode }));
        if (oldDoc) {
          dom2.doc = oldDoc;
        }
        return clonedNode;
      };
      var shouldFireEvent = function(editor, args) {
        return editor && editor.hasEventListeners("PreProcess") && !args.no_events;
      };
      var process = function(editor, node, args) {
        return shouldFireEvent(editor, args) ? preProcess(editor, node, args) : node;
      };
      var addTempAttr = function(htmlParser, tempAttrs, name2) {
        if (Tools.inArray(tempAttrs, name2) === -1) {
          htmlParser.addAttributeFilter(name2, function(nodes, name3) {
            var i = nodes.length;
            while (i--) {
              nodes[i].attr(name3, null);
            }
          });
          tempAttrs.push(name2);
        }
      };
      var postProcess = function(editor, args, content) {
        if (!args.no_events && editor) {
          var outArgs = firePostProcess(editor, __assign(__assign({}, args), { content }));
          return outArgs.content;
        } else {
          return content;
        }
      };
      var getHtmlFromNode = function(dom2, node, args) {
        var html = trim$2(args.getInner ? node.innerHTML : dom2.getOuterHTML(node));
        return args.selection || isWsPreserveElement(SugarElement.fromDom(node)) ? html : Tools.trim(html);
      };
      var parseHtml = function(htmlParser, html, args) {
        var parserArgs = args.selection ? __assign({ forced_root_block: false }, args) : args;
        var rootNode = htmlParser.parse(html, parserArgs);
        trimTrailingBr(rootNode);
        return rootNode;
      };
      var serializeNode = function(settings, schema, node) {
        var htmlSerializer = HtmlSerializer(settings, schema);
        return htmlSerializer.serialize(node);
      };
      var toHtml = function(editor, settings, schema, rootNode, args) {
        var content = serializeNode(settings, schema, rootNode);
        return postProcess(editor, args, content);
      };
      var DomSerializerImpl = function(settings, editor) {
        var tempAttrs = ["data-mce-selected"];
        var dom2 = editor && editor.dom ? editor.dom : DOMUtils.DOM;
        var schema = editor && editor.schema ? editor.schema : Schema(settings);
        settings.entity_encoding = settings.entity_encoding || "named";
        settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
        var htmlParser = DomParser(settings, schema);
        register(htmlParser, settings, dom2);
        var serialize2 = function(node, parserArgs) {
          if (parserArgs === void 0) {
            parserArgs = {};
          }
          var args = __assign({ format: "html" }, parserArgs);
          var targetNode = process(editor, node, args);
          var html = getHtmlFromNode(dom2, targetNode, args);
          var rootNode = parseHtml(htmlParser, html, args);
          return args.format === "tree" ? rootNode : toHtml(editor, settings, schema, rootNode, args);
        };
        return {
          schema,
          addNodeFilter: htmlParser.addNodeFilter,
          addAttributeFilter: htmlParser.addAttributeFilter,
          serialize: serialize2,
          addRules: schema.addValidElements,
          setRules: schema.setValidElements,
          addTempAttr: curry(addTempAttr, htmlParser, tempAttrs),
          getTempAttrs: constant(tempAttrs),
          getNodeFilters: htmlParser.getNodeFilters,
          getAttributeFilters: htmlParser.getAttributeFilters
        };
      };
      var DomSerializer = function(settings, editor) {
        var domSerializer = DomSerializerImpl(settings, editor);
        return {
          schema: domSerializer.schema,
          addNodeFilter: domSerializer.addNodeFilter,
          addAttributeFilter: domSerializer.addAttributeFilter,
          serialize: domSerializer.serialize,
          addRules: domSerializer.addRules,
          setRules: domSerializer.setRules,
          addTempAttr: domSerializer.addTempAttr,
          getTempAttrs: domSerializer.getTempAttrs,
          getNodeFilters: domSerializer.getNodeFilters,
          getAttributeFilters: domSerializer.getAttributeFilters
        };
      };
      var defaultFormat = "html";
      var getContent = function(editor, args) {
        if (args === void 0) {
          args = {};
        }
        var format = args.format ? args.format : defaultFormat;
        return getContent$2(editor, args, format);
      };
      var setContent = function(editor, content, args) {
        if (args === void 0) {
          args = {};
        }
        return setContent$2(editor, content, args);
      };
      var DOM$7 = DOMUtils.DOM;
      var restoreOriginalStyles = function(editor) {
        DOM$7.setStyle(editor.id, "display", editor.orgDisplay);
      };
      var safeDestroy = function(x) {
        return Optional.from(x).each(function(x2) {
          return x2.destroy();
        });
      };
      var clearDomReferences = function(editor) {
        editor.contentAreaContainer = editor.formElement = editor.container = editor.editorContainer = null;
        editor.bodyElement = editor.contentDocument = editor.contentWindow = null;
        editor.iframeElement = editor.targetElm = null;
        if (editor.selection) {
          editor.selection = editor.selection.win = editor.selection.dom = editor.selection.dom.doc = null;
        }
      };
      var restoreForm = function(editor) {
        var form = editor.formElement;
        if (form) {
          if (form._mceOldSubmit) {
            form.submit = form._mceOldSubmit;
            form._mceOldSubmit = null;
          }
          DOM$7.unbind(form, "submit reset", editor.formEventDelegate);
        }
      };
      var remove = function(editor) {
        if (!editor.removed) {
          var _selectionOverrides = editor._selectionOverrides, editorUpload = editor.editorUpload;
          var body = editor.getBody();
          var element = editor.getElement();
          if (body) {
            editor.save({ is_removing: true });
          }
          editor.removed = true;
          editor.unbindAllNativeEvents();
          if (editor.hasHiddenInput && element) {
            DOM$7.remove(element.nextSibling);
          }
          fireRemove(editor);
          editor.editorManager.remove(editor);
          if (!editor.inline && body) {
            restoreOriginalStyles(editor);
          }
          fireDetach(editor);
          DOM$7.remove(editor.getContainer());
          safeDestroy(_selectionOverrides);
          safeDestroy(editorUpload);
          editor.destroy();
        }
      };
      var destroy = function(editor, automatic) {
        var selection = editor.selection, dom2 = editor.dom;
        if (editor.destroyed) {
          return;
        }
        if (!automatic && !editor.removed) {
          editor.remove();
          return;
        }
        if (!automatic) {
          editor.editorManager.off("beforeunload", editor._beforeUnload);
          if (editor.theme && editor.theme.destroy) {
            editor.theme.destroy();
          }
          safeDestroy(selection);
          safeDestroy(dom2);
        }
        restoreForm(editor);
        clearDomReferences(editor);
        editor.destroyed = true;
      };
      var deep = function(old, nu2) {
        var bothObjects = isObject(old) && isObject(nu2);
        return bothObjects ? deepMerge(old, nu2) : nu2;
      };
      var baseMerge = function(merger) {
        return function() {
          var objects = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            objects[_i] = arguments[_i];
          }
          if (objects.length === 0) {
            throw new Error("Can't merge zero objects");
          }
          var ret = {};
          for (var j = 0; j < objects.length; j++) {
            var curObject = objects[j];
            for (var key in curObject) {
              if (has$2(curObject, key)) {
                ret[key] = merger(ret[key], curObject[key]);
              }
            }
          }
          return ret;
        };
      };
      var deepMerge = baseMerge(deep);
      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(",");
      var deprecatedPlugins = "bbcode,colorpicker,contextmenu,fullpage,legacyoutput,spellchecker,textcolor".split(",");
      var movedToPremiumPlugins = "imagetools,toc".split(",");
      var getDeprecatedSettings = function(settings) {
        var settingNames = filter$4(deprecatedSettings, function(setting) {
          return has$2(settings, setting);
        });
        var forcedRootBlock = settings.forced_root_block;
        if (forcedRootBlock === false || forcedRootBlock === "") {
          settingNames.push("forced_root_block (false only)");
        }
        return sort(settingNames);
      };
      var getDeprecatedPlugins = function(settings) {
        var plugins = Tools.makeMap(settings.plugins, " ");
        var hasPlugin = function(plugin) {
          return has$2(plugins, plugin);
        };
        var pluginNames = __spreadArray(__spreadArray([], filter$4(deprecatedPlugins, hasPlugin), true), bind(movedToPremiumPlugins, function(plugin) {
          return hasPlugin(plugin) ? [plugin + " (moving to premium)"] : [];
        }), true);
        return sort(pluginNames);
      };
      var logDeprecationsWarning = function(rawSettings, finalSettings) {
        var deprecatedSettings2 = getDeprecatedSettings(rawSettings);
        var deprecatedPlugins2 = getDeprecatedPlugins(finalSettings);
        var hasDeprecatedPlugins = deprecatedPlugins2.length > 0;
        var hasDeprecatedSettings = deprecatedSettings2.length > 0;
        var isLegacyMobileTheme = finalSettings.theme === "mobile";
        if (hasDeprecatedPlugins || hasDeprecatedSettings || isLegacyMobileTheme) {
          var listJoiner = "\n- ";
          var themesMessage = isLegacyMobileTheme ? "\n\nThemes:" + listJoiner + "mobile" : "";
          var pluginsMessage = hasDeprecatedPlugins ? "\n\nPlugins:" + listJoiner + deprecatedPlugins2.join(listJoiner) : "";
          var settingsMessage = hasDeprecatedSettings ? "\n\nSettings:" + listJoiner + deprecatedSettings2.join(listJoiner) : "";
          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);
        }
      };
      var sectionResult = function(sections, settings) {
        return {
          sections: constant(sections),
          settings: constant(settings)
        };
      };
      var deviceDetection = detect().deviceType;
      var isTouch = deviceDetection.isTouch();
      var isPhone = deviceDetection.isPhone();
      var isTablet = deviceDetection.isTablet();
      var legacyMobilePlugins = [
        "lists",
        "autolink",
        "autosave"
      ];
      var defaultTouchSettings = {
        table_grid: false,
        object_resizing: false,
        resize: false
      };
      var normalizePlugins = function(plugins) {
        var pluginNames = isArray$1(plugins) ? plugins.join(" ") : plugins;
        var trimmedPlugins = map$3(isString$1(pluginNames) ? pluginNames.split(" ") : [], trim$4);
        return filter$4(trimmedPlugins, function(item) {
          return item.length > 0;
        });
      };
      var filterLegacyMobilePlugins = function(plugins) {
        return filter$4(plugins, curry(contains$3, legacyMobilePlugins));
      };
      var extractSections = function(keys2, settings) {
        var result = bifilter(settings, function(value2, key) {
          return contains$3(keys2, key);
        });
        return sectionResult(result.t, result.f);
      };
      var getSection = function(sectionResult2, name2, defaults) {
        if (defaults === void 0) {
          defaults = {};
        }
        var sections = sectionResult2.sections();
        var sectionSettings = get$9(sections, name2).getOr({});
        return Tools.extend({}, defaults, sectionSettings);
      };
      var hasSection = function(sectionResult2, name2) {
        return has$2(sectionResult2.sections(), name2);
      };
      var isSectionTheme = function(sectionResult2, name2, theme) {
        var section = sectionResult2.sections();
        return hasSection(sectionResult2, name2) && section[name2].theme === theme;
      };
      var getSectionConfig = function(sectionResult2, name2) {
        return hasSection(sectionResult2, name2) ? sectionResult2.sections()[name2] : {};
      };
      var getToolbarMode = function(settings, defaultVal) {
        return get$9(settings, "toolbar_mode").orThunk(function() {
          return get$9(settings, "toolbar_drawer").map(function(val) {
            return val === false ? "wrap" : val;
          });
        }).getOr(defaultVal);
      };
      var getDefaultSettings = function(settings, id, documentBaseUrl, isTouch2, editor) {
        var baseDefaults = {
          id,
          theme: "silver",
          toolbar_mode: getToolbarMode(settings, "floating"),
          plugins: "",
          document_base_url: documentBaseUrl,
          add_form_submit_trigger: true,
          submit_patch: true,
          add_unload_trigger: true,
          convert_urls: true,
          relative_urls: true,
          remove_script_host: true,
          object_resizing: true,
          doctype: "<!DOCTYPE html>",
          visual: true,
          font_size_legacy_values: "xx-small,small,medium,large,x-large,xx-large,300%",
          forced_root_block: "p",
          hidden_input: true,
          inline_styles: true,
          convert_fonts_to_spans: true,
          indent: true,
          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",
          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",
          entity_encoding: "named",
          url_converter: editor.convertURL,
          url_converter_scope: editor
        };
        return __assign(__assign({}, baseDefaults), isTouch2 ? defaultTouchSettings : {});
      };
      var getDefaultMobileSettings = function(mobileSettings, isPhone2) {
        var defaultMobileSettings = {
          resize: false,
          toolbar_mode: getToolbarMode(mobileSettings, "scrolling"),
          toolbar_sticky: false
        };
        var defaultPhoneSettings = { menubar: false };
        return __assign(__assign(__assign({}, defaultTouchSettings), defaultMobileSettings), isPhone2 ? defaultPhoneSettings : {});
      };
      var getExternalPlugins = function(overrideSettings, settings) {
        var userDefinedExternalPlugins = settings.external_plugins ? settings.external_plugins : {};
        if (overrideSettings && overrideSettings.external_plugins) {
          return Tools.extend({}, overrideSettings.external_plugins, userDefinedExternalPlugins);
        } else {
          return userDefinedExternalPlugins;
        }
      };
      var combinePlugins = function(forcedPlugins, plugins) {
        return [].concat(normalizePlugins(forcedPlugins)).concat(normalizePlugins(plugins));
      };
      var getPlatformPlugins = function(isMobileDevice, sectionResult2, desktopPlugins, mobilePlugins) {
        if (isMobileDevice && isSectionTheme(sectionResult2, "mobile", "mobile")) {
          return filterLegacyMobilePlugins(mobilePlugins);
        } else if (isMobileDevice && hasSection(sectionResult2, "mobile")) {
          return mobilePlugins;
        } else {
          return desktopPlugins;
        }
      };
      var processPlugins = function(isMobileDevice, sectionResult2, defaultOverrideSettings, settings) {
        var forcedPlugins = normalizePlugins(defaultOverrideSettings.forced_plugins);
        var desktopPlugins = normalizePlugins(settings.plugins);
        var mobileConfig = getSectionConfig(sectionResult2, "mobile");
        var mobilePlugins = mobileConfig.plugins ? normalizePlugins(mobileConfig.plugins) : desktopPlugins;
        var platformPlugins = getPlatformPlugins(isMobileDevice, sectionResult2, desktopPlugins, mobilePlugins);
        var combinedPlugins = combinePlugins(forcedPlugins, platformPlugins);
        if (Env.browser.isIE() && contains$3(combinedPlugins, "rtc")) {
          throw new Error("RTC plugin is not supported on IE 11.");
        }
        return Tools.extend(settings, { plugins: combinedPlugins.join(" ") });
      };
      var isOnMobile = function(isMobileDevice, sectionResult2) {
        return isMobileDevice && hasSection(sectionResult2, "mobile");
      };
      var combineSettings = function(isMobileDevice, isPhone2, defaultSettings, defaultOverrideSettings, settings) {
        var defaultDeviceSettings = isMobileDevice ? { mobile: getDefaultMobileSettings(settings.mobile || {}, isPhone2) } : {};
        var sectionResult2 = extractSections(["mobile"], deepMerge(defaultDeviceSettings, settings));
        var extendedSettings = Tools.extend(defaultSettings, defaultOverrideSettings, sectionResult2.settings(), isOnMobile(isMobileDevice, sectionResult2) ? getSection(sectionResult2, "mobile") : {}, {
          validate: true,
          external_plugins: getExternalPlugins(defaultOverrideSettings, sectionResult2.settings())
        });
        return processPlugins(isMobileDevice, sectionResult2, defaultOverrideSettings, extendedSettings);
      };
      var getEditorSettings = function(editor, id, documentBaseUrl, defaultOverrideSettings, settings) {
        var defaultSettings = getDefaultSettings(settings, id, documentBaseUrl, isTouch, editor);
        var finalSettings = combineSettings(isPhone || isTablet, isPhone, defaultSettings, defaultOverrideSettings, settings);
        if (finalSettings.deprecation_warnings !== false) {
          logDeprecationsWarning(settings, finalSettings);
        }
        return finalSettings;
      };
      var getFiltered = function(predicate, editor, name2) {
        return Optional.from(editor.settings[name2]).filter(predicate);
      };
      var getParamObject = function(value2) {
        var output = {};
        if (typeof value2 === "string") {
          each$k(value2.indexOf("=") > 0 ? value2.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value2.split(","), function(val) {
            var arr2 = val.split("=");
            if (arr2.length > 1) {
              output[Tools.trim(arr2[0])] = Tools.trim(arr2[1]);
            } else {
              output[Tools.trim(arr2[0])] = Tools.trim(arr2[0]);
            }
          });
        } else {
          output = value2;
        }
        return output;
      };
      var isArrayOf = function(p) {
        return function(a) {
          return isArray$1(a) && forall(a, p);
        };
      };
      var getParam = function(editor, name2, defaultVal, type2) {
        var value2 = name2 in editor.settings ? editor.settings[name2] : defaultVal;
        if (type2 === "hash") {
          return getParamObject(value2);
        } else if (type2 === "string") {
          return getFiltered(isString$1, editor, name2).getOr(defaultVal);
        } else if (type2 === "number") {
          return getFiltered(isNumber, editor, name2).getOr(defaultVal);
        } else if (type2 === "boolean") {
          return getFiltered(isBoolean, editor, name2).getOr(defaultVal);
        } else if (type2 === "object") {
          return getFiltered(isObject, editor, name2).getOr(defaultVal);
        } else if (type2 === "array") {
          return getFiltered(isArray$1, editor, name2).getOr(defaultVal);
        } else if (type2 === "string[]") {
          return getFiltered(isArrayOf(isString$1), editor, name2).getOr(defaultVal);
        } else if (type2 === "function") {
          return getFiltered(isFunction, editor, name2).getOr(defaultVal);
        } else {
          return value2;
        }
      };
      var CreateIconManager = function() {
        var lookup = {};
        var add2 = function(id, iconPack) {
          lookup[id] = iconPack;
        };
        var get2 = function(id) {
          if (lookup[id]) {
            return lookup[id];
          }
          return { icons: {} };
        };
        var has2 = function(id) {
          return has$2(lookup, id);
        };
        return {
          add: add2,
          get: get2,
          has: has2
        };
      };
      var IconManager = CreateIconManager();
      var getProp = function(propName, elm) {
        var rawElm = elm.dom;
        return rawElm[propName];
      };
      var getComputedSizeProp = function(propName, elm) {
        return parseInt(get$5(elm, propName), 10);
      };
      var getClientWidth = curry(getProp, "clientWidth");
      var getClientHeight = curry(getProp, "clientHeight");
      var getMarginTop = curry(getComputedSizeProp, "margin-top");
      var getMarginLeft = curry(getComputedSizeProp, "margin-left");
      var getBoundingClientRect = function(elm) {
        return elm.dom.getBoundingClientRect();
      };
      var isInsideElementContentArea = function(bodyElm, clientX, clientY) {
        var clientWidth = getClientWidth(bodyElm);
        var clientHeight = getClientHeight(bodyElm);
        return clientX >= 0 && clientY >= 0 && clientX <= clientWidth && clientY <= clientHeight;
      };
      var transpose = function(inline, elm, clientX, clientY) {
        var clientRect = getBoundingClientRect(elm);
        var deltaX = inline ? clientRect.left + elm.dom.clientLeft + getMarginLeft(elm) : 0;
        var deltaY = inline ? clientRect.top + elm.dom.clientTop + getMarginTop(elm) : 0;
        var x = clientX - deltaX;
        var y = clientY - deltaY;
        return {
          x,
          y
        };
      };
      var isXYInContentArea = function(editor, clientX, clientY) {
        var bodyElm = SugarElement.fromDom(editor.getBody());
        var targetElm = editor.inline ? bodyElm : documentElement(bodyElm);
        var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY);
        return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y);
      };
      var fromDomSafe = function(node) {
        return Optional.from(node).map(SugarElement.fromDom);
      };
      var isEditorAttachedToDom = function(editor) {
        var rawContainer = editor.inline ? editor.getBody() : editor.getContentAreaContainer();
        return fromDomSafe(rawContainer).map(inBody).getOr(false);
      };
      var NotificationManagerImpl = function() {
        var unimplemented = function() {
          throw new Error("Theme did not provide a NotificationManager implementation.");
        };
        return {
          open: unimplemented,
          close: unimplemented,
          reposition: unimplemented,
          getArgs: unimplemented
        };
      };
      var NotificationManager = function(editor) {
        var notifications = [];
        var getImplementation = function() {
          var theme = editor.theme;
          return theme && theme.getNotificationManagerImpl ? theme.getNotificationManagerImpl() : NotificationManagerImpl();
        };
        var getTopNotification = function() {
          return Optional.from(notifications[0]);
        };
        var isEqual2 = function(a, b) {
          return a.type === b.type && a.text === b.text && !a.progressBar && !a.timeout && !b.progressBar && !b.timeout;
        };
        var reposition2 = function() {
          if (notifications.length > 0) {
            getImplementation().reposition(notifications);
          }
        };
        var addNotification = function(notification) {
          notifications.push(notification);
        };
        var closeNotification = function(notification) {
          findIndex$2(notifications, function(otherNotification) {
            return otherNotification === notification;
          }).each(function(index) {
            notifications.splice(index, 1);
          });
        };
        var open = function(spec, fireEvent2) {
          if (fireEvent2 === void 0) {
            fireEvent2 = true;
          }
          if (editor.removed || !isEditorAttachedToDom(editor)) {
            return;
          }
          if (fireEvent2) {
            editor.fire("BeforeOpenNotification", { notification: spec });
          }
          return find$3(notifications, function(notification) {
            return isEqual2(getImplementation().getArgs(notification), spec);
          }).getOrThunk(function() {
            editor.editorManager.setActive(editor);
            var notification = getImplementation().open(spec, function() {
              closeNotification(notification);
              reposition2();
              getTopNotification().fold(function() {
                return editor.focus();
              }, function(top) {
                return focus$1(SugarElement.fromDom(top.getEl()));
              });
            });
            addNotification(notification);
            reposition2();
            editor.fire("OpenNotification", { notification: __assign({}, notification) });
            return notification;
          });
        };
        var close = function() {
          getTopNotification().each(function(notification) {
            getImplementation().close(notification);
            closeNotification(notification);
            reposition2();
          });
        };
        var getNotifications = constant(notifications);
        var registerEvents2 = function(editor2) {
          editor2.on("SkinLoaded", function() {
            var serviceMessage = getServiceMessage(editor2);
            if (serviceMessage) {
              open({
                text: serviceMessage,
                type: "warning",
                timeout: 0
              }, false);
            }
            reposition2();
          });
          editor2.on("show ResizeEditor ResizeWindow NodeChange", function() {
            Delay.requestAnimationFrame(reposition2);
          });
          editor2.on("remove", function() {
            each$k(notifications.slice(), function(notification) {
              getImplementation().close(notification);
            });
          });
        };
        registerEvents2(editor);
        return {
          open,
          close,
          getNotifications
        };
      };
      var PluginManager = AddOnManager.PluginManager;
      var ThemeManager = AddOnManager.ThemeManager;
      function WindowManagerImpl() {
        var unimplemented = function() {
          throw new Error("Theme did not provide a WindowManager implementation.");
        };
        return {
          open: unimplemented,
          openUrl: unimplemented,
          alert: unimplemented,
          confirm: unimplemented,
          close: unimplemented,
          getParams: unimplemented,
          setParams: unimplemented
        };
      }
      var WindowManager = function(editor) {
        var dialogs = [];
        var getImplementation = function() {
          var theme = editor.theme;
          return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
        };
        var funcBind = function(scope, f) {
          return function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            return f ? f.apply(scope, args) : void 0;
          };
        };
        var fireOpenEvent = function(dialog) {
          editor.fire("OpenWindow", { dialog });
        };
        var fireCloseEvent = function(dialog) {
          editor.fire("CloseWindow", { dialog });
        };
        var addDialog = function(dialog) {
          dialogs.push(dialog);
          fireOpenEvent(dialog);
        };
        var closeDialog = function(dialog) {
          fireCloseEvent(dialog);
          dialogs = filter$4(dialogs, function(otherDialog) {
            return otherDialog !== dialog;
          });
          if (dialogs.length === 0) {
            editor.focus();
          }
        };
        var getTopDialog = function() {
          return Optional.from(dialogs[dialogs.length - 1]);
        };
        var storeSelectionAndOpenDialog = function(openDialog) {
          editor.editorManager.setActive(editor);
          store(editor);
          var dialog = openDialog();
          addDialog(dialog);
          return dialog;
        };
        var open = function(args, params) {
          return storeSelectionAndOpenDialog(function() {
            return getImplementation().open(args, params, closeDialog);
          });
        };
        var openUrl = function(args) {
          return storeSelectionAndOpenDialog(function() {
            return getImplementation().openUrl(args, closeDialog);
          });
        };
        var alert = function(message, callback, scope) {
          var windowManagerImpl = getImplementation();
          windowManagerImpl.alert(message, funcBind(scope ? scope : windowManagerImpl, callback));
        };
        var confirm = function(message, callback, scope) {
          var windowManagerImpl = getImplementation();
          windowManagerImpl.confirm(message, funcBind(scope ? scope : windowManagerImpl, callback));
        };
        var close = function() {
          getTopDialog().each(function(dialog) {
            getImplementation().close(dialog);
            closeDialog(dialog);
          });
        };
        editor.on("remove", function() {
          each$k(dialogs, function(dialog) {
            getImplementation().close(dialog);
          });
        });
        return {
          open,
          openUrl,
          alert,
          confirm,
          close
        };
      };
      var displayNotification = function(editor, message) {
        editor.notificationManager.open({
          type: "error",
          text: message
        });
      };
      var displayError = function(editor, message) {
        if (editor._skinLoaded) {
          displayNotification(editor, message);
        } else {
          editor.on("SkinLoaded", function() {
            displayNotification(editor, message);
          });
        }
      };
      var uploadError = function(editor, message) {
        displayError(editor, I18n.translate([
          "Failed to upload image: {0}",
          message
        ]));
      };
      var logError = function(editor, errorType, msg) {
        fireError(editor, errorType, { message: msg });
        console.error(msg);
      };
      var createLoadError = function(type2, url, name2) {
        return name2 ? "Failed to load " + type2 + ": " + name2 + " from url " + url : "Failed to load " + type2 + " url: " + url;
      };
      var pluginLoadError = function(editor, url, name2) {
        logError(editor, "PluginLoadError", createLoadError("plugin", url, name2));
      };
      var iconsLoadError = function(editor, url, name2) {
        logError(editor, "IconsLoadError", createLoadError("icons", url, name2));
      };
      var languageLoadError = function(editor, url, name2) {
        logError(editor, "LanguageLoadError", createLoadError("language", url, name2));
      };
      var pluginInitError = function(editor, name2, err) {
        var message = I18n.translate([
          "Failed to initialize plugin: {0}",
          name2
        ]);
        fireError(editor, "PluginLoadError", { message });
        initError(message, err);
        displayError(editor, message);
      };
      var initError = function(message) {
        var x = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          x[_i - 1] = arguments[_i];
        }
        var console2 = window.console;
        if (console2) {
          if (console2.error) {
            console2.error.apply(console2, __spreadArray([message], x, false));
          } else {
            console2.log.apply(console2, __spreadArray([message], x, false));
          }
        }
      };
      var isContentCssSkinName = function(url) {
        return /^[a-z0-9\-]+$/i.test(url);
      };
      var getContentCssUrls = function(editor) {
        return transformToUrls(editor, getContentCss(editor));
      };
      var getFontCssUrls = function(editor) {
        return transformToUrls(editor, getFontCss(editor));
      };
      var transformToUrls = function(editor, cssLinks) {
        var skinUrl = editor.editorManager.baseURL + "/skins/content";
        var suffix = editor.editorManager.suffix;
        var contentCssFile = "content" + suffix + ".css";
        var inline = editor.inline === true;
        return map$3(cssLinks, function(url) {
          if (isContentCssSkinName(url) && !inline) {
            return skinUrl + "/" + url + "/" + contentCssFile;
          } else {
            return editor.documentBaseURI.toAbsolute(url);
          }
        });
      };
      var appendContentCssFromSettings = function(editor) {
        editor.contentCSS = editor.contentCSS.concat(getContentCssUrls(editor), getFontCssUrls(editor));
      };
      var UploadStatus = function() {
        var PENDING = 1, UPLOADED = 2;
        var blobUriStatuses = {};
        var createStatus = function(status, resultUri) {
          return {
            status,
            resultUri
          };
        };
        var hasBlobUri = function(blobUri) {
          return blobUri in blobUriStatuses;
        };
        var getResultUri = function(blobUri) {
          var result = blobUriStatuses[blobUri];
          return result ? result.resultUri : null;
        };
        var isPending = function(blobUri) {
          return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
        };
        var isUploaded = function(blobUri) {
          return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
        };
        var markPending = function(blobUri) {
          blobUriStatuses[blobUri] = createStatus(PENDING, null);
        };
        var markUploaded = function(blobUri, resultUri) {
          blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
        };
        var removeFailed = function(blobUri) {
          delete blobUriStatuses[blobUri];
        };
        var destroy2 = function() {
          blobUriStatuses = {};
        };
        return {
          hasBlobUri,
          getResultUri,
          isPending,
          isUploaded,
          markPending,
          markUploaded,
          removeFailed,
          destroy: destroy2
        };
      };
      var count = 0;
      var seed = function() {
        var rnd = function() {
          return Math.round(Math.random() * 4294967295).toString(36);
        };
        var now = new Date().getTime();
        return "s" + now.toString(36) + rnd() + rnd() + rnd();
      };
      var uuid = function(prefix) {
        return prefix + count++ + seed();
      };
      var BlobCache = function() {
        var cache = [];
        var mimeToExt = function(mime) {
          var mimes = {
            "image/jpeg": "jpg",
            "image/jpg": "jpg",
            "image/gif": "gif",
            "image/png": "png",
            "image/apng": "apng",
            "image/avif": "avif",
            "image/svg+xml": "svg",
            "image/webp": "webp",
            "image/bmp": "bmp",
            "image/tiff": "tiff"
          };
          return mimes[mime.toLowerCase()] || "dat";
        };
        var create2 = function(o, blob, base64, name2, filename) {
          if (isString$1(o)) {
            var id = o;
            return toBlobInfo({
              id,
              name: name2,
              filename,
              blob,
              base64
            });
          } else if (isObject(o)) {
            return toBlobInfo(o);
          } else {
            throw new Error("Unknown input type");
          }
        };
        var toBlobInfo = function(o) {
          if (!o.blob || !o.base64) {
            throw new Error("blob and base64 representations of the image are required for BlobInfo to be created");
          }
          var id = o.id || uuid("blobid");
          var name2 = o.name || id;
          var blob = o.blob;
          return {
            id: constant(id),
            name: constant(name2),
            filename: constant(o.filename || name2 + "." + mimeToExt(blob.type)),
            blob: constant(blob),
            base64: constant(o.base64),
            blobUri: constant(o.blobUri || URL.createObjectURL(blob)),
            uri: constant(o.uri)
          };
        };
        var add2 = function(blobInfo) {
          if (!get2(blobInfo.id())) {
            cache.push(blobInfo);
          }
        };
        var findFirst = function(predicate) {
          return find$3(cache, predicate).getOrUndefined();
        };
        var get2 = function(id) {
          return findFirst(function(cachedBlobInfo) {
            return cachedBlobInfo.id() === id;
          });
        };
        var getByUri = function(blobUri) {
          return findFirst(function(blobInfo) {
            return blobInfo.blobUri() === blobUri;
          });
        };
        var getByData = function(base64, type2) {
          return findFirst(function(blobInfo) {
            return blobInfo.base64() === base64 && blobInfo.blob().type === type2;
          });
        };
        var removeByUri = function(blobUri) {
          cache = filter$4(cache, function(blobInfo) {
            if (blobInfo.blobUri() === blobUri) {
              URL.revokeObjectURL(blobInfo.blobUri());
              return false;
            }
            return true;
          });
        };
        var destroy2 = function() {
          each$k(cache, function(cachedBlobInfo) {
            URL.revokeObjectURL(cachedBlobInfo.blobUri());
          });
          cache = [];
        };
        return {
          create: create2,
          add: add2,
          get: get2,
          getByUri,
          getByData,
          findFirst,
          removeByUri,
          destroy: destroy2
        };
      };
      var Uploader = function(uploadStatus, settings) {
        var pendingPromises = {};
        var pathJoin = function(path1, path2) {
          if (path1) {
            return path1.replace(/\/$/, "") + "/" + path2.replace(/^\//, "");
          }
          return path2;
        };
        var defaultHandler = function(blobInfo, success, failure, progress) {
          var xhr = new XMLHttpRequest();
          xhr.open("POST", settings.url);
          xhr.withCredentials = settings.credentials;
          xhr.upload.onprogress = function(e) {
            progress(e.loaded / e.total * 100);
          };
          xhr.onerror = function() {
            failure("Image upload failed due to a XHR Transport error. Code: " + xhr.status);
          };
          xhr.onload = function() {
            if (xhr.status < 200 || xhr.status >= 300) {
              failure("HTTP Error: " + xhr.status);
              return;
            }
            var json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location !== "string") {
              failure("Invalid JSON: " + xhr.responseText);
              return;
            }
            success(pathJoin(settings.basePath, json.location));
          };
          var formData = new FormData();
          formData.append("file", blobInfo.blob(), blobInfo.filename());
          xhr.send(formData);
        };
        var noUpload = function() {
          return new promiseObj(function(resolve2) {
            resolve2([]);
          });
        };
        var handlerSuccess = function(blobInfo, url) {
          return {
            url,
            blobInfo,
            status: true
          };
        };
        var handlerFailure = function(blobInfo, message, options) {
          return {
            url: "",
            blobInfo,
            status: false,
            error: {
              message,
              options
            }
          };
        };
        var resolvePending = function(blobUri, result) {
          Tools.each(pendingPromises[blobUri], function(resolve2) {
            resolve2(result);
          });
          delete pendingPromises[blobUri];
        };
        var uploadBlobInfo = function(blobInfo, handler, openNotification2) {
          uploadStatus.markPending(blobInfo.blobUri());
          return new promiseObj(function(resolve2) {
            var notification, progress;
            try {
              var closeNotification_1 = function() {
                if (notification) {
                  notification.close();
                  progress = noop;
                }
              };
              var success = function(url) {
                closeNotification_1();
                uploadStatus.markUploaded(blobInfo.blobUri(), url);
                resolvePending(blobInfo.blobUri(), handlerSuccess(blobInfo, url));
                resolve2(handlerSuccess(blobInfo, url));
              };
              var failure = function(error2, options) {
                var failureOptions = options ? options : {};
                closeNotification_1();
                uploadStatus.removeFailed(blobInfo.blobUri());
                resolvePending(blobInfo.blobUri(), handlerFailure(blobInfo, error2, failureOptions));
                resolve2(handlerFailure(blobInfo, error2, failureOptions));
              };
              progress = function(percent) {
                if (percent < 0 || percent > 100) {
                  return;
                }
                Optional.from(notification).orThunk(function() {
                  return Optional.from(openNotification2).map(apply);
                }).each(function(n) {
                  notification = n;
                  n.progressBar.value(percent);
                });
              };
              handler(blobInfo, success, failure, progress);
            } catch (ex) {
              resolve2(handlerFailure(blobInfo, ex.message, {}));
            }
          });
        };
        var isDefaultHandler = function(handler) {
          return handler === defaultHandler;
        };
        var pendingUploadBlobInfo = function(blobInfo) {
          var blobUri = blobInfo.blobUri();
          return new promiseObj(function(resolve2) {
            pendingPromises[blobUri] = pendingPromises[blobUri] || [];
            pendingPromises[blobUri].push(resolve2);
          });
        };
        var uploadBlobs = function(blobInfos, openNotification2) {
          blobInfos = Tools.grep(blobInfos, function(blobInfo) {
            return !uploadStatus.isUploaded(blobInfo.blobUri());
          });
          return promiseObj.all(Tools.map(blobInfos, function(blobInfo) {
            return uploadStatus.isPending(blobInfo.blobUri()) ? pendingUploadBlobInfo(blobInfo) : uploadBlobInfo(blobInfo, settings.handler, openNotification2);
          }));
        };
        var upload = function(blobInfos, openNotification2) {
          return !settings.url && isDefaultHandler(settings.handler) ? noUpload() : uploadBlobs(blobInfos, openNotification2);
        };
        if (isFunction(settings.handler) === false) {
          settings.handler = defaultHandler;
        }
        return { upload };
      };
      var openNotification = function(editor) {
        return function() {
          return editor.notificationManager.open({
            text: editor.translate("Image uploading..."),
            type: "info",
            timeout: -1,
            progressBar: true
          });
        };
      };
      var createUploader = function(editor, uploadStatus) {
        return Uploader(uploadStatus, {
          url: getImageUploadUrl(editor),
          basePath: getImageUploadBasePath(editor),
          credentials: getImagesUploadCredentials(editor),
          handler: getImagesUploadHandler(editor)
        });
      };
      var ImageUploader = function(editor) {
        var uploadStatus = UploadStatus();
        var uploader = createUploader(editor, uploadStatus);
        return {
          upload: function(blobInfos, showNotification) {
            if (showNotification === void 0) {
              showNotification = true;
            }
            return uploader.upload(blobInfos, showNotification ? openNotification(editor) : void 0);
          }
        };
      };
      var UploadChangeHandler = function(editor) {
        var lastChangedLevel = Cell(null);
        editor.on("change AddUndo", function(e) {
          lastChangedLevel.set(__assign({}, e.level));
        });
        var fireIfChanged = function() {
          var data2 = editor.undoManager.data;
          last$2(data2).filter(function(level) {
            return !isEq$1(lastChangedLevel.get(), level);
          }).each(function(level) {
            editor.setDirty(true);
            editor.fire("change", {
              level,
              lastLevel: get$a(data2, data2.length - 2).getOrNull()
            });
          });
        };
        return { fireIfChanged };
      };
      var EditorUpload = function(editor) {
        var blobCache = BlobCache();
        var uploader, imageScanner;
        var uploadStatus = UploadStatus();
        var urlFilters = [];
        var changeHandler = UploadChangeHandler(editor);
        var aliveGuard = function(callback) {
          return function(result) {
            if (editor.selection) {
              return callback(result);
            }
            return [];
          };
        };
        var cacheInvalidator = function(url) {
          return url + (url.indexOf("?") === -1 ? "?" : "&") + new Date().getTime();
        };
        var replaceString = function(content, search2, replace) {
          var index = 0;
          do {
            index = content.indexOf(search2, index);
            if (index !== -1) {
              content = content.substring(0, index) + replace + content.substr(index + search2.length);
              index += replace.length - search2.length + 1;
            }
          } while (index !== -1);
          return content;
        };
        var replaceImageUrl = function(content, targetUrl, replacementUrl) {
          var replacementString = 'src="' + replacementUrl + '"' + (replacementUrl === Env.transparentSrc ? ' data-mce-placeholder="1"' : "");
          content = replaceString(content, 'src="' + targetUrl + '"', replacementString);
          content = replaceString(content, 'data-mce-src="' + targetUrl + '"', 'data-mce-src="' + replacementUrl + '"');
          return content;
        };
        var replaceUrlInUndoStack = function(targetUrl, replacementUrl) {
          each$k(editor.undoManager.data, function(level) {
            if (level.type === "fragmented") {
              level.fragments = map$3(level.fragments, function(fragment) {
                return replaceImageUrl(fragment, targetUrl, replacementUrl);
              });
            } else {
              level.content = replaceImageUrl(level.content, targetUrl, replacementUrl);
            }
          });
        };
        var replaceImageUriInView = function(image, resultUri) {
          var src = editor.convertURL(resultUri, "src");
          replaceUrlInUndoStack(image.src, resultUri);
          editor.$(image).attr({
            "src": shouldReuseFileName(editor) ? cacheInvalidator(resultUri) : resultUri,
            "data-mce-src": src
          });
        };
        var uploadImages = function(callback) {
          if (!uploader) {
            uploader = createUploader(editor, uploadStatus);
          }
          return scanForImages().then(aliveGuard(function(imageInfos) {
            var blobInfos = map$3(imageInfos, function(imageInfo) {
              return imageInfo.blobInfo;
            });
            return uploader.upload(blobInfos, openNotification(editor)).then(aliveGuard(function(result) {
              var imagesToRemove = [];
              var filteredResult = map$3(result, function(uploadInfo, index) {
                var blobInfo = imageInfos[index].blobInfo;
                var image = imageInfos[index].image;
                if (uploadInfo.status && shouldReplaceBlobUris(editor)) {
                  blobCache.removeByUri(image.src);
                  if (isRtc(editor))
                    ;
                  else {
                    replaceImageUriInView(image, uploadInfo.url);
                  }
                } else if (uploadInfo.error) {
                  if (uploadInfo.error.options.remove) {
                    replaceUrlInUndoStack(image.getAttribute("src"), Env.transparentSrc);
                    imagesToRemove.push(image);
                  }
                  uploadError(editor, uploadInfo.error.message);
                }
                return {
                  element: image,
                  status: uploadInfo.status,
                  uploadUri: uploadInfo.url,
                  blobInfo
                };
              });
              if (filteredResult.length > 0) {
                changeHandler.fireIfChanged();
              }
              if (imagesToRemove.length > 0) {
                if (isRtc(editor)) {
                  console.error("Removing images on failed uploads is currently unsupported for RTC");
                } else {
                  editor.undoManager.transact(function() {
                    each$k(imagesToRemove, function(element) {
                      editor.dom.remove(element);
                      blobCache.removeByUri(element.src);
                    });
                  });
                }
              }
              if (callback) {
                callback(filteredResult);
              }
              return filteredResult;
            }));
          }));
        };
        var uploadImagesAuto = function(callback) {
          if (isAutomaticUploadsEnabled(editor)) {
            return uploadImages(callback);
          }
        };
        var isValidDataUriImage = function(imgElm) {
          if (forall(urlFilters, function(filter2) {
            return filter2(imgElm);
          }) === false) {
            return false;
          }
          if (imgElm.getAttribute("src").indexOf("data:") === 0) {
            var dataImgFilter = getImagesDataImgFilter(editor);
            return dataImgFilter(imgElm);
          }
          return true;
        };
        var addFilter = function(filter2) {
          urlFilters.push(filter2);
        };
        var scanForImages = function() {
          if (!imageScanner) {
            imageScanner = ImageScanner(uploadStatus, blobCache);
          }
          return imageScanner.findAll(editor.getBody(), isValidDataUriImage).then(aliveGuard(function(result) {
            result = filter$4(result, function(resultItem) {
              if (typeof resultItem === "string") {
                displayError(editor, resultItem);
                return false;
              }
              return true;
            });
            if (isRtc(editor))
              ;
            else {
              each$k(result, function(resultItem) {
                replaceUrlInUndoStack(resultItem.image.src, resultItem.blobInfo.blobUri());
                resultItem.image.src = resultItem.blobInfo.blobUri();
                resultItem.image.removeAttribute("data-mce-src");
              });
            }
            return result;
          }));
        };
        var destroy2 = function() {
          blobCache.destroy();
          uploadStatus.destroy();
          imageScanner = uploader = null;
        };
        var replaceBlobUris = function(content) {
          return content.replace(/src="(blob:[^"]+)"/g, function(match2, blobUri) {
            var resultUri = uploadStatus.getResultUri(blobUri);
            if (resultUri) {
              return 'src="' + resultUri + '"';
            }
            var blobInfo = blobCache.getByUri(blobUri);
            if (!blobInfo) {
              blobInfo = foldl(editor.editorManager.get(), function(result, editor2) {
                return result || editor2.editorUpload && editor2.editorUpload.blobCache.getByUri(blobUri);
              }, null);
            }
            if (blobInfo) {
              var blob = blobInfo.blob();
              return 'src="data:' + blob.type + ";base64," + blobInfo.base64() + '"';
            }
            return match2;
          });
        };
        editor.on("SetContent", function() {
          if (isAutomaticUploadsEnabled(editor)) {
            uploadImagesAuto();
          } else {
            scanForImages();
          }
        });
        editor.on("RawSaveContent", function(e) {
          e.content = replaceBlobUris(e.content);
        });
        editor.on("GetContent", function(e) {
          if (e.source_view || e.format === "raw" || e.format === "tree") {
            return;
          }
          e.content = replaceBlobUris(e.content);
        });
        editor.on("PostRender", function() {
          editor.parser.addNodeFilter("img", function(images) {
            each$k(images, function(img) {
              var src = img.attr("src");
              if (blobCache.getByUri(src)) {
                return;
              }
              var resultUri = uploadStatus.getResultUri(src);
              if (resultUri) {
                img.attr("src", resultUri);
              }
            });
          });
        });
        return {
          blobCache,
          addFilter,
          uploadImages,
          uploadImagesAuto,
          scanForImages,
          destroy: destroy2
        };
      };
      var get = function(dom2) {
        var formats = {
          valigntop: [{
            selector: "td,th",
            styles: { verticalAlign: "top" }
          }],
          valignmiddle: [{
            selector: "td,th",
            styles: { verticalAlign: "middle" }
          }],
          valignbottom: [{
            selector: "td,th",
            styles: { verticalAlign: "bottom" }
          }],
          alignleft: [
            {
              selector: "figure.image",
              collapsed: false,
              classes: "align-left",
              ceFalseOverride: true,
              preview: "font-family font-size"
            },
            {
              selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
              styles: { textAlign: "left" },
              inherit: false,
              preview: false,
              defaultBlock: "div"
            },
            {
              selector: "img,table,audio,video",
              collapsed: false,
              styles: { float: "left" },
              preview: "font-family font-size"
            }
          ],
          aligncenter: [
            {
              selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
              styles: { textAlign: "center" },
              inherit: false,
              preview: "font-family font-size",
              defaultBlock: "div"
            },
            {
              selector: "figure.image",
              collapsed: false,
              classes: "align-center",
              ceFalseOverride: true,
              preview: "font-family font-size"
            },
            {
              selector: "img,audio,video",
              collapsed: false,
              styles: {
                display: "block",
                marginLeft: "auto",
                marginRight: "auto"
              },
              preview: false
            },
            {
              selector: "table",
              collapsed: false,
              styles: {
                marginLeft: "auto",
                marginRight: "auto"
              },
              preview: "font-family font-size"
            }
          ],
          alignright: [
            {
              selector: "figure.image",
              collapsed: false,
              classes: "align-right",
              ceFalseOverride: true,
              preview: "font-family font-size"
            },
            {
              selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
              styles: { textAlign: "right" },
              inherit: false,
              preview: "font-family font-size",
              defaultBlock: "div"
            },
            {
              selector: "img,table,audio,video",
              collapsed: false,
              styles: { float: "right" },
              preview: "font-family font-size"
            }
          ],
          alignjustify: [{
            selector: "figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li",
            styles: { textAlign: "justify" },
            inherit: false,
            defaultBlock: "div",
            preview: "font-family font-size"
          }],
          bold: [
            {
              inline: "strong",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            },
            {
              inline: "span",
              styles: { fontWeight: "bold" }
            },
            {
              inline: "b",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            }
          ],
          italic: [
            {
              inline: "em",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            },
            {
              inline: "span",
              styles: { fontStyle: "italic" }
            },
            {
              inline: "i",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            }
          ],
          underline: [
            {
              inline: "span",
              styles: { textDecoration: "underline" },
              exact: true
            },
            {
              inline: "u",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            }
          ],
          strikethrough: [
            {
              inline: "span",
              styles: { textDecoration: "line-through" },
              exact: true
            },
            {
              inline: "strike",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            },
            {
              inline: "s",
              remove: "all",
              preserve_attributes: [
                "class",
                "style"
              ]
            }
          ],
          forecolor: {
            inline: "span",
            styles: { color: "%value" },
            links: true,
            remove_similar: true,
            clear_child_styles: true
          },
          hilitecolor: {
            inline: "span",
            styles: { backgroundColor: "%value" },
            links: true,
            remove_similar: true,
            clear_child_styles: true
          },
          fontname: {
            inline: "span",
            toggle: false,
            styles: { fontFamily: "%value" },
            clear_child_styles: true
          },
          fontsize: {
            inline: "span",
            toggle: false,
            styles: { fontSize: "%value" },
            clear_child_styles: true
          },
          lineheight: {
            selector: "h1,h2,h3,h4,h5,h6,p,li,td,th,div",
            defaultBlock: "p",
            styles: { lineHeight: "%value" }
          },
          fontsize_class: {
            inline: "span",
            attributes: { class: "%value" }
          },
          blockquote: {
            block: "blockquote",
            wrapper: true,
            remove: "all"
          },
          subscript: { inline: "sub" },
          superscript: { inline: "sup" },
          code: { inline: "code" },
          link: {
            inline: "a",
            selector: "a",
            remove: "all",
            split: true,
            deep: true,
            onmatch: function(node, _fmt, _itemName) {
              return isElement$5(node) && node.hasAttribute("href");
            },
            onformat: function(elm, _fmt, vars) {
              Tools.each(vars, function(value2, key) {
                dom2.setAttrib(elm, key, value2);
              });
            }
          },
          lang: {
            inline: "span",
            clear_child_styles: true,
            remove_similar: true,
            attributes: {
              "lang": "%value",
              "data-mce-lang": function(vars) {
                var _a;
                return (_a = vars === null || vars === void 0 ? void 0 : vars.customValue) !== null && _a !== void 0 ? _a : null;
              }
            }
          },
          removeformat: [
            {
              selector: "b,strong,em,i,font,u,strike,s,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,small",
              remove: "all",
              split: true,
              expand: false,
              block_expand: true,
              deep: true
            },
            {
              selector: "span",
              attributes: [
                "style",
                "class"
              ],
              remove: "empty",
              split: true,
              expand: false,
              deep: true
            },
            {
              selector: "*",
              attributes: [
                "style",
                "class"
              ],
              split: false,
              expand: false,
              deep: true
            }
          ]
        };
        Tools.each("p h1 h2 h3 h4 h5 h6 div address pre dt dd samp".split(/\s/), function(name2) {
          formats[name2] = {
            block: name2,
            remove: "all"
          };
        });
        return formats;
      };
      var FormatRegistry = function(editor) {
        var formats = {};
        var get$12 = function(name2) {
          return isNonNullable(name2) ? formats[name2] : formats;
        };
        var has2 = function(name2) {
          return has$2(formats, name2);
        };
        var register2 = function(name2, format) {
          if (name2) {
            if (!isString$1(name2)) {
              each$j(name2, function(format2, name3) {
                register2(name3, format2);
              });
            } else {
              if (!isArray$1(format)) {
                format = [format];
              }
              each$k(format, function(format2) {
                if (isUndefined(format2.deep)) {
                  format2.deep = !isSelectorFormat(format2);
                }
                if (isUndefined(format2.split)) {
                  format2.split = !isSelectorFormat(format2) || isInlineFormat(format2);
                }
                if (isUndefined(format2.remove) && isSelectorFormat(format2) && !isInlineFormat(format2)) {
                  format2.remove = "none";
                }
                if (isSelectorFormat(format2) && isInlineFormat(format2)) {
                  format2.mixed = true;
                  format2.block_expand = true;
                }
                if (isString$1(format2.classes)) {
                  format2.classes = format2.classes.split(/\s+/);
                }
              });
              formats[name2] = format;
            }
          }
        };
        var unregister = function(name2) {
          if (name2 && formats[name2]) {
            delete formats[name2];
          }
          return formats;
        };
        register2(get(editor.dom));
        register2(getFormats(editor));
        return {
          get: get$12,
          has: has2,
          register: register2,
          unregister
        };
      };
      var each$5 = Tools.each;
      var dom = DOMUtils.DOM;
      var parsedSelectorToHtml = function(ancestry, editor) {
        var elm, item, fragment;
        var schema = editor && editor.schema || Schema({});
        var decorate = function(elm2, item2) {
          if (item2.classes.length) {
            dom.addClass(elm2, item2.classes.join(" "));
          }
          dom.setAttribs(elm2, item2.attrs);
        };
        var createElement = function(sItem) {
          item = typeof sItem === "string" ? {
            name: sItem,
            classes: [],
            attrs: {}
          } : sItem;
          var elm2 = dom.create(item.name);
          decorate(elm2, item);
          return elm2;
        };
        var getRequiredParent = function(elm2, candidate) {
          var name2 = typeof elm2 !== "string" ? elm2.nodeName.toLowerCase() : elm2;
          var elmRule = schema.getElementRule(name2);
          var parentsRequired = elmRule && elmRule.parentsRequired;
          if (parentsRequired && parentsRequired.length) {
            return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0];
          } else {
            return false;
          }
        };
        var wrapInHtml = function(elm2, ancestry2, siblings2) {
          var parent2, parentCandidate;
          var ancestor2 = ancestry2.length > 0 && ancestry2[0];
          var ancestorName = ancestor2 && ancestor2.name;
          var parentRequired = getRequiredParent(elm2, ancestorName);
          if (parentRequired) {
            if (ancestorName === parentRequired) {
              parentCandidate = ancestry2[0];
              ancestry2 = ancestry2.slice(1);
            } else {
              parentCandidate = parentRequired;
            }
          } else if (ancestor2) {
            parentCandidate = ancestry2[0];
            ancestry2 = ancestry2.slice(1);
          } else if (!siblings2) {
            return elm2;
          }
          if (parentCandidate) {
            parent2 = createElement(parentCandidate);
            parent2.appendChild(elm2);
          }
          if (siblings2) {
            if (!parent2) {
              parent2 = dom.create("div");
              parent2.appendChild(elm2);
            }
            Tools.each(siblings2, function(sibling2) {
              var siblingElm = createElement(sibling2);
              parent2.insertBefore(siblingElm, elm2);
            });
          }
          return wrapInHtml(parent2, ancestry2, parentCandidate && parentCandidate.siblings);
        };
        if (ancestry && ancestry.length) {
          item = ancestry[0];
          elm = createElement(item);
          fragment = dom.create("div");
          fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings));
          return fragment;
        } else {
          return "";
        }
      };
      var parseSelectorItem = function(item) {
        var tagName;
        var obj = {
          classes: [],
          attrs: {}
        };
        item = obj.selector = Tools.trim(item);
        if (item !== "*") {
          tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function($0, $1, $2, $3, $4) {
            switch ($1) {
              case "#":
                obj.attrs.id = $2;
                break;
              case ".":
                obj.classes.push($2);
                break;
              case ":":
                if (Tools.inArray("checked disabled enabled read-only required".split(" "), $2) !== -1) {
                  obj.attrs[$2] = $2;
                }
                break;
            }
            if ($3 === "[") {
              var m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/);
              if (m) {
                obj.attrs[m[1]] = m[2];
              }
            }
            return "";
          });
        }
        obj.name = tagName || "div";
        return obj;
      };
      var parseSelector = function(selector) {
        if (!selector || typeof selector !== "string") {
          return [];
        }
        selector = selector.split(/\s*,\s*/)[0];
        selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, "$1");
        return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function(item) {
          var siblings2 = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem);
          var obj = siblings2.pop();
          if (siblings2.length) {
            obj.siblings = siblings2;
          }
          return obj;
        }).reverse();
      };
      var getCssText = function(editor, format) {
        var name2, previewFrag;
        var previewCss = "", parentFontSize;
        var previewStyles = getPreviewStyles(editor);
        if (previewStyles === "") {
          return "";
        }
        var removeVars = function(val) {
          return val.replace(/%(\w+)/g, "");
        };
        if (typeof format === "string") {
          format = editor.formatter.get(format);
          if (!format) {
            return;
          }
          format = format[0];
        }
        if ("preview" in format) {
          var previewOpt = get$9(format, "preview");
          if (is$1(previewOpt, false)) {
            return "";
          } else {
            previewStyles = previewOpt.getOr(previewStyles);
          }
        }
        name2 = format.block || format.inline || "span";
        var items = parseSelector(format.selector);
        if (items.length) {
          if (!items[0].name) {
            items[0].name = name2;
          }
          name2 = format.selector;
          previewFrag = parsedSelectorToHtml(items, editor);
        } else {
          previewFrag = parsedSelectorToHtml([name2], editor);
        }
        var previewElm = dom.select(name2, previewFrag)[0] || previewFrag.firstChild;
        each$5(format.styles, function(value2, name3) {
          var newValue = removeVars(value2);
          if (newValue) {
            dom.setStyle(previewElm, name3, newValue);
          }
        });
        each$5(format.attributes, function(value2, name3) {
          var newValue = removeVars(value2);
          if (newValue) {
            dom.setAttrib(previewElm, name3, newValue);
          }
        });
        each$5(format.classes, function(value2) {
          var newValue = removeVars(value2);
          if (!dom.hasClass(previewElm, newValue)) {
            dom.addClass(previewElm, newValue);
          }
        });
        editor.fire("PreviewFormats");
        dom.setStyles(previewFrag, {
          position: "absolute",
          left: -65535
        });
        editor.getBody().appendChild(previewFrag);
        parentFontSize = dom.getStyle(editor.getBody(), "fontSize", true);
        parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
        each$5(previewStyles.split(" "), function(name3) {
          var value2 = dom.getStyle(previewElm, name3, true);
          if (name3 === "background-color" && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value2)) {
            value2 = dom.getStyle(editor.getBody(), name3, true);
            if (dom.toHex(value2).toLowerCase() === "#ffffff") {
              return;
            }
          }
          if (name3 === "color") {
            if (dom.toHex(value2).toLowerCase() === "#000000") {
              return;
            }
          }
          if (name3 === "font-size") {
            if (/em|%$/.test(value2)) {
              if (parentFontSize === 0) {
                return;
              }
              var numValue = parseFloat(value2) / (/%$/.test(value2) ? 100 : 1);
              value2 = numValue * parentFontSize + "px";
            }
          }
          if (name3 === "border" && value2) {
            previewCss += "padding:0 2px;";
          }
          previewCss += name3 + ":" + value2 + ";";
        });
        editor.fire("AfterPreviewFormats");
        dom.remove(previewFrag);
        return previewCss;
      };
      var setup$h = function(editor) {
        editor.addShortcut("meta+b", "", "Bold");
        editor.addShortcut("meta+i", "", "Italic");
        editor.addShortcut("meta+u", "", "Underline");
        for (var i = 1; i <= 6; i++) {
          editor.addShortcut("access+" + i, "", [
            "FormatBlock",
            false,
            "h" + i
          ]);
        }
        editor.addShortcut("access+7", "", [
          "FormatBlock",
          false,
          "p"
        ]);
        editor.addShortcut("access+8", "", [
          "FormatBlock",
          false,
          "div"
        ]);
        editor.addShortcut("access+9", "", [
          "FormatBlock",
          false,
          "address"
        ]);
      };
      var Formatter = function(editor) {
        var formats = FormatRegistry(editor);
        var formatChangeState = Cell(null);
        setup$h(editor);
        setup$k(editor);
        return {
          get: formats.get,
          has: formats.has,
          register: formats.register,
          unregister: formats.unregister,
          apply: function(name2, vars, node) {
            applyFormat(editor, name2, vars, node);
          },
          remove: function(name2, vars, node, similar) {
            removeFormat(editor, name2, vars, node, similar);
          },
          toggle: function(name2, vars, node) {
            toggleFormat(editor, name2, vars, node);
          },
          match: function(name2, vars, node, similar) {
            return matchFormat(editor, name2, vars, node, similar);
          },
          closest: function(names) {
            return closestFormat(editor, names);
          },
          matchAll: function(names, vars) {
            return matchAllFormats(editor, names, vars);
          },
          matchNode: function(node, name2, vars, similar) {
            return matchNodeFormat(editor, node, name2, vars, similar);
          },
          canApply: function(name2) {
            return canApplyFormat(editor, name2);
          },
          formatChanged: function(formats2, callback, similar, vars) {
            return formatChanged(editor, formatChangeState, formats2, callback, similar, vars);
          },
          getCssText: curry(getCssText, editor)
        };
      };
      var shouldIgnoreCommand = function(cmd) {
        switch (cmd.toLowerCase()) {
          case "undo":
          case "redo":
          case "mcerepaint":
          case "mcefocus":
            return true;
          default:
            return false;
        }
      };
      var registerEvents = function(editor, undoManager, locks) {
        var isFirstTypedCharacter = Cell(false);
        var addNonTypingUndoLevel = function(e) {
          setTyping(undoManager, false, locks);
          undoManager.add({}, e);
        };
        editor.on("init", function() {
          undoManager.add();
        });
        editor.on("BeforeExecCommand", function(e) {
          var cmd = e.command;
          if (!shouldIgnoreCommand(cmd)) {
            endTyping(undoManager, locks);
            undoManager.beforeChange();
          }
        });
        editor.on("ExecCommand", function(e) {
          var cmd = e.command;
          if (!shouldIgnoreCommand(cmd)) {
            addNonTypingUndoLevel(e);
          }
        });
        editor.on("ObjectResizeStart cut", function() {
          undoManager.beforeChange();
        });
        editor.on("SaveContent ObjectResized blur", addNonTypingUndoLevel);
        editor.on("dragend", addNonTypingUndoLevel);
        editor.on("keyup", function(e) {
          var keyCode = e.keyCode;
          if (e.isDefaultPrevented()) {
            return;
          }
          if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45 || e.ctrlKey) {
            addNonTypingUndoLevel();
            editor.nodeChanged();
          }
          if (keyCode === 46 || keyCode === 8) {
            editor.nodeChanged();
          }
          if (isFirstTypedCharacter.get() && undoManager.typing && isEq$1(createFromEditor(editor), undoManager.data[0]) === false) {
            if (editor.isDirty() === false) {
              editor.setDirty(true);
              editor.fire("change", {
                level: undoManager.data[0],
                lastLevel: null
              });
            }
            editor.fire("TypingUndo");
            isFirstTypedCharacter.set(false);
            editor.nodeChanged();
          }
        });
        editor.on("keydown", function(e) {
          var keyCode = e.keyCode;
          if (e.isDefaultPrevented()) {
            return;
          }
          if (keyCode >= 33 && keyCode <= 36 || keyCode >= 37 && keyCode <= 40 || keyCode === 45) {
            if (undoManager.typing) {
              addNonTypingUndoLevel(e);
            }
            return;
          }
          var modKey = e.ctrlKey && !e.altKey || e.metaKey;
          if ((keyCode < 16 || keyCode > 20) && keyCode !== 224 && keyCode !== 91 && !undoManager.typing && !modKey) {
            undoManager.beforeChange();
            setTyping(undoManager, true, locks);
            undoManager.add({}, e);
            isFirstTypedCharacter.set(true);
          }
        });
        editor.on("mousedown", function(e) {
          if (undoManager.typing) {
            addNonTypingUndoLevel(e);
          }
        });
        var isInsertReplacementText = function(event) {
          return event.inputType === "insertReplacementText";
        };
        var isInsertTextDataNull = function(event) {
          return event.inputType === "insertText" && event.data === null;
        };
        var isInsertFromPasteOrDrop = function(event) {
          return event.inputType === "insertFromPaste" || event.inputType === "insertFromDrop";
        };
        editor.on("input", function(e) {
          if (e.inputType && (isInsertReplacementText(e) || isInsertTextDataNull(e) || isInsertFromPasteOrDrop(e))) {
            addNonTypingUndoLevel(e);
          }
        });
        editor.on("AddUndo Undo Redo ClearUndos", function(e) {
          if (!e.isDefaultPrevented()) {
            editor.nodeChanged();
          }
        });
      };
      var addKeyboardShortcuts = function(editor) {
        editor.addShortcut("meta+z", "", "Undo");
        editor.addShortcut("meta+y,meta+shift+z", "", "Redo");
      };
      var UndoManager = function(editor) {
        var beforeBookmark = value();
        var locks = Cell(0);
        var index = Cell(0);
        var undoManager = {
          data: [],
          typing: false,
          beforeChange: function() {
            beforeChange(editor, locks, beforeBookmark);
          },
          add: function(level, event) {
            return addUndoLevel(editor, undoManager, index, locks, beforeBookmark, level, event);
          },
          undo: function() {
            return undo(editor, undoManager, locks, index);
          },
          redo: function() {
            return redo(editor, index, undoManager.data);
          },
          clear: function() {
            clear(editor, undoManager, index);
          },
          reset: function() {
            reset(editor, undoManager);
          },
          hasUndo: function() {
            return hasUndo(editor, undoManager, index);
          },
          hasRedo: function() {
            return hasRedo(editor, undoManager, index);
          },
          transact: function(callback) {
            return transact(editor, undoManager, locks, callback);
          },
          ignore: function(callback) {
            ignore(editor, locks, callback);
          },
          extra: function(callback1, callback2) {
            extra(editor, undoManager, index, callback1, callback2);
          }
        };
        if (!isRtc(editor)) {
          registerEvents(editor, undoManager, locks);
        }
        addKeyboardShortcuts(editor);
        return undoManager;
      };
      var nonTypingKeycodes = [
        9,
        27,
        VK.HOME,
        VK.END,
        19,
        20,
        44,
        144,
        145,
        33,
        34,
        45,
        16,
        17,
        18,
        91,
        92,
        93,
        VK.DOWN,
        VK.UP,
        VK.LEFT,
        VK.RIGHT
      ].concat(Env.browser.isFirefox() ? [224] : []);
      var placeholderAttr = "data-mce-placeholder";
      var isKeyboardEvent = function(e) {
        return e.type === "keydown" || e.type === "keyup";
      };
      var isDeleteEvent = function(e) {
        var keyCode = e.keyCode;
        return keyCode === VK.BACKSPACE || keyCode === VK.DELETE;
      };
      var isNonTypingKeyboardEvent = function(e) {
        if (isKeyboardEvent(e)) {
          var keyCode = e.keyCode;
          return !isDeleteEvent(e) && (VK.metaKeyPressed(e) || e.altKey || keyCode >= 112 && keyCode <= 123 || contains$3(nonTypingKeycodes, keyCode));
        } else {
          return false;
        }
      };
      var isTypingKeyboardEvent = function(e) {
        return isKeyboardEvent(e) && !(isDeleteEvent(e) || e.type === "keyup" && e.keyCode === 229);
      };
      var isVisuallyEmpty = function(dom2, rootElm, forcedRootBlock) {
        if (isEmpty$2(SugarElement.fromDom(rootElm), false)) {
          var isForcedRootBlockFalse = forcedRootBlock === "";
          var firstElement2 = rootElm.firstElementChild;
          if (!firstElement2) {
            return true;
          } else if (dom2.getStyle(rootElm.firstElementChild, "padding-left") || dom2.getStyle(rootElm.firstElementChild, "padding-right")) {
            return false;
          } else {
            return isForcedRootBlockFalse ? !dom2.isBlock(firstElement2) : forcedRootBlock === firstElement2.nodeName.toLowerCase();
          }
        } else {
          return false;
        }
      };
      var setup$g = function(editor) {
        var dom2 = editor.dom;
        var rootBlock = getForcedRootBlock(editor);
        var placeholder = getPlaceholder(editor);
        var updatePlaceholder = function(e, initial) {
          if (isNonTypingKeyboardEvent(e)) {
            return;
          }
          var body = editor.getBody();
          var showPlaceholder = isTypingKeyboardEvent(e) ? false : isVisuallyEmpty(dom2, body, rootBlock);
          var isPlaceholderShown = dom2.getAttrib(body, placeholderAttr) !== "";
          if (isPlaceholderShown !== showPlaceholder || initial) {
            dom2.setAttrib(body, placeholderAttr, showPlaceholder ? placeholder : null);
            dom2.setAttrib(body, "aria-placeholder", showPlaceholder ? placeholder : null);
            firePlaceholderToggle(editor, showPlaceholder);
            editor.on(showPlaceholder ? "keydown" : "keyup", updatePlaceholder);
            editor.off(showPlaceholder ? "keyup" : "keydown", updatePlaceholder);
          }
        };
        if (placeholder) {
          editor.on("init", function(e) {
            updatePlaceholder(e, true);
            editor.on("change SetContent ExecCommand", updatePlaceholder);
            editor.on("paste", function(e2) {
              return Delay.setEditorTimeout(editor, function() {
                return updatePlaceholder(e2);
              });
            });
          });
        }
      };
      var strongRtl = /[\u0591-\u07FF\uFB1D-\uFDFF\uFE70-\uFEFC]/;
      var hasStrongRtl = function(text) {
        return strongRtl.test(text);
      };
      var isInlineTarget = function(editor, elm) {
        return is$2(SugarElement.fromDom(elm), getInlineBoundarySelector(editor));
      };
      var isRtl = function(element) {
        return DOMUtils.DOM.getStyle(element, "direction", true) === "rtl" || hasStrongRtl(element.textContent);
      };
      var findInlineParents = function(isInlineTarget2, rootNode, pos) {
        return filter$4(DOMUtils.DOM.getParents(pos.container(), "*", rootNode), isInlineTarget2);
      };
      var findRootInline = function(isInlineTarget2, rootNode, pos) {
        var parents2 = findInlineParents(isInlineTarget2, rootNode, pos);
        return Optional.from(parents2[parents2.length - 1]);
      };
      var hasSameParentBlock = function(rootNode, node1, node2) {
        var block1 = getParentBlock$2(node1, rootNode);
        var block2 = getParentBlock$2(node2, rootNode);
        return block1 && block1 === block2;
      };
      var isAtZwsp = function(pos) {
        return isBeforeInline(pos) || isAfterInline(pos);
      };
      var normalizePosition = function(forward, pos) {
        if (!pos) {
          return pos;
        }
        var container = pos.container(), offset = pos.offset();
        if (forward) {
          if (isCaretContainerInline(container)) {
            if (isText$7(container.nextSibling)) {
              return CaretPosition(container.nextSibling, 0);
            } else {
              return CaretPosition.after(container);
            }
          } else {
            return isBeforeInline(pos) ? CaretPosition(container, offset + 1) : pos;
          }
        } else {
          if (isCaretContainerInline(container)) {
            if (isText$7(container.previousSibling)) {
              return CaretPosition(container.previousSibling, container.previousSibling.data.length);
            } else {
              return CaretPosition.before(container);
            }
          } else {
            return isAfterInline(pos) ? CaretPosition(container, offset - 1) : pos;
          }
        }
      };
      var normalizeForwards = curry(normalizePosition, true);
      var normalizeBackwards = curry(normalizePosition, false);
      var isBeforeRoot = function(rootNode) {
        return function(elm) {
          return eq(rootNode, SugarElement.fromDom(elm.dom.parentNode));
        };
      };
      var isTextBlockOrListItem = function(element) {
        return isTextBlock$2(element) || isListItem(element);
      };
      var getParentBlock$1 = function(rootNode, elm) {
        if (contains$1(rootNode, elm)) {
          return closest$3(elm, isTextBlockOrListItem, isBeforeRoot(rootNode));
        } else {
          return Optional.none();
        }
      };
      var placeCaretInEmptyBody = function(editor) {
        var body = editor.getBody();
        var node = body.firstChild && editor.dom.isBlock(body.firstChild) ? body.firstChild : body;
        editor.selection.setCursorLocation(node, 0);
      };
      var paddEmptyBody = function(editor) {
        if (editor.dom.isEmpty(editor.getBody())) {
          editor.setContent("");
          placeCaretInEmptyBody(editor);
        }
      };
      var willDeleteLastPositionInElement = function(forward, fromPos, elm) {
        return lift2(firstPositionIn(elm), lastPositionIn(elm), function(firstPos, lastPos) {
          var normalizedFirstPos = normalizePosition(true, firstPos);
          var normalizedLastPos = normalizePosition(false, lastPos);
          var normalizedFromPos = normalizePosition(false, fromPos);
          if (forward) {
            return nextPosition(elm, normalizedFromPos).exists(function(nextPos) {
              return nextPos.isEqual(normalizedLastPos) && fromPos.isEqual(normalizedFirstPos);
            });
          } else {
            return prevPosition(elm, normalizedFromPos).exists(function(prevPos) {
              return prevPos.isEqual(normalizedFirstPos) && fromPos.isEqual(normalizedLastPos);
            });
          }
        }).getOr(true);
      };
      var blockPosition = function(block, position) {
        return {
          block,
          position
        };
      };
      var blockBoundary = function(from2, to2) {
        return {
          from: from2,
          to: to2
        };
      };
      var getBlockPosition = function(rootNode, pos) {
        var rootElm = SugarElement.fromDom(rootNode);
        var containerElm = SugarElement.fromDom(pos.container());
        return getParentBlock$1(rootElm, containerElm).map(function(block) {
          return blockPosition(block, pos);
        });
      };
      var isDifferentBlocks = function(blockBoundary2) {
        return eq(blockBoundary2.from.block, blockBoundary2.to.block) === false;
      };
      var hasSameParent = function(blockBoundary2) {
        return parent(blockBoundary2.from.block).bind(function(parent1) {
          return parent(blockBoundary2.to.block).filter(function(parent2) {
            return eq(parent1, parent2);
          });
        }).isSome();
      };
      var isEditable$1 = function(blockBoundary2) {
        return isContentEditableFalse$b(blockBoundary2.from.block.dom) === false && isContentEditableFalse$b(blockBoundary2.to.block.dom) === false;
      };
      var skipLastBr = function(rootNode, forward, blockPosition2) {
        if (isBr$5(blockPosition2.position.getNode()) && isEmpty$2(blockPosition2.block) === false) {
          return positionIn(false, blockPosition2.block.dom).bind(function(lastPositionInBlock) {
            if (lastPositionInBlock.isEqual(blockPosition2.position)) {
              return fromPosition(forward, rootNode, lastPositionInBlock).bind(function(to2) {
                return getBlockPosition(rootNode, to2);
              });
            } else {
              return Optional.some(blockPosition2);
            }
          }).getOr(blockPosition2);
        } else {
          return blockPosition2;
        }
      };
      var readFromRange = function(rootNode, forward, rng) {
        var fromBlockPos = getBlockPosition(rootNode, CaretPosition.fromRangeStart(rng));
        var toBlockPos = fromBlockPos.bind(function(blockPos) {
          return fromPosition(forward, rootNode, blockPos.position).bind(function(to2) {
            return getBlockPosition(rootNode, to2).map(function(blockPos2) {
              return skipLastBr(rootNode, forward, blockPos2);
            });
          });
        });
        return lift2(fromBlockPos, toBlockPos, blockBoundary).filter(function(blockBoundary2) {
          return isDifferentBlocks(blockBoundary2) && hasSameParent(blockBoundary2) && isEditable$1(blockBoundary2);
        });
      };
      var read$1 = function(rootNode, forward, rng) {
        return rng.collapsed ? readFromRange(rootNode, forward, rng) : Optional.none();
      };
      var getChildrenUntilBlockBoundary = function(block) {
        var children$1 = children(block);
        return findIndex$2(children$1, isBlock$2).fold(constant(children$1), function(index) {
          return children$1.slice(0, index);
        });
      };
      var extractChildren = function(block) {
        var children2 = getChildrenUntilBlockBoundary(block);
        each$k(children2, remove$7);
        return children2;
      };
      var removeEmptyRoot = function(rootNode, block) {
        var parents2 = parentsAndSelf(block, rootNode);
        return find$3(parents2.reverse(), function(element) {
          return isEmpty$2(element);
        }).each(remove$7);
      };
      var isEmptyBefore = function(el) {
        return filter$4(prevSiblings(el), function(el2) {
          return !isEmpty$2(el2);
        }).length === 0;
      };
      var nestedBlockMerge = function(rootNode, fromBlock, toBlock, insertionPoint) {
        if (isEmpty$2(toBlock)) {
          fillWithPaddingBr(toBlock);
          return firstPositionIn(toBlock.dom);
        }
        if (isEmptyBefore(insertionPoint) && isEmpty$2(fromBlock)) {
          before$4(insertionPoint, SugarElement.fromTag("br"));
        }
        var position = prevPosition(toBlock.dom, CaretPosition.before(insertionPoint.dom));
        each$k(extractChildren(fromBlock), function(child2) {
          before$4(insertionPoint, child2);
        });
        removeEmptyRoot(rootNode, fromBlock);
        return position;
      };
      var sidelongBlockMerge = function(rootNode, fromBlock, toBlock) {
        if (isEmpty$2(toBlock)) {
          remove$7(toBlock);
          if (isEmpty$2(fromBlock)) {
            fillWithPaddingBr(fromBlock);
          }
          return firstPositionIn(fromBlock.dom);
        }
        var position = lastPositionIn(toBlock.dom);
        each$k(extractChildren(fromBlock), function(child2) {
          append$1(toBlock, child2);
        });
        removeEmptyRoot(rootNode, fromBlock);
        return position;
      };
      var findInsertionPoint = function(toBlock, block) {
        var parentsAndSelf$1 = parentsAndSelf(block, toBlock);
        return Optional.from(parentsAndSelf$1[parentsAndSelf$1.length - 1]);
      };
      var getInsertionPoint = function(fromBlock, toBlock) {
        return contains$1(toBlock, fromBlock) ? findInsertionPoint(toBlock, fromBlock) : Optional.none();
      };
      var trimBr = function(first2, block) {
        positionIn(first2, block.dom).map(function(position) {
          return position.getNode();
        }).map(SugarElement.fromDom).filter(isBr$4).each(remove$7);
      };
      var mergeBlockInto = function(rootNode, fromBlock, toBlock) {
        trimBr(true, fromBlock);
        trimBr(false, toBlock);
        return getInsertionPoint(fromBlock, toBlock).fold(curry(sidelongBlockMerge, rootNode, fromBlock, toBlock), curry(nestedBlockMerge, rootNode, fromBlock, toBlock));
      };
      var mergeBlocks = function(rootNode, forward, block1, block2) {
        return forward ? mergeBlockInto(rootNode, block2, block1) : mergeBlockInto(rootNode, block1, block2);
      };
      var backspaceDelete$8 = function(editor, forward) {
        var rootNode = SugarElement.fromDom(editor.getBody());
        var position = read$1(rootNode.dom, forward, editor.selection.getRng()).bind(function(blockBoundary2) {
          return mergeBlocks(rootNode, forward, blockBoundary2.from.block, blockBoundary2.to.block);
        });
        position.each(function(pos) {
          editor.selection.setRng(pos.toRange());
        });
        return position.isSome();
      };
      var deleteRangeMergeBlocks = function(rootNode, selection) {
        var rng = selection.getRng();
        return lift2(getParentBlock$1(rootNode, SugarElement.fromDom(rng.startContainer)), getParentBlock$1(rootNode, SugarElement.fromDom(rng.endContainer)), function(block1, block2) {
          if (eq(block1, block2) === false) {
            rng.deleteContents();
            mergeBlocks(rootNode, true, block1, block2).each(function(pos) {
              selection.setRng(pos.toRange());
            });
            return true;
          } else {
            return false;
          }
        }).getOr(false);
      };
      var isRawNodeInTable = function(root, rawNode) {
        var node = SugarElement.fromDom(rawNode);
        var isRoot = curry(eq, root);
        return ancestor$3(node, isTableCell$4, isRoot).isSome();
      };
      var isSelectionInTable = function(root, rng) {
        return isRawNodeInTable(root, rng.startContainer) || isRawNodeInTable(root, rng.endContainer);
      };
      var isEverythingSelected = function(root, rng) {
        var noPrevious = prevPosition(root.dom, CaretPosition.fromRangeStart(rng)).isNone();
        var noNext = nextPosition(root.dom, CaretPosition.fromRangeEnd(rng)).isNone();
        return !isSelectionInTable(root, rng) && noPrevious && noNext;
      };
      var emptyEditor = function(editor) {
        editor.setContent("");
        editor.selection.setCursorLocation();
        return true;
      };
      var deleteRange$1 = function(editor) {
        var rootNode = SugarElement.fromDom(editor.getBody());
        var rng = editor.selection.getRng();
        return isEverythingSelected(rootNode, rng) ? emptyEditor(editor) : deleteRangeMergeBlocks(rootNode, editor.selection);
      };
      var backspaceDelete$7 = function(editor, _forward) {
        return editor.selection.isCollapsed() ? false : deleteRange$1(editor);
      };
      var isContentEditableTrue$2 = isContentEditableTrue$4;
      var isContentEditableFalse$4 = isContentEditableFalse$b;
      var showCaret = function(direction, editor, node, before2, scrollIntoView) {
        return Optional.from(editor._selectionOverrides.showCaret(direction, node, before2, scrollIntoView));
      };
      var getNodeRange = function(node) {
        var rng = node.ownerDocument.createRange();
        rng.selectNode(node);
        return rng;
      };
      var selectNode = function(editor, node) {
        var e = editor.fire("BeforeObjectSelected", { target: node });
        if (e.isDefaultPrevented()) {
          return Optional.none();
        }
        return Optional.some(getNodeRange(node));
      };
      var renderCaretAtRange = function(editor, range2, scrollIntoView) {
        var normalizedRange = normalizeRange(1, editor.getBody(), range2);
        var caretPosition = CaretPosition.fromRangeStart(normalizedRange);
        var caretPositionNode = caretPosition.getNode();
        if (isInlineFakeCaretTarget(caretPositionNode)) {
          return showCaret(1, editor, caretPositionNode, !caretPosition.isAtEnd(), false);
        }
        var caretPositionBeforeNode = caretPosition.getNode(true);
        if (isInlineFakeCaretTarget(caretPositionBeforeNode)) {
          return showCaret(1, editor, caretPositionBeforeNode, false, false);
        }
        var ceRoot = editor.dom.getParent(caretPosition.getNode(), function(node) {
          return isContentEditableFalse$4(node) || isContentEditableTrue$2(node);
        });
        if (isInlineFakeCaretTarget(ceRoot)) {
          return showCaret(1, editor, ceRoot, false, scrollIntoView);
        }
        return Optional.none();
      };
      var renderRangeCaret = function(editor, range2, scrollIntoView) {
        return range2.collapsed ? renderCaretAtRange(editor, range2, scrollIntoView).getOr(range2) : range2;
      };
      var isBeforeBoundary = function(pos) {
        return isBeforeContentEditableFalse(pos) || isBeforeMedia(pos);
      };
      var isAfterBoundary = function(pos) {
        return isAfterContentEditableFalse(pos) || isAfterMedia(pos);
      };
      var trimEmptyTextNode = function(dom2, node) {
        if (isText$7(node) && node.data.length === 0) {
          dom2.remove(node);
        }
      };
      var deleteContentAndShowCaret = function(editor, range2, node, direction, forward, peekCaretPosition) {
        showCaret(direction, editor, peekCaretPosition.getNode(!forward), forward, true).each(function(caretRange) {
          if (range2.collapsed) {
            var deleteRange2 = range2.cloneRange();
            if (forward) {
              deleteRange2.setEnd(caretRange.startContainer, caretRange.startOffset);
            } else {
              deleteRange2.setStart(caretRange.endContainer, caretRange.endOffset);
            }
            deleteRange2.deleteContents();
          } else {
            range2.deleteContents();
          }
          editor.selection.setRng(caretRange);
        });
        trimEmptyTextNode(editor.dom, node);
        return true;
      };
      var deleteBoundaryText = function(editor, forward) {
        var range2 = editor.selection.getRng();
        if (!isText$7(range2.commonAncestorContainer)) {
          return false;
        }
        var direction = forward ? HDirection.Forwards : HDirection.Backwards;
        var caretWalker = CaretWalker(editor.getBody());
        var getNextPosFn = curry(getVisualCaretPosition, forward ? caretWalker.next : caretWalker.prev);
        var isBeforeFn = forward ? isBeforeBoundary : isAfterBoundary;
        var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
        var nextCaretPosition = normalizePosition(forward, getNextPosFn(caretPosition));
        if (!nextCaretPosition || !isMoveInsideSameBlock(caretPosition, nextCaretPosition)) {
          return false;
        } else if (isBeforeFn(nextCaretPosition)) {
          return deleteContentAndShowCaret(editor, range2, caretPosition.getNode(), direction, forward, nextCaretPosition);
        }
        var peekCaretPosition = getNextPosFn(nextCaretPosition);
        if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
          if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
            return deleteContentAndShowCaret(editor, range2, caretPosition.getNode(), direction, forward, peekCaretPosition);
          }
        }
        return false;
      };
      var backspaceDelete$6 = function(editor, forward) {
        return deleteBoundaryText(editor, forward);
      };
      var isCompoundElement = function(node) {
        return isTableCell$4(SugarElement.fromDom(node)) || isListItem(SugarElement.fromDom(node));
      };
      var DeleteAction = Adt.generate([
        { remove: ["element"] },
        { moveToElement: ["element"] },
        { moveToPosition: ["position"] }
      ]);
      var isAtContentEditableBlockCaret = function(forward, from2) {
        var elm = from2.getNode(forward === false);
        var caretLocation = forward ? "after" : "before";
        return isElement$5(elm) && elm.getAttribute("data-mce-caret") === caretLocation;
      };
      var isDeleteFromCefDifferentBlocks = function(root, forward, from2, to2) {
        var inSameBlock = function(elm) {
          return isInline$1(SugarElement.fromDom(elm)) && !isInSameBlock(from2, to2, root);
        };
        return getRelativeCefElm(!forward, from2).fold(function() {
          return getRelativeCefElm(forward, to2).fold(never, inSameBlock);
        }, inSameBlock);
      };
      var deleteEmptyBlockOrMoveToCef = function(root, forward, from2, to2) {
        var toCefElm = to2.getNode(forward === false);
        return getParentBlock$1(SugarElement.fromDom(root), SugarElement.fromDom(from2.getNode())).map(function(blockElm) {
          return isEmpty$2(blockElm) ? DeleteAction.remove(blockElm.dom) : DeleteAction.moveToElement(toCefElm);
        }).orThunk(function() {
          return Optional.some(DeleteAction.moveToElement(toCefElm));
        });
      };
      var findCefPosition = function(root, forward, from2) {
        return fromPosition(forward, root, from2).bind(function(to2) {
          if (isCompoundElement(to2.getNode())) {
            return Optional.none();
          } else if (isDeleteFromCefDifferentBlocks(root, forward, from2, to2)) {
            return Optional.none();
          } else if (forward && isContentEditableFalse$b(to2.getNode())) {
            return deleteEmptyBlockOrMoveToCef(root, forward, from2, to2);
          } else if (forward === false && isContentEditableFalse$b(to2.getNode(true))) {
            return deleteEmptyBlockOrMoveToCef(root, forward, from2, to2);
          } else if (forward && isAfterContentEditableFalse(from2)) {
            return Optional.some(DeleteAction.moveToPosition(to2));
          } else if (forward === false && isBeforeContentEditableFalse(from2)) {
            return Optional.some(DeleteAction.moveToPosition(to2));
          } else {
            return Optional.none();
          }
        });
      };
      var getContentEditableBlockAction = function(forward, elm) {
        if (forward && isContentEditableFalse$b(elm.nextSibling)) {
          return Optional.some(DeleteAction.moveToElement(elm.nextSibling));
        } else if (forward === false && isContentEditableFalse$b(elm.previousSibling)) {
          return Optional.some(DeleteAction.moveToElement(elm.previousSibling));
        } else {
          return Optional.none();
        }
      };
      var skipMoveToActionFromInlineCefToContent = function(root, from2, deleteAction2) {
        return deleteAction2.fold(function(elm) {
          return Optional.some(DeleteAction.remove(elm));
        }, function(elm) {
          return Optional.some(DeleteAction.moveToElement(elm));
        }, function(to2) {
          if (isInSameBlock(from2, to2, root)) {
            return Optional.none();
          } else {
            return Optional.some(DeleteAction.moveToPosition(to2));
          }
        });
      };
      var getContentEditableAction = function(root, forward, from2) {
        if (isAtContentEditableBlockCaret(forward, from2)) {
          return getContentEditableBlockAction(forward, from2.getNode(forward === false)).fold(function() {
            return findCefPosition(root, forward, from2);
          }, Optional.some);
        } else {
          return findCefPosition(root, forward, from2).bind(function(deleteAction2) {
            return skipMoveToActionFromInlineCefToContent(root, from2, deleteAction2);
          });
        }
      };
      var read = function(root, forward, rng) {
        var normalizedRange = normalizeRange(forward ? 1 : -1, root, rng);
        var from2 = CaretPosition.fromRangeStart(normalizedRange);
        var rootElement = SugarElement.fromDom(root);
        if (forward === false && isAfterContentEditableFalse(from2)) {
          return Optional.some(DeleteAction.remove(from2.getNode(true)));
        } else if (forward && isBeforeContentEditableFalse(from2)) {
          return Optional.some(DeleteAction.remove(from2.getNode()));
        } else if (forward === false && isBeforeContentEditableFalse(from2) && isAfterBr(rootElement, from2)) {
          return findPreviousBr(rootElement, from2).map(function(br) {
            return DeleteAction.remove(br.getNode());
          });
        } else if (forward && isAfterContentEditableFalse(from2) && isBeforeBr$1(rootElement, from2)) {
          return findNextBr(rootElement, from2).map(function(br) {
            return DeleteAction.remove(br.getNode());
          });
        } else {
          return getContentEditableAction(root, forward, from2);
        }
      };
      var deleteElement$1 = function(editor, forward) {
        return function(element) {
          editor._selectionOverrides.hideFakeCaret();
          deleteElement$2(editor, forward, SugarElement.fromDom(element));
          return true;
        };
      };
      var moveToElement = function(editor, forward) {
        return function(element) {
          var pos = forward ? CaretPosition.before(element) : CaretPosition.after(element);
          editor.selection.setRng(pos.toRange());
          return true;
        };
      };
      var moveToPosition = function(editor) {
        return function(pos) {
          editor.selection.setRng(pos.toRange());
          return true;
        };
      };
      var getAncestorCe = function(editor, node) {
        return Optional.from(getContentEditableRoot$1(editor.getBody(), node));
      };
      var backspaceDeleteCaret = function(editor, forward) {
        var selectedNode = editor.selection.getNode();
        return getAncestorCe(editor, selectedNode).filter(isContentEditableFalse$b).fold(function() {
          return read(editor.getBody(), forward, editor.selection.getRng()).exists(function(deleteAction2) {
            return deleteAction2.fold(deleteElement$1(editor, forward), moveToElement(editor, forward), moveToPosition(editor));
          });
        }, always);
      };
      var deleteOffscreenSelection = function(rootElement) {
        each$k(descendants(rootElement, ".mce-offscreen-selection"), remove$7);
      };
      var backspaceDeleteRange = function(editor, forward) {
        var selectedNode = editor.selection.getNode();
        if (isContentEditableFalse$b(selectedNode) && !isTableCell$5(selectedNode)) {
          var hasCefAncestor = getAncestorCe(editor, selectedNode.parentNode).filter(isContentEditableFalse$b);
          return hasCefAncestor.fold(function() {
            deleteOffscreenSelection(SugarElement.fromDom(editor.getBody()));
            deleteElement$2(editor, forward, SugarElement.fromDom(editor.selection.getNode()));
            paddEmptyBody(editor);
            return true;
          }, always);
        }
        return false;
      };
      var paddEmptyElement = function(editor) {
        var dom2 = editor.dom, selection = editor.selection;
        var ceRoot = getContentEditableRoot$1(editor.getBody(), selection.getNode());
        if (isContentEditableTrue$4(ceRoot) && dom2.isBlock(ceRoot) && dom2.isEmpty(ceRoot)) {
          var br = dom2.create("br", { "data-mce-bogus": "1" });
          dom2.setHTML(ceRoot, "");
          ceRoot.appendChild(br);
          selection.setRng(CaretPosition.before(br).toRange());
        }
        return true;
      };
      var backspaceDelete$5 = function(editor, forward) {
        if (editor.selection.isCollapsed()) {
          return backspaceDeleteCaret(editor, forward);
        } else {
          return backspaceDeleteRange(editor, forward);
        }
      };
      var deleteCaret$2 = function(editor, forward) {
        var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
        return fromPosition(forward, editor.getBody(), fromPos).filter(function(pos) {
          return forward ? isBeforeImageBlock(pos) : isAfterImageBlock(pos);
        }).bind(function(pos) {
          return Optional.from(getChildNodeAtRelativeOffset(forward ? 0 : -1, pos));
        }).exists(function(elm) {
          editor.selection.select(elm);
          return true;
        });
      };
      var backspaceDelete$4 = function(editor, forward) {
        return editor.selection.isCollapsed() ? deleteCaret$2(editor, forward) : false;
      };
      var isText = isText$7;
      var startsWithCaretContainer = function(node) {
        return isText(node) && node.data[0] === ZWSP$1;
      };
      var endsWithCaretContainer = function(node) {
        return isText(node) && node.data[node.data.length - 1] === ZWSP$1;
      };
      var createZwsp = function(node) {
        return node.ownerDocument.createTextNode(ZWSP$1);
      };
      var insertBefore = function(node) {
        if (isText(node.previousSibling)) {
          if (endsWithCaretContainer(node.previousSibling)) {
            return node.previousSibling;
          } else {
            node.previousSibling.appendData(ZWSP$1);
            return node.previousSibling;
          }
        } else if (isText(node)) {
          if (startsWithCaretContainer(node)) {
            return node;
          } else {
            node.insertData(0, ZWSP$1);
            return node;
          }
        } else {
          var newNode = createZwsp(node);
          node.parentNode.insertBefore(newNode, node);
          return newNode;
        }
      };
      var insertAfter = function(node) {
        if (isText(node.nextSibling)) {
          if (startsWithCaretContainer(node.nextSibling)) {
            return node.nextSibling;
          } else {
            node.nextSibling.insertData(0, ZWSP$1);
            return node.nextSibling;
          }
        } else if (isText(node)) {
          if (endsWithCaretContainer(node)) {
            return node;
          } else {
            node.appendData(ZWSP$1);
            return node;
          }
        } else {
          var newNode = createZwsp(node);
          if (node.nextSibling) {
            node.parentNode.insertBefore(newNode, node.nextSibling);
          } else {
            node.parentNode.appendChild(newNode);
          }
          return newNode;
        }
      };
      var insertInline = function(before2, node) {
        return before2 ? insertBefore(node) : insertAfter(node);
      };
      var insertInlineBefore = curry(insertInline, true);
      var insertInlineAfter = curry(insertInline, false);
      var insertInlinePos = function(pos, before2) {
        if (isText$7(pos.container())) {
          return insertInline(before2, pos.container());
        } else {
          return insertInline(before2, pos.getNode());
        }
      };
      var isPosCaretContainer = function(pos, caret) {
        var caretNode = caret.get();
        return caretNode && pos.container() === caretNode && isCaretContainerInline(caretNode);
      };
      var renderCaret = function(caret, location) {
        return location.fold(function(element) {
          remove$2(caret.get());
          var text = insertInlineBefore(element);
          caret.set(text);
          return Optional.some(CaretPosition(text, text.length - 1));
        }, function(element) {
          return firstPositionIn(element).map(function(pos) {
            if (!isPosCaretContainer(pos, caret)) {
              remove$2(caret.get());
              var text = insertInlinePos(pos, true);
              caret.set(text);
              return CaretPosition(text, 1);
            } else {
              return CaretPosition(caret.get(), 1);
            }
          });
        }, function(element) {
          return lastPositionIn(element).map(function(pos) {
            if (!isPosCaretContainer(pos, caret)) {
              remove$2(caret.get());
              var text = insertInlinePos(pos, false);
              caret.set(text);
              return CaretPosition(text, text.length - 1);
            } else {
              return CaretPosition(caret.get(), caret.get().length - 1);
            }
          });
        }, function(element) {
          remove$2(caret.get());
          var text = insertInlineAfter(element);
          caret.set(text);
          return Optional.some(CaretPosition(text, 1));
        });
      };
      var evaluateUntil = function(fns, args) {
        for (var i = 0; i < fns.length; i++) {
          var result = fns[i].apply(null, args);
          if (result.isSome()) {
            return result;
          }
        }
        return Optional.none();
      };
      var Location = Adt.generate([
        { before: ["element"] },
        { start: ["element"] },
        { end: ["element"] },
        { after: ["element"] }
      ]);
      var rescope$1 = function(rootNode, node) {
        var parentBlock = getParentBlock$2(node, rootNode);
        return parentBlock ? parentBlock : rootNode;
      };
      var before = function(isInlineTarget2, rootNode, pos) {
        var nPos = normalizeForwards(pos);
        var scope = rescope$1(rootNode, nPos.container());
        return findRootInline(isInlineTarget2, scope, nPos).fold(function() {
          return nextPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget2, scope)).map(function(inline) {
            return Location.before(inline);
          });
        }, Optional.none);
      };
      var isNotInsideFormatCaretContainer = function(rootNode, elm) {
        return getParentCaretContainer(rootNode, elm) === null;
      };
      var findInsideRootInline = function(isInlineTarget2, rootNode, pos) {
        return findRootInline(isInlineTarget2, rootNode, pos).filter(curry(isNotInsideFormatCaretContainer, rootNode));
      };
      var start$1 = function(isInlineTarget2, rootNode, pos) {
        var nPos = normalizeBackwards(pos);
        return findInsideRootInline(isInlineTarget2, rootNode, nPos).bind(function(inline) {
          var prevPos = prevPosition(inline, nPos);
          return prevPos.isNone() ? Optional.some(Location.start(inline)) : Optional.none();
        });
      };
      var end = function(isInlineTarget2, rootNode, pos) {
        var nPos = normalizeForwards(pos);
        return findInsideRootInline(isInlineTarget2, rootNode, nPos).bind(function(inline) {
          var nextPos = nextPosition(inline, nPos);
          return nextPos.isNone() ? Optional.some(Location.end(inline)) : Optional.none();
        });
      };
      var after = function(isInlineTarget2, rootNode, pos) {
        var nPos = normalizeBackwards(pos);
        var scope = rescope$1(rootNode, nPos.container());
        return findRootInline(isInlineTarget2, scope, nPos).fold(function() {
          return prevPosition(scope, nPos).bind(curry(findRootInline, isInlineTarget2, scope)).map(function(inline) {
            return Location.after(inline);
          });
        }, Optional.none);
      };
      var isValidLocation = function(location) {
        return isRtl(getElement(location)) === false;
      };
      var readLocation = function(isInlineTarget2, rootNode, pos) {
        var location = evaluateUntil([
          before,
          start$1,
          end,
          after
        ], [
          isInlineTarget2,
          rootNode,
          pos
        ]);
        return location.filter(isValidLocation);
      };
      var getElement = function(location) {
        return location.fold(identity, identity, identity, identity);
      };
      var getName = function(location) {
        return location.fold(constant("before"), constant("start"), constant("end"), constant("after"));
      };
      var outside = function(location) {
        return location.fold(Location.before, Location.before, Location.after, Location.after);
      };
      var inside = function(location) {
        return location.fold(Location.start, Location.start, Location.end, Location.end);
      };
      var isEq = function(location1, location2) {
        return getName(location1) === getName(location2) && getElement(location1) === getElement(location2);
      };
      var betweenInlines = function(forward, isInlineTarget2, rootNode, from2, to2, location) {
        return lift2(findRootInline(isInlineTarget2, rootNode, from2), findRootInline(isInlineTarget2, rootNode, to2), function(fromInline, toInline) {
          if (fromInline !== toInline && hasSameParentBlock(rootNode, fromInline, toInline)) {
            return Location.after(forward ? fromInline : toInline);
          } else {
            return location;
          }
        }).getOr(location);
      };
      var skipNoMovement = function(fromLocation, toLocation) {
        return fromLocation.fold(always, function(fromLocation2) {
          return !isEq(fromLocation2, toLocation);
        });
      };
      var findLocationTraverse = function(forward, isInlineTarget2, rootNode, fromLocation, pos) {
        var from2 = normalizePosition(forward, pos);
        var to2 = fromPosition(forward, rootNode, from2).map(curry(normalizePosition, forward));
        var location = to2.fold(function() {
          return fromLocation.map(outside);
        }, function(to3) {
          return readLocation(isInlineTarget2, rootNode, to3).map(curry(betweenInlines, forward, isInlineTarget2, rootNode, from2, to3)).filter(curry(skipNoMovement, fromLocation));
        });
        return location.filter(isValidLocation);
      };
      var findLocationSimple = function(forward, location) {
        if (forward) {
          return location.fold(compose(Optional.some, Location.start), Optional.none, compose(Optional.some, Location.after), Optional.none);
        } else {
          return location.fold(Optional.none, compose(Optional.some, Location.before), Optional.none, compose(Optional.some, Location.end));
        }
      };
      var findLocation$1 = function(forward, isInlineTarget2, rootNode, pos) {
        var from2 = normalizePosition(forward, pos);
        var fromLocation = readLocation(isInlineTarget2, rootNode, from2);
        return readLocation(isInlineTarget2, rootNode, from2).bind(curry(findLocationSimple, forward)).orThunk(function() {
          return findLocationTraverse(forward, isInlineTarget2, rootNode, fromLocation, pos);
        });
      };
      curry(findLocation$1, false);
      curry(findLocation$1, true);
      var hasSelectionModifyApi = function(editor) {
        return isFunction(editor.selection.getSel().modify);
      };
      var moveRel = function(forward, selection, pos) {
        var delta = forward ? 1 : -1;
        selection.setRng(CaretPosition(pos.container(), pos.offset() + delta).toRange());
        selection.getSel().modify("move", forward ? "forward" : "backward", "word");
        return true;
      };
      var moveByWord = function(forward, editor) {
        var rng = editor.selection.getRng();
        var pos = forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
        if (!hasSelectionModifyApi(editor)) {
          return false;
        } else if (forward && isBeforeInline(pos)) {
          return moveRel(true, editor.selection, pos);
        } else if (!forward && isAfterInline(pos)) {
          return moveRel(false, editor.selection, pos);
        } else {
          return false;
        }
      };
      var BreakType;
      (function(BreakType2) {
        BreakType2[BreakType2["Br"] = 0] = "Br";
        BreakType2[BreakType2["Block"] = 1] = "Block";
        BreakType2[BreakType2["Wrap"] = 2] = "Wrap";
        BreakType2[BreakType2["Eol"] = 3] = "Eol";
      })(BreakType || (BreakType = {}));
      var flip = function(direction, positions) {
        return direction === HDirection.Backwards ? reverse(positions) : positions;
      };
      var walk = function(direction, caretWalker, pos) {
        return direction === HDirection.Forwards ? caretWalker.next(pos) : caretWalker.prev(pos);
      };
      var getBreakType = function(scope, direction, currentPos, nextPos) {
        if (isBr$5(nextPos.getNode(direction === HDirection.Forwards))) {
          return BreakType.Br;
        } else if (isInSameBlock(currentPos, nextPos) === false) {
          return BreakType.Block;
        } else {
          return BreakType.Wrap;
        }
      };
      var getPositionsUntil = function(predicate, direction, scope, start2) {
        var caretWalker = CaretWalker(scope);
        var currentPos = start2;
        var positions = [];
        while (currentPos) {
          var nextPos = walk(direction, caretWalker, currentPos);
          if (!nextPos) {
            break;
          }
          if (isBr$5(nextPos.getNode(false))) {
            if (direction === HDirection.Forwards) {
              return {
                positions: flip(direction, positions).concat([nextPos]),
                breakType: BreakType.Br,
                breakAt: Optional.some(nextPos)
              };
            } else {
              return {
                positions: flip(direction, positions),
                breakType: BreakType.Br,
                breakAt: Optional.some(nextPos)
              };
            }
          }
          if (!nextPos.isVisible()) {
            currentPos = nextPos;
            continue;
          }
          if (predicate(currentPos, nextPos)) {
            var breakType = getBreakType(scope, direction, currentPos, nextPos);
            return {
              positions: flip(direction, positions),
              breakType,
              breakAt: Optional.some(nextPos)
            };
          }
          positions.push(nextPos);
          currentPos = nextPos;
        }
        return {
          positions: flip(direction, positions),
          breakType: BreakType.Eol,
          breakAt: Optional.none()
        };
      };
      var getAdjacentLinePositions = function(direction, getPositionsUntilBreak, scope, start2) {
        return getPositionsUntilBreak(scope, start2).breakAt.map(function(pos) {
          var positions = getPositionsUntilBreak(scope, pos).positions;
          return direction === HDirection.Backwards ? positions.concat(pos) : [pos].concat(positions);
        }).getOr([]);
      };
      var findClosestHorizontalPositionFromPoint = function(positions, x) {
        return foldl(positions, function(acc, newPos) {
          return acc.fold(function() {
            return Optional.some(newPos);
          }, function(lastPos) {
            return lift2(head(lastPos.getClientRects()), head(newPos.getClientRects()), function(lastRect, newRect) {
              var lastDist = Math.abs(x - lastRect.left);
              var newDist = Math.abs(x - newRect.left);
              return newDist <= lastDist ? newPos : lastPos;
            }).or(acc);
          });
        }, Optional.none());
      };
      var findClosestHorizontalPosition = function(positions, pos) {
        return head(pos.getClientRects()).bind(function(targetRect) {
          return findClosestHorizontalPositionFromPoint(positions, targetRect.left);
        });
      };
      var getPositionsUntilPreviousLine = curry(getPositionsUntil, CaretPosition.isAbove, -1);
      var getPositionsUntilNextLine = curry(getPositionsUntil, CaretPosition.isBelow, 1);
      var getPositionsAbove = curry(getAdjacentLinePositions, -1, getPositionsUntilPreviousLine);
      var getPositionsBelow = curry(getAdjacentLinePositions, 1, getPositionsUntilNextLine);
      var isAtFirstLine = function(scope, pos) {
        return getPositionsUntilPreviousLine(scope, pos).breakAt.isNone();
      };
      var isAtLastLine = function(scope, pos) {
        return getPositionsUntilNextLine(scope, pos).breakAt.isNone();
      };
      var getFirstLinePositions = function(scope) {
        return firstPositionIn(scope).map(function(pos) {
          return [pos].concat(getPositionsUntilNextLine(scope, pos).positions);
        }).getOr([]);
      };
      var getLastLinePositions = function(scope) {
        return lastPositionIn(scope).map(function(pos) {
          return getPositionsUntilPreviousLine(scope, pos).positions.concat(pos);
        }).getOr([]);
      };
      var getNodeClientRects = function(node) {
        var toArrayWithNode = function(clientRects) {
          return map$3(clientRects, function(rect) {
            var clientRect = clone(rect);
            clientRect.node = node;
            return clientRect;
          });
        };
        if (isElement$5(node)) {
          return toArrayWithNode(node.getClientRects());
        }
        if (isText$7(node)) {
          var rng = node.ownerDocument.createRange();
          rng.setStart(node, 0);
          rng.setEnd(node, node.data.length);
          return toArrayWithNode(rng.getClientRects());
        }
      };
      var getClientRects = function(nodes) {
        return bind(nodes, getNodeClientRects);
      };
      var VDirection;
      (function(VDirection2) {
        VDirection2[VDirection2["Up"] = -1] = "Up";
        VDirection2[VDirection2["Down"] = 1] = "Down";
      })(VDirection || (VDirection = {}));
      var findUntil = function(direction, root, predicateFn, node) {
        while (node = findNode$1(node, direction, isEditableCaretCandidate$1, root)) {
          if (predicateFn(node)) {
            return;
          }
        }
      };
      var walkUntil$1 = function(direction, isAboveFn, isBeflowFn, root, predicateFn, caretPosition) {
        var line = 0;
        var result = [];
        var add2 = function(node2) {
          var clientRects = getClientRects([node2]);
          if (direction === -1) {
            clientRects = clientRects.reverse();
          }
          for (var i = 0; i < clientRects.length; i++) {
            var clientRect = clientRects[i];
            if (isBeflowFn(clientRect, targetClientRect)) {
              continue;
            }
            if (result.length > 0 && isAboveFn(clientRect, last$1(result))) {
              line++;
            }
            clientRect.line = line;
            if (predicateFn(clientRect)) {
              return true;
            }
            result.push(clientRect);
          }
        };
        var targetClientRect = last$1(caretPosition.getClientRects());
        if (!targetClientRect) {
          return result;
        }
        var node = caretPosition.getNode();
        add2(node);
        findUntil(direction, root, add2, node);
        return result;
      };
      var aboveLineNumber = function(lineNumber, clientRect) {
        return clientRect.line > lineNumber;
      };
      var isLineNumber = function(lineNumber, clientRect) {
        return clientRect.line === lineNumber;
      };
      var upUntil = curry(walkUntil$1, VDirection.Up, isAbove$1, isBelow$1);
      var downUntil = curry(walkUntil$1, VDirection.Down, isBelow$1, isAbove$1);
      var positionsUntil = function(direction, root, predicateFn, node) {
        var caretWalker = CaretWalker(root);
        var walkFn;
        var isBelowFn;
        var isAboveFn;
        var caretPosition;
        var result = [];
        var line = 0;
        var getClientRect = function(caretPosition2) {
          if (direction === 1) {
            return last$1(caretPosition2.getClientRects());
          }
          return last$1(caretPosition2.getClientRects());
        };
        if (direction === 1) {
          walkFn = caretWalker.next;
          isBelowFn = isBelow$1;
          isAboveFn = isAbove$1;
          caretPosition = CaretPosition.after(node);
        } else {
          walkFn = caretWalker.prev;
          isBelowFn = isAbove$1;
          isAboveFn = isBelow$1;
          caretPosition = CaretPosition.before(node);
        }
        var targetClientRect = getClientRect(caretPosition);
        do {
          if (!caretPosition.isVisible()) {
            continue;
          }
          var rect = getClientRect(caretPosition);
          if (isAboveFn(rect, targetClientRect)) {
            continue;
          }
          if (result.length > 0 && isBelowFn(rect, last$1(result))) {
            line++;
          }
          var clientRect = clone(rect);
          clientRect.position = caretPosition;
          clientRect.line = line;
          if (predicateFn(clientRect)) {
            return result;
          }
          result.push(clientRect);
        } while (caretPosition = walkFn(caretPosition));
        return result;
      };
      var isAboveLine = function(lineNumber) {
        return function(clientRect) {
          return aboveLineNumber(lineNumber, clientRect);
        };
      };
      var isLine = function(lineNumber) {
        return function(clientRect) {
          return isLineNumber(lineNumber, clientRect);
        };
      };
      var isContentEditableFalse$3 = isContentEditableFalse$b;
      var findNode = findNode$1;
      var distanceToRectLeft = function(clientRect, clientX) {
        return Math.abs(clientRect.left - clientX);
      };
      var distanceToRectRight = function(clientRect, clientX) {
        return Math.abs(clientRect.right - clientX);
      };
      var isInsideX = function(clientX, clientRect) {
        return clientX >= clientRect.left && clientX <= clientRect.right;
      };
      var isInsideY = function(clientY, clientRect) {
        return clientY >= clientRect.top && clientY <= clientRect.bottom;
      };
      var isNodeClientRect = function(rect) {
        return hasNonNullableKey(rect, "node");
      };
      var findClosestClientRect = function(clientRects, clientX, allowInside) {
        if (allowInside === void 0) {
          allowInside = always;
        }
        return reduce(clientRects, function(oldClientRect, clientRect) {
          if (isInsideX(clientX, clientRect)) {
            return allowInside(clientRect) ? clientRect : oldClientRect;
          }
          if (isInsideX(clientX, oldClientRect)) {
            return allowInside(oldClientRect) ? oldClientRect : clientRect;
          }
          var oldDistance = Math.min(distanceToRectLeft(oldClientRect, clientX), distanceToRectRight(oldClientRect, clientX));
          var newDistance = Math.min(distanceToRectLeft(clientRect, clientX), distanceToRectRight(clientRect, clientX));
          if (newDistance === oldDistance && isNodeClientRect(clientRect) && isContentEditableFalse$3(clientRect.node)) {
            return clientRect;
          }
          if (newDistance < oldDistance) {
            return clientRect;
          }
          return oldClientRect;
        });
      };
      var walkUntil = function(direction, root, predicateFn, startNode, includeChildren) {
        var node = findNode(startNode, direction, isEditableCaretCandidate$1, root, !includeChildren);
        do {
          if (!node || predicateFn(node)) {
            return;
          }
        } while (node = findNode(node, direction, isEditableCaretCandidate$1, root));
      };
      var findLineNodeRects = function(root, targetNodeRect, includeChildren) {
        if (includeChildren === void 0) {
          includeChildren = true;
        }
        var clientRects = [];
        var collect = function(checkPosFn, node) {
          var lineRects = filter$4(getClientRects([node]), function(clientRect) {
            return !checkPosFn(clientRect, targetNodeRect);
          });
          clientRects = clientRects.concat(lineRects);
          return lineRects.length === 0;
        };
        clientRects.push(targetNodeRect);
        walkUntil(VDirection.Up, root, curry(collect, isAbove$1), targetNodeRect.node, includeChildren);
        walkUntil(VDirection.Down, root, curry(collect, isBelow$1), targetNodeRect.node, includeChildren);
        return clientRects;
      };
      var getFakeCaretTargets = function(root) {
        return filter$4(from(root.getElementsByTagName("*")), isFakeCaretTarget);
      };
      var caretInfo = function(clientRect, clientX) {
        return {
          node: clientRect.node,
          before: distanceToRectLeft(clientRect, clientX) < distanceToRectRight(clientRect, clientX)
        };
      };
      var closestFakeCaret = function(root, clientX, clientY) {
        var fakeTargetNodeRects = getClientRects(getFakeCaretTargets(root));
        var targetNodeRects = filter$4(fakeTargetNodeRects, curry(isInsideY, clientY));
        var checkInside = function(clientRect) {
          return !isTable$3(clientRect.node) && !isMedia$2(clientRect.node);
        };
        var closestNodeRect = findClosestClientRect(targetNodeRects, clientX, checkInside);
        if (closestNodeRect) {
          var includeChildren = checkInside(closestNodeRect);
          closestNodeRect = findClosestClientRect(findLineNodeRects(root, closestNodeRect, includeChildren), clientX, checkInside);
          if (closestNodeRect && isFakeCaretTarget(closestNodeRect.node)) {
            return caretInfo(closestNodeRect, clientX);
          }
        }
        return null;
      };
      var moveToRange = function(editor, rng) {
        editor.selection.setRng(rng);
        scrollRangeIntoView(editor, editor.selection.getRng());
      };
      var renderRangeCaretOpt = function(editor, range2, scrollIntoView) {
        return Optional.some(renderRangeCaret(editor, range2, scrollIntoView));
      };
      var moveHorizontally = function(editor, direction, range2, isBefore, isAfter, isElement2) {
        var forwards = direction === HDirection.Forwards;
        var caretWalker = CaretWalker(editor.getBody());
        var getNextPosFn = curry(getVisualCaretPosition, forwards ? caretWalker.next : caretWalker.prev);
        var isBeforeFn = forwards ? isBefore : isAfter;
        if (!range2.collapsed) {
          var node = getSelectedNode(range2);
          if (isElement2(node)) {
            return showCaret(direction, editor, node, direction === HDirection.Backwards, false);
          }
        }
        var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
        if (isBeforeFn(caretPosition)) {
          return selectNode(editor, caretPosition.getNode(!forwards));
        }
        var nextCaretPosition = normalizePosition(forwards, getNextPosFn(caretPosition));
        var rangeIsInContainerBlock = isRangeInCaretContainerBlock(range2);
        if (!nextCaretPosition) {
          return rangeIsInContainerBlock ? Optional.some(range2) : Optional.none();
        }
        if (isBeforeFn(nextCaretPosition)) {
          return showCaret(direction, editor, nextCaretPosition.getNode(!forwards), forwards, false);
        }
        var peekCaretPosition = getNextPosFn(nextCaretPosition);
        if (peekCaretPosition && isBeforeFn(peekCaretPosition)) {
          if (isMoveInsideSameBlock(nextCaretPosition, peekCaretPosition)) {
            return showCaret(direction, editor, peekCaretPosition.getNode(!forwards), forwards, false);
          }
        }
        if (rangeIsInContainerBlock) {
          return renderRangeCaretOpt(editor, nextCaretPosition.toRange(), false);
        }
        return Optional.none();
      };
      var moveVertically = function(editor, direction, range2, isBefore, isAfter, isElement2) {
        var caretPosition = getNormalizedRangeEndPoint(direction, editor.getBody(), range2);
        var caretClientRect = last$1(caretPosition.getClientRects());
        var forwards = direction === VDirection.Down;
        if (!caretClientRect) {
          return Optional.none();
        }
        var walkerFn = forwards ? downUntil : upUntil;
        var linePositions = walkerFn(editor.getBody(), isAboveLine(1), caretPosition);
        var nextLinePositions = filter$4(linePositions, isLine(1));
        var clientX = caretClientRect.left;
        var nextLineRect = findClosestClientRect(nextLinePositions, clientX);
        if (nextLineRect && isElement2(nextLineRect.node)) {
          var dist1 = Math.abs(clientX - nextLineRect.left);
          var dist2 = Math.abs(clientX - nextLineRect.right);
          return showCaret(direction, editor, nextLineRect.node, dist1 < dist2, false);
        }
        var currentNode;
        if (isBefore(caretPosition)) {
          currentNode = caretPosition.getNode();
        } else if (isAfter(caretPosition)) {
          currentNode = caretPosition.getNode(true);
        } else {
          currentNode = getSelectedNode(range2);
        }
        if (currentNode) {
          var caretPositions = positionsUntil(direction, editor.getBody(), isAboveLine(1), currentNode);
          var closestNextLineRect = findClosestClientRect(filter$4(caretPositions, isLine(1)), clientX);
          if (closestNextLineRect) {
            return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
          }
          closestNextLineRect = last$1(filter$4(caretPositions, isLine(0)));
          if (closestNextLineRect) {
            return renderRangeCaretOpt(editor, closestNextLineRect.position.toRange(), false);
          }
        }
        if (nextLinePositions.length === 0) {
          return getLineEndPoint(editor, forwards).filter(forwards ? isAfter : isBefore).map(function(pos) {
            return renderRangeCaret(editor, pos.toRange(), false);
          });
        }
        return Optional.none();
      };
      var getLineEndPoint = function(editor, forward) {
        var rng = editor.selection.getRng();
        var body = editor.getBody();
        if (forward) {
          var from2 = CaretPosition.fromRangeEnd(rng);
          var result = getPositionsUntilNextLine(body, from2);
          return last$2(result.positions);
        } else {
          var from2 = CaretPosition.fromRangeStart(rng);
          var result = getPositionsUntilPreviousLine(body, from2);
          return head(result.positions);
        }
      };
      var moveToLineEndPoint$3 = function(editor, forward, isElementPosition) {
        return getLineEndPoint(editor, forward).filter(isElementPosition).exists(function(pos) {
          editor.selection.setRng(pos.toRange());
          return true;
        });
      };
      var setCaretPosition = function(editor, pos) {
        var rng = editor.dom.createRng();
        rng.setStart(pos.container(), pos.offset());
        rng.setEnd(pos.container(), pos.offset());
        editor.selection.setRng(rng);
      };
      var setSelected = function(state, elm) {
        if (state) {
          elm.setAttribute("data-mce-selected", "inline-boundary");
        } else {
          elm.removeAttribute("data-mce-selected");
        }
      };
      var renderCaretLocation = function(editor, caret, location) {
        return renderCaret(caret, location).map(function(pos) {
          setCaretPosition(editor, pos);
          return location;
        });
      };
      var findLocation = function(editor, caret, forward) {
        var rootNode = editor.getBody();
        var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        var location = findLocation$1(forward, isInlineTarget$1, rootNode, from2);
        return location.bind(function(location2) {
          return renderCaretLocation(editor, caret, location2);
        });
      };
      var toggleInlines = function(isInlineTarget2, dom2, elms) {
        var inlineBoundaries = map$3(descendants(SugarElement.fromDom(dom2.getRoot()), '*[data-mce-selected="inline-boundary"]'), function(e) {
          return e.dom;
        });
        var selectedInlines = filter$4(inlineBoundaries, isInlineTarget2);
        var targetInlines = filter$4(elms, isInlineTarget2);
        each$k(difference(selectedInlines, targetInlines), curry(setSelected, false));
        each$k(difference(targetInlines, selectedInlines), curry(setSelected, true));
      };
      var safeRemoveCaretContainer = function(editor, caret) {
        if (editor.selection.isCollapsed() && editor.composing !== true && caret.get()) {
          var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
          if (CaretPosition.isTextPosition(pos) && isAtZwsp(pos) === false) {
            setCaretPosition(editor, removeAndReposition(caret.get(), pos));
            caret.set(null);
          }
        }
      };
      var renderInsideInlineCaret = function(isInlineTarget2, editor, caret, elms) {
        if (editor.selection.isCollapsed()) {
          var inlines = filter$4(elms, isInlineTarget2);
          each$k(inlines, function(_inline) {
            var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
            readLocation(isInlineTarget2, editor.getBody(), pos).bind(function(location) {
              return renderCaretLocation(editor, caret, location);
            });
          });
        }
      };
      var move$2 = function(editor, caret, forward) {
        return isInlineBoundariesEnabled(editor) ? findLocation(editor, caret, forward).isSome() : false;
      };
      var moveWord = function(forward, editor, _caret) {
        return isInlineBoundariesEnabled(editor) ? moveByWord(forward, editor) : false;
      };
      var setupSelectedState = function(editor) {
        var caret = Cell(null);
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        editor.on("NodeChange", function(e) {
          if (isInlineBoundariesEnabled(editor) && !(Env.browser.isIE() && e.initial)) {
            toggleInlines(isInlineTarget$1, editor.dom, e.parents);
            safeRemoveCaretContainer(editor, caret);
            renderInsideInlineCaret(isInlineTarget$1, editor, caret, e.parents);
          }
        });
        return caret;
      };
      var moveNextWord = curry(moveWord, true);
      var movePrevWord = curry(moveWord, false);
      var moveToLineEndPoint$2 = function(editor, forward, caret) {
        if (isInlineBoundariesEnabled(editor)) {
          var linePoint = getLineEndPoint(editor, forward).getOrThunk(function() {
            var rng = editor.selection.getRng();
            return forward ? CaretPosition.fromRangeEnd(rng) : CaretPosition.fromRangeStart(rng);
          });
          return readLocation(curry(isInlineTarget, editor), editor.getBody(), linePoint).exists(function(loc) {
            var outsideLoc = outside(loc);
            return renderCaret(caret, outsideLoc).exists(function(pos) {
              setCaretPosition(editor, pos);
              return true;
            });
          });
        } else {
          return false;
        }
      };
      var rangeFromPositions = function(from2, to2) {
        var range2 = document.createRange();
        range2.setStart(from2.container(), from2.offset());
        range2.setEnd(to2.container(), to2.offset());
        return range2;
      };
      var hasOnlyTwoOrLessPositionsLeft = function(elm) {
        return lift2(firstPositionIn(elm), lastPositionIn(elm), function(firstPos, lastPos) {
          var normalizedFirstPos = normalizePosition(true, firstPos);
          var normalizedLastPos = normalizePosition(false, lastPos);
          return nextPosition(elm, normalizedFirstPos).forall(function(pos) {
            return pos.isEqual(normalizedLastPos);
          });
        }).getOr(true);
      };
      var setCaretLocation = function(editor, caret) {
        return function(location) {
          return renderCaret(caret, location).exists(function(pos) {
            setCaretPosition(editor, pos);
            return true;
          });
        };
      };
      var deleteFromTo = function(editor, caret, from2, to2) {
        var rootNode = editor.getBody();
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        editor.undoManager.ignore(function() {
          editor.selection.setRng(rangeFromPositions(from2, to2));
          editor.execCommand("Delete");
          readLocation(isInlineTarget$1, rootNode, CaretPosition.fromRangeStart(editor.selection.getRng())).map(inside).map(setCaretLocation(editor, caret));
        });
        editor.nodeChanged();
      };
      var rescope = function(rootNode, node) {
        var parentBlock = getParentBlock$2(node, rootNode);
        return parentBlock ? parentBlock : rootNode;
      };
      var backspaceDeleteCollapsed = function(editor, caret, forward, from2) {
        var rootNode = rescope(editor.getBody(), from2.container());
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        var fromLocation = readLocation(isInlineTarget$1, rootNode, from2);
        return fromLocation.bind(function(location) {
          if (forward) {
            return location.fold(constant(Optional.some(inside(location))), Optional.none, constant(Optional.some(outside(location))), Optional.none);
          } else {
            return location.fold(Optional.none, constant(Optional.some(outside(location))), Optional.none, constant(Optional.some(inside(location))));
          }
        }).map(setCaretLocation(editor, caret)).getOrThunk(function() {
          var toPosition = navigate(forward, rootNode, from2);
          var toLocation = toPosition.bind(function(pos) {
            return readLocation(isInlineTarget$1, rootNode, pos);
          });
          return lift2(fromLocation, toLocation, function() {
            return findRootInline(isInlineTarget$1, rootNode, from2).exists(function(elm) {
              if (hasOnlyTwoOrLessPositionsLeft(elm)) {
                deleteElement$2(editor, forward, SugarElement.fromDom(elm));
                return true;
              } else {
                return false;
              }
            });
          }).orThunk(function() {
            return toLocation.bind(function(_) {
              return toPosition.map(function(to2) {
                if (forward) {
                  deleteFromTo(editor, caret, from2, to2);
                } else {
                  deleteFromTo(editor, caret, to2, from2);
                }
                return true;
              });
            });
          }).getOr(false);
        });
      };
      var backspaceDelete$3 = function(editor, caret, forward) {
        if (editor.selection.isCollapsed() && isInlineBoundariesEnabled(editor)) {
          var from2 = CaretPosition.fromRangeStart(editor.selection.getRng());
          return backspaceDeleteCollapsed(editor, caret, forward, from2);
        }
        return false;
      };
      var getParentInlines = function(rootElm, startElm) {
        var parents2 = parentsAndSelf(startElm, rootElm);
        return findIndex$2(parents2, isBlock$2).fold(constant(parents2), function(index) {
          return parents2.slice(0, index);
        });
      };
      var hasOnlyOneChild = function(elm) {
        return childNodesCount(elm) === 1;
      };
      var deleteLastPosition = function(forward, editor, target, parentInlines) {
        var isFormatElement$1 = curry(isFormatElement, editor);
        var formatNodes = map$3(filter$4(parentInlines, isFormatElement$1), function(elm) {
          return elm.dom;
        });
        if (formatNodes.length === 0) {
          deleteElement$2(editor, forward, target);
        } else {
          var pos = replaceWithCaretFormat(target.dom, formatNodes);
          editor.selection.setRng(pos.toRange());
        }
      };
      var deleteCaret$1 = function(editor, forward) {
        var rootElm = SugarElement.fromDom(editor.getBody());
        var startElm = SugarElement.fromDom(editor.selection.getStart());
        var parentInlines = filter$4(getParentInlines(rootElm, startElm), hasOnlyOneChild);
        return last$2(parentInlines).exists(function(target) {
          var fromPos = CaretPosition.fromRangeStart(editor.selection.getRng());
          if (willDeleteLastPositionInElement(forward, fromPos, target.dom) && !isEmptyCaretFormatElement(target)) {
            deleteLastPosition(forward, editor, target, parentInlines);
            return true;
          } else {
            return false;
          }
        });
      };
      var backspaceDelete$2 = function(editor, forward) {
        return editor.selection.isCollapsed() ? deleteCaret$1(editor, forward) : false;
      };
      var deleteElement = function(editor, forward, element) {
        editor._selectionOverrides.hideFakeCaret();
        deleteElement$2(editor, forward, SugarElement.fromDom(element));
        return true;
      };
      var deleteCaret = function(editor, forward) {
        var isNearMedia = forward ? isBeforeMedia : isAfterMedia;
        var direction = forward ? HDirection.Forwards : HDirection.Backwards;
        var fromPos = getNormalizedRangeEndPoint(direction, editor.getBody(), editor.selection.getRng());
        if (isNearMedia(fromPos)) {
          return deleteElement(editor, forward, fromPos.getNode(!forward));
        } else {
          return Optional.from(normalizePosition(forward, fromPos)).filter(function(pos) {
            return isNearMedia(pos) && isMoveInsideSameBlock(fromPos, pos);
          }).exists(function(pos) {
            return deleteElement(editor, forward, pos.getNode(!forward));
          });
        }
      };
      var deleteRange = function(editor, forward) {
        var selectedNode = editor.selection.getNode();
        return isMedia$2(selectedNode) ? deleteElement(editor, forward, selectedNode) : false;
      };
      var backspaceDelete$1 = function(editor, forward) {
        return editor.selection.isCollapsed() ? deleteCaret(editor, forward) : deleteRange(editor, forward);
      };
      var isEditable = function(target) {
        return closest$3(target, function(elm) {
          return isContentEditableTrue$4(elm.dom) || isContentEditableFalse$b(elm.dom);
        }).exists(function(elm) {
          return isContentEditableTrue$4(elm.dom);
        });
      };
      var parseIndentValue = function(value2) {
        var number = parseInt(value2, 10);
        return isNaN(number) ? 0 : number;
      };
      var getIndentStyleName = function(useMargin, element) {
        var indentStyleName = useMargin || isTable$2(element) ? "margin" : "padding";
        var suffix = get$5(element, "direction") === "rtl" ? "-right" : "-left";
        return indentStyleName + suffix;
      };
      var indentElement = function(dom2, command, useMargin, value2, unit, element) {
        var indentStyleName = getIndentStyleName(useMargin, SugarElement.fromDom(element));
        if (command === "outdent") {
          var styleValue = Math.max(0, parseIndentValue(element.style[indentStyleName]) - value2);
          dom2.setStyle(element, indentStyleName, styleValue ? styleValue + unit : "");
        } else {
          var styleValue = parseIndentValue(element.style[indentStyleName]) + value2 + unit;
          dom2.setStyle(element, indentStyleName, styleValue);
        }
      };
      var validateBlocks = function(editor, blocks2) {
        return forall(blocks2, function(block) {
          var indentStyleName = getIndentStyleName(shouldIndentUseMargin(editor), block);
          var intentValue = getRaw(block, indentStyleName).map(parseIndentValue).getOr(0);
          var contentEditable = editor.dom.getContentEditable(block.dom);
          return contentEditable !== "false" && intentValue > 0;
        });
      };
      var canOutdent = function(editor) {
        var blocks2 = getBlocksToIndent(editor);
        return !editor.mode.isReadOnly() && (blocks2.length > 1 || validateBlocks(editor, blocks2));
      };
      var isListComponent = function(el) {
        return isList(el) || isListItem(el);
      };
      var parentIsListComponent = function(el) {
        return parent(el).exists(isListComponent);
      };
      var getBlocksToIndent = function(editor) {
        return filter$4(fromDom$1(editor.selection.getSelectedBlocks()), function(el) {
          return !isListComponent(el) && !parentIsListComponent(el) && isEditable(el);
        });
      };
      var handle = function(editor, command) {
        var dom2 = editor.dom, selection = editor.selection, formatter = editor.formatter;
        var indentation = getIndentation(editor);
        var indentUnit = /[a-z%]+$/i.exec(indentation)[0];
        var indentValue = parseInt(indentation, 10);
        var useMargin = shouldIndentUseMargin(editor);
        var forcedRootBlock = getForcedRootBlock(editor);
        if (!editor.queryCommandState("InsertUnorderedList") && !editor.queryCommandState("InsertOrderedList")) {
          if (forcedRootBlock === "" && !dom2.getParent(selection.getNode(), dom2.isBlock)) {
            formatter.apply("div");
          }
        }
        each$k(getBlocksToIndent(editor), function(block) {
          indentElement(dom2, command, useMargin, indentValue, indentUnit, block.dom);
        });
      };
      var backspaceDelete = function(editor, _forward) {
        if (editor.selection.isCollapsed() && canOutdent(editor)) {
          var dom2 = editor.dom;
          var rng = editor.selection.getRng();
          var pos = CaretPosition.fromRangeStart(rng);
          var block = dom2.getParent(rng.startContainer, dom2.isBlock);
          if (block !== null && isAtStartOfBlock(SugarElement.fromDom(block), pos)) {
            handle(editor, "outdent");
            return true;
          }
        }
        return false;
      };
      var nativeCommand = function(editor, command) {
        editor.getDoc().execCommand(command, false, null);
      };
      var deleteCommand = function(editor, caret) {
        if (backspaceDelete(editor)) {
          return;
        } else if (backspaceDelete$5(editor, false)) {
          return;
        } else if (backspaceDelete$6(editor, false)) {
          return;
        } else if (backspaceDelete$3(editor, caret, false)) {
          return;
        } else if (backspaceDelete$8(editor, false)) {
          return;
        } else if (backspaceDelete$9(editor)) {
          return;
        } else if (backspaceDelete$4(editor, false)) {
          return;
        } else if (backspaceDelete$1(editor, false)) {
          return;
        } else if (backspaceDelete$7(editor)) {
          return;
        } else if (backspaceDelete$2(editor, false)) {
          return;
        } else {
          nativeCommand(editor, "Delete");
          paddEmptyBody(editor);
        }
      };
      var forwardDeleteCommand = function(editor, caret) {
        if (backspaceDelete$5(editor, true)) {
          return;
        } else if (backspaceDelete$6(editor, true)) {
          return;
        } else if (backspaceDelete$3(editor, caret, true)) {
          return;
        } else if (backspaceDelete$8(editor, true)) {
          return;
        } else if (backspaceDelete$9(editor)) {
          return;
        } else if (backspaceDelete$4(editor, true)) {
          return;
        } else if (backspaceDelete$1(editor, true)) {
          return;
        } else if (backspaceDelete$7(editor)) {
          return;
        } else if (backspaceDelete$2(editor, true)) {
          return;
        } else {
          nativeCommand(editor, "ForwardDelete");
        }
      };
      var setup$f = function(editor, caret) {
        editor.addCommand("delete", function() {
          deleteCommand(editor, caret);
        });
        editor.addCommand("forwardDelete", function() {
          forwardDeleteCommand(editor, caret);
        });
      };
      var SIGNIFICANT_MOVE = 5;
      var LONGPRESS_DELAY = 400;
      var getTouch = function(event) {
        if (event.touches === void 0 || event.touches.length !== 1) {
          return Optional.none();
        }
        return Optional.some(event.touches[0]);
      };
      var isFarEnough = function(touch, data2) {
        var distX = Math.abs(touch.clientX - data2.x);
        var distY = Math.abs(touch.clientY - data2.y);
        return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
      };
      var setup$e = function(editor) {
        var startData = value();
        var longpressFired = Cell(false);
        var debounceLongpress = last(function(e) {
          editor.fire("longpress", __assign(__assign({}, e), { type: "longpress" }));
          longpressFired.set(true);
        }, LONGPRESS_DELAY);
        editor.on("touchstart", function(e) {
          getTouch(e).each(function(touch) {
            debounceLongpress.cancel();
            var data2 = {
              x: touch.clientX,
              y: touch.clientY,
              target: e.target
            };
            debounceLongpress.throttle(e);
            longpressFired.set(false);
            startData.set(data2);
          });
        }, true);
        editor.on("touchmove", function(e) {
          debounceLongpress.cancel();
          getTouch(e).each(function(touch) {
            startData.on(function(data2) {
              if (isFarEnough(touch, data2)) {
                startData.clear();
                longpressFired.set(false);
                editor.fire("longpresscancel");
              }
            });
          });
        }, true);
        editor.on("touchend touchcancel", function(e) {
          debounceLongpress.cancel();
          if (e.type === "touchcancel") {
            return;
          }
          startData.get().filter(function(data2) {
            return data2.target.isEqualNode(e.target);
          }).each(function() {
            if (longpressFired.get()) {
              e.preventDefault();
            } else {
              editor.fire("tap", __assign(__assign({}, e), { type: "tap" }));
            }
          });
        }, true);
      };
      var isBlockElement = function(blockElements, node) {
        return has$2(blockElements, node.nodeName);
      };
      var isValidTarget = function(blockElements, node) {
        if (isText$7(node)) {
          return true;
        } else if (isElement$5(node)) {
          return !isBlockElement(blockElements, node) && !isBookmarkNode$1(node);
        } else {
          return false;
        }
      };
      var hasBlockParent = function(blockElements, root, node) {
        return exists(parents(SugarElement.fromDom(node), SugarElement.fromDom(root)), function(elm) {
          return isBlockElement(blockElements, elm.dom);
        });
      };
      var shouldRemoveTextNode = function(blockElements, node) {
        if (isText$7(node)) {
          if (node.nodeValue.length === 0) {
            return true;
          } else if (/^\s+$/.test(node.nodeValue) && (!node.nextSibling || isBlockElement(blockElements, node.nextSibling))) {
            return true;
          }
        }
        return false;
      };
      var addRootBlocks = function(editor) {
        var dom2 = editor.dom, selection = editor.selection;
        var schema = editor.schema, blockElements = schema.getBlockElements();
        var node = selection.getStart();
        var rootNode = editor.getBody();
        var rootBlockNode, tempNode, wrapped;
        var forcedRootBlock = getForcedRootBlock(editor);
        if (!node || !isElement$5(node) || !forcedRootBlock) {
          return;
        }
        var rootNodeName = rootNode.nodeName.toLowerCase();
        if (!schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase()) || hasBlockParent(blockElements, rootNode, node)) {
          return;
        }
        var rng = selection.getRng();
        var startContainer = rng.startContainer;
        var startOffset = rng.startOffset;
        var endContainer = rng.endContainer;
        var endOffset = rng.endOffset;
        var restoreSelection = hasFocus(editor);
        node = rootNode.firstChild;
        while (node) {
          if (isValidTarget(blockElements, node)) {
            if (shouldRemoveTextNode(blockElements, node)) {
              tempNode = node;
              node = node.nextSibling;
              dom2.remove(tempNode);
              continue;
            }
            if (!rootBlockNode) {
              rootBlockNode = dom2.create(forcedRootBlock, getForcedRootBlockAttrs(editor));
              node.parentNode.insertBefore(rootBlockNode, node);
              wrapped = true;
            }
            tempNode = node;
            node = node.nextSibling;
            rootBlockNode.appendChild(tempNode);
          } else {
            rootBlockNode = null;
            node = node.nextSibling;
          }
        }
        if (wrapped && restoreSelection) {
          rng.setStart(startContainer, startOffset);
          rng.setEnd(endContainer, endOffset);
          selection.setRng(rng);
          editor.nodeChanged();
        }
      };
      var setup$d = function(editor) {
        if (getForcedRootBlock(editor)) {
          editor.on("NodeChange", curry(addRootBlocks, editor));
        }
      };
      var findBlockCaretContainer = function(editor) {
        return descendant(SugarElement.fromDom(editor.getBody()), "*[data-mce-caret]").map(function(elm) {
          return elm.dom;
        }).getOrNull();
      };
      var removeIeControlRect = function(editor) {
        editor.selection.setRng(editor.selection.getRng());
      };
      var showBlockCaretContainer = function(editor, blockCaretContainer) {
        if (blockCaretContainer.hasAttribute("data-mce-caret")) {
          showCaretContainerBlock(blockCaretContainer);
          removeIeControlRect(editor);
          editor.selection.scrollIntoView(blockCaretContainer);
        }
      };
      var handleBlockContainer = function(editor, e) {
        var blockCaretContainer = findBlockCaretContainer(editor);
        if (!blockCaretContainer) {
          return;
        }
        if (e.type === "compositionstart") {
          e.preventDefault();
          e.stopPropagation();
          showBlockCaretContainer(editor, blockCaretContainer);
          return;
        }
        if (hasContent(blockCaretContainer)) {
          showBlockCaretContainer(editor, blockCaretContainer);
          editor.undoManager.add();
        }
      };
      var setup$c = function(editor) {
        editor.on("keyup compositionstart", curry(handleBlockContainer, editor));
      };
      var isContentEditableFalse$2 = isContentEditableFalse$b;
      var moveToCeFalseHorizontally = function(direction, editor, range2) {
        return moveHorizontally(editor, direction, range2, isBeforeContentEditableFalse, isAfterContentEditableFalse, isContentEditableFalse$2);
      };
      var moveToCeFalseVertically = function(direction, editor, range2) {
        var isBefore = function(caretPosition) {
          return isBeforeContentEditableFalse(caretPosition) || isBeforeTable(caretPosition);
        };
        var isAfter = function(caretPosition) {
          return isAfterContentEditableFalse(caretPosition) || isAfterTable(caretPosition);
        };
        return moveVertically(editor, direction, range2, isBefore, isAfter, isContentEditableFalse$2);
      };
      var createTextBlock = function(editor) {
        var textBlock = editor.dom.create(getForcedRootBlock(editor));
        if (!Env.ie || Env.ie >= 11) {
          textBlock.innerHTML = '<br data-mce-bogus="1">';
        }
        return textBlock;
      };
      var exitPreBlock = function(editor, direction, range2) {
        var caretWalker = CaretWalker(editor.getBody());
        var getVisualCaretPosition$1 = curry(getVisualCaretPosition, direction === 1 ? caretWalker.next : caretWalker.prev);
        if (range2.collapsed && hasForcedRootBlock(editor)) {
          var pre = editor.dom.getParent(range2.startContainer, "PRE");
          if (!pre) {
            return;
          }
          var caretPos = getVisualCaretPosition$1(CaretPosition.fromRangeStart(range2));
          if (!caretPos) {
            var newBlock = createTextBlock(editor);
            if (direction === 1) {
              editor.$(pre).after(newBlock);
            } else {
              editor.$(pre).before(newBlock);
            }
            editor.selection.select(newBlock, true);
            editor.selection.collapse();
          }
        }
      };
      var getHorizontalRange = function(editor, forward) {
        var direction = forward ? HDirection.Forwards : HDirection.Backwards;
        var range2 = editor.selection.getRng();
        return moveToCeFalseHorizontally(direction, editor, range2).orThunk(function() {
          exitPreBlock(editor, direction, range2);
          return Optional.none();
        });
      };
      var getVerticalRange = function(editor, down) {
        var direction = down ? 1 : -1;
        var range2 = editor.selection.getRng();
        return moveToCeFalseVertically(direction, editor, range2).orThunk(function() {
          exitPreBlock(editor, direction, range2);
          return Optional.none();
        });
      };
      var moveH$2 = function(editor, forward) {
        return getHorizontalRange(editor, forward).exists(function(newRange) {
          moveToRange(editor, newRange);
          return true;
        });
      };
      var moveV$3 = function(editor, down) {
        return getVerticalRange(editor, down).exists(function(newRange) {
          moveToRange(editor, newRange);
          return true;
        });
      };
      var moveToLineEndPoint$1 = function(editor, forward) {
        var isCefPosition = forward ? isAfterContentEditableFalse : isBeforeContentEditableFalse;
        return moveToLineEndPoint$3(editor, forward, isCefPosition);
      };
      var isTarget = function(node) {
        return contains$3(["figcaption"], name(node));
      };
      var rangeBefore = function(target) {
        var rng = document.createRange();
        rng.setStartBefore(target.dom);
        rng.setEndBefore(target.dom);
        return rng;
      };
      var insertElement = function(root, elm, forward) {
        if (forward) {
          append$1(root, elm);
        } else {
          prepend(root, elm);
        }
      };
      var insertBr = function(root, forward) {
        var br = SugarElement.fromTag("br");
        insertElement(root, br, forward);
        return rangeBefore(br);
      };
      var insertBlock = function(root, forward, blockName, attrs) {
        var block = SugarElement.fromTag(blockName);
        var br = SugarElement.fromTag("br");
        setAll$1(block, attrs);
        append$1(block, br);
        insertElement(root, block, forward);
        return rangeBefore(br);
      };
      var insertEmptyLine = function(root, rootBlockName, attrs, forward) {
        if (rootBlockName === "") {
          return insertBr(root, forward);
        } else {
          return insertBlock(root, forward, rootBlockName, attrs);
        }
      };
      var getClosestTargetBlock = function(pos, root) {
        var isRoot = curry(eq, root);
        return closest$3(SugarElement.fromDom(pos.container()), isBlock$2, isRoot).filter(isTarget);
      };
      var isAtFirstOrLastLine = function(root, forward, pos) {
        return forward ? isAtLastLine(root.dom, pos) : isAtFirstLine(root.dom, pos);
      };
      var moveCaretToNewEmptyLine = function(editor, forward) {
        var root = SugarElement.fromDom(editor.getBody());
        var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
        var rootBlock = getForcedRootBlock(editor);
        var rootBlockAttrs = getForcedRootBlockAttrs(editor);
        return getClosestTargetBlock(pos, root).exists(function() {
          if (isAtFirstOrLastLine(root, forward, pos)) {
            var rng = insertEmptyLine(root, rootBlock, rootBlockAttrs, forward);
            editor.selection.setRng(rng);
            return true;
          } else {
            return false;
          }
        });
      };
      var moveV$2 = function(editor, forward) {
        if (editor.selection.isCollapsed()) {
          return moveCaretToNewEmptyLine(editor, forward);
        } else {
          return false;
        }
      };
      var defaultPatterns = function(patterns) {
        return map$3(patterns, function(pattern) {
          return __assign({
            shiftKey: false,
            altKey: false,
            ctrlKey: false,
            metaKey: false,
            keyCode: 0,
            action: noop
          }, pattern);
        });
      };
      var matchesEvent = function(pattern, evt) {
        return evt.keyCode === pattern.keyCode && evt.shiftKey === pattern.shiftKey && evt.altKey === pattern.altKey && evt.ctrlKey === pattern.ctrlKey && evt.metaKey === pattern.metaKey;
      };
      var match$1 = function(patterns, evt) {
        return bind(defaultPatterns(patterns), function(pattern) {
          return matchesEvent(pattern, evt) ? [pattern] : [];
        });
      };
      var action = function(f) {
        var x = [];
        for (var _i = 1; _i < arguments.length; _i++) {
          x[_i - 1] = arguments[_i];
        }
        return function() {
          return f.apply(null, x);
        };
      };
      var execute = function(patterns, evt) {
        return find$3(match$1(patterns, evt), function(pattern) {
          return pattern.action();
        });
      };
      var moveH$1 = function(editor, forward) {
        var direction = forward ? HDirection.Forwards : HDirection.Backwards;
        var range2 = editor.selection.getRng();
        return moveHorizontally(editor, direction, range2, isBeforeMedia, isAfterMedia, isMedia$2).exists(function(newRange) {
          moveToRange(editor, newRange);
          return true;
        });
      };
      var moveV$1 = function(editor, down) {
        var direction = down ? 1 : -1;
        var range2 = editor.selection.getRng();
        return moveVertically(editor, direction, range2, isBeforeMedia, isAfterMedia, isMedia$2).exists(function(newRange) {
          moveToRange(editor, newRange);
          return true;
        });
      };
      var moveToLineEndPoint = function(editor, forward) {
        var isNearMedia = forward ? isAfterMedia : isBeforeMedia;
        return moveToLineEndPoint$3(editor, forward, isNearMedia);
      };
      var deflate = function(rect, delta) {
        return {
          left: rect.left - delta,
          top: rect.top - delta,
          right: rect.right + delta * 2,
          bottom: rect.bottom + delta * 2,
          width: rect.width + delta,
          height: rect.height + delta
        };
      };
      var getCorners = function(getYAxisValue, tds) {
        return bind(tds, function(td) {
          var rect = deflate(clone(td.getBoundingClientRect()), -1);
          return [
            {
              x: rect.left,
              y: getYAxisValue(rect),
              cell: td
            },
            {
              x: rect.right,
              y: getYAxisValue(rect),
              cell: td
            }
          ];
        });
      };
      var findClosestCorner = function(corners, x, y) {
        return foldl(corners, function(acc, newCorner) {
          return acc.fold(function() {
            return Optional.some(newCorner);
          }, function(oldCorner) {
            var oldDist = Math.sqrt(Math.abs(oldCorner.x - x) + Math.abs(oldCorner.y - y));
            var newDist = Math.sqrt(Math.abs(newCorner.x - x) + Math.abs(newCorner.y - y));
            return Optional.some(newDist < oldDist ? newCorner : oldCorner);
          });
        }, Optional.none());
      };
      var getClosestCell = function(getYAxisValue, isTargetCorner, table, x, y) {
        var cells = descendants(SugarElement.fromDom(table), "td,th,caption").map(function(e) {
          return e.dom;
        });
        var corners = filter$4(getCorners(getYAxisValue, cells), function(corner) {
          return isTargetCorner(corner, y);
        });
        return findClosestCorner(corners, x, y).map(function(corner) {
          return corner.cell;
        });
      };
      var getBottomValue = function(rect) {
        return rect.bottom;
      };
      var getTopValue = function(rect) {
        return rect.top;
      };
      var isAbove = function(corner, y) {
        return corner.y < y;
      };
      var isBelow = function(corner, y) {
        return corner.y > y;
      };
      var getClosestCellAbove = curry(getClosestCell, getBottomValue, isAbove);
      var getClosestCellBelow = curry(getClosestCell, getTopValue, isBelow);
      var findClosestPositionInAboveCell = function(table, pos) {
        return head(pos.getClientRects()).bind(function(rect) {
          return getClosestCellAbove(table, rect.left, rect.top);
        }).bind(function(cell) {
          return findClosestHorizontalPosition(getLastLinePositions(cell), pos);
        });
      };
      var findClosestPositionInBelowCell = function(table, pos) {
        return last$2(pos.getClientRects()).bind(function(rect) {
          return getClosestCellBelow(table, rect.left, rect.top);
        }).bind(function(cell) {
          return findClosestHorizontalPosition(getFirstLinePositions(cell), pos);
        });
      };
      var hasNextBreak = function(getPositionsUntil2, scope, lineInfo) {
        return lineInfo.breakAt.exists(function(breakPos) {
          return getPositionsUntil2(scope, breakPos).breakAt.isSome();
        });
      };
      var startsWithWrapBreak = function(lineInfo) {
        return lineInfo.breakType === BreakType.Wrap && lineInfo.positions.length === 0;
      };
      var startsWithBrBreak = function(lineInfo) {
        return lineInfo.breakType === BreakType.Br && lineInfo.positions.length === 1;
      };
      var isAtTableCellLine = function(getPositionsUntil2, scope, pos) {
        var lineInfo = getPositionsUntil2(scope, pos);
        if (startsWithWrapBreak(lineInfo) || !isBr$5(pos.getNode()) && startsWithBrBreak(lineInfo)) {
          return !hasNextBreak(getPositionsUntil2, scope, lineInfo);
        } else {
          return lineInfo.breakAt.isNone();
        }
      };
      var isAtFirstTableCellLine = curry(isAtTableCellLine, getPositionsUntilPreviousLine);
      var isAtLastTableCellLine = curry(isAtTableCellLine, getPositionsUntilNextLine);
      var isCaretAtStartOrEndOfTable = function(forward, rng, table) {
        var caretPos = CaretPosition.fromRangeStart(rng);
        return positionIn(!forward, table).exists(function(pos) {
          return pos.isEqual(caretPos);
        });
      };
      var navigateHorizontally = function(editor, forward, table, _td) {
        var rng = editor.selection.getRng();
        var direction = forward ? 1 : -1;
        if (isFakeCaretTableBrowser() && isCaretAtStartOrEndOfTable(forward, rng, table)) {
          showCaret(direction, editor, table, !forward, false).each(function(newRng) {
            moveToRange(editor, newRng);
          });
          return true;
        }
        return false;
      };
      var getClosestAbovePosition = function(root, table, start2) {
        return findClosestPositionInAboveCell(table, start2).orThunk(function() {
          return head(start2.getClientRects()).bind(function(rect) {
            return findClosestHorizontalPositionFromPoint(getPositionsAbove(root, CaretPosition.before(table)), rect.left);
          });
        }).getOr(CaretPosition.before(table));
      };
      var getClosestBelowPosition = function(root, table, start2) {
        return findClosestPositionInBelowCell(table, start2).orThunk(function() {
          return head(start2.getClientRects()).bind(function(rect) {
            return findClosestHorizontalPositionFromPoint(getPositionsBelow(root, CaretPosition.after(table)), rect.left);
          });
        }).getOr(CaretPosition.after(table));
      };
      var getTable = function(previous, pos) {
        var node = pos.getNode(previous);
        return isElement$5(node) && node.nodeName === "TABLE" ? Optional.some(node) : Optional.none();
      };
      var renderBlock = function(down, editor, table, pos) {
        var forcedRootBlock = getForcedRootBlock(editor);
        if (forcedRootBlock) {
          editor.undoManager.transact(function() {
            var element = SugarElement.fromTag(forcedRootBlock);
            setAll$1(element, getForcedRootBlockAttrs(editor));
            append$1(element, SugarElement.fromTag("br"));
            if (down) {
              after$3(SugarElement.fromDom(table), element);
            } else {
              before$4(SugarElement.fromDom(table), element);
            }
            var rng = editor.dom.createRng();
            rng.setStart(element.dom, 0);
            rng.setEnd(element.dom, 0);
            moveToRange(editor, rng);
          });
        } else {
          moveToRange(editor, pos.toRange());
        }
      };
      var moveCaret = function(editor, down, pos) {
        var table = down ? getTable(true, pos) : getTable(false, pos);
        var last2 = down === false;
        table.fold(function() {
          return moveToRange(editor, pos.toRange());
        }, function(table2) {
          return positionIn(last2, editor.getBody()).filter(function(lastPos) {
            return lastPos.isEqual(pos);
          }).fold(function() {
            return moveToRange(editor, pos.toRange());
          }, function(_) {
            return renderBlock(down, editor, table2, pos);
          });
        });
      };
      var navigateVertically = function(editor, down, table, td) {
        var rng = editor.selection.getRng();
        var pos = CaretPosition.fromRangeStart(rng);
        var root = editor.getBody();
        if (!down && isAtFirstTableCellLine(td, pos)) {
          var newPos = getClosestAbovePosition(root, table, pos);
          moveCaret(editor, down, newPos);
          return true;
        } else if (down && isAtLastTableCellLine(td, pos)) {
          var newPos = getClosestBelowPosition(root, table, pos);
          moveCaret(editor, down, newPos);
          return true;
        } else {
          return false;
        }
      };
      var move$1 = function(editor, forward, mover) {
        return Optional.from(editor.dom.getParent(editor.selection.getNode(), "td,th")).bind(function(td) {
          return Optional.from(editor.dom.getParent(td, "table")).map(function(table) {
            return mover(editor, forward, table, td);
          });
        }).getOr(false);
      };
      var moveH = function(editor, forward) {
        return move$1(editor, forward, navigateHorizontally);
      };
      var moveV = function(editor, forward) {
        return move$1(editor, forward, navigateVertically);
      };
      var executeKeydownOverride$3 = function(editor, caret, evt) {
        var os2 = detect().os;
        execute([
          {
            keyCode: VK.RIGHT,
            action: action(moveH$2, editor, true)
          },
          {
            keyCode: VK.LEFT,
            action: action(moveH$2, editor, false)
          },
          {
            keyCode: VK.UP,
            action: action(moveV$3, editor, false)
          },
          {
            keyCode: VK.DOWN,
            action: action(moveV$3, editor, true)
          },
          {
            keyCode: VK.RIGHT,
            action: action(moveH, editor, true)
          },
          {
            keyCode: VK.LEFT,
            action: action(moveH, editor, false)
          },
          {
            keyCode: VK.UP,
            action: action(moveV, editor, false)
          },
          {
            keyCode: VK.DOWN,
            action: action(moveV, editor, true)
          },
          {
            keyCode: VK.RIGHT,
            action: action(moveH$1, editor, true)
          },
          {
            keyCode: VK.LEFT,
            action: action(moveH$1, editor, false)
          },
          {
            keyCode: VK.UP,
            action: action(moveV$1, editor, false)
          },
          {
            keyCode: VK.DOWN,
            action: action(moveV$1, editor, true)
          },
          {
            keyCode: VK.RIGHT,
            action: action(move$2, editor, caret, true)
          },
          {
            keyCode: VK.LEFT,
            action: action(move$2, editor, caret, false)
          },
          {
            keyCode: VK.RIGHT,
            ctrlKey: !os2.isOSX(),
            altKey: os2.isOSX(),
            action: action(moveNextWord, editor, caret)
          },
          {
            keyCode: VK.LEFT,
            ctrlKey: !os2.isOSX(),
            altKey: os2.isOSX(),
            action: action(movePrevWord, editor, caret)
          },
          {
            keyCode: VK.UP,
            action: action(moveV$2, editor, false)
          },
          {
            keyCode: VK.DOWN,
            action: action(moveV$2, editor, true)
          }
        ], evt).each(function(_) {
          evt.preventDefault();
        });
      };
      var setup$b = function(editor, caret) {
        editor.on("keydown", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeydownOverride$3(editor, caret, evt);
          }
        });
      };
      var executeKeydownOverride$2 = function(editor, caret, evt) {
        execute([
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete, editor, false)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$5, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$5, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$6, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$6, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$3, editor, caret, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$3, editor, caret, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$9, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$9, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$4, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$4, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$1, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$1, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$7, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$7, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$8, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$8, editor, true)
          },
          {
            keyCode: VK.BACKSPACE,
            action: action(backspaceDelete$2, editor, false)
          },
          {
            keyCode: VK.DELETE,
            action: action(backspaceDelete$2, editor, true)
          }
        ], evt).each(function(_) {
          evt.preventDefault();
        });
      };
      var executeKeyupOverride = function(editor, evt) {
        execute([
          {
            keyCode: VK.BACKSPACE,
            action: action(paddEmptyElement, editor)
          },
          {
            keyCode: VK.DELETE,
            action: action(paddEmptyElement, editor)
          }
        ], evt);
      };
      var setup$a = function(editor, caret) {
        editor.on("keydown", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeydownOverride$2(editor, caret, evt);
          }
        });
        editor.on("keyup", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeyupOverride(editor, evt);
          }
        });
      };
      var firstNonWhiteSpaceNodeSibling = function(node) {
        while (node) {
          if (node.nodeType === 1 || node.nodeType === 3 && node.data && /[\r\n\s]/.test(node.data)) {
            return node;
          }
          node = node.nextSibling;
        }
      };
      var moveToCaretPosition = function(editor, root) {
        var node, lastNode = root;
        var dom2 = editor.dom;
        var moveCaretBeforeOnEnterElementsMap = editor.schema.getMoveCaretBeforeOnEnterElements();
        if (!root) {
          return;
        }
        if (/^(LI|DT|DD)$/.test(root.nodeName)) {
          var firstChild2 = firstNonWhiteSpaceNodeSibling(root.firstChild);
          if (firstChild2 && /^(UL|OL|DL)$/.test(firstChild2.nodeName)) {
            root.insertBefore(dom2.doc.createTextNode(nbsp), root.firstChild);
          }
        }
        var rng = dom2.createRng();
        root.normalize();
        if (root.hasChildNodes()) {
          var walker = new DomTreeWalker(root, root);
          while (node = walker.current()) {
            if (isText$7(node)) {
              rng.setStart(node, 0);
              rng.setEnd(node, 0);
              break;
            }
            if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) {
              rng.setStartBefore(node);
              rng.setEndBefore(node);
              break;
            }
            lastNode = node;
            node = walker.next();
          }
          if (!node) {
            rng.setStart(lastNode, 0);
            rng.setEnd(lastNode, 0);
          }
        } else {
          if (isBr$5(root)) {
            if (root.nextSibling && dom2.isBlock(root.nextSibling)) {
              rng.setStartBefore(root);
              rng.setEndBefore(root);
            } else {
              rng.setStartAfter(root);
              rng.setEndAfter(root);
            }
          } else {
            rng.setStart(root, 0);
            rng.setEnd(root, 0);
          }
        }
        editor.selection.setRng(rng);
        scrollRangeIntoView(editor, rng);
      };
      var getEditableRoot$1 = function(dom2, node) {
        var root = dom2.getRoot();
        var parent2, editableRoot;
        parent2 = node;
        while (parent2 !== root && dom2.getContentEditable(parent2) !== "false") {
          if (dom2.getContentEditable(parent2) === "true") {
            editableRoot = parent2;
          }
          parent2 = parent2.parentNode;
        }
        return parent2 !== root ? editableRoot : root;
      };
      var getParentBlock = function(editor) {
        return Optional.from(editor.dom.getParent(editor.selection.getStart(true), editor.dom.isBlock));
      };
      var getParentBlockName = function(editor) {
        return getParentBlock(editor).fold(constant(""), function(parentBlock) {
          return parentBlock.nodeName.toUpperCase();
        });
      };
      var isListItemParentBlock = function(editor) {
        return getParentBlock(editor).filter(function(elm) {
          return isListItem(SugarElement.fromDom(elm));
        }).isSome();
      };
      var hasFirstChild = function(elm, name2) {
        return elm.firstChild && elm.firstChild.nodeName === name2;
      };
      var isFirstChild = function(elm) {
        var _a;
        return ((_a = elm.parentNode) === null || _a === void 0 ? void 0 : _a.firstChild) === elm;
      };
      var hasParent = function(elm, parentName) {
        return elm && elm.parentNode && elm.parentNode.nodeName === parentName;
      };
      var isListBlock = function(elm) {
        return elm && /^(OL|UL|LI)$/.test(elm.nodeName);
      };
      var isNestedList = function(elm) {
        return isListBlock(elm) && isListBlock(elm.parentNode);
      };
      var getContainerBlock = function(containerBlock) {
        var containerBlockParent = containerBlock.parentNode;
        if (/^(LI|DT|DD)$/.test(containerBlockParent.nodeName)) {
          return containerBlockParent;
        }
        return containerBlock;
      };
      var isFirstOrLastLi = function(containerBlock, parentBlock, first2) {
        var node = containerBlock[first2 ? "firstChild" : "lastChild"];
        while (node) {
          if (isElement$5(node)) {
            break;
          }
          node = node[first2 ? "nextSibling" : "previousSibling"];
        }
        return node === parentBlock;
      };
      var insert$3 = function(editor, createNewBlock, containerBlock, parentBlock, newBlockName) {
        var dom2 = editor.dom;
        var rng = editor.selection.getRng();
        if (containerBlock === editor.getBody()) {
          return;
        }
        if (isNestedList(containerBlock)) {
          newBlockName = "LI";
        }
        var newBlock = newBlockName ? createNewBlock(newBlockName) : dom2.create("BR");
        if (isFirstOrLastLi(containerBlock, parentBlock, true) && isFirstOrLastLi(containerBlock, parentBlock, false)) {
          if (hasParent(containerBlock, "LI")) {
            var containerBlockParent = getContainerBlock(containerBlock);
            dom2.insertAfter(newBlock, containerBlockParent);
            if (isFirstChild(containerBlock)) {
              dom2.remove(containerBlockParent);
            } else {
              dom2.remove(containerBlock);
            }
          } else {
            dom2.replace(newBlock, containerBlock);
          }
        } else if (isFirstOrLastLi(containerBlock, parentBlock, true)) {
          if (hasParent(containerBlock, "LI")) {
            dom2.insertAfter(newBlock, getContainerBlock(containerBlock));
            newBlock.appendChild(dom2.doc.createTextNode(" "));
            newBlock.appendChild(containerBlock);
          } else {
            containerBlock.parentNode.insertBefore(newBlock, containerBlock);
          }
          dom2.remove(parentBlock);
        } else if (isFirstOrLastLi(containerBlock, parentBlock, false)) {
          dom2.insertAfter(newBlock, getContainerBlock(containerBlock));
          dom2.remove(parentBlock);
        } else {
          containerBlock = getContainerBlock(containerBlock);
          var tmpRng = rng.cloneRange();
          tmpRng.setStartAfter(parentBlock);
          tmpRng.setEndAfter(containerBlock);
          var fragment = tmpRng.extractContents();
          if (newBlockName === "LI" && hasFirstChild(fragment, "LI")) {
            newBlock = fragment.firstChild;
            dom2.insertAfter(fragment, containerBlock);
          } else {
            dom2.insertAfter(fragment, containerBlock);
            dom2.insertAfter(newBlock, containerBlock);
          }
          dom2.remove(parentBlock);
        }
        moveToCaretPosition(editor, newBlock);
      };
      var trimZwsp = function(fragment) {
        each$k(descendants$1(SugarElement.fromDom(fragment), isText$8), function(text) {
          var rawNode = text.dom;
          rawNode.nodeValue = trim$2(rawNode.nodeValue);
        });
      };
      var isEmptyAnchor = function(dom2, elm) {
        return elm && elm.nodeName === "A" && dom2.isEmpty(elm);
      };
      var isTableCell = function(node) {
        return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
      };
      var emptyBlock = function(elm) {
        elm.innerHTML = '<br data-mce-bogus="1">';
      };
      var containerAndSiblingName = function(container, nodeName) {
        return container.nodeName === nodeName || container.previousSibling && container.previousSibling.nodeName === nodeName;
      };
      var canSplitBlock = function(dom2, node) {
        return node && dom2.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom2.getContentEditable(node) !== "true";
      };
      var trimInlineElementsOnLeftSideOfBlock = function(dom2, nonEmptyElementsMap, block) {
        var node = block;
        var firstChilds = [];
        var i;
        if (!node) {
          return;
        }
        while (node = node.firstChild) {
          if (dom2.isBlock(node)) {
            return;
          }
          if (isElement$5(node) && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
            firstChilds.push(node);
          }
        }
        i = firstChilds.length;
        while (i--) {
          node = firstChilds[i];
          if (!node.hasChildNodes() || node.firstChild === node.lastChild && node.firstChild.nodeValue === "") {
            dom2.remove(node);
          } else {
            if (isEmptyAnchor(dom2, node)) {
              dom2.remove(node);
            }
          }
        }
      };
      var normalizeZwspOffset = function(start2, container, offset) {
        if (isText$7(container) === false) {
          return offset;
        } else if (start2) {
          return offset === 1 && container.data.charAt(offset - 1) === ZWSP$1 ? 0 : offset;
        } else {
          return offset === container.data.length - 1 && container.data.charAt(offset) === ZWSP$1 ? container.data.length : offset;
        }
      };
      var includeZwspInRange = function(rng) {
        var newRng = rng.cloneRange();
        newRng.setStart(rng.startContainer, normalizeZwspOffset(true, rng.startContainer, rng.startOffset));
        newRng.setEnd(rng.endContainer, normalizeZwspOffset(false, rng.endContainer, rng.endOffset));
        return newRng;
      };
      var trimLeadingLineBreaks = function(node) {
        do {
          if (isText$7(node)) {
            node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, "");
          }
          node = node.firstChild;
        } while (node);
      };
      var getEditableRoot = function(dom2, node) {
        var root = dom2.getRoot();
        var parent2, editableRoot;
        parent2 = node;
        while (parent2 !== root && dom2.getContentEditable(parent2) !== "false") {
          if (dom2.getContentEditable(parent2) === "true") {
            editableRoot = parent2;
          }
          parent2 = parent2.parentNode;
        }
        return parent2 !== root ? editableRoot : root;
      };
      var applyAttributes = function(editor, node, forcedRootBlockAttrs) {
        var dom2 = editor.dom;
        Optional.from(forcedRootBlockAttrs.style).map(dom2.parseStyle).each(function(attrStyles) {
          var currentStyles = getAllRaw(SugarElement.fromDom(node));
          var newStyles = __assign(__assign({}, currentStyles), attrStyles);
          dom2.setStyles(node, newStyles);
        });
        var attrClassesOpt = Optional.from(forcedRootBlockAttrs.class).map(function(attrClasses) {
          return attrClasses.split(/\s+/);
        });
        var currentClassesOpt = Optional.from(node.className).map(function(currentClasses) {
          return filter$4(currentClasses.split(/\s+/), function(clazz) {
            return clazz !== "";
          });
        });
        lift2(attrClassesOpt, currentClassesOpt, function(attrClasses, currentClasses) {
          var filteredClasses = filter$4(currentClasses, function(clazz) {
            return !contains$3(attrClasses, clazz);
          });
          var newClasses = __spreadArray(__spreadArray([], attrClasses, true), filteredClasses, true);
          dom2.setAttrib(node, "class", newClasses.join(" "));
        });
        var appliedAttrs = [
          "style",
          "class"
        ];
        var remainingAttrs = filter$3(forcedRootBlockAttrs, function(_, attrs) {
          return !contains$3(appliedAttrs, attrs);
        });
        dom2.setAttribs(node, remainingAttrs);
      };
      var setForcedBlockAttrs = function(editor, node) {
        var forcedRootBlockName = getForcedRootBlock(editor);
        if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
          var forcedRootBlockAttrs = getForcedRootBlockAttrs(editor);
          applyAttributes(editor, node, forcedRootBlockAttrs);
        }
      };
      var wrapSelfAndSiblingsInDefaultBlock = function(editor, newBlockName, rng, container, offset) {
        var newBlock, parentBlock, startNode, node, next, rootBlockName;
        var blockName = newBlockName || "P";
        var dom2 = editor.dom, editableRoot = getEditableRoot(dom2, container);
        parentBlock = dom2.getParent(container, dom2.isBlock);
        if (!parentBlock || !canSplitBlock(dom2, parentBlock)) {
          parentBlock = parentBlock || editableRoot;
          if (parentBlock === editor.getBody() || isTableCell(parentBlock)) {
            rootBlockName = parentBlock.nodeName.toLowerCase();
          } else {
            rootBlockName = parentBlock.parentNode.nodeName.toLowerCase();
          }
          if (!parentBlock.hasChildNodes()) {
            newBlock = dom2.create(blockName);
            setForcedBlockAttrs(editor, newBlock);
            parentBlock.appendChild(newBlock);
            rng.setStart(newBlock, 0);
            rng.setEnd(newBlock, 0);
            return newBlock;
          }
          node = container;
          while (node.parentNode !== parentBlock) {
            node = node.parentNode;
          }
          while (node && !dom2.isBlock(node)) {
            startNode = node;
            node = node.previousSibling;
          }
          if (startNode && editor.schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
            newBlock = dom2.create(blockName);
            setForcedBlockAttrs(editor, newBlock);
            startNode.parentNode.insertBefore(newBlock, startNode);
            node = startNode;
            while (node && !dom2.isBlock(node)) {
              next = node.nextSibling;
              newBlock.appendChild(node);
              node = next;
            }
            rng.setStart(container, offset);
            rng.setEnd(container, offset);
          }
        }
        return container;
      };
      var addBrToBlockIfNeeded = function(dom2, block) {
        block.normalize();
        var lastChild2 = block.lastChild;
        if (!lastChild2 || /^(left|right)$/gi.test(dom2.getStyle(lastChild2, "float", true))) {
          dom2.add(block, "br");
        }
      };
      var insert$2 = function(editor, evt) {
        var tmpRng, container, offset, parentBlock;
        var newBlock, fragment, containerBlock, parentBlockName, newBlockName, isAfterLastNodeInContainer;
        var dom2 = editor.dom;
        var schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
        var rng = editor.selection.getRng();
        var createNewBlock = function(name2) {
          var node = container, block, clonedNode, caretNode;
          var textInlineElements = schema.getTextInlineElements();
          if (name2 || parentBlockName === "TABLE" || parentBlockName === "HR") {
            block = dom2.create(name2 || newBlockName);
          } else {
            block = parentBlock.cloneNode(false);
          }
          caretNode = block;
          if (shouldKeepStyles(editor) === false) {
            dom2.setAttrib(block, "style", null);
            dom2.setAttrib(block, "class", null);
          } else {
            do {
              if (textInlineElements[node.nodeName]) {
                if (isCaretNode(node) || isBookmarkNode$1(node)) {
                  continue;
                }
                clonedNode = node.cloneNode(false);
                dom2.setAttrib(clonedNode, "id", "");
                if (block.hasChildNodes()) {
                  clonedNode.appendChild(block.firstChild);
                  block.appendChild(clonedNode);
                } else {
                  caretNode = clonedNode;
                  block.appendChild(clonedNode);
                }
              }
            } while ((node = node.parentNode) && node !== editableRoot);
          }
          setForcedBlockAttrs(editor, block);
          emptyBlock(caretNode);
          return block;
        };
        var isCaretAtStartOrEndOfBlock = function(start2) {
          var node, name2;
          var normalizedOffset = normalizeZwspOffset(start2, container, offset);
          if (isText$7(container) && (start2 ? normalizedOffset > 0 : normalizedOffset < container.nodeValue.length)) {
            return false;
          }
          if (container.parentNode === parentBlock && isAfterLastNodeInContainer && !start2) {
            return true;
          }
          if (start2 && isElement$5(container) && container === parentBlock.firstChild) {
            return true;
          }
          if (containerAndSiblingName(container, "TABLE") || containerAndSiblingName(container, "HR")) {
            return isAfterLastNodeInContainer && !start2 || !isAfterLastNodeInContainer && start2;
          }
          var walker = new DomTreeWalker(container, parentBlock);
          if (isText$7(container)) {
            if (start2 && normalizedOffset === 0) {
              walker.prev();
            } else if (!start2 && normalizedOffset === container.nodeValue.length) {
              walker.next();
            }
          }
          while (node = walker.current()) {
            if (isElement$5(node)) {
              if (!node.getAttribute("data-mce-bogus")) {
                name2 = node.nodeName.toLowerCase();
                if (nonEmptyElementsMap[name2] && name2 !== "br") {
                  return false;
                }
              }
            } else if (isText$7(node) && !isWhitespaceText(node.nodeValue)) {
              return false;
            }
            if (start2) {
              walker.prev();
            } else {
              walker.next();
            }
          }
          return true;
        };
        var insertNewBlockAfter = function() {
          if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName !== "HGROUP") {
            newBlock = createNewBlock(newBlockName);
          } else {
            newBlock = createNewBlock();
          }
          if (shouldEndContainerOnEmptyBlock(editor) && canSplitBlock(dom2, containerBlock) && dom2.isEmpty(parentBlock)) {
            newBlock = dom2.split(containerBlock, parentBlock);
          } else {
            dom2.insertAfter(newBlock, parentBlock);
          }
          moveToCaretPosition(editor, newBlock);
        };
        normalize$2(dom2, rng).each(function(normRng) {
          rng.setStart(normRng.startContainer, normRng.startOffset);
          rng.setEnd(normRng.endContainer, normRng.endOffset);
        });
        container = rng.startContainer;
        offset = rng.startOffset;
        newBlockName = getForcedRootBlock(editor);
        var shiftKey = !!(evt && evt.shiftKey);
        var ctrlKey = !!(evt && evt.ctrlKey);
        if (isElement$5(container) && container.hasChildNodes()) {
          isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
          container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
          if (isAfterLastNodeInContainer && isText$7(container)) {
            offset = container.nodeValue.length;
          } else {
            offset = 0;
          }
        }
        var editableRoot = getEditableRoot(dom2, container);
        if (!editableRoot) {
          return;
        }
        if (newBlockName && !shiftKey || !newBlockName && shiftKey) {
          container = wrapSelfAndSiblingsInDefaultBlock(editor, newBlockName, rng, container, offset);
        }
        parentBlock = dom2.getParent(container, dom2.isBlock);
        containerBlock = parentBlock ? dom2.getParent(parentBlock.parentNode, dom2.isBlock) : null;
        parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : "";
        var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : "";
        if (containerBlockName === "LI" && !ctrlKey) {
          parentBlock = containerBlock;
          containerBlock = containerBlock.parentNode;
          parentBlockName = containerBlockName;
        }
        if (/^(LI|DT|DD)$/.test(parentBlockName)) {
          if (dom2.isEmpty(parentBlock)) {
            insert$3(editor, createNewBlock, containerBlock, parentBlock, newBlockName);
            return;
          }
        }
        if (newBlockName && parentBlock === editor.getBody()) {
          return;
        }
        newBlockName = newBlockName || "P";
        if (isCaretContainerBlock$1(parentBlock)) {
          newBlock = showCaretContainerBlock(parentBlock);
          if (dom2.isEmpty(parentBlock)) {
            emptyBlock(parentBlock);
          }
          setForcedBlockAttrs(editor, newBlock);
          moveToCaretPosition(editor, newBlock);
        } else if (isCaretAtStartOrEndOfBlock()) {
          insertNewBlockAfter();
        } else if (isCaretAtStartOrEndOfBlock(true)) {
          newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
          moveToCaretPosition(editor, containerAndSiblingName(parentBlock, "HR") ? newBlock : parentBlock);
        } else {
          tmpRng = includeZwspInRange(rng).cloneRange();
          tmpRng.setEndAfter(parentBlock);
          fragment = tmpRng.extractContents();
          trimZwsp(fragment);
          trimLeadingLineBreaks(fragment);
          newBlock = fragment.firstChild;
          dom2.insertAfter(fragment, parentBlock);
          trimInlineElementsOnLeftSideOfBlock(dom2, nonEmptyElementsMap, newBlock);
          addBrToBlockIfNeeded(dom2, parentBlock);
          if (dom2.isEmpty(parentBlock)) {
            emptyBlock(parentBlock);
          }
          newBlock.normalize();
          if (dom2.isEmpty(newBlock)) {
            dom2.remove(newBlock);
            insertNewBlockAfter();
          } else {
            setForcedBlockAttrs(editor, newBlock);
            moveToCaretPosition(editor, newBlock);
          }
        }
        dom2.setAttrib(newBlock, "id", "");
        editor.fire("NewBlock", { newBlock });
      };
      var hasRightSideContent = function(schema, container, parentBlock) {
        var walker = new DomTreeWalker(container, parentBlock);
        var node;
        var nonEmptyElementsMap = schema.getNonEmptyElements();
        while (node = walker.next()) {
          if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
            return true;
          }
        }
      };
      var moveSelectionToBr = function(editor, brElm, extraBr) {
        var rng = editor.dom.createRng();
        if (!extraBr) {
          rng.setStartAfter(brElm);
          rng.setEndAfter(brElm);
        } else {
          rng.setStartBefore(brElm);
          rng.setEndBefore(brElm);
        }
        editor.selection.setRng(rng);
        scrollRangeIntoView(editor, rng);
      };
      var insertBrAtCaret = function(editor, evt) {
        var selection = editor.selection;
        var dom2 = editor.dom;
        var rng = selection.getRng();
        var brElm;
        var extraBr;
        normalize$2(dom2, rng).each(function(normRng) {
          rng.setStart(normRng.startContainer, normRng.startOffset);
          rng.setEnd(normRng.endContainer, normRng.endOffset);
        });
        var offset = rng.startOffset;
        var container = rng.startContainer;
        if (container.nodeType === 1 && container.hasChildNodes()) {
          var isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
          container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
          if (isAfterLastNodeInContainer && container.nodeType === 3) {
            offset = container.nodeValue.length;
          } else {
            offset = 0;
          }
        }
        var parentBlock = dom2.getParent(container, dom2.isBlock);
        var containerBlock = parentBlock ? dom2.getParent(parentBlock.parentNode, dom2.isBlock) : null;
        var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : "";
        var isControlKey = !!(evt && evt.ctrlKey);
        if (containerBlockName === "LI" && !isControlKey) {
          parentBlock = containerBlock;
        }
        if (container && container.nodeType === 3 && offset >= container.nodeValue.length) {
          if (!hasRightSideContent(editor.schema, container, parentBlock)) {
            brElm = dom2.create("br");
            rng.insertNode(brElm);
            rng.setStartAfter(brElm);
            rng.setEndAfter(brElm);
            extraBr = true;
          }
        }
        brElm = dom2.create("br");
        rangeInsertNode(dom2, rng, brElm);
        moveSelectionToBr(editor, brElm, extraBr);
        editor.undoManager.add();
      };
      var insertBrBefore = function(editor, inline) {
        var br = SugarElement.fromTag("br");
        before$4(SugarElement.fromDom(inline), br);
        editor.undoManager.add();
      };
      var insertBrAfter = function(editor, inline) {
        if (!hasBrAfter(editor.getBody(), inline)) {
          after$3(SugarElement.fromDom(inline), SugarElement.fromTag("br"));
        }
        var br = SugarElement.fromTag("br");
        after$3(SugarElement.fromDom(inline), br);
        moveSelectionToBr(editor, br.dom, false);
        editor.undoManager.add();
      };
      var isBeforeBr = function(pos) {
        return isBr$5(pos.getNode());
      };
      var hasBrAfter = function(rootNode, startNode) {
        if (isBeforeBr(CaretPosition.after(startNode))) {
          return true;
        } else {
          return nextPosition(rootNode, CaretPosition.after(startNode)).map(function(pos) {
            return isBr$5(pos.getNode());
          }).getOr(false);
        }
      };
      var isAnchorLink = function(elm) {
        return elm && elm.nodeName === "A" && "href" in elm;
      };
      var isInsideAnchor = function(location) {
        return location.fold(never, isAnchorLink, isAnchorLink, never);
      };
      var readInlineAnchorLocation = function(editor) {
        var isInlineTarget$1 = curry(isInlineTarget, editor);
        var position = CaretPosition.fromRangeStart(editor.selection.getRng());
        return readLocation(isInlineTarget$1, editor.getBody(), position).filter(isInsideAnchor);
      };
      var insertBrOutsideAnchor = function(editor, location) {
        location.fold(noop, curry(insertBrBefore, editor), curry(insertBrAfter, editor), noop);
      };
      var insert$1 = function(editor, evt) {
        var anchorLocation = readInlineAnchorLocation(editor);
        if (anchorLocation.isSome()) {
          anchorLocation.each(curry(insertBrOutsideAnchor, editor));
        } else {
          insertBrAtCaret(editor, evt);
        }
      };
      var matchesSelector = function(editor, selector) {
        return getParentBlock(editor).filter(function(parentBlock) {
          return selector.length > 0 && is$2(SugarElement.fromDom(parentBlock), selector);
        }).isSome();
      };
      var shouldInsertBr = function(editor) {
        return matchesSelector(editor, getBrNewLineSelector(editor));
      };
      var shouldBlockNewLine$1 = function(editor) {
        return matchesSelector(editor, getNoNewLineSelector(editor));
      };
      var newLineAction = Adt.generate([
        { br: [] },
        { block: [] },
        { none: [] }
      ]);
      var shouldBlockNewLine = function(editor, _shiftKey) {
        return shouldBlockNewLine$1(editor);
      };
      var isBrMode = function(requiredState) {
        return function(editor, _shiftKey) {
          var brMode = getForcedRootBlock(editor) === "";
          return brMode === requiredState;
        };
      };
      var inListBlock = function(requiredState) {
        return function(editor, _shiftKey) {
          return isListItemParentBlock(editor) === requiredState;
        };
      };
      var inBlock = function(blockName, requiredState) {
        return function(editor, _shiftKey) {
          var state = getParentBlockName(editor) === blockName.toUpperCase();
          return state === requiredState;
        };
      };
      var inPreBlock = function(requiredState) {
        return inBlock("pre", requiredState);
      };
      var inSummaryBlock = function() {
        return inBlock("summary", true);
      };
      var shouldPutBrInPre = function(requiredState) {
        return function(editor, _shiftKey) {
          return shouldPutBrInPre$1(editor) === requiredState;
        };
      };
      var inBrContext = function(editor, _shiftKey) {
        return shouldInsertBr(editor);
      };
      var hasShiftKey = function(_editor, shiftKey) {
        return shiftKey;
      };
      var canInsertIntoEditableRoot = function(editor) {
        var forcedRootBlock = getForcedRootBlock(editor);
        var rootEditable = getEditableRoot$1(editor.dom, editor.selection.getStart());
        return rootEditable && editor.schema.isValidChild(rootEditable.nodeName, forcedRootBlock ? forcedRootBlock : "P");
      };
      var match = function(predicates, action2) {
        return function(editor, shiftKey) {
          var isMatch = foldl(predicates, function(res, p) {
            return res && p(editor, shiftKey);
          }, true);
          return isMatch ? Optional.some(action2) : Optional.none();
        };
      };
      var getAction = function(editor, evt) {
        return evaluateUntil([
          match([shouldBlockNewLine], newLineAction.none()),
          match([inSummaryBlock()], newLineAction.br()),
          match([
            inPreBlock(true),
            shouldPutBrInPre(false),
            hasShiftKey
          ], newLineAction.br()),
          match([
            inPreBlock(true),
            shouldPutBrInPre(false)
          ], newLineAction.block()),
          match([
            inPreBlock(true),
            shouldPutBrInPre(true),
            hasShiftKey
          ], newLineAction.block()),
          match([
            inPreBlock(true),
            shouldPutBrInPre(true)
          ], newLineAction.br()),
          match([
            inListBlock(true),
            hasShiftKey
          ], newLineAction.br()),
          match([inListBlock(true)], newLineAction.block()),
          match([
            isBrMode(true),
            hasShiftKey,
            canInsertIntoEditableRoot
          ], newLineAction.block()),
          match([isBrMode(true)], newLineAction.br()),
          match([inBrContext], newLineAction.br()),
          match([
            isBrMode(false),
            hasShiftKey
          ], newLineAction.br()),
          match([canInsertIntoEditableRoot], newLineAction.block())
        ], [
          editor,
          !!(evt && evt.shiftKey)
        ]).getOr(newLineAction.none());
      };
      var insert = function(editor, evt) {
        getAction(editor, evt).fold(function() {
          insert$1(editor, evt);
        }, function() {
          insert$2(editor, evt);
        }, noop);
      };
      var handleEnterKeyEvent = function(editor, event) {
        if (event.isDefaultPrevented()) {
          return;
        }
        event.preventDefault();
        endTypingLevelIgnoreLocks(editor.undoManager);
        editor.undoManager.transact(function() {
          if (editor.selection.isCollapsed() === false) {
            editor.execCommand("Delete");
          }
          insert(editor, event);
        });
      };
      var setup$9 = function(editor) {
        editor.on("keydown", function(event) {
          if (event.keyCode === VK.ENTER) {
            handleEnterKeyEvent(editor, event);
          }
        });
      };
      var executeKeydownOverride$1 = function(editor, caret, evt) {
        execute([
          {
            keyCode: VK.END,
            action: action(moveToLineEndPoint$1, editor, true)
          },
          {
            keyCode: VK.HOME,
            action: action(moveToLineEndPoint$1, editor, false)
          },
          {
            keyCode: VK.END,
            action: action(moveToLineEndPoint, editor, true)
          },
          {
            keyCode: VK.HOME,
            action: action(moveToLineEndPoint, editor, false)
          },
          {
            keyCode: VK.END,
            action: action(moveToLineEndPoint$2, editor, true, caret)
          },
          {
            keyCode: VK.HOME,
            action: action(moveToLineEndPoint$2, editor, false, caret)
          }
        ], evt).each(function(_) {
          evt.preventDefault();
        });
      };
      var setup$8 = function(editor, caret) {
        editor.on("keydown", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeydownOverride$1(editor, caret, evt);
          }
        });
      };
      var browser = detect().browser;
      var setupIeInput = function(editor) {
        var keypressThrotter = first(function() {
          if (!editor.composing) {
            normalizeNbspsInEditor(editor);
          }
        }, 0);
        if (browser.isIE()) {
          editor.on("keypress", function(_e) {
            keypressThrotter.throttle();
          });
          editor.on("remove", function(_e) {
            keypressThrotter.cancel();
          });
        }
      };
      var setup$7 = function(editor) {
        setupIeInput(editor);
        editor.on("input", function(e) {
          if (e.isComposing === false) {
            normalizeNbspsInEditor(editor);
          }
        });
      };
      var platform = detect();
      var executeKeyupAction = function(editor, caret, evt) {
        execute([
          {
            keyCode: VK.PAGE_UP,
            action: action(moveToLineEndPoint$2, editor, false, caret)
          },
          {
            keyCode: VK.PAGE_DOWN,
            action: action(moveToLineEndPoint$2, editor, true, caret)
          }
        ], evt);
      };
      var stopImmediatePropagation = function(e) {
        return e.stopImmediatePropagation();
      };
      var isPageUpDown = function(evt) {
        return evt.keyCode === VK.PAGE_UP || evt.keyCode === VK.PAGE_DOWN;
      };
      var setNodeChangeBlocker = function(blocked, editor, block) {
        if (block && !blocked.get()) {
          editor.on("NodeChange", stopImmediatePropagation, true);
        } else if (!block && blocked.get()) {
          editor.off("NodeChange", stopImmediatePropagation);
        }
        blocked.set(block);
      };
      var setup$6 = function(editor, caret) {
        if (platform.os.isOSX()) {
          return;
        }
        var blocked = Cell(false);
        editor.on("keydown", function(evt) {
          if (isPageUpDown(evt)) {
            setNodeChangeBlocker(blocked, editor, true);
          }
        });
        editor.on("keyup", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeyupAction(editor, caret, evt);
          }
          if (isPageUpDown(evt) && blocked.get()) {
            setNodeChangeBlocker(blocked, editor, false);
            editor.nodeChanged();
          }
        });
      };
      var insertTextAtPosition = function(text, pos) {
        var container = pos.container();
        var offset = pos.offset();
        if (isText$7(container)) {
          container.insertData(offset, text);
          return Optional.some(CaretPosition(container, offset + text.length));
        } else {
          return getElementFromPosition(pos).map(function(elm) {
            var textNode = SugarElement.fromText(text);
            if (pos.isAtEnd()) {
              after$3(elm, textNode);
            } else {
              before$4(elm, textNode);
            }
            return CaretPosition(textNode.dom, text.length);
          });
        }
      };
      var insertNbspAtPosition = curry(insertTextAtPosition, nbsp);
      var insertSpaceAtPosition = curry(insertTextAtPosition, " ");
      var locationToCaretPosition = function(root) {
        return function(location) {
          return location.fold(function(element) {
            return prevPosition(root.dom, CaretPosition.before(element));
          }, function(element) {
            return firstPositionIn(element);
          }, function(element) {
            return lastPositionIn(element);
          }, function(element) {
            return nextPosition(root.dom, CaretPosition.after(element));
          });
        };
      };
      var insertInlineBoundarySpaceOrNbsp = function(root, pos) {
        return function(checkPos) {
          return needsToHaveNbsp(root, checkPos) ? insertNbspAtPosition(pos) : insertSpaceAtPosition(pos);
        };
      };
      var setSelection = function(editor) {
        return function(pos) {
          editor.selection.setRng(pos.toRange());
          editor.nodeChanged();
          return true;
        };
      };
      var insertSpaceOrNbspAtSelection = function(editor) {
        var pos = CaretPosition.fromRangeStart(editor.selection.getRng());
        var root = SugarElement.fromDom(editor.getBody());
        if (editor.selection.isCollapsed()) {
          var isInlineTarget$1 = curry(isInlineTarget, editor);
          var caretPosition = CaretPosition.fromRangeStart(editor.selection.getRng());
          return readLocation(isInlineTarget$1, editor.getBody(), caretPosition).bind(locationToCaretPosition(root)).bind(insertInlineBoundarySpaceOrNbsp(root, pos)).exists(setSelection(editor));
        } else {
          return false;
        }
      };
      var executeKeydownOverride = function(editor, evt) {
        execute([{
          keyCode: VK.SPACEBAR,
          action: action(insertSpaceOrNbspAtSelection, editor)
        }], evt).each(function(_) {
          evt.preventDefault();
        });
      };
      var setup$5 = function(editor) {
        editor.on("keydown", function(evt) {
          if (evt.isDefaultPrevented() === false) {
            executeKeydownOverride(editor, evt);
          }
        });
      };
      var registerKeyboardOverrides = function(editor) {
        var caret = setupSelectedState(editor);
        setup$c(editor);
        setup$b(editor, caret);
        setup$a(editor, caret);
        setup$9(editor);
        setup$5(editor);
        setup$7(editor);
        setup$8(editor, caret);
        setup$6(editor, caret);
        return caret;
      };
      var setup$4 = function(editor) {
        if (!isRtc(editor)) {
          return registerKeyboardOverrides(editor);
        } else {
          return Cell(null);
        }
      };
      var NodeChange = function() {
        function NodeChange2(editor) {
          this.lastPath = [];
          this.editor = editor;
          var lastRng;
          var self2 = this;
          if (!("onselectionchange" in editor.getDoc())) {
            editor.on("NodeChange click mouseup keyup focus", function(e) {
              var nativeRng = editor.selection.getRng();
              var fakeRng = {
                startContainer: nativeRng.startContainer,
                startOffset: nativeRng.startOffset,
                endContainer: nativeRng.endContainer,
                endOffset: nativeRng.endOffset
              };
              if (e.type === "nodechange" || !isEq$4(fakeRng, lastRng)) {
                editor.fire("SelectionChange");
              }
              lastRng = fakeRng;
            });
          }
          editor.on("contextmenu", function() {
            editor.fire("SelectionChange");
          });
          editor.on("SelectionChange", function() {
            var startElm = editor.selection.getStart(true);
            if (!startElm || !Env.range && editor.selection.isCollapsed()) {
              return;
            }
            if (hasAnyRanges(editor) && !self2.isSameElementPath(startElm) && editor.dom.isChildOf(startElm, editor.getBody())) {
              editor.nodeChanged({ selectionChange: true });
            }
          });
          editor.on("mouseup", function(e) {
            if (!e.isDefaultPrevented() && hasAnyRanges(editor)) {
              if (editor.selection.getNode().nodeName === "IMG") {
                Delay.setEditorTimeout(editor, function() {
                  editor.nodeChanged();
                });
              } else {
                editor.nodeChanged();
              }
            }
          });
        }
        NodeChange2.prototype.nodeChanged = function(args) {
          var selection = this.editor.selection;
          var node, parents2, root;
          if (this.editor.initialized && selection && !shouldDisableNodeChange(this.editor) && !this.editor.mode.isReadOnly()) {
            root = this.editor.getBody();
            node = selection.getStart(true) || root;
            if (node.ownerDocument !== this.editor.getDoc() || !this.editor.dom.isChildOf(node, root)) {
              node = root;
            }
            parents2 = [];
            this.editor.dom.getParent(node, function(node2) {
              if (node2 === root) {
                return true;
              }
              parents2.push(node2);
            });
            args = args || {};
            args.element = node;
            args.parents = parents2;
            this.editor.fire("NodeChange", args);
          }
        };
        NodeChange2.prototype.isSameElementPath = function(startElm) {
          var i;
          var currentPath = this.editor.$(startElm).parentsUntil(this.editor.getBody()).add(startElm);
          if (currentPath.length === this.lastPath.length) {
            for (i = currentPath.length; i >= 0; i--) {
              if (currentPath[i] !== this.lastPath[i]) {
                break;
              }
            }
            if (i === -1) {
              this.lastPath = currentPath;
              return true;
            }
          }
          this.lastPath = currentPath;
          return false;
        };
        return NodeChange2;
      }();
      var preventSummaryToggle = function(editor) {
        editor.on("click", function(e) {
          if (editor.dom.getParent(e.target, "details")) {
            e.preventDefault();
          }
        });
      };
      var filterDetails = function(editor) {
        editor.parser.addNodeFilter("details", function(elms) {
          each$k(elms, function(details) {
            details.attr("data-mce-open", details.attr("open"));
            details.attr("open", "open");
          });
        });
        editor.serializer.addNodeFilter("details", function(elms) {
          each$k(elms, function(details) {
            var open = details.attr("data-mce-open");
            details.attr("open", isString$1(open) ? open : null);
            details.attr("data-mce-open", null);
          });
        });
      };
      var setup$3 = function(editor) {
        preventSummaryToggle(editor);
        filterDetails(editor);
      };
      var isTextBlockNode = function(node) {
        return isElement$5(node) && isTextBlock$2(SugarElement.fromDom(node));
      };
      var normalizeSelection = function(editor) {
        var rng = editor.selection.getRng();
        var startPos = CaretPosition.fromRangeStart(rng);
        var endPos = CaretPosition.fromRangeEnd(rng);
        if (CaretPosition.isElementPosition(startPos)) {
          var container = startPos.container();
          if (isTextBlockNode(container)) {
            firstPositionIn(container).each(function(pos) {
              return rng.setStart(pos.container(), pos.offset());
            });
          }
        }
        if (CaretPosition.isElementPosition(endPos)) {
          var container = startPos.container();
          if (isTextBlockNode(container)) {
            lastPositionIn(container).each(function(pos) {
              return rng.setEnd(pos.container(), pos.offset());
            });
          }
        }
        editor.selection.setRng(normalize(rng));
      };
      var setup$2 = function(editor) {
        editor.on("click", function(e) {
          if (e.detail >= 3) {
            normalizeSelection(editor);
          }
        });
      };
      var getAbsolutePosition = function(elm) {
        var clientRect = elm.getBoundingClientRect();
        var doc2 = elm.ownerDocument;
        var docElem2 = doc2.documentElement;
        var win = doc2.defaultView;
        return {
          top: clientRect.top + win.pageYOffset - docElem2.clientTop,
          left: clientRect.left + win.pageXOffset - docElem2.clientLeft
        };
      };
      var getBodyPosition = function(editor) {
        return editor.inline ? getAbsolutePosition(editor.getBody()) : {
          left: 0,
          top: 0
        };
      };
      var getScrollPosition = function(editor) {
        var body = editor.getBody();
        return editor.inline ? {
          left: body.scrollLeft,
          top: body.scrollTop
        } : {
          left: 0,
          top: 0
        };
      };
      var getBodyScroll = function(editor) {
        var body = editor.getBody(), docElm = editor.getDoc().documentElement;
        var inlineScroll = {
          left: body.scrollLeft,
          top: body.scrollTop
        };
        var iframeScroll = {
          left: body.scrollLeft || docElm.scrollLeft,
          top: body.scrollTop || docElm.scrollTop
        };
        return editor.inline ? inlineScroll : iframeScroll;
      };
      var getMousePosition = function(editor, event) {
        if (event.target.ownerDocument !== editor.getDoc()) {
          var iframePosition = getAbsolutePosition(editor.getContentAreaContainer());
          var scrollPosition = getBodyScroll(editor);
          return {
            left: event.pageX - iframePosition.left + scrollPosition.left,
            top: event.pageY - iframePosition.top + scrollPosition.top
          };
        }
        return {
          left: event.pageX,
          top: event.pageY
        };
      };
      var calculatePosition = function(bodyPosition, scrollPosition, mousePosition) {
        return {
          pageX: mousePosition.left - bodyPosition.left + scrollPosition.left,
          pageY: mousePosition.top - bodyPosition.top + scrollPosition.top
        };
      };
      var calc = function(editor, event) {
        return calculatePosition(getBodyPosition(editor), getScrollPosition(editor), getMousePosition(editor, event));
      };
      var isContentEditableFalse$1 = isContentEditableFalse$b, isContentEditableTrue$1 = isContentEditableTrue$4;
      var isDraggable = function(rootElm, elm) {
        return isContentEditableFalse$1(elm) && elm !== rootElm;
      };
      var isValidDropTarget = function(editor, targetElement, dragElement) {
        if (targetElement === dragElement || editor.dom.isChildOf(targetElement, dragElement)) {
          return false;
        }
        return !isContentEditableFalse$1(targetElement);
      };
      var cloneElement = function(elm) {
        var cloneElm = elm.cloneNode(true);
        cloneElm.removeAttribute("data-mce-selected");
        return cloneElm;
      };
      var createGhost = function(editor, elm, width, height) {
        var dom2 = editor.dom;
        var clonedElm = elm.cloneNode(true);
        dom2.setStyles(clonedElm, {
          width,
          height
        });
        dom2.setAttrib(clonedElm, "data-mce-selected", null);
        var ghostElm = dom2.create("div", {
          "class": "mce-drag-container",
          "data-mce-bogus": "all",
          "unselectable": "on",
          "contenteditable": "false"
        });
        dom2.setStyles(ghostElm, {
          position: "absolute",
          opacity: 0.5,
          overflow: "hidden",
          border: 0,
          padding: 0,
          margin: 0,
          width,
          height
        });
        dom2.setStyles(clonedElm, {
          margin: 0,
          boxSizing: "border-box"
        });
        ghostElm.appendChild(clonedElm);
        return ghostElm;
      };
      var appendGhostToBody = function(ghostElm, bodyElm) {
        if (ghostElm.parentNode !== bodyElm) {
          bodyElm.appendChild(ghostElm);
        }
      };
      var moveGhost = function(ghostElm, position, width, height, maxX, maxY) {
        var overflowX = 0, overflowY = 0;
        ghostElm.style.left = position.pageX + "px";
        ghostElm.style.top = position.pageY + "px";
        if (position.pageX + width > maxX) {
          overflowX = position.pageX + width - maxX;
        }
        if (position.pageY + height > maxY) {
          overflowY = position.pageY + height - maxY;
        }
        ghostElm.style.width = width - overflowX + "px";
        ghostElm.style.height = height - overflowY + "px";
      };
      var removeElement = function(elm) {
        if (elm && elm.parentNode) {
          elm.parentNode.removeChild(elm);
        }
      };
      var isLeftMouseButtonPressed = function(e) {
        return e.button === 0;
      };
      var applyRelPos = function(state, position) {
        return {
          pageX: position.pageX - state.relX,
          pageY: position.pageY + 5
        };
      };
      var start = function(state, editor) {
        return function(e) {
          if (isLeftMouseButtonPressed(e)) {
            var ceElm = find$3(editor.dom.getParents(e.target), or(isContentEditableFalse$1, isContentEditableTrue$1)).getOr(null);
            if (isDraggable(editor.getBody(), ceElm)) {
              var elmPos = editor.dom.getPos(ceElm);
              var bodyElm = editor.getBody();
              var docElm = editor.getDoc().documentElement;
              state.set({
                element: ceElm,
                dragging: false,
                screenX: e.screenX,
                screenY: e.screenY,
                maxX: (editor.inline ? bodyElm.scrollWidth : docElm.offsetWidth) - 2,
                maxY: (editor.inline ? bodyElm.scrollHeight : docElm.offsetHeight) - 2,
                relX: e.pageX - elmPos.x,
                relY: e.pageY - elmPos.y,
                width: ceElm.offsetWidth,
                height: ceElm.offsetHeight,
                ghost: createGhost(editor, ceElm, ceElm.offsetWidth, ceElm.offsetHeight)
              });
            }
          }
        };
      };
      var move = function(state, editor) {
        var throttledPlaceCaretAt = Delay.throttle(function(clientX, clientY) {
          editor._selectionOverrides.hideFakeCaret();
          editor.selection.placeCaretAt(clientX, clientY);
        }, 0);
        editor.on("remove", throttledPlaceCaretAt.stop);
        return function(e) {
          return state.on(function(state2) {
            var movement = Math.max(Math.abs(e.screenX - state2.screenX), Math.abs(e.screenY - state2.screenY));
            if (!state2.dragging && movement > 10) {
              var args = editor.fire("dragstart", { target: state2.element });
              if (args.isDefaultPrevented()) {
                return;
              }
              state2.dragging = true;
              editor.focus();
            }
            if (state2.dragging) {
              var targetPos = applyRelPos(state2, calc(editor, e));
              appendGhostToBody(state2.ghost, editor.getBody());
              moveGhost(state2.ghost, targetPos, state2.width, state2.height, state2.maxX, state2.maxY);
              throttledPlaceCaretAt(e.clientX, e.clientY);
            }
          });
        };
      };
      var getRawTarget = function(selection) {
        var rng = selection.getSel().getRangeAt(0);
        var startContainer = rng.startContainer;
        return startContainer.nodeType === 3 ? startContainer.parentNode : startContainer;
      };
      var drop = function(state, editor) {
        return function(e) {
          state.on(function(state2) {
            if (state2.dragging) {
              if (isValidDropTarget(editor, getRawTarget(editor.selection), state2.element)) {
                var targetClone_1 = cloneElement(state2.element);
                var args = editor.fire("drop", {
                  clientX: e.clientX,
                  clientY: e.clientY
                });
                if (!args.isDefaultPrevented()) {
                  editor.undoManager.transact(function() {
                    removeElement(state2.element);
                    editor.insertContent(editor.dom.getOuterHTML(targetClone_1));
                    editor._selectionOverrides.hideFakeCaret();
                  });
                }
              }
              editor.fire("dragend");
            }
          });
          removeDragState(state);
        };
      };
      var stop = function(state, editor) {
        return function() {
          state.on(function(state2) {
            if (state2.dragging) {
              editor.fire("dragend");
            }
          });
          removeDragState(state);
        };
      };
      var removeDragState = function(state) {
        state.on(function(state2) {
          removeElement(state2.ghost);
        });
        state.clear();
      };
      var bindFakeDragEvents = function(editor) {
        var state = value();
        var pageDom = DOMUtils.DOM;
        var rootDocument = document;
        var dragStartHandler = start(state, editor);
        var dragHandler = move(state, editor);
        var dropHandler = drop(state, editor);
        var dragEndHandler = stop(state, editor);
        editor.on("mousedown", dragStartHandler);
        editor.on("mousemove", dragHandler);
        editor.on("mouseup", dropHandler);
        pageDom.bind(rootDocument, "mousemove", dragHandler);
        pageDom.bind(rootDocument, "mouseup", dragEndHandler);
        editor.on("remove", function() {
          pageDom.unbind(rootDocument, "mousemove", dragHandler);
          pageDom.unbind(rootDocument, "mouseup", dragEndHandler);
        });
        editor.on("keydown", function(e) {
          if (e.keyCode === VK.ESC) {
            dragEndHandler();
          }
        });
      };
      var blockIeDrop = function(editor) {
        editor.on("drop", function(e) {
          var realTarget = typeof e.clientX !== "undefined" ? editor.getDoc().elementFromPoint(e.clientX, e.clientY) : null;
          if (isContentEditableFalse$1(realTarget) || editor.dom.getContentEditableParent(realTarget) === "false") {
            e.preventDefault();
          }
        });
      };
      var blockUnsupportedFileDrop = function(editor) {
        var preventFileDrop = function(e) {
          if (!e.isDefaultPrevented()) {
            var dataTransfer = e.dataTransfer;
            if (dataTransfer && (contains$3(dataTransfer.types, "Files") || dataTransfer.files.length > 0)) {
              e.preventDefault();
              if (e.type === "drop") {
                displayError(editor, "Dropped file type is not supported");
              }
            }
          }
        };
        var preventFileDropIfUIElement = function(e) {
          if (isUIElement(editor, e.target)) {
            preventFileDrop(e);
          }
        };
        var setup2 = function() {
          var pageDom = DOMUtils.DOM;
          var dom2 = editor.dom;
          var doc2 = document;
          var editorRoot = editor.inline ? editor.getBody() : editor.getDoc();
          var eventNames = [
            "drop",
            "dragover"
          ];
          each$k(eventNames, function(name2) {
            pageDom.bind(doc2, name2, preventFileDropIfUIElement);
            dom2.bind(editorRoot, name2, preventFileDrop);
          });
          editor.on("remove", function() {
            each$k(eventNames, function(name2) {
              pageDom.unbind(doc2, name2, preventFileDropIfUIElement);
              dom2.unbind(editorRoot, name2, preventFileDrop);
            });
          });
        };
        editor.on("init", function() {
          Delay.setEditorTimeout(editor, setup2, 0);
        });
      };
      var init$2 = function(editor) {
        bindFakeDragEvents(editor);
        blockIeDrop(editor);
        if (shouldBlockUnsupportedDrop(editor)) {
          blockUnsupportedFileDrop(editor);
        }
      };
      var setup$1 = function(editor) {
        var renderFocusCaret = first(function() {
          if (!editor.removed && editor.getBody().contains(document.activeElement)) {
            var rng = editor.selection.getRng();
            if (rng.collapsed) {
              var caretRange = renderRangeCaret(editor, rng, false);
              editor.selection.setRng(caretRange);
            }
          }
        }, 0);
        editor.on("focus", function() {
          renderFocusCaret.throttle();
        });
        editor.on("blur", function() {
          renderFocusCaret.cancel();
        });
      };
      var setup = function(editor) {
        editor.on("init", function() {
          editor.on("focusin", function(e) {
            var target = e.target;
            if (isMedia$2(target)) {
              var ceRoot = getContentEditableRoot$1(editor.getBody(), target);
              var node = isContentEditableFalse$b(ceRoot) ? ceRoot : target;
              if (editor.selection.getNode() !== node) {
                selectNode(editor, node).each(function(rng) {
                  return editor.selection.setRng(rng);
                });
              }
            }
          });
        });
      };
      var isContentEditableTrue = isContentEditableTrue$4;
      var isContentEditableFalse = isContentEditableFalse$b;
      var getContentEditableRoot = function(editor, node) {
        return getContentEditableRoot$1(editor.getBody(), node);
      };
      var SelectionOverrides = function(editor) {
        var selection = editor.selection, dom2 = editor.dom;
        var isBlock2 = dom2.isBlock;
        var rootNode = editor.getBody();
        var fakeCaret = FakeCaret(editor, rootNode, isBlock2, function() {
          return hasFocus(editor);
        });
        var realSelectionId = "sel-" + dom2.uniqueId();
        var elementSelectionAttr = "data-mce-selected";
        var selectedElement;
        var isFakeSelectionElement = function(node) {
          return dom2.hasClass(node, "mce-offscreen-selection");
        };
        var isFakeSelectionTargetElement = function(node) {
          return node !== rootNode && (isContentEditableFalse(node) || isMedia$2(node)) && dom2.isChildOf(node, rootNode);
        };
        var isNearFakeSelectionElement = function(pos) {
          return isBeforeContentEditableFalse(pos) || isAfterContentEditableFalse(pos) || isBeforeMedia(pos) || isAfterMedia(pos);
        };
        var getRealSelectionElement = function() {
          var container = dom2.get(realSelectionId);
          return container ? container.getElementsByTagName("*")[0] : container;
        };
        var setRange = function(range2) {
          if (range2) {
            selection.setRng(range2);
          }
        };
        var getRange = selection.getRng;
        var showCaret2 = function(direction, node, before2, scrollIntoView) {
          if (scrollIntoView === void 0) {
            scrollIntoView = true;
          }
          var e = editor.fire("ShowCaret", {
            target: node,
            direction,
            before: before2
          });
          if (e.isDefaultPrevented()) {
            return null;
          }
          if (scrollIntoView) {
            selection.scrollIntoView(node, direction === -1);
          }
          return fakeCaret.show(before2, node);
        };
        var showBlockCaretContainer2 = function(blockCaretContainer) {
          if (blockCaretContainer.hasAttribute("data-mce-caret")) {
            showCaretContainerBlock(blockCaretContainer);
            setRange(getRange());
            selection.scrollIntoView(blockCaretContainer);
          }
        };
        var registerEvents2 = function() {
          editor.on("mouseup", function(e) {
            var range2 = getRange();
            if (range2.collapsed && isXYInContentArea(editor, e.clientX, e.clientY)) {
              renderCaretAtRange(editor, range2, false).each(setRange);
            }
          });
          editor.on("click", function(e) {
            var contentEditableRoot = getContentEditableRoot(editor, e.target);
            if (contentEditableRoot) {
              if (isContentEditableFalse(contentEditableRoot)) {
                e.preventDefault();
                editor.focus();
              }
              if (isContentEditableTrue(contentEditableRoot)) {
                if (dom2.isChildOf(contentEditableRoot, selection.getNode())) {
                  removeElementSelection();
                }
              }
            }
          });
          editor.on("blur NewBlock", removeElementSelection);
          editor.on("ResizeWindow FullscreenStateChanged", fakeCaret.reposition);
          var hasNormalCaretPosition = function(elm) {
            var start2 = elm.firstChild;
            if (isNullable(start2)) {
              return false;
            }
            var startPos = CaretPosition.before(start2);
            if (isBr$5(startPos.getNode()) && elm.childNodes.length === 1) {
              return !isNearFakeSelectionElement(startPos);
            } else {
              var caretWalker = CaretWalker(elm);
              var newPos = caretWalker.next(startPos);
              return newPos && !isNearFakeSelectionElement(newPos);
            }
          };
          var isInSameBlock2 = function(node1, node2) {
            var block1 = dom2.getParent(node1, isBlock2);
            var block2 = dom2.getParent(node2, isBlock2);
            return block1 === block2;
          };
          var hasBetterMouseTarget = function(targetNode, caretNode) {
            var targetBlock = dom2.getParent(targetNode, isBlock2);
            var caretBlock = dom2.getParent(caretNode, isBlock2);
            if (isNullable(targetBlock)) {
              return false;
            }
            if (targetNode !== caretBlock && dom2.isChildOf(targetBlock, caretBlock) && isContentEditableFalse(getContentEditableRoot(editor, targetBlock)) === false) {
              return true;
            }
            return !dom2.isChildOf(caretBlock, targetBlock) && !isInSameBlock2(targetBlock, caretBlock) && hasNormalCaretPosition(targetBlock);
          };
          editor.on("tap", function(e) {
            var targetElm = e.target;
            var contentEditableRoot = getContentEditableRoot(editor, targetElm);
            if (isContentEditableFalse(contentEditableRoot)) {
              e.preventDefault();
              selectNode(editor, contentEditableRoot).each(setElementSelection);
            } else if (isFakeSelectionTargetElement(targetElm)) {
              selectNode(editor, targetElm).each(setElementSelection);
            }
          }, true);
          editor.on("mousedown", function(e) {
            var targetElm = e.target;
            if (targetElm !== rootNode && targetElm.nodeName !== "HTML" && !dom2.isChildOf(targetElm, rootNode)) {
              return;
            }
            if (isXYInContentArea(editor, e.clientX, e.clientY) === false) {
              return;
            }
            var contentEditableRoot = getContentEditableRoot(editor, targetElm);
            if (contentEditableRoot) {
              if (isContentEditableFalse(contentEditableRoot)) {
                e.preventDefault();
                selectNode(editor, contentEditableRoot).each(setElementSelection);
              } else {
                removeElementSelection();
                if (!(isContentEditableTrue(contentEditableRoot) && e.shiftKey) && !isXYWithinRange(e.clientX, e.clientY, selection.getRng())) {
                  hideFakeCaret();
                  selection.placeCaretAt(e.clientX, e.clientY);
                }
              }
            } else if (isFakeSelectionTargetElement(targetElm)) {
              selectNode(editor, targetElm).each(setElementSelection);
            } else if (isFakeCaretTarget(targetElm) === false) {
              removeElementSelection();
              hideFakeCaret();
              var fakeCaretInfo = closestFakeCaret(rootNode, e.clientX, e.clientY);
              if (fakeCaretInfo) {
                if (!hasBetterMouseTarget(targetElm, fakeCaretInfo.node)) {
                  e.preventDefault();
                  var range2 = showCaret2(1, fakeCaretInfo.node, fakeCaretInfo.before, false);
                  setRange(range2);
                  editor.getBody().focus();
                }
              }
            }
          });
          editor.on("keypress", function(e) {
            if (VK.modifierPressed(e)) {
              return;
            }
            if (isContentEditableFalse(selection.getNode())) {
              e.preventDefault();
            }
          });
          editor.on("GetSelectionRange", function(e) {
            var rng = e.range;
            if (selectedElement) {
              if (!selectedElement.parentNode) {
                selectedElement = null;
                return;
              }
              rng = rng.cloneRange();
              rng.selectNode(selectedElement);
              e.range = rng;
            }
          });
          editor.on("SetSelectionRange", function(e) {
            e.range = normalizeShortEndedElementSelection(e.range);
            var rng = setElementSelection(e.range, e.forward);
            if (rng) {
              e.range = rng;
            }
          });
          var isPasteBin = function(node) {
            return node.id === "mcepastebin";
          };
          editor.on("AfterSetSelectionRange", function(e) {
            var rng = e.range;
            var parentNode = rng.startContainer.parentNode;
            if (!isRangeInCaretContainer(rng) && !isPasteBin(parentNode)) {
              hideFakeCaret();
            }
            if (!isFakeSelectionElement(parentNode)) {
              removeElementSelection();
            }
          });
          editor.on("copy", function(e) {
            var clipboardData = e.clipboardData;
            if (!e.isDefaultPrevented() && e.clipboardData && !Env.ie) {
              var realSelectionElement = getRealSelectionElement();
              if (realSelectionElement) {
                e.preventDefault();
                clipboardData.clearData();
                clipboardData.setData("text/html", realSelectionElement.outerHTML);
                clipboardData.setData("text/plain", realSelectionElement.outerText || realSelectionElement.innerText);
              }
            }
          });
          init$2(editor);
          setup$1(editor);
          setup(editor);
        };
        var isWithinCaretContainer = function(node) {
          return isCaretContainer$2(node) || startsWithCaretContainer$1(node) || endsWithCaretContainer$1(node);
        };
        var isRangeInCaretContainer = function(rng) {
          return isWithinCaretContainer(rng.startContainer) || isWithinCaretContainer(rng.endContainer);
        };
        var normalizeShortEndedElementSelection = function(rng) {
          var shortEndedElements = editor.schema.getShortEndedElements();
          var newRng = dom2.createRng();
          var startContainer = rng.startContainer;
          var startOffset = rng.startOffset;
          var endContainer = rng.endContainer;
          var endOffset = rng.endOffset;
          if (has$2(shortEndedElements, startContainer.nodeName.toLowerCase())) {
            if (startOffset === 0) {
              newRng.setStartBefore(startContainer);
            } else {
              newRng.setStartAfter(startContainer);
            }
          } else {
            newRng.setStart(startContainer, startOffset);
          }
          if (has$2(shortEndedElements, endContainer.nodeName.toLowerCase())) {
            if (endOffset === 0) {
              newRng.setEndBefore(endContainer);
            } else {
              newRng.setEndAfter(endContainer);
            }
          } else {
            newRng.setEnd(endContainer, endOffset);
          }
          return newRng;
        };
        var setupOffscreenSelection = function(node, targetClone, origTargetClone) {
          var $ = editor.$;
          var $realSelectionContainer = descendant(SugarElement.fromDom(editor.getBody()), "#" + realSelectionId).fold(function() {
            return $([]);
          }, function(elm) {
            return $([elm.dom]);
          });
          if ($realSelectionContainer.length === 0) {
            $realSelectionContainer = $('<div data-mce-bogus="all" class="mce-offscreen-selection"></div>').attr("id", realSelectionId);
            $realSelectionContainer.appendTo(editor.getBody());
          }
          var newRange = dom2.createRng();
          if (targetClone === origTargetClone && Env.ie) {
            $realSelectionContainer.empty().append('<p style="font-size: 0" data-mce-bogus="all">\xA0</p>').append(targetClone);
            newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild);
            newRange.setEndAfter(targetClone);
          } else {
            $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp);
            newRange.setStart($realSelectionContainer[0].firstChild, 1);
            newRange.setEnd($realSelectionContainer[0].lastChild, 0);
          }
          $realSelectionContainer.css({ top: dom2.getPos(node, editor.getBody()).y });
          $realSelectionContainer[0].focus();
          var sel = selection.getSel();
          sel.removeAllRanges();
          sel.addRange(newRange);
          return newRange;
        };
        var selectElement = function(elm) {
          var targetClone = elm.cloneNode(true);
          var e = editor.fire("ObjectSelected", {
            target: elm,
            targetClone
          });
          if (e.isDefaultPrevented()) {
            return null;
          }
          var range2 = setupOffscreenSelection(elm, e.targetClone, targetClone);
          var nodeElm = SugarElement.fromDom(elm);
          each$k(descendants(SugarElement.fromDom(editor.getBody()), "*[data-mce-selected]"), function(elm2) {
            if (!eq(nodeElm, elm2)) {
              remove$6(elm2, elementSelectionAttr);
            }
          });
          if (!dom2.getAttrib(elm, elementSelectionAttr)) {
            elm.setAttribute(elementSelectionAttr, "1");
          }
          selectedElement = elm;
          hideFakeCaret();
          return range2;
        };
        var setElementSelection = function(range2, forward) {
          if (!range2) {
            return null;
          }
          if (range2.collapsed) {
            if (!isRangeInCaretContainer(range2)) {
              var dir2 = forward ? 1 : -1;
              var caretPosition = getNormalizedRangeEndPoint(dir2, rootNode, range2);
              var beforeNode = caretPosition.getNode(!forward);
              if (isFakeCaretTarget(beforeNode)) {
                return showCaret2(dir2, beforeNode, forward ? !caretPosition.isAtEnd() : false, false);
              }
              var afterNode = caretPosition.getNode(forward);
              if (isFakeCaretTarget(afterNode)) {
                return showCaret2(dir2, afterNode, forward ? false : !caretPosition.isAtEnd(), false);
              }
            }
            return null;
          }
          var startContainer = range2.startContainer;
          var startOffset = range2.startOffset;
          var endOffset = range2.endOffset;
          if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse(startContainer.parentNode)) {
            startContainer = startContainer.parentNode;
            startOffset = dom2.nodeIndex(startContainer);
            startContainer = startContainer.parentNode;
          }
          if (startContainer.nodeType !== 1) {
            return null;
          }
          if (endOffset === startOffset + 1 && startContainer === range2.endContainer) {
            var node = startContainer.childNodes[startOffset];
            if (isFakeSelectionTargetElement(node)) {
              return selectElement(node);
            }
          }
          return null;
        };
        var removeElementSelection = function() {
          if (selectedElement) {
            selectedElement.removeAttribute(elementSelectionAttr);
          }
          descendant(SugarElement.fromDom(editor.getBody()), "#" + realSelectionId).each(remove$7);
          selectedElement = null;
        };
        var destroy2 = function() {
          fakeCaret.destroy();
          selectedElement = null;
        };
        var hideFakeCaret = function() {
          fakeCaret.hide();
        };
        if (Env.ceFalse && !isRtc(editor)) {
          registerEvents2();
        }
        return {
          showCaret: showCaret2,
          showBlockCaretContainer: showBlockCaretContainer2,
          hideFakeCaret,
          destroy: destroy2
        };
      };
      var Quirks = function(editor) {
        var each2 = Tools.each;
        var BACKSPACE = VK.BACKSPACE, DELETE2 = VK.DELETE, dom2 = editor.dom, selection = editor.selection, parser = editor.parser;
        var isGecko = Env.gecko, isIE2 = Env.ie, isWebKit = Env.webkit;
        var mceInternalUrlPrefix = "data:text/mce-internal,";
        var mceInternalDataType = isIE2 ? "Text" : "URL";
        var setEditorCommandState2 = function(cmd, state) {
          try {
            editor.getDoc().execCommand(cmd, false, state);
          } catch (ex) {
          }
        };
        var isDefaultPrevented = function(e) {
          return e.isDefaultPrevented();
        };
        var setMceInternalContent = function(e) {
          var selectionHtml, internalContent;
          if (e.dataTransfer) {
            if (editor.selection.isCollapsed() && e.target.tagName === "IMG") {
              selection.select(e.target);
            }
            selectionHtml = editor.selection.getContent();
            if (selectionHtml.length > 0) {
              internalContent = mceInternalUrlPrefix + escape(editor.id) + "," + escape(selectionHtml);
              e.dataTransfer.setData(mceInternalDataType, internalContent);
            }
          }
        };
        var getMceInternalContent = function(e) {
          var internalContent;
          if (e.dataTransfer) {
            internalContent = e.dataTransfer.getData(mceInternalDataType);
            if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
              internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(",");
              return {
                id: unescape(internalContent[0]),
                html: unescape(internalContent[1])
              };
            }
          }
          return null;
        };
        var insertClipboardContents = function(content, internal) {
          if (editor.queryCommandSupported("mceInsertClipboardContent")) {
            editor.execCommand("mceInsertClipboardContent", false, {
              content,
              internal
            });
          } else {
            editor.execCommand("mceInsertContent", false, content);
          }
        };
        var emptyEditorWhenDeleting = function() {
          var serializeRng = function(rng) {
            var body = dom2.create("body");
            var contents = rng.cloneContents();
            body.appendChild(contents);
            return selection.serializer.serialize(body, { format: "html" });
          };
          var allContentsSelected = function(rng) {
            var selection2 = serializeRng(rng);
            var allRng = dom2.createRng();
            allRng.selectNode(editor.getBody());
            var allSelection = serializeRng(allRng);
            return selection2 === allSelection;
          };
          editor.on("keydown", function(e) {
            var keyCode = e.keyCode;
            var isCollapsed, body;
            if (!isDefaultPrevented(e) && (keyCode === DELETE2 || keyCode === BACKSPACE)) {
              isCollapsed = editor.selection.isCollapsed();
              body = editor.getBody();
              if (isCollapsed && !dom2.isEmpty(body)) {
                return;
              }
              if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
                return;
              }
              e.preventDefault();
              editor.setContent("");
              if (body.firstChild && dom2.isBlock(body.firstChild)) {
                editor.selection.setCursorLocation(body.firstChild, 0);
              } else {
                editor.selection.setCursorLocation(body, 0);
              }
              editor.nodeChanged();
            }
          });
        };
        var selectAll = function() {
          editor.shortcuts.add("meta+a", null, "SelectAll");
        };
        var documentElementEditingFocus = function() {
          if (!editor.inline) {
            dom2.bind(editor.getDoc(), "mousedown mouseup", function(e) {
              var rng;
              if (e.target === editor.getDoc().documentElement) {
                rng = selection.getRng();
                editor.getBody().focus();
                if (e.type === "mousedown") {
                  if (isCaretContainer$2(rng.startContainer)) {
                    return;
                  }
                  selection.placeCaretAt(e.clientX, e.clientY);
                } else {
                  selection.setRng(rng);
                }
              }
            });
          }
        };
        var removeHrOnBackspace = function() {
          editor.on("keydown", function(e) {
            if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
              if (!editor.getBody().getElementsByTagName("hr").length) {
                return;
              }
              if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
                var node = selection.getNode();
                var previousSibling = node.previousSibling;
                if (node.nodeName === "HR") {
                  dom2.remove(node);
                  e.preventDefault();
                  return;
                }
                if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
                  dom2.remove(previousSibling);
                  e.preventDefault();
                }
              }
            }
          });
        };
        var focusBody2 = function() {
          if (!Range.prototype.getClientRects) {
            editor.on("mousedown", function(e) {
              if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") {
                var body_1 = editor.getBody();
                body_1.blur();
                Delay.setEditorTimeout(editor, function() {
                  body_1.focus();
                });
              }
            });
          }
        };
        var selectControlElements = function() {
          editor.on("click", function(e) {
            var target = e.target;
            if (/^(IMG|HR)$/.test(target.nodeName) && dom2.getContentEditableParent(target) !== "false") {
              e.preventDefault();
              editor.selection.select(target);
              editor.nodeChanged();
            }
            if (target.nodeName === "A" && dom2.hasClass(target, "mce-item-anchor")) {
              e.preventDefault();
              selection.select(target);
            }
          });
        };
        var removeStylesWhenDeletingAcrossBlockElements = function() {
          var getAttributeApplyFunction = function() {
            var template = dom2.getAttribs(selection.getStart().cloneNode(false));
            return function() {
              var target = selection.getStart();
              if (target !== editor.getBody()) {
                dom2.setAttrib(target, "style", null);
                each2(template, function(attr) {
                  target.setAttributeNode(attr.cloneNode(true));
                });
              }
            };
          };
          var isSelectionAcrossElements = function() {
            return !selection.isCollapsed() && dom2.getParent(selection.getStart(), dom2.isBlock) !== dom2.getParent(selection.getEnd(), dom2.isBlock);
          };
          editor.on("keypress", function(e) {
            var applyAttributes2;
            if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) {
              applyAttributes2 = getAttributeApplyFunction();
              editor.getDoc().execCommand("delete", false, null);
              applyAttributes2();
              e.preventDefault();
              return false;
            }
          });
          dom2.bind(editor.getDoc(), "cut", function(e) {
            var applyAttributes2;
            if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
              applyAttributes2 = getAttributeApplyFunction();
              Delay.setEditorTimeout(editor, function() {
                applyAttributes2();
              });
            }
          });
        };
        var disableBackspaceIntoATable = function() {
          editor.on("keydown", function(e) {
            if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
              if (selection.isCollapsed() && selection.getRng().startOffset === 0) {
                var previousSibling = selection.getNode().previousSibling;
                if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") {
                  e.preventDefault();
                  return false;
                }
              }
            }
          });
        };
        var removeBlockQuoteOnBackSpace = function() {
          editor.on("keydown", function(e) {
            var rng, parent2;
            if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) {
              return;
            }
            rng = selection.getRng();
            var container = rng.startContainer;
            var offset = rng.startOffset;
            var root = dom2.getRoot();
            parent2 = container;
            if (!rng.collapsed || offset !== 0) {
              return;
            }
            while (parent2 && parent2.parentNode && parent2.parentNode.firstChild === parent2 && parent2.parentNode !== root) {
              parent2 = parent2.parentNode;
            }
            if (parent2.tagName === "BLOCKQUOTE") {
              editor.formatter.toggle("blockquote", null, parent2);
              rng = dom2.createRng();
              rng.setStart(container, 0);
              rng.setEnd(container, 0);
              selection.setRng(rng);
            }
          });
        };
        var setGeckoEditingOptions = function() {
          var setOpts = function() {
            setEditorCommandState2("StyleWithCSS", false);
            setEditorCommandState2("enableInlineTableEditing", false);
            if (!getObjectResizing(editor)) {
              setEditorCommandState2("enableObjectResizing", false);
            }
          };
          if (!isReadOnly$1(editor)) {
            editor.on("BeforeExecCommand mousedown", setOpts);
          }
        };
        var addBrAfterLastLinks = function() {
          var fixLinks = function() {
            each2(dom2.select("a"), function(node) {
              var parentNode = node.parentNode;
              var root = dom2.getRoot();
              if (parentNode.lastChild === node) {
                while (parentNode && !dom2.isBlock(parentNode)) {
                  if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
                    return;
                  }
                  parentNode = parentNode.parentNode;
                }
                dom2.add(parentNode, "br", { "data-mce-bogus": 1 });
              }
            });
          };
          editor.on("SetContent ExecCommand", function(e) {
            if (e.type === "setcontent" || e.command === "mceInsertLink") {
              fixLinks();
            }
          });
        };
        var setDefaultBlockType = function() {
          if (getForcedRootBlock(editor)) {
            editor.on("init", function() {
              setEditorCommandState2("DefaultParagraphSeparator", getForcedRootBlock(editor));
            });
          }
        };
        var normalizeSelection2 = function() {
          editor.on("keyup focusin mouseup", function(e) {
            if (!VK.modifierPressed(e)) {
              selection.normalize();
            }
          }, true);
        };
        var showBrokenImageIcon = function() {
          editor.contentStyles.push("img:-moz-broken {-moz-force-broken-image-icon:1;min-width:24px;min-height:24px}");
        };
        var restoreFocusOnKeyDown = function() {
          if (!editor.inline) {
            editor.on("keydown", function() {
              if (document.activeElement === document.body) {
                editor.getWin().focus();
              }
            });
          }
        };
        var bodyHeight = function() {
          if (!editor.inline) {
            editor.contentStyles.push("body {min-height: 150px}");
            editor.on("click", function(e) {
              var rng;
              if (e.target.nodeName === "HTML") {
                if (Env.ie > 11) {
                  editor.getBody().focus();
                  return;
                }
                rng = editor.selection.getRng();
                editor.getBody().focus();
                editor.selection.setRng(rng);
                editor.selection.normalize();
                editor.nodeChanged();
              }
            });
          }
        };
        var blockCmdArrowNavigation = function() {
          if (Env.mac) {
            editor.on("keydown", function(e) {
              if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) {
                e.preventDefault();
                var selection_1 = editor.selection.getSel();
                selection_1.modify("move", e.keyCode === 37 ? "backward" : "forward", "lineboundary");
              }
            });
          }
        };
        var disableAutoUrlDetect = function() {
          setEditorCommandState2("AutoUrlDetect", false);
        };
        var tapLinksAndImages = function() {
          editor.on("click", function(e) {
            var elm = e.target;
            do {
              if (elm.tagName === "A") {
                e.preventDefault();
                return;
              }
            } while (elm = elm.parentNode);
          });
          editor.contentStyles.push(".mce-content-body {-webkit-touch-callout: none}");
        };
        var blockFormSubmitInsideEditor = function() {
          editor.on("init", function() {
            editor.dom.bind(editor.getBody(), "submit", function(e) {
              e.preventDefault();
            });
          });
        };
        var removeAppleInterchangeBrs = function() {
          parser.addNodeFilter("br", function(nodes) {
            var i = nodes.length;
            while (i--) {
              if (nodes[i].attr("class") === "Apple-interchange-newline") {
                nodes[i].remove();
              }
            }
          });
        };
        var ieInternalDragAndDrop = function() {
          editor.on("dragstart", function(e) {
            setMceInternalContent(e);
          });
          editor.on("drop", function(e) {
            if (!isDefaultPrevented(e)) {
              var internalContent = getMceInternalContent(e);
              if (internalContent && internalContent.id !== editor.id) {
                e.preventDefault();
                var rng = fromPoint(e.x, e.y, editor.getDoc());
                selection.setRng(rng);
                insertClipboardContents(internalContent.html, true);
              }
            }
          });
        };
        var refreshContentEditable = noop;
        var isHidden = function() {
          if (!isGecko || editor.removed) {
            return false;
          }
          var sel = editor.selection.getSel();
          return !sel || !sel.rangeCount || sel.rangeCount === 0;
        };
        var setupRtc = function() {
          if (isWebKit) {
            documentElementEditingFocus();
            selectControlElements();
            blockFormSubmitInsideEditor();
            selectAll();
            if (Env.iOS) {
              restoreFocusOnKeyDown();
              bodyHeight();
              tapLinksAndImages();
            }
          }
          if (isGecko) {
            focusBody2();
            setGeckoEditingOptions();
            showBrokenImageIcon();
            blockCmdArrowNavigation();
          }
        };
        var setup2 = function() {
          removeBlockQuoteOnBackSpace();
          emptyEditorWhenDeleting();
          if (!Env.windowsPhone) {
            normalizeSelection2();
          }
          if (isWebKit) {
            documentElementEditingFocus();
            selectControlElements();
            setDefaultBlockType();
            blockFormSubmitInsideEditor();
            disableBackspaceIntoATable();
            removeAppleInterchangeBrs();
            if (Env.iOS) {
              restoreFocusOnKeyDown();
              bodyHeight();
              tapLinksAndImages();
            } else {
              selectAll();
            }
          }
          if (Env.ie >= 11) {
            bodyHeight();
            disableBackspaceIntoATable();
          }
          if (Env.ie) {
            selectAll();
            disableAutoUrlDetect();
            ieInternalDragAndDrop();
          }
          if (isGecko) {
            removeHrOnBackspace();
            focusBody2();
            removeStylesWhenDeletingAcrossBlockElements();
            setGeckoEditingOptions();
            addBrAfterLastLinks();
            showBrokenImageIcon();
            blockCmdArrowNavigation();
            disableBackspaceIntoATable();
          }
        };
        if (isRtc(editor)) {
          setupRtc();
        } else {
          setup2();
        }
        return {
          refreshContentEditable,
          isHidden
        };
      };
      var DOM$6 = DOMUtils.DOM;
      var appendStyle = function(editor, text) {
        var body = SugarElement.fromDom(editor.getBody());
        var container = getStyleContainer(getRootNode(body));
        var style = SugarElement.fromTag("style");
        set$1(style, "type", "text/css");
        append$1(style, SugarElement.fromText(text));
        append$1(container, style);
        editor.on("remove", function() {
          remove$7(style);
        });
      };
      var getRootName = function(editor) {
        return editor.inline ? editor.getElement().nodeName.toLowerCase() : void 0;
      };
      var removeUndefined = function(obj) {
        return filter$3(obj, function(v) {
          return isUndefined(v) === false;
        });
      };
      var mkSchemaSettings = function(editor) {
        var settings = editor.settings;
        return removeUndefined({
          block_elements: settings.block_elements,
          boolean_attributes: settings.boolean_attributes,
          custom_elements: settings.custom_elements,
          extended_valid_elements: settings.extended_valid_elements,
          invalid_elements: settings.invalid_elements,
          invalid_styles: settings.invalid_styles,
          move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements,
          non_empty_elements: settings.non_empty_elements,
          schema: settings.schema,
          self_closing_elements: settings.self_closing_elements,
          short_ended_elements: settings.short_ended_elements,
          special: settings.special,
          text_block_elements: settings.text_block_elements,
          text_inline_elements: settings.text_inline_elements,
          valid_children: settings.valid_children,
          valid_classes: settings.valid_classes,
          valid_elements: settings.valid_elements,
          valid_styles: settings.valid_styles,
          verify_html: settings.verify_html,
          whitespace_elements: settings.whitespace_elements,
          padd_empty_block_inline_children: settings.format_empty_lines
        });
      };
      var mkParserSettings = function(editor) {
        var settings = editor.settings;
        var blobCache = editor.editorUpload.blobCache;
        return removeUndefined({
          allow_conditional_comments: settings.allow_conditional_comments,
          allow_html_data_urls: settings.allow_html_data_urls,
          allow_svg_data_urls: settings.allow_svg_data_urls,
          allow_html_in_named_anchor: settings.allow_html_in_named_anchor,
          allow_script_urls: settings.allow_script_urls,
          allow_unsafe_link_target: settings.allow_unsafe_link_target,
          convert_fonts_to_spans: settings.convert_fonts_to_spans,
          fix_list_elements: settings.fix_list_elements,
          font_size_legacy_values: settings.font_size_legacy_values,
          forced_root_block: settings.forced_root_block,
          forced_root_block_attrs: settings.forced_root_block_attrs,
          padd_empty_with_br: settings.padd_empty_with_br,
          preserve_cdata: settings.preserve_cdata,
          remove_trailing_brs: settings.remove_trailing_brs,
          inline_styles: settings.inline_styles,
          root_name: getRootName(editor),
          validate: true,
          blob_cache: blobCache,
          document: editor.getDoc(),
          images_dataimg_filter: settings.images_dataimg_filter
        });
      };
      var mkSerializerSettings = function(editor) {
        var settings = editor.settings;
        return __assign(__assign(__assign({}, mkParserSettings(editor)), mkSchemaSettings(editor)), removeUndefined({
          url_converter: settings.url_converter,
          url_converter_scope: settings.url_converter_scope,
          element_format: settings.element_format,
          entities: settings.entities,
          entity_encoding: settings.entity_encoding,
          indent: settings.indent,
          indent_after: settings.indent_after,
          indent_before: settings.indent_before
        }));
      };
      var createParser = function(editor) {
        var parser = DomParser(mkParserSettings(editor), editor.schema);
        parser.addAttributeFilter("src,href,style,tabindex", function(nodes, name2) {
          var i = nodes.length, node, value2;
          var dom2 = editor.dom;
          var internalName = "data-mce-" + name2;
          while (i--) {
            node = nodes[i];
            value2 = node.attr(name2);
            if (value2 && !node.attr(internalName)) {
              if (value2.indexOf("data:") === 0 || value2.indexOf("blob:") === 0) {
                continue;
              }
              if (name2 === "style") {
                value2 = dom2.serializeStyle(dom2.parseStyle(value2), node.name);
                if (!value2.length) {
                  value2 = null;
                }
                node.attr(internalName, value2);
                node.attr(name2, value2);
              } else if (name2 === "tabindex") {
                node.attr(internalName, value2);
                node.attr(name2, null);
              } else {
                node.attr(internalName, editor.convertURL(value2, name2, node.name));
              }
            }
          }
        });
        parser.addNodeFilter("script", function(nodes) {
          var i = nodes.length;
          while (i--) {
            var node = nodes[i];
            var type2 = node.attr("type") || "no/type";
            if (type2.indexOf("mce-") !== 0) {
              node.attr("type", "mce-" + type2);
            }
          }
        });
        if (editor.settings.preserve_cdata) {
          parser.addNodeFilter("#cdata", function(nodes) {
            var i = nodes.length;
            while (i--) {
              var node = nodes[i];
              node.type = 8;
              node.name = "#comment";
              node.value = "[CDATA[" + editor.dom.encode(node.value) + "]]";
            }
          });
        }
        parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div", function(nodes) {
          var i = nodes.length;
          var nonEmptyElements = editor.schema.getNonEmptyElements();
          while (i--) {
            var node = nodes[i];
            if (node.isEmpty(nonEmptyElements) && node.getAll("br").length === 0) {
              node.append(new AstNode("br", 1)).shortEnded = true;
            }
          }
        });
        return parser;
      };
      var autoFocus = function(editor) {
        if (editor.settings.auto_focus) {
          Delay.setEditorTimeout(editor, function() {
            var focusEditor2;
            if (editor.settings.auto_focus === true) {
              focusEditor2 = editor;
            } else {
              focusEditor2 = editor.editorManager.get(editor.settings.auto_focus);
            }
            if (!focusEditor2.destroyed) {
              focusEditor2.focus();
            }
          }, 100);
        }
      };
      var moveSelectionToFirstCaretPosition = function(editor) {
        var root = editor.dom.getRoot();
        if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) {
          firstPositionIn(root).each(function(pos) {
            var node = pos.getNode();
            var caretPos = isTable$3(node) ? firstPositionIn(node).getOr(pos) : pos;
            if (Env.browser.isIE()) {
              storeNative(editor, caretPos.toRange());
            } else {
              editor.selection.setRng(caretPos.toRange());
            }
          });
        }
      };
      var initEditor = function(editor) {
        editor.bindPendingEventDelegates();
        editor.initialized = true;
        fireInit(editor);
        editor.focus(true);
        moveSelectionToFirstCaretPosition(editor);
        editor.nodeChanged({ initial: true });
        editor.execCallback("init_instance_callback", editor);
        autoFocus(editor);
      };
      var getStyleSheetLoader$1 = function(editor) {
        return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader;
      };
      var makeStylesheetLoadingPromises = function(editor, css, framedFonts) {
        var promises = [new promiseObj(function(resolve2, reject) {
          return getStyleSheetLoader$1(editor).loadAll(css, resolve2, reject);
        })];
        if (editor.inline) {
          return promises;
        } else {
          return promises.concat([new promiseObj(function(resolve2, reject) {
            return editor.ui.styleSheetLoader.loadAll(framedFonts, resolve2, reject);
          })]);
        }
      };
      var loadContentCss = function(editor) {
        var styleSheetLoader = getStyleSheetLoader$1(editor);
        var fontCss = getFontCss(editor);
        var css = editor.contentCSS;
        var removeCss = function() {
          styleSheetLoader.unloadAll(css);
          if (!editor.inline) {
            editor.ui.styleSheetLoader.unloadAll(fontCss);
          }
        };
        var loaded = function() {
          if (editor.removed) {
            removeCss();
          } else {
            editor.on("remove", removeCss);
          }
        };
        if (editor.contentStyles.length > 0) {
          var contentCssText_1 = "";
          Tools.each(editor.contentStyles, function(style) {
            contentCssText_1 += style + "\r\n";
          });
          editor.dom.addStyle(contentCssText_1);
        }
        var allStylesheets = promiseObj.all(makeStylesheetLoadingPromises(editor, css, fontCss)).then(loaded).catch(loaded);
        if (editor.settings.content_style) {
          appendStyle(editor, editor.settings.content_style);
        }
        return allStylesheets;
      };
      var preInit = function(editor) {
        var settings = editor.settings, doc2 = editor.getDoc(), body = editor.getBody();
        firePreInit(editor);
        if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
          doc2.body.spellcheck = false;
          DOM$6.setAttrib(body, "spellcheck", "false");
        }
        editor.quirks = Quirks(editor);
        firePostRender(editor);
        var directionality = getDirectionality(editor);
        if (directionality !== void 0) {
          body.dir = directionality;
        }
        if (settings.protect) {
          editor.on("BeforeSetContent", function(e) {
            Tools.each(settings.protect, function(pattern) {
              e.content = e.content.replace(pattern, function(str) {
                return "<!--mce:protected " + escape(str) + "-->";
              });
            });
          });
        }
        editor.on("SetContent", function() {
          editor.addVisual(editor.getBody());
        });
        editor.on("compositionstart compositionend", function(e) {
          editor.composing = e.type === "compositionstart";
        });
      };
      var loadInitialContent = function(editor) {
        if (!isRtc(editor)) {
          editor.load({
            initial: true,
            format: "html"
          });
        }
        editor.startContent = editor.getContent({ format: "raw" });
      };
      var initEditorWithInitialContent = function(editor) {
        if (editor.removed !== true) {
          loadInitialContent(editor);
          initEditor(editor);
        }
      };
      var initContentBody = function(editor, skipWrite) {
        var settings = editor.settings;
        var targetElm = editor.getElement();
        var doc2 = editor.getDoc();
        if (!settings.inline) {
          editor.getElement().style.visibility = editor.orgVisibility;
        }
        if (!skipWrite && !editor.inline) {
          doc2.open();
          doc2.write(editor.iframeHTML);
          doc2.close();
        }
        if (editor.inline) {
          DOM$6.addClass(targetElm, "mce-content-body");
          editor.contentDocument = doc2 = document;
          editor.contentWindow = window;
          editor.bodyElement = targetElm;
          editor.contentAreaContainer = targetElm;
        }
        var body = editor.getBody();
        body.disabled = true;
        editor.readonly = !!settings.readonly;
        if (!editor.readonly) {
          if (editor.inline && DOM$6.getStyle(body, "position", true) === "static") {
            body.style.position = "relative";
          }
          body.contentEditable = editor.getParam("content_editable_state", true);
        }
        body.disabled = false;
        editor.editorUpload = EditorUpload(editor);
        editor.schema = Schema(mkSchemaSettings(editor));
        editor.dom = DOMUtils(doc2, {
          keep_values: true,
          url_converter: editor.convertURL,
          url_converter_scope: editor,
          hex_colors: settings.force_hex_style_colors,
          update_styles: true,
          root_element: editor.inline ? editor.getBody() : null,
          collect: function() {
            return editor.inline;
          },
          schema: editor.schema,
          contentCssCors: shouldUseContentCssCors(editor),
          referrerPolicy: getReferrerPolicy(editor),
          onSetAttrib: function(e) {
            editor.fire("SetAttrib", e);
          }
        });
        editor.parser = createParser(editor);
        editor.serializer = DomSerializer(mkSerializerSettings(editor), editor);
        editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor);
        editor.annotator = Annotator(editor);
        editor.formatter = Formatter(editor);
        editor.undoManager = UndoManager(editor);
        editor._nodeChangeDispatcher = new NodeChange(editor);
        editor._selectionOverrides = SelectionOverrides(editor);
        setup$e(editor);
        setup$3(editor);
        if (!isRtc(editor)) {
          setup$2(editor);
        }
        var caret = setup$4(editor);
        setup$f(editor, caret);
        setup$d(editor);
        setup$g(editor);
        var setupRtcThunk = setup$i(editor);
        preInit(editor);
        setupRtcThunk.fold(function() {
          loadContentCss(editor).then(function() {
            return initEditorWithInitialContent(editor);
          });
        }, function(setupRtc) {
          editor.setProgressState(true);
          loadContentCss(editor).then(function() {
            setupRtc().then(function(_rtcMode) {
              editor.setProgressState(false);
              initEditorWithInitialContent(editor);
            }, function(err) {
              editor.notificationManager.open({
                type: "error",
                text: String(err)
              });
              initEditorWithInitialContent(editor);
            });
          });
        });
      };
      var DOM$5 = DOMUtils.DOM;
      var relaxDomain = function(editor, ifr) {
        if (document.domain !== window.location.hostname && Env.browser.isIE()) {
          var bodyUuid = uuid("mce");
          editor[bodyUuid] = function() {
            initContentBody(editor);
          };
          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);})()";
          DOM$5.setAttrib(ifr, "src", domainRelaxUrl);
          return true;
        }
        return false;
      };
      var createIframeElement = function(id, title, height, customAttrs) {
        var iframe = SugarElement.fromTag("iframe");
        setAll$1(iframe, customAttrs);
        setAll$1(iframe, {
          id: id + "_ifr",
          frameBorder: "0",
          allowTransparency: "true",
          title
        });
        add$1(iframe, "tox-edit-area__iframe");
        return iframe;
      };
      var getIframeHtml = function(editor) {
        var iframeHTML = getDocType(editor) + "<html><head>";
        if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) {
          iframeHTML += '<base href="' + editor.documentBaseURI.getURI() + '" />';
        }
        iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
        var bodyId = getBodyId(editor);
        var bodyClass = getBodyClass(editor);
        var translatedAriaText = editor.translate(getIframeAriaText(editor));
        if (getContentSecurityPolicy(editor)) {
          iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + getContentSecurityPolicy(editor) + '" />';
        }
        iframeHTML += "</head>" + ('<body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" data-id="' + editor.id + '" aria-label="' + translatedAriaText + '">') + "<br></body></html>";
        return iframeHTML;
      };
      var createIframe = function(editor, o) {
        var iframeTitle = editor.translate("Rich Text Area");
        var ifr = createIframeElement(editor.id, iframeTitle, o.height, getIframeAttrs(editor)).dom;
        ifr.onload = function() {
          ifr.onload = null;
          editor.fire("load");
        };
        var isDomainRelaxed = relaxDomain(editor, ifr);
        editor.contentAreaContainer = o.iframeContainer;
        editor.iframeElement = ifr;
        editor.iframeHTML = getIframeHtml(editor);
        DOM$5.add(o.iframeContainer, ifr);
        return isDomainRelaxed;
      };
      var init$1 = function(editor, boxInfo) {
        var isDomainRelaxed = createIframe(editor, boxInfo);
        if (boxInfo.editorContainer) {
          DOM$5.get(boxInfo.editorContainer).style.display = editor.orgDisplay;
          editor.hidden = DOM$5.isHidden(boxInfo.editorContainer);
        }
        editor.getElement().style.display = "none";
        DOM$5.setAttrib(editor.id, "aria-hidden", "true");
        if (!isDomainRelaxed) {
          initContentBody(editor);
        }
      };
      var DOM$4 = DOMUtils.DOM;
      var initPlugin = function(editor, initializedPlugins, plugin) {
        var Plugin = PluginManager.get(plugin);
        var pluginUrl = PluginManager.urls[plugin] || editor.documentBaseUrl.replace(/\/$/, "");
        plugin = Tools.trim(plugin);
        if (Plugin && Tools.inArray(initializedPlugins, plugin) === -1) {
          Tools.each(PluginManager.dependencies(plugin), function(dep) {
            initPlugin(editor, initializedPlugins, dep);
          });
          if (editor.plugins[plugin]) {
            return;
          }
          try {
            var pluginInstance = new Plugin(editor, pluginUrl, editor.$);
            editor.plugins[plugin] = pluginInstance;
            if (pluginInstance.init) {
              pluginInstance.init(editor, pluginUrl);
              initializedPlugins.push(plugin);
            }
          } catch (e) {
            pluginInitError(editor, plugin, e);
          }
        }
      };
      var trimLegacyPrefix = function(name2) {
        return name2.replace(/^\-/, "");
      };
      var initPlugins = function(editor) {
        var initializedPlugins = [];
        Tools.each(getPlugins(editor).split(/[ ,]/), function(name2) {
          initPlugin(editor, initializedPlugins, trimLegacyPrefix(name2));
        });
      };
      var initIcons = function(editor) {
        var iconPackName = Tools.trim(getIconPackName(editor));
        var currentIcons = editor.ui.registry.getAll().icons;
        var loadIcons2 = __assign(__assign({}, IconManager.get("default").icons), IconManager.get(iconPackName).icons);
        each$j(loadIcons2, function(svgData, icon) {
          if (!has$2(currentIcons, icon)) {
            editor.ui.registry.addIcon(icon, svgData);
          }
        });
      };
      var initTheme = function(editor) {
        var theme = getTheme(editor);
        if (isString$1(theme)) {
          editor.settings.theme = trimLegacyPrefix(theme);
          var Theme = ThemeManager.get(theme);
          editor.theme = new Theme(editor, ThemeManager.urls[theme]);
          if (editor.theme.init) {
            editor.theme.init(editor, ThemeManager.urls[theme] || editor.documentBaseUrl.replace(/\/$/, ""), editor.$);
          }
        } else {
          editor.theme = {};
        }
      };
      var renderFromLoadedTheme = function(editor) {
        return editor.theme.renderUI();
      };
      var renderFromThemeFunc = function(editor) {
        var elm = editor.getElement();
        var theme = getTheme(editor);
        var info = theme(editor, elm);
        if (info.editorContainer.nodeType) {
          info.editorContainer.id = info.editorContainer.id || editor.id + "_parent";
        }
        if (info.iframeContainer && info.iframeContainer.nodeType) {
          info.iframeContainer.id = info.iframeContainer.id || editor.id + "_iframecontainer";
        }
        info.height = info.iframeHeight ? info.iframeHeight : elm.offsetHeight;
        return info;
      };
      var createThemeFalseResult = function(element) {
        return {
          editorContainer: element,
          iframeContainer: element,
          api: {}
        };
      };
      var renderThemeFalseIframe = function(targetElement) {
        var iframeContainer = DOM$4.create("div");
        DOM$4.insertAfter(iframeContainer, targetElement);
        return createThemeFalseResult(iframeContainer);
      };
      var renderThemeFalse = function(editor) {
        var targetElement = editor.getElement();
        return editor.inline ? createThemeFalseResult(null) : renderThemeFalseIframe(targetElement);
      };
      var renderThemeUi = function(editor) {
        var elm = editor.getElement();
        editor.orgDisplay = elm.style.display;
        if (isString$1(getTheme(editor))) {
          return renderFromLoadedTheme(editor);
        } else if (isFunction(getTheme(editor))) {
          return renderFromThemeFunc(editor);
        } else {
          return renderThemeFalse(editor);
        }
      };
      var augmentEditorUiApi = function(editor, api2) {
        var uiApiFacade = {
          show: Optional.from(api2.show).getOr(noop),
          hide: Optional.from(api2.hide).getOr(noop),
          disable: Optional.from(api2.disable).getOr(noop),
          isDisabled: Optional.from(api2.isDisabled).getOr(never),
          enable: function() {
            if (!editor.mode.isReadOnly()) {
              Optional.from(api2.enable).map(call);
            }
          }
        };
        editor.ui = __assign(__assign({}, editor.ui), uiApiFacade);
      };
      var init = function(editor) {
        editor.fire("ScriptsLoaded");
        initIcons(editor);
        initTheme(editor);
        initPlugins(editor);
        var renderInfo = renderThemeUi(editor);
        augmentEditorUiApi(editor, Optional.from(renderInfo.api).getOr({}));
        var boxInfo = {
          editorContainer: renderInfo.editorContainer,
          iframeContainer: renderInfo.iframeContainer
        };
        editor.editorContainer = boxInfo.editorContainer ? boxInfo.editorContainer : null;
        appendContentCssFromSettings(editor);
        if (editor.inline) {
          return initContentBody(editor);
        } else {
          return init$1(editor, boxInfo);
        }
      };
      var DOM$3 = DOMUtils.DOM;
      var hasSkipLoadPrefix = function(name2) {
        return name2.charAt(0) === "-";
      };
      var loadLanguage = function(scriptLoader, editor) {
        var languageCode = getLanguageCode(editor);
        var languageUrl = getLanguageUrl(editor);
        if (I18n.hasCode(languageCode) === false && languageCode !== "en") {
          var url_1 = languageUrl !== "" ? languageUrl : editor.editorManager.baseURL + "/langs/" + languageCode + ".js";
          scriptLoader.add(url_1, noop, void 0, function() {
            languageLoadError(editor, url_1, languageCode);
          });
        }
      };
      var loadTheme = function(scriptLoader, editor, suffix, callback) {
        var theme = getTheme(editor);
        if (isString$1(theme)) {
          if (!hasSkipLoadPrefix(theme) && !has$2(ThemeManager.urls, theme)) {
            var themeUrl = getThemeUrl(editor);
            if (themeUrl) {
              ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
            } else {
              ThemeManager.load(theme, "themes/" + theme + "/theme" + suffix + ".js");
            }
          }
          scriptLoader.loadQueue(function() {
            ThemeManager.waitFor(theme, callback);
          });
        } else {
          callback();
        }
      };
      var getIconsUrlMetaFromUrl = function(editor) {
        return Optional.from(getIconsUrl(editor)).filter(function(url) {
          return url.length > 0;
        }).map(function(url) {
          return {
            url,
            name: Optional.none()
          };
        });
      };
      var getIconsUrlMetaFromName = function(editor, name2, suffix) {
        return Optional.from(name2).filter(function(name3) {
          return name3.length > 0 && !IconManager.has(name3);
        }).map(function(name3) {
          return {
            url: editor.editorManager.baseURL + "/icons/" + name3 + "/icons" + suffix + ".js",
            name: Optional.some(name3)
          };
        });
      };
      var loadIcons = function(scriptLoader, editor, suffix) {
        var defaultIconsUrl = getIconsUrlMetaFromName(editor, "default", suffix);
        var customIconsUrl = getIconsUrlMetaFromUrl(editor).orThunk(function() {
          return getIconsUrlMetaFromName(editor, getIconPackName(editor), "");
        });
        each$k(cat([
          defaultIconsUrl,
          customIconsUrl
        ]), function(urlMeta) {
          scriptLoader.add(urlMeta.url, noop, void 0, function() {
            iconsLoadError(editor, urlMeta.url, urlMeta.name.getOrUndefined());
          });
        });
      };
      var loadPlugins = function(editor, suffix) {
        Tools.each(getExternalPlugins$1(editor), function(url, name2) {
          PluginManager.load(name2, url, noop, void 0, function() {
            pluginLoadError(editor, url, name2);
          });
          editor.settings.plugins += " " + name2;
        });
        Tools.each(getPlugins(editor).split(/[ ,]/), function(plugin) {
          plugin = Tools.trim(plugin);
          if (plugin && !PluginManager.urls[plugin]) {
            if (hasSkipLoadPrefix(plugin)) {
              plugin = plugin.substr(1, plugin.length);
              var dependencies = PluginManager.dependencies(plugin);
              Tools.each(dependencies, function(depPlugin) {
                var defaultSettings = {
                  prefix: "plugins/",
                  resource: depPlugin,
                  suffix: "/plugin" + suffix + ".js"
                };
                var dep = PluginManager.createUrl(defaultSettings, depPlugin);
                PluginManager.load(dep.resource, dep, noop, void 0, function() {
                  pluginLoadError(editor, dep.prefix + dep.resource + dep.suffix, dep.resource);
                });
              });
            } else {
              var url_2 = {
                prefix: "plugins/",
                resource: plugin,
                suffix: "/plugin" + suffix + ".js"
              };
              PluginManager.load(plugin, url_2, noop, void 0, function() {
                pluginLoadError(editor, url_2.prefix + url_2.resource + url_2.suffix, plugin);
              });
            }
          }
        });
      };
      var loadScripts = function(editor, suffix) {
        var scriptLoader = ScriptLoader.ScriptLoader;
        loadTheme(scriptLoader, editor, suffix, function() {
          loadLanguage(scriptLoader, editor);
          loadIcons(scriptLoader, editor, suffix);
          loadPlugins(editor, suffix);
          scriptLoader.loadQueue(function() {
            if (!editor.removed) {
              init(editor);
            }
          }, editor, function() {
            if (!editor.removed) {
              init(editor);
            }
          });
        });
      };
      var getStyleSheetLoader = function(element, editor) {
        return instance.forElement(element, {
          contentCssCors: hasContentCssCors(editor),
          referrerPolicy: getReferrerPolicy(editor)
        });
      };
      var render = function(editor) {
        var id = editor.id;
        I18n.setCode(getLanguageCode(editor));
        var readyHandler = function() {
          DOM$3.unbind(window, "ready", readyHandler);
          editor.render();
        };
        if (!EventUtils.Event.domLoaded) {
          DOM$3.bind(window, "ready", readyHandler);
          return;
        }
        if (!editor.getElement()) {
          return;
        }
        if (!Env.contentEditable) {
          return;
        }
        var element = SugarElement.fromDom(editor.getElement());
        var snapshot = clone$3(element);
        editor.on("remove", function() {
          eachr(element.dom.attributes, function(attr) {
            return remove$6(element, attr.name);
          });
          setAll$1(element, snapshot);
        });
        editor.ui.styleSheetLoader = getStyleSheetLoader(element, editor);
        if (!isInline(editor)) {
          editor.orgVisibility = editor.getElement().style.visibility;
          editor.getElement().style.visibility = "hidden";
        } else {
          editor.inline = true;
        }
        var form = editor.getElement().form || DOM$3.getParent(id, "form");
        if (form) {
          editor.formElement = form;
          if (hasHiddenInput(editor) && !isTextareaOrInput(editor.getElement())) {
            DOM$3.insertAfter(DOM$3.create("input", {
              type: "hidden",
              name: id
            }), id);
            editor.hasHiddenInput = true;
          }
          editor.formEventDelegate = function(e) {
            editor.fire(e.type, e);
          };
          DOM$3.bind(form, "submit reset", editor.formEventDelegate);
          editor.on("reset", function() {
            editor.resetContent();
          });
          if (shouldPatchSubmit(editor) && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
            form._mceOldSubmit = form.submit;
            form.submit = function() {
              editor.editorManager.triggerSave();
              editor.setDirty(false);
              return form._mceOldSubmit(form);
            };
          }
        }
        editor.windowManager = WindowManager(editor);
        editor.notificationManager = NotificationManager(editor);
        if (isEncodingXml(editor)) {
          editor.on("GetContent", function(e) {
            if (e.save) {
              e.content = DOM$3.encode(e.content);
            }
          });
        }
        if (shouldAddFormSubmitTrigger(editor)) {
          editor.on("submit", function() {
            if (editor.initialized) {
              editor.save();
            }
          });
        }
        if (shouldAddUnloadTrigger(editor)) {
          editor._beforeUnload = function() {
            if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
              editor.save({
                format: "raw",
                no_events: true,
                set_dirty: false
              });
            }
          };
          editor.editorManager.on("BeforeUnload", editor._beforeUnload);
        }
        editor.editorManager.add(editor);
        loadScripts(editor, editor.suffix);
      };
      var addVisual = function(editor, elm) {
        return addVisual$1(editor, elm);
      };
      var legacyPropNames = {
        "font-size": "size",
        "font-family": "face"
      };
      var getSpecifiedFontProp = function(propName, rootElm, elm) {
        var getProperty = function(elm2) {
          return getRaw(elm2, propName).orThunk(function() {
            if (name(elm2) === "font") {
              return get$9(legacyPropNames, propName).bind(function(legacyPropName) {
                return getOpt(elm2, legacyPropName);
              });
            } else {
              return Optional.none();
            }
          });
        };
        var isRoot = function(elm2) {
          return eq(SugarElement.fromDom(rootElm), elm2);
        };
        return closest$1(SugarElement.fromDom(elm), function(elm2) {
          return getProperty(elm2);
        }, isRoot);
      };
      var normalizeFontFamily = function(fontFamily) {
        return fontFamily.replace(/[\'\"\\]/g, "").replace(/,\s+/g, ",");
      };
      var getComputedFontProp = function(propName, elm) {
        return Optional.from(DOMUtils.DOM.getStyle(elm, propName, true));
      };
      var getFontProp = function(propName) {
        return function(rootElm, elm) {
          return Optional.from(elm).map(SugarElement.fromDom).filter(isElement$6).bind(function(element) {
            return getSpecifiedFontProp(propName, rootElm, element.dom).or(getComputedFontProp(propName, element.dom));
          }).getOr("");
        };
      };
      var getFontSize = getFontProp("font-size");
      var getFontFamily = compose(normalizeFontFamily, getFontProp("font-family"));
      var findFirstCaretElement = function(editor) {
        return firstPositionIn(editor.getBody()).map(function(caret) {
          var container = caret.container();
          return isText$7(container) ? container.parentNode : container;
        });
      };
      var getCaretElement = function(editor) {
        return Optional.from(editor.selection.getRng()).bind(function(rng) {
          var root = editor.getBody();
          var atStartOfNode = rng.startContainer === root && rng.startOffset === 0;
          return atStartOfNode ? Optional.none() : Optional.from(editor.selection.getStart(true));
        });
      };
      var bindRange = function(editor, binder) {
        return getCaretElement(editor).orThunk(curry(findFirstCaretElement, editor)).map(SugarElement.fromDom).filter(isElement$6).bind(binder);
      };
      var mapRange = function(editor, mapper) {
        return bindRange(editor, compose1(Optional.some, mapper));
      };
      var fromFontSizeNumber = function(editor, value2) {
        if (/^[0-9.]+$/.test(value2)) {
          var fontSizeNumber = parseInt(value2, 10);
          if (fontSizeNumber >= 1 && fontSizeNumber <= 7) {
            var fontSizes = getFontStyleValues(editor);
            var fontClasses = getFontSizeClasses(editor);
            if (fontClasses) {
              return fontClasses[fontSizeNumber - 1] || value2;
            } else {
              return fontSizes[fontSizeNumber - 1] || value2;
            }
          } else {
            return value2;
          }
        } else {
          return value2;
        }
      };
      var normalizeFontNames = function(font) {
        var fonts = font.split(/\s*,\s*/);
        return map$3(fonts, function(font2) {
          if (font2.indexOf(" ") !== -1 && !(startsWith(font2, '"') || startsWith(font2, "'"))) {
            return "'" + font2 + "'";
          } else {
            return font2;
          }
        }).join(",");
      };
      var fontNameAction = function(editor, value2) {
        var font = fromFontSizeNumber(editor, value2);
        editor.formatter.toggle("fontname", { value: normalizeFontNames(font) });
        editor.nodeChanged();
      };
      var fontNameQuery = function(editor) {
        return mapRange(editor, function(elm) {
          return getFontFamily(editor.getBody(), elm.dom);
        }).getOr("");
      };
      var fontSizeAction = function(editor, value2) {
        editor.formatter.toggle("fontsize", { value: fromFontSizeNumber(editor, value2) });
        editor.nodeChanged();
      };
      var fontSizeQuery = function(editor) {
        return mapRange(editor, function(elm) {
          return getFontSize(editor.getBody(), elm.dom);
        }).getOr("");
      };
      var lineHeightQuery = function(editor) {
        return mapRange(editor, function(elm) {
          var root = SugarElement.fromDom(editor.getBody());
          var specifiedStyle = closest$1(elm, function(elm2) {
            return getRaw(elm2, "line-height");
          }, curry(eq, root));
          var computedStyle = function() {
            var lineHeight = parseFloat(get$5(elm, "line-height"));
            var fontSize = parseFloat(get$5(elm, "font-size"));
            return String(lineHeight / fontSize);
          };
          return specifiedStyle.getOrThunk(computedStyle);
        }).getOr("");
      };
      var lineHeightAction = function(editor, lineHeight) {
        editor.formatter.toggle("lineheight", { value: String(lineHeight) });
        editor.nodeChanged();
      };
      var processValue = function(value2) {
        if (typeof value2 !== "string") {
          var details = Tools.extend({
            paste: value2.paste,
            data: { paste: value2.paste }
          }, value2);
          return {
            content: value2.content,
            details
          };
        }
        return {
          content: value2,
          details: {}
        };
      };
      var insertAtCaret = function(editor, value2) {
        var result = processValue(value2);
        insertContent(editor, result.content, result.details);
      };
      var each$4 = Tools.each;
      var map = Tools.map, inArray = Tools.inArray;
      var EditorCommands = function() {
        function EditorCommands2(editor) {
          this.commands = {
            state: {},
            exec: {},
            value: {}
          };
          this.editor = editor;
          this.setupCommands(editor);
        }
        EditorCommands2.prototype.execCommand = function(command, ui, value2, args) {
          var func, state = false;
          var self2 = this;
          if (self2.editor.removed) {
            return;
          }
          if (command.toLowerCase() !== "mcefocus") {
            if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) {
              self2.editor.focus();
            } else {
              restore(self2.editor);
            }
          }
          args = self2.editor.fire("BeforeExecCommand", {
            command,
            ui,
            value: value2
          });
          if (args.isDefaultPrevented()) {
            return false;
          }
          var customCommand = command.toLowerCase();
          if (func = self2.commands.exec[customCommand]) {
            func(customCommand, ui, value2);
            self2.editor.fire("ExecCommand", {
              command,
              ui,
              value: value2
            });
            return true;
          }
          each$4(this.editor.plugins, function(p) {
            if (p.execCommand && p.execCommand(command, ui, value2)) {
              self2.editor.fire("ExecCommand", {
                command,
                ui,
                value: value2
              });
              state = true;
              return false;
            }
          });
          if (state) {
            return state;
          }
          if (self2.editor.theme && self2.editor.theme.execCommand && self2.editor.theme.execCommand(command, ui, value2)) {
            self2.editor.fire("ExecCommand", {
              command,
              ui,
              value: value2
            });
            return true;
          }
          try {
            state = self2.editor.getDoc().execCommand(command, ui, value2);
          } catch (ex) {
          }
          if (state) {
            self2.editor.fire("ExecCommand", {
              command,
              ui,
              value: value2
            });
            return true;
          }
          return false;
        };
        EditorCommands2.prototype.queryCommandState = function(command) {
          var func;
          if (this.editor.quirks.isHidden() || this.editor.removed) {
            return;
          }
          command = command.toLowerCase();
          if (func = this.commands.state[command]) {
            return func(command);
          }
          try {
            return this.editor.getDoc().queryCommandState(command);
          } catch (ex) {
          }
          return false;
        };
        EditorCommands2.prototype.queryCommandValue = function(command) {
          var func;
          if (this.editor.quirks.isHidden() || this.editor.removed) {
            return;
          }
          command = command.toLowerCase();
          if (func = this.commands.value[command]) {
            return func(command);
          }
          try {
            return this.editor.getDoc().queryCommandValue(command);
          } catch (ex) {
          }
        };
        EditorCommands2.prototype.addCommands = function(commandList, type2) {
          if (type2 === void 0) {
            type2 = "exec";
          }
          var self2 = this;
          each$4(commandList, function(callback, command) {
            each$4(command.toLowerCase().split(","), function(command2) {
              self2.commands[type2][command2] = callback;
            });
          });
        };
        EditorCommands2.prototype.addCommand = function(command, callback, scope) {
          var _this = this;
          command = command.toLowerCase();
          this.commands.exec[command] = function(command2, ui, value2, args) {
            return callback.call(scope || _this.editor, ui, value2, args);
          };
        };
        EditorCommands2.prototype.queryCommandSupported = function(command) {
          command = command.toLowerCase();
          if (this.commands.exec[command]) {
            return true;
          }
          try {
            return this.editor.getDoc().queryCommandSupported(command);
          } catch (ex) {
          }
          return false;
        };
        EditorCommands2.prototype.addQueryStateHandler = function(command, callback, scope) {
          var _this = this;
          command = command.toLowerCase();
          this.commands.state[command] = function() {
            return callback.call(scope || _this.editor);
          };
        };
        EditorCommands2.prototype.addQueryValueHandler = function(command, callback, scope) {
          var _this = this;
          command = command.toLowerCase();
          this.commands.value[command] = function() {
            return callback.call(scope || _this.editor);
          };
        };
        EditorCommands2.prototype.hasCustomCommand = function(command) {
          command = command.toLowerCase();
          return !!this.commands.exec[command];
        };
        EditorCommands2.prototype.execNativeCommand = function(command, ui, value2) {
          if (ui === void 0) {
            ui = false;
          }
          if (value2 === void 0) {
            value2 = null;
          }
          return this.editor.getDoc().execCommand(command, ui, value2);
        };
        EditorCommands2.prototype.isFormatMatch = function(name2) {
          return this.editor.formatter.match(name2);
        };
        EditorCommands2.prototype.toggleFormat = function(name2, value2) {
          this.editor.formatter.toggle(name2, value2);
          this.editor.nodeChanged();
        };
        EditorCommands2.prototype.storeSelection = function(type2) {
          this.selectionBookmark = this.editor.selection.getBookmark(type2);
        };
        EditorCommands2.prototype.restoreSelection = function() {
          this.editor.selection.moveToBookmark(this.selectionBookmark);
        };
        EditorCommands2.prototype.setupCommands = function(editor) {
          var self2 = this;
          this.addCommands({
            "mceResetDesignMode,mceBeginUndoLevel": noop,
            "mceEndUndoLevel,mceAddUndoLevel": function() {
              editor.undoManager.add();
            },
            "mceFocus": function(_command, _ui, value2) {
              focus(editor, value2);
            },
            "Cut,Copy,Paste": function(command) {
              var doc2 = editor.getDoc();
              var failed;
              try {
                self2.execNativeCommand(command);
              } catch (ex) {
                failed = true;
              }
              if (command === "paste" && !doc2.queryCommandEnabled(command)) {
                failed = true;
              }
              if (failed || !doc2.queryCommandSupported(command)) {
                var msg = editor.translate("Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead.");
                if (Env.mac) {
                  msg = msg.replace(/Ctrl\+/g, "\u2318+");
                }
                editor.notificationManager.open({
                  text: msg,
                  type: "error"
                });
              }
            },
            "unlink": function() {
              if (editor.selection.isCollapsed()) {
                var elm = editor.dom.getParent(editor.selection.getStart(), "a");
                if (elm) {
                  editor.dom.remove(elm, true);
                }
                return;
              }
              editor.formatter.remove("link");
            },
            "JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone": function(command) {
              var align = command.substring(7);
              if (align === "full") {
                align = "justify";
              }
              each$4("left,center,right,justify".split(","), function(name2) {
                if (align !== name2) {
                  editor.formatter.remove("align" + name2);
                }
              });
              if (align !== "none") {
                self2.toggleFormat("align" + align);
              }
            },
            "InsertUnorderedList,InsertOrderedList": function(command) {
              var listParent;
              self2.execNativeCommand(command);
              var listElm = editor.dom.getParent(editor.selection.getNode(), "ol,ul");
              if (listElm) {
                listParent = listElm.parentNode;
                if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
                  self2.storeSelection();
                  editor.dom.split(listParent, listElm);
                  self2.restoreSelection();
                }
              }
            },
            "Bold,Italic,Underline,Strikethrough,Superscript,Subscript": function(command) {
              self2.toggleFormat(command);
            },
            "ForeColor,HiliteColor": function(command, ui, value2) {
              self2.toggleFormat(command, { value: value2 });
            },
            "FontName": function(command, ui, value2) {
              fontNameAction(editor, value2);
            },
            "FontSize": function(command, ui, value2) {
              fontSizeAction(editor, value2);
            },
            "LineHeight": function(command, ui, value2) {
              lineHeightAction(editor, value2);
            },
            "Lang": function(command, ui, lang) {
              self2.toggleFormat(command, {
                value: lang.code,
                customValue: lang.customCode
              });
            },
            "RemoveFormat": function(command) {
              editor.formatter.remove(command);
            },
            "mceBlockQuote": function() {
              self2.toggleFormat("blockquote");
            },
            "FormatBlock": function(command, ui, value2) {
              return self2.toggleFormat(value2 || "p");
            },
            "mceCleanup": function() {
              var bookmark = editor.selection.getBookmark();
              editor.setContent(editor.getContent());
              editor.selection.moveToBookmark(bookmark);
            },
            "mceRemoveNode": function(command, ui, value2) {
              var node = value2 || editor.selection.getNode();
              if (node !== editor.getBody()) {
                self2.storeSelection();
                editor.dom.remove(node, true);
                self2.restoreSelection();
              }
            },
            "mceSelectNodeDepth": function(command, ui, value2) {
              var counter = 0;
              editor.dom.getParent(editor.selection.getNode(), function(node) {
                if (node.nodeType === 1 && counter++ === value2) {
                  editor.selection.select(node);
                  return false;
                }
              }, editor.getBody());
            },
            "mceSelectNode": function(command, ui, value2) {
              editor.selection.select(value2);
            },
            "mceInsertContent": function(command, ui, value2) {
              insertAtCaret(editor, value2);
            },
            "mceInsertRawHTML": function(command, ui, value2) {
              editor.selection.setContent("tiny_mce_marker");
              var content = editor.getContent();
              editor.setContent(content.replace(/tiny_mce_marker/g, function() {
                return value2;
              }));
            },
            "mceInsertNewLine": function(command, ui, value2) {
              insert(editor, value2);
            },
            "mceToggleFormat": function(command, ui, value2) {
              self2.toggleFormat(value2);
            },
            "mceSetContent": function(command, ui, value2) {
              editor.setContent(value2);
            },
            "Indent,Outdent": function(command) {
              handle(editor, command);
            },
            "mceRepaint": noop,
            "InsertHorizontalRule": function() {
              editor.execCommand("mceInsertContent", false, "<hr />");
            },
            "mceToggleVisualAid": function() {
              editor.hasVisual = !editor.hasVisual;
              editor.addVisual();
            },
            "mceReplaceContent": function(command, ui, value2) {
              editor.execCommand("mceInsertContent", false, value2.replace(/\{\$selection\}/g, editor.selection.getContent({ format: "text" })));
            },
            "mceInsertLink": function(command, ui, value2) {
              if (typeof value2 === "string") {
                value2 = { href: value2 };
              }
              var anchor = editor.dom.getParent(editor.selection.getNode(), "a");
              value2.href = value2.href.replace(/ /g, "%20");
              if (!anchor || !value2.href) {
                editor.formatter.remove("link");
              }
              if (value2.href) {
                editor.formatter.apply("link", value2, anchor);
              }
            },
            "selectAll": function() {
              var editingHost = editor.dom.getParent(editor.selection.getStart(), isContentEditableTrue$4);
              if (editingHost) {
                var rng = editor.dom.createRng();
                rng.selectNodeContents(editingHost);
                editor.selection.setRng(rng);
              }
            },
            "mceNewDocument": function() {
              editor.setContent("");
            },
            "InsertLineBreak": function(command, ui, value2) {
              insert$1(editor, value2);
              return true;
            }
          });
          var alignStates = function(name2) {
            return function() {
              var selection = editor.selection;
              var nodes = selection.isCollapsed() ? [editor.dom.getParent(selection.getNode(), editor.dom.isBlock)] : selection.getSelectedBlocks();
              var matches2 = map(nodes, function(node) {
                return !!editor.formatter.matchNode(node, name2);
              });
              return inArray(matches2, true) !== -1;
            };
          };
          self2.addCommands({
            "JustifyLeft": alignStates("alignleft"),
            "JustifyCenter": alignStates("aligncenter"),
            "JustifyRight": alignStates("alignright"),
            "JustifyFull": alignStates("alignjustify"),
            "Bold,Italic,Underline,Strikethrough,Superscript,Subscript": function(command) {
              return self2.isFormatMatch(command);
            },
            "mceBlockQuote": function() {
              return self2.isFormatMatch("blockquote");
            },
            "Outdent": function() {
              return canOutdent(editor);
            },
            "InsertUnorderedList,InsertOrderedList": function(command) {
              var list = editor.dom.getParent(editor.selection.getNode(), "ul,ol");
              return list && (command === "insertunorderedlist" && list.tagName === "UL" || command === "insertorderedlist" && list.tagName === "OL");
            }
          }, "state");
          self2.addCommands({
            Undo: function() {
              editor.undoManager.undo();
            },
            Redo: function() {
              editor.undoManager.redo();
            }
          });
          self2.addQueryValueHandler("FontName", function() {
            return fontNameQuery(editor);
          }, this);
          self2.addQueryValueHandler("FontSize", function() {
            return fontSizeQuery(editor);
          }, this);
          self2.addQueryValueHandler("LineHeight", function() {
            return lineHeightQuery(editor);
          }, this);
        };
        return EditorCommands2;
      }();
      var internalContentEditableAttr = "data-mce-contenteditable";
      var toggleClass = function(elm, cls, state) {
        if (has(elm, cls) && state === false) {
          remove$3(elm, cls);
        } else if (state) {
          add$1(elm, cls);
        }
      };
      var setEditorCommandState = function(editor, cmd, state) {
        try {
          editor.getDoc().execCommand(cmd, false, String(state));
        } catch (ex) {
        }
      };
      var setContentEditable = function(elm, state) {
        elm.dom.contentEditable = state ? "true" : "false";
      };
      var switchOffContentEditableTrue = function(elm) {
        each$k(descendants(elm, '*[contenteditable="true"]'), function(elm2) {
          set$1(elm2, internalContentEditableAttr, "true");
          setContentEditable(elm2, false);
        });
      };
      var switchOnContentEditableTrue = function(elm) {
        each$k(descendants(elm, "*[" + internalContentEditableAttr + '="true"]'), function(elm2) {
          remove$6(elm2, internalContentEditableAttr);
          setContentEditable(elm2, true);
        });
      };
      var removeFakeSelection = function(editor) {
        Optional.from(editor.selection.getNode()).each(function(elm) {
          elm.removeAttribute("data-mce-selected");
        });
      };
      var restoreFakeSelection = function(editor) {
        editor.selection.setRng(editor.selection.getRng());
      };
      var toggleReadOnly = function(editor, state) {
        var body = SugarElement.fromDom(editor.getBody());
        toggleClass(body, "mce-content-readonly", state);
        if (state) {
          editor.selection.controlSelection.hideResizeRect();
          editor._selectionOverrides.hideFakeCaret();
          removeFakeSelection(editor);
          editor.readonly = true;
          setContentEditable(body, false);
          switchOffContentEditableTrue(body);
        } else {
          editor.readonly = false;
          setContentEditable(body, true);
          switchOnContentEditableTrue(body);
          setEditorCommandState(editor, "StyleWithCSS", false);
          setEditorCommandState(editor, "enableInlineTableEditing", false);
          setEditorCommandState(editor, "enableObjectResizing", false);
          if (hasEditorOrUiFocus(editor)) {
            editor.focus();
          }
          restoreFakeSelection(editor);
          editor.nodeChanged();
        }
      };
      var isReadOnly = function(editor) {
        return editor.readonly;
      };
      var registerFilters = function(editor) {
        editor.parser.addAttributeFilter("contenteditable", function(nodes) {
          if (isReadOnly(editor)) {
            each$k(nodes, function(node) {
              node.attr(internalContentEditableAttr, node.attr("contenteditable"));
              node.attr("contenteditable", "false");
            });
          }
        });
        editor.serializer.addAttributeFilter(internalContentEditableAttr, function(nodes) {
          if (isReadOnly(editor)) {
            each$k(nodes, function(node) {
              node.attr("contenteditable", node.attr(internalContentEditableAttr));
            });
          }
        });
        editor.serializer.addTempAttr(internalContentEditableAttr);
      };
      var registerReadOnlyContentFilters = function(editor) {
        if (editor.serializer) {
          registerFilters(editor);
        } else {
          editor.on("PreInit", function() {
            registerFilters(editor);
          });
        }
      };
      var isClickEvent = function(e) {
        return e.type === "click";
      };
      var getAnchorHrefOpt = function(editor, elm) {
        var isRoot = function(elm2) {
          return eq(elm2, SugarElement.fromDom(editor.getBody()));
        };
        return closest$2(elm, "a", isRoot).bind(function(a) {
          return getOpt(a, "href");
        });
      };
      var processReadonlyEvents = function(editor, e) {
        if (isClickEvent(e) && !VK.metaKeyPressed(e)) {
          var elm = SugarElement.fromDom(e.target);
          getAnchorHrefOpt(editor, elm).each(function(href) {
            e.preventDefault();
            if (/^#/.test(href)) {
              var targetEl = editor.dom.select(href + ',[name="' + removeLeading(href, "#") + '"]');
              if (targetEl.length) {
                editor.selection.scrollIntoView(targetEl[0], true);
              }
            } else {
              window.open(href, "_blank", "rel=noopener noreferrer,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes,scrollbars=yes");
            }
          });
        }
      };
      var registerReadOnlySelectionBlockers = function(editor) {
        editor.on("ShowCaret", function(e) {
          if (isReadOnly(editor)) {
            e.preventDefault();
          }
        });
        editor.on("ObjectSelected", function(e) {
          if (isReadOnly(editor)) {
            e.preventDefault();
          }
        });
      };
      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", " ");
      var EventDispatcher = function() {
        function EventDispatcher2(settings) {
          this.bindings = {};
          this.settings = settings || {};
          this.scope = this.settings.scope || this;
          this.toggleEvent = this.settings.toggleEvent || never;
        }
        EventDispatcher2.isNative = function(name2) {
          return !!nativeEvents[name2.toLowerCase()];
        };
        EventDispatcher2.prototype.fire = function(name2, args) {
          var lcName = name2.toLowerCase();
          var event = normalize$3(lcName, args || {}, this.scope);
          if (this.settings.beforeFire) {
            this.settings.beforeFire(event);
          }
          var handlers = this.bindings[lcName];
          if (handlers) {
            for (var i = 0, l = handlers.length; i < l; i++) {
              var callback = handlers[i];
              if (callback.removed) {
                continue;
              }
              if (callback.once) {
                this.off(lcName, callback.func);
              }
              if (event.isImmediatePropagationStopped()) {
                return event;
              }
              if (callback.func.call(this.scope, event) === false) {
                event.preventDefault();
                return event;
              }
            }
          }
          return event;
        };
        EventDispatcher2.prototype.on = function(name2, callback, prepend2, extra2) {
          if (callback === false) {
            callback = never;
          }
          if (callback) {
            var wrappedCallback = {
              func: callback,
              removed: false
            };
            if (extra2) {
              Tools.extend(wrappedCallback, extra2);
            }
            var names = name2.toLowerCase().split(" ");
            var i = names.length;
            while (i--) {
              var currentName = names[i];
              var handlers = this.bindings[currentName];
              if (!handlers) {
                handlers = [];
                this.toggleEvent(currentName, true);
              }
              if (prepend2) {
                handlers = __spreadArray([wrappedCallback], handlers, true);
              } else {
                handlers = __spreadArray(__spreadArray([], handlers, true), [wrappedCallback], false);
              }
              this.bindings[currentName] = handlers;
            }
          }
          return this;
        };
        EventDispatcher2.prototype.off = function(name2, callback) {
          var _this = this;
          if (name2) {
            var names = name2.toLowerCase().split(" ");
            var i = names.length;
            while (i--) {
              var currentName = names[i];
              var handlers = this.bindings[currentName];
              if (!currentName) {
                each$j(this.bindings, function(_value, bindingName) {
                  _this.toggleEvent(bindingName, false);
                  delete _this.bindings[bindingName];
                });
                return this;
              }
              if (handlers) {
                if (!callback) {
                  handlers.length = 0;
                } else {
                  var filteredHandlers = partition(handlers, function(handler) {
                    return handler.func === callback;
                  });
                  handlers = filteredHandlers.fail;
                  this.bindings[currentName] = handlers;
                  each$k(filteredHandlers.pass, function(handler) {
                    handler.removed = true;
                  });
                }
                if (!handlers.length) {
                  this.toggleEvent(name2, false);
                  delete this.bindings[currentName];
                }
              }
            }
          } else {
            each$j(this.bindings, function(_value, name3) {
              _this.toggleEvent(name3, false);
            });
            this.bindings = {};
          }
          return this;
        };
        EventDispatcher2.prototype.once = function(name2, callback, prepend2) {
          return this.on(name2, callback, prepend2, { once: true });
        };
        EventDispatcher2.prototype.has = function(name2) {
          name2 = name2.toLowerCase();
          return !(!this.bindings[name2] || this.bindings[name2].length === 0);
        };
        return EventDispatcher2;
      }();
      var getEventDispatcher = function(obj) {
        if (!obj._eventDispatcher) {
          obj._eventDispatcher = new EventDispatcher({
            scope: obj,
            toggleEvent: function(name2, state) {
              if (EventDispatcher.isNative(name2) && obj.toggleNativeEvent) {
                obj.toggleNativeEvent(name2, state);
              }
            }
          });
        }
        return obj._eventDispatcher;
      };
      var Observable = {
        fire: function(name2, args, bubble) {
          var self2 = this;
          if (self2.removed && name2 !== "remove" && name2 !== "detach") {
            return args;
          }
          var dispatcherArgs = getEventDispatcher(self2).fire(name2, args);
          if (bubble !== false && self2.parent) {
            var parent_1 = self2.parent();
            while (parent_1 && !dispatcherArgs.isPropagationStopped()) {
              parent_1.fire(name2, dispatcherArgs, false);
              parent_1 = parent_1.parent();
            }
          }
          return dispatcherArgs;
        },
        on: function(name2, callback, prepend2) {
          return getEventDispatcher(this).on(name2, callback, prepend2);
        },
        off: function(name2, callback) {
          return getEventDispatcher(this).off(name2, callback);
        },
        once: function(name2, callback) {
          return getEventDispatcher(this).once(name2, callback);
        },
        hasEventListeners: function(name2) {
          return getEventDispatcher(this).has(name2);
        }
      };
      var DOM$2 = DOMUtils.DOM;
      var customEventRootDelegates;
      var getEventTarget = function(editor, eventName) {
        if (eventName === "selectionchange") {
          return editor.getDoc();
        }
        if (!editor.inline && /^mouse|touch|click|contextmenu|drop|dragover|dragend/.test(eventName)) {
          return editor.getDoc().documentElement;
        }
        var eventRoot = getEventRoot(editor);
        if (eventRoot) {
          if (!editor.eventRoot) {
            editor.eventRoot = DOM$2.select(eventRoot)[0];
          }
          return editor.eventRoot;
        }
        return editor.getBody();
      };
      var isListening = function(editor) {
        return !editor.hidden && !isReadOnly(editor);
      };
      var fireEvent = function(editor, eventName, e) {
        if (isListening(editor)) {
          editor.fire(eventName, e);
        } else if (isReadOnly(editor)) {
          processReadonlyEvents(editor, e);
        }
      };
      var bindEventDelegate = function(editor, eventName) {
        var delegate;
        if (!editor.delegates) {
          editor.delegates = {};
        }
        if (editor.delegates[eventName] || editor.removed) {
          return;
        }
        var eventRootElm = getEventTarget(editor, eventName);
        if (getEventRoot(editor)) {
          if (!customEventRootDelegates) {
            customEventRootDelegates = {};
            editor.editorManager.on("removeEditor", function() {
              if (!editor.editorManager.activeEditor) {
                if (customEventRootDelegates) {
                  each$j(customEventRootDelegates, function(_value, name2) {
                    editor.dom.unbind(getEventTarget(editor, name2));
                  });
                  customEventRootDelegates = null;
                }
              }
            });
          }
          if (customEventRootDelegates[eventName]) {
            return;
          }
          delegate = function(e) {
            var target = e.target;
            var editors2 = editor.editorManager.get();
            var i = editors2.length;
            while (i--) {
              var body = editors2[i].getBody();
              if (body === target || DOM$2.isChildOf(target, body)) {
                fireEvent(editors2[i], eventName, e);
              }
            }
          };
          customEventRootDelegates[eventName] = delegate;
          DOM$2.bind(eventRootElm, eventName, delegate);
        } else {
          delegate = function(e) {
            fireEvent(editor, eventName, e);
          };
          DOM$2.bind(eventRootElm, eventName, delegate);
          editor.delegates[eventName] = delegate;
        }
      };
      var EditorObservable = __assign(__assign({}, Observable), {
        bindPendingEventDelegates: function() {
          var self2 = this;
          Tools.each(self2._pendingNativeEvents, function(name2) {
            bindEventDelegate(self2, name2);
          });
        },
        toggleNativeEvent: function(name2, state) {
          var self2 = this;
          if (name2 === "focus" || name2 === "blur") {
            return;
          }
          if (self2.removed) {
            return;
          }
          if (state) {
            if (self2.initialized) {
              bindEventDelegate(self2, name2);
            } else {
              if (!self2._pendingNativeEvents) {
                self2._pendingNativeEvents = [name2];
              } else {
                self2._pendingNativeEvents.push(name2);
              }
            }
          } else if (self2.initialized) {
            self2.dom.unbind(getEventTarget(self2, name2), name2, self2.delegates[name2]);
            delete self2.delegates[name2];
          }
        },
        unbindAllNativeEvents: function() {
          var self2 = this;
          var body = self2.getBody();
          var dom2 = self2.dom;
          if (self2.delegates) {
            each$j(self2.delegates, function(value2, name2) {
              self2.dom.unbind(getEventTarget(self2, name2), name2, value2);
            });
            delete self2.delegates;
          }
          if (!self2.inline && body && dom2) {
            body.onload = null;
            dom2.unbind(self2.getWin());
            dom2.unbind(self2.getDoc());
          }
          if (dom2) {
            dom2.unbind(body);
            dom2.unbind(self2.getContainer());
          }
        }
      });
      var defaultModes = [
        "design",
        "readonly"
      ];
      var switchToMode = function(editor, activeMode, availableModes, mode) {
        var oldMode = availableModes[activeMode.get()];
        var newMode = availableModes[mode];
        try {
          newMode.activate();
        } catch (e) {
          console.error("problem while activating editor mode " + mode + ":", e);
          return;
        }
        oldMode.deactivate();
        if (oldMode.editorReadOnly !== newMode.editorReadOnly) {
          toggleReadOnly(editor, newMode.editorReadOnly);
        }
        activeMode.set(mode);
        fireSwitchMode(editor, mode);
      };
      var setMode = function(editor, availableModes, activeMode, mode) {
        if (mode === activeMode.get()) {
          return;
        } else if (!has$2(availableModes, mode)) {
          throw new Error("Editor mode '" + mode + "' is invalid");
        }
        if (editor.initialized) {
          switchToMode(editor, activeMode, availableModes, mode);
        } else {
          editor.on("init", function() {
            return switchToMode(editor, activeMode, availableModes, mode);
          });
        }
      };
      var registerMode = function(availableModes, mode, api2) {
        var _a;
        if (contains$3(defaultModes, mode)) {
          throw new Error("Cannot override default mode " + mode);
        }
        return __assign(__assign({}, availableModes), (_a = {}, _a[mode] = __assign(__assign({}, api2), {
          deactivate: function() {
            try {
              api2.deactivate();
            } catch (e) {
              console.error("problem while deactivating editor mode " + mode + ":", e);
            }
          }
        }), _a));
      };
      var create$4 = function(editor) {
        var activeMode = Cell("design");
        var availableModes = Cell({
          design: {
            activate: noop,
            deactivate: noop,
            editorReadOnly: false
          },
          readonly: {
            activate: noop,
            deactivate: noop,
            editorReadOnly: true
          }
        });
        registerReadOnlyContentFilters(editor);
        registerReadOnlySelectionBlockers(editor);
        return {
          isReadOnly: function() {
            return isReadOnly(editor);
          },
          set: function(mode) {
            return setMode(editor, availableModes.get(), activeMode, mode);
          },
          get: function() {
            return activeMode.get();
          },
          register: function(mode, api2) {
            availableModes.set(registerMode(availableModes.get(), mode, api2));
          }
        };
      };
      var each$3 = Tools.each, explode$1 = Tools.explode;
      var keyCodeLookup = {
        f1: 112,
        f2: 113,
        f3: 114,
        f4: 115,
        f5: 116,
        f6: 117,
        f7: 118,
        f8: 119,
        f9: 120,
        f10: 121,
        f11: 122,
        f12: 123
      };
      var modifierNames = Tools.makeMap("alt,ctrl,shift,meta,access");
      var parseShortcut = function(pattern) {
        var key;
        var shortcut = {};
        each$3(explode$1(pattern.toLowerCase(), "+"), function(value2) {
          if (value2 in modifierNames) {
            shortcut[value2] = true;
          } else {
            if (/^[0-9]{2,}$/.test(value2)) {
              shortcut.keyCode = parseInt(value2, 10);
            } else {
              shortcut.charCode = value2.charCodeAt(0);
              shortcut.keyCode = keyCodeLookup[value2] || value2.toUpperCase().charCodeAt(0);
            }
          }
        });
        var id = [shortcut.keyCode];
        for (key in modifierNames) {
          if (shortcut[key]) {
            id.push(key);
          } else {
            shortcut[key] = false;
          }
        }
        shortcut.id = id.join(",");
        if (shortcut.access) {
          shortcut.alt = true;
          if (Env.mac) {
            shortcut.ctrl = true;
          } else {
            shortcut.shift = true;
          }
        }
        if (shortcut.meta) {
          if (Env.mac) {
            shortcut.meta = true;
          } else {
            shortcut.ctrl = true;
            shortcut.meta = false;
          }
        }
        return shortcut;
      };
      var Shortcuts = function() {
        function Shortcuts2(editor) {
          this.shortcuts = {};
          this.pendingPatterns = [];
          this.editor = editor;
          var self2 = this;
          editor.on("keyup keypress keydown", function(e) {
            if ((self2.hasModifier(e) || self2.isFunctionKey(e)) && !e.isDefaultPrevented()) {
              each$3(self2.shortcuts, function(shortcut) {
                if (self2.matchShortcut(e, shortcut)) {
                  self2.pendingPatterns = shortcut.subpatterns.slice(0);
                  if (e.type === "keydown") {
                    self2.executeShortcutAction(shortcut);
                  }
                  return true;
                }
              });
              if (self2.matchShortcut(e, self2.pendingPatterns[0])) {
                if (self2.pendingPatterns.length === 1) {
                  if (e.type === "keydown") {
                    self2.executeShortcutAction(self2.pendingPatterns[0]);
                  }
                }
                self2.pendingPatterns.shift();
              }
            }
          });
        }
        Shortcuts2.prototype.add = function(pattern, desc, cmdFunc, scope) {
          var self2 = this;
          var func = self2.normalizeCommandFunc(cmdFunc);
          each$3(explode$1(Tools.trim(pattern)), function(pattern2) {
            var shortcut = self2.createShortcut(pattern2, desc, func, scope);
            self2.shortcuts[shortcut.id] = shortcut;
          });
          return true;
        };
        Shortcuts2.prototype.remove = function(pattern) {
          var shortcut = this.createShortcut(pattern);
          if (this.shortcuts[shortcut.id]) {
            delete this.shortcuts[shortcut.id];
            return true;
          }
          return false;
        };
        Shortcuts2.prototype.normalizeCommandFunc = function(cmdFunc) {
          var self2 = this;
          var cmd = cmdFunc;
          if (typeof cmd === "string") {
            return function() {
              self2.editor.execCommand(cmd, false, null);
            };
          } else if (Tools.isArray(cmd)) {
            return function() {
              self2.editor.execCommand(cmd[0], cmd[1], cmd[2]);
            };
          } else {
            return cmd;
          }
        };
        Shortcuts2.prototype.createShortcut = function(pattern, desc, cmdFunc, scope) {
          var shortcuts = Tools.map(explode$1(pattern, ">"), parseShortcut);
          shortcuts[shortcuts.length - 1] = Tools.extend(shortcuts[shortcuts.length - 1], {
            func: cmdFunc,
            scope: scope || this.editor
          });
          return Tools.extend(shortcuts[0], {
            desc: this.editor.translate(desc),
            subpatterns: shortcuts.slice(1)
          });
        };
        Shortcuts2.prototype.hasModifier = function(e) {
          return e.altKey || e.ctrlKey || e.metaKey;
        };
        Shortcuts2.prototype.isFunctionKey = function(e) {
          return e.type === "keydown" && e.keyCode >= 112 && e.keyCode <= 123;
        };
        Shortcuts2.prototype.matchShortcut = function(e, shortcut) {
          if (!shortcut) {
            return false;
          }
          if (shortcut.ctrl !== e.ctrlKey || shortcut.meta !== e.metaKey) {
            return false;
          }
          if (shortcut.alt !== e.altKey || shortcut.shift !== e.shiftKey) {
            return false;
          }
          if (e.keyCode === shortcut.keyCode || e.charCode && e.charCode === shortcut.charCode) {
            e.preventDefault();
            return true;
          }
          return false;
        };
        Shortcuts2.prototype.executeShortcutAction = function(shortcut) {
          return shortcut.func ? shortcut.func.call(shortcut.scope) : null;
        };
        return Shortcuts2;
      }();
      var create$3 = function() {
        var buttons = {};
        var menuItems = {};
        var popups = {};
        var icons = {};
        var contextMenus = {};
        var contextToolbars = {};
        var sidebars = {};
        var add2 = function(collection, type2) {
          return function(name2, spec) {
            return collection[name2.toLowerCase()] = __assign(__assign({}, spec), { type: type2 });
          };
        };
        var addIcon = function(name2, svgData) {
          return icons[name2.toLowerCase()] = svgData;
        };
        return {
          addButton: add2(buttons, "button"),
          addGroupToolbarButton: add2(buttons, "grouptoolbarbutton"),
          addToggleButton: add2(buttons, "togglebutton"),
          addMenuButton: add2(buttons, "menubutton"),
          addSplitButton: add2(buttons, "splitbutton"),
          addMenuItem: add2(menuItems, "menuitem"),
          addNestedMenuItem: add2(menuItems, "nestedmenuitem"),
          addToggleMenuItem: add2(menuItems, "togglemenuitem"),
          addAutocompleter: add2(popups, "autocompleter"),
          addContextMenu: add2(contextMenus, "contextmenu"),
          addContextToolbar: add2(contextToolbars, "contexttoolbar"),
          addContextForm: add2(contextToolbars, "contextform"),
          addSidebar: add2(sidebars, "sidebar"),
          addIcon,
          getAll: function() {
            return {
              buttons,
              menuItems,
              icons,
              popups,
              contextMenus,
              contextToolbars,
              sidebars
            };
          }
        };
      };
      var registry = function() {
        var bridge = create$3();
        return {
          addAutocompleter: bridge.addAutocompleter,
          addButton: bridge.addButton,
          addContextForm: bridge.addContextForm,
          addContextMenu: bridge.addContextMenu,
          addContextToolbar: bridge.addContextToolbar,
          addIcon: bridge.addIcon,
          addMenuButton: bridge.addMenuButton,
          addMenuItem: bridge.addMenuItem,
          addNestedMenuItem: bridge.addNestedMenuItem,
          addSidebar: bridge.addSidebar,
          addSplitButton: bridge.addSplitButton,
          addToggleButton: bridge.addToggleButton,
          addGroupToolbarButton: bridge.addGroupToolbarButton,
          addToggleMenuItem: bridge.addToggleMenuItem,
          getAll: bridge.getAll
        };
      };
      var DOM$1 = DOMUtils.DOM;
      var extend$3 = Tools.extend, each$2 = Tools.each;
      var resolve = Tools.resolve;
      var ie = Env.ie;
      var Editor = function() {
        function Editor2(id, settings, editorManager) {
          var _this = this;
          this.plugins = {};
          this.contentCSS = [];
          this.contentStyles = [];
          this.loadedCSS = {};
          this.isNotDirty = false;
          this.editorManager = editorManager;
          this.documentBaseUrl = editorManager.documentBaseURL;
          extend$3(this, EditorObservable);
          this.settings = getEditorSettings(this, id, this.documentBaseUrl, editorManager.defaultSettings, settings);
          if (this.settings.suffix) {
            editorManager.suffix = this.settings.suffix;
          }
          this.suffix = editorManager.suffix;
          if (this.settings.base_url) {
            editorManager._setBaseUrl(this.settings.base_url);
          }
          this.baseUri = editorManager.baseURI;
          if (this.settings.referrer_policy) {
            ScriptLoader.ScriptLoader._setReferrerPolicy(this.settings.referrer_policy);
            DOMUtils.DOM.styleSheetLoader._setReferrerPolicy(this.settings.referrer_policy);
          }
          AddOnManager.languageLoad = this.settings.language_load;
          AddOnManager.baseURL = editorManager.baseURL;
          this.id = id;
          this.setDirty(false);
          this.documentBaseURI = new URI(this.settings.document_base_url, { base_uri: this.baseUri });
          this.baseURI = this.baseUri;
          this.inline = !!this.settings.inline;
          this.shortcuts = new Shortcuts(this);
          this.editorCommands = new EditorCommands(this);
          if (this.settings.cache_suffix) {
            Env.cacheSuffix = this.settings.cache_suffix.replace(/^[\?\&]+/, "");
          }
          this.ui = {
            registry: registry(),
            styleSheetLoader: void 0,
            show: noop,
            hide: noop,
            enable: noop,
            disable: noop,
            isDisabled: never
          };
          var self2 = this;
          var modeInstance = create$4(self2);
          this.mode = modeInstance;
          this.setMode = modeInstance.set;
          editorManager.fire("SetupEditor", { editor: this });
          this.execCallback("setup", this);
          this.$ = DomQuery.overrideDefaults(function() {
            return {
              context: _this.inline ? _this.getBody() : _this.getDoc(),
              element: _this.getBody()
            };
          });
        }
        Editor2.prototype.render = function() {
          render(this);
        };
        Editor2.prototype.focus = function(skipFocus) {
          this.execCommand("mceFocus", false, skipFocus);
        };
        Editor2.prototype.hasFocus = function() {
          return hasFocus(this);
        };
        Editor2.prototype.execCallback = function(name2) {
          var x = [];
          for (var _i = 1; _i < arguments.length; _i++) {
            x[_i - 1] = arguments[_i];
          }
          var self2 = this;
          var callback = self2.settings[name2], scope;
          if (!callback) {
            return;
          }
          if (self2.callbackLookup && (scope = self2.callbackLookup[name2])) {
            callback = scope.func;
            scope = scope.scope;
          }
          if (typeof callback === "string") {
            scope = callback.replace(/\.\w+$/, "");
            scope = scope ? resolve(scope) : 0;
            callback = resolve(callback);
            self2.callbackLookup = self2.callbackLookup || {};
            self2.callbackLookup[name2] = {
              func: callback,
              scope
            };
          }
          return callback.apply(scope || self2, x);
        };
        Editor2.prototype.translate = function(text) {
          return I18n.translate(text);
        };
        Editor2.prototype.getParam = function(name2, defaultVal, type2) {
          return getParam(this, name2, defaultVal, type2);
        };
        Editor2.prototype.hasPlugin = function(name2, loaded) {
          var hasPlugin = contains$3(getPlugins(this).split(/[ ,]/), name2);
          if (hasPlugin) {
            return loaded ? PluginManager.get(name2) !== void 0 : true;
          } else {
            return false;
          }
        };
        Editor2.prototype.nodeChanged = function(args) {
          this._nodeChangeDispatcher.nodeChanged(args);
        };
        Editor2.prototype.addCommand = function(name2, callback, scope) {
          this.editorCommands.addCommand(name2, callback, scope);
        };
        Editor2.prototype.addQueryStateHandler = function(name2, callback, scope) {
          this.editorCommands.addQueryStateHandler(name2, callback, scope);
        };
        Editor2.prototype.addQueryValueHandler = function(name2, callback, scope) {
          this.editorCommands.addQueryValueHandler(name2, callback, scope);
        };
        Editor2.prototype.addShortcut = function(pattern, desc, cmdFunc, scope) {
          this.shortcuts.add(pattern, desc, cmdFunc, scope);
        };
        Editor2.prototype.execCommand = function(cmd, ui, value2, args) {
          return this.editorCommands.execCommand(cmd, ui, value2, args);
        };
        Editor2.prototype.queryCommandState = function(cmd) {
          return this.editorCommands.queryCommandState(cmd);
        };
        Editor2.prototype.queryCommandValue = function(cmd) {
          return this.editorCommands.queryCommandValue(cmd);
        };
        Editor2.prototype.queryCommandSupported = function(cmd) {
          return this.editorCommands.queryCommandSupported(cmd);
        };
        Editor2.prototype.show = function() {
          var self2 = this;
          if (self2.hidden) {
            self2.hidden = false;
            if (self2.inline) {
              self2.getBody().contentEditable = "true";
            } else {
              DOM$1.show(self2.getContainer());
              DOM$1.hide(self2.id);
            }
            self2.load();
            self2.fire("show");
          }
        };
        Editor2.prototype.hide = function() {
          var self2 = this, doc2 = self2.getDoc();
          if (!self2.hidden) {
            if (ie && doc2 && !self2.inline) {
              doc2.execCommand("SelectAll");
            }
            self2.save();
            if (self2.inline) {
              self2.getBody().contentEditable = "false";
              if (self2 === self2.editorManager.focusedEditor) {
                self2.editorManager.focusedEditor = null;
              }
            } else {
              DOM$1.hide(self2.getContainer());
              DOM$1.setStyle(self2.id, "display", self2.orgDisplay);
            }
            self2.hidden = true;
            self2.fire("hide");
          }
        };
        Editor2.prototype.isHidden = function() {
          return !!this.hidden;
        };
        Editor2.prototype.setProgressState = function(state, time) {
          this.fire("ProgressState", {
            state,
            time
          });
        };
        Editor2.prototype.load = function(args) {
          var self2 = this;
          var elm = self2.getElement(), html;
          if (self2.removed) {
            return "";
          }
          if (elm) {
            args = args || {};
            args.load = true;
            var value2 = isTextareaOrInput(elm) ? elm.value : elm.innerHTML;
            html = self2.setContent(value2, args);
            args.element = elm;
            if (!args.no_events) {
              self2.fire("LoadContent", args);
            }
            args.element = elm = null;
            return html;
          }
        };
        Editor2.prototype.save = function(args) {
          var self2 = this;
          var elm = self2.getElement(), html, form;
          if (!elm || !self2.initialized || self2.removed) {
            return;
          }
          args = args || {};
          args.save = true;
          args.element = elm;
          html = args.content = self2.getContent(args);
          if (!args.no_events) {
            self2.fire("SaveContent", args);
          }
          if (args.format === "raw") {
            self2.fire("RawSaveContent", args);
          }
          html = args.content;
          if (!isTextareaOrInput(elm)) {
            if (args.is_removing || !self2.inline) {
              elm.innerHTML = html;
            }
            if (form = DOM$1.getParent(self2.id, "form")) {
              each$2(form.elements, function(elm2) {
                if (elm2.name === self2.id) {
                  elm2.value = html;
                  return false;
                }
              });
            }
          } else {
            elm.value = html;
          }
          args.element = elm = null;
          if (args.set_dirty !== false) {
            self2.setDirty(false);
          }
          return html;
        };
        Editor2.prototype.setContent = function(content, args) {
          return setContent(this, content, args);
        };
        Editor2.prototype.getContent = function(args) {
          return getContent(this, args);
        };
        Editor2.prototype.insertContent = function(content, args) {
          if (args) {
            content = extend$3({ content }, args);
          }
          this.execCommand("mceInsertContent", false, content);
        };
        Editor2.prototype.resetContent = function(initialContent) {
          if (initialContent === void 0) {
            setContent(this, this.startContent, { format: "raw" });
          } else {
            setContent(this, initialContent);
          }
          this.undoManager.reset();
          this.setDirty(false);
          this.nodeChanged();
        };
        Editor2.prototype.isDirty = function() {
          return !this.isNotDirty;
        };
        Editor2.prototype.setDirty = function(state) {
          var oldState = !this.isNotDirty;
          this.isNotDirty = !state;
          if (state && state !== oldState) {
            this.fire("dirty");
          }
        };
        Editor2.prototype.getContainer = function() {
          var self2 = this;
          if (!self2.container) {
            self2.container = DOM$1.get(self2.editorContainer || self2.id + "_parent");
          }
          return self2.container;
        };
        Editor2.prototype.getContentAreaContainer = function() {
          return this.contentAreaContainer;
        };
        Editor2.prototype.getElement = function() {
          if (!this.targetElm) {
            this.targetElm = DOM$1.get(this.id);
          }
          return this.targetElm;
        };
        Editor2.prototype.getWin = function() {
          var self2 = this;
          var elm;
          if (!self2.contentWindow) {
            elm = self2.iframeElement;
            if (elm) {
              self2.contentWindow = elm.contentWindow;
            }
          }
          return self2.contentWindow;
        };
        Editor2.prototype.getDoc = function() {
          var self2 = this;
          var win;
          if (!self2.contentDocument) {
            win = self2.getWin();
            if (win) {
              self2.contentDocument = win.document;
            }
          }
          return self2.contentDocument;
        };
        Editor2.prototype.getBody = function() {
          var doc2 = this.getDoc();
          return this.bodyElement || (doc2 ? doc2.body : null);
        };
        Editor2.prototype.convertURL = function(url, name2, elm) {
          var self2 = this, settings = self2.settings;
          if (settings.urlconverter_callback) {
            return self2.execCallback("urlconverter_callback", url, elm, true, name2);
          }
          if (!settings.convert_urls || elm && elm.nodeName === "LINK" || url.indexOf("file:") === 0 || url.length === 0) {
            return url;
          }
          if (settings.relative_urls) {
            return self2.documentBaseURI.toRelative(url);
          }
          url = self2.documentBaseURI.toAbsolute(url, settings.remove_script_host);
          return url;
        };
        Editor2.prototype.addVisual = function(elm) {
          addVisual(this, elm);
        };
        Editor2.prototype.remove = function() {
          remove(this);
        };
        Editor2.prototype.destroy = function(automatic) {
          destroy(this, automatic);
        };
        Editor2.prototype.uploadImages = function(callback) {
          return this.editorUpload.uploadImages(callback);
        };
        Editor2.prototype._scanForImages = function() {
          return this.editorUpload.scanForImages();
        };
        Editor2.prototype.addButton = function() {
          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");
        };
        Editor2.prototype.addSidebar = function() {
          throw new Error("editor.addSidebar has been removed in tinymce 5x, use editor.ui.registry.addSidebar instead");
        };
        Editor2.prototype.addMenuItem = function() {
          throw new Error("editor.addMenuItem has been removed in tinymce 5x, use editor.ui.registry.addMenuItem instead");
        };
        Editor2.prototype.addContextToolbar = function() {
          throw new Error("editor.addContextToolbar has been removed in tinymce 5x, use editor.ui.registry.addContextToolbar instead");
        };
        return Editor2;
      }();
      var DOM = DOMUtils.DOM;
      var explode = Tools.explode, each$1 = Tools.each, extend$2 = Tools.extend;
      var instanceCounter = 0, boundGlobalEvents = false;
      var beforeUnloadDelegate;
      var legacyEditors = [];
      var editors = [];
      var isValidLegacyKey = function(id) {
        return id !== "length";
      };
      var globalEventDelegate = function(e) {
        var type2 = e.type;
        each$1(EditorManager.get(), function(editor) {
          switch (type2) {
            case "scroll":
              editor.fire("ScrollWindow", e);
              break;
            case "resize":
              editor.fire("ResizeWindow", e);
              break;
          }
        });
      };
      var toggleGlobalEvents = function(state) {
        if (state !== boundGlobalEvents) {
          if (state) {
            DomQuery(window).on("resize scroll", globalEventDelegate);
          } else {
            DomQuery(window).off("resize scroll", globalEventDelegate);
          }
          boundGlobalEvents = state;
        }
      };
      var removeEditorFromList = function(targetEditor) {
        var oldEditors = editors;
        delete legacyEditors[targetEditor.id];
        for (var i = 0; i < legacyEditors.length; i++) {
          if (legacyEditors[i] === targetEditor) {
            legacyEditors.splice(i, 1);
            break;
          }
        }
        editors = filter$4(editors, function(editor) {
          return targetEditor !== editor;
        });
        if (EditorManager.activeEditor === targetEditor) {
          EditorManager.activeEditor = editors.length > 0 ? editors[0] : null;
        }
        if (EditorManager.focusedEditor === targetEditor) {
          EditorManager.focusedEditor = null;
        }
        return oldEditors.length !== editors.length;
      };
      var purgeDestroyedEditor = function(editor) {
        if (editor && editor.initialized && !(editor.getContainer() || editor.getBody()).parentNode) {
          removeEditorFromList(editor);
          editor.unbindAllNativeEvents();
          editor.destroy(true);
          editor.removed = true;
          editor = null;
        }
        return editor;
      };
      var isQuirksMode = document.compatMode !== "CSS1Compat";
      var EditorManager = __assign(__assign({}, Observable), {
        baseURI: null,
        baseURL: null,
        defaultSettings: {},
        documentBaseURL: null,
        suffix: null,
        $: DomQuery,
        majorVersion: "5",
        minorVersion: "10.5",
        releaseDate: "2022-05-25",
        editors: legacyEditors,
        i18n: I18n,
        activeEditor: null,
        focusedEditor: null,
        settings: {},
        setup: function() {
          var self2 = this;
          var baseURL, documentBaseURL, suffix = "";
          documentBaseURL = URI.getDocumentBaseUrl(document.location);
          if (/^[^:]+:\/\/\/?[^\/]+\//.test(documentBaseURL)) {
            documentBaseURL = documentBaseURL.replace(/[\?#].*$/, "").replace(/[\/\\][^\/]+$/, "");
            if (!/[\/\\]$/.test(documentBaseURL)) {
              documentBaseURL += "/";
            }
          }
          var preInit2 = window.tinymce || window.tinyMCEPreInit;
          if (preInit2) {
            baseURL = preInit2.base || preInit2.baseURL;
            suffix = preInit2.suffix;
          } else {
            var scripts = document.getElementsByTagName("script");
            for (var i = 0; i < scripts.length; i++) {
              var src = scripts[i].src || "";
              if (src === "") {
                continue;
              }
              var srcScript = src.substring(src.lastIndexOf("/"));
              if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
                if (srcScript.indexOf(".min") !== -1) {
                  suffix = ".min";
                }
                baseURL = src.substring(0, src.lastIndexOf("/"));
                break;
              }
            }
            if (!baseURL && document.currentScript) {
              var src = document.currentScript.src;
              if (src.indexOf(".min") !== -1) {
                suffix = ".min";
              }
              baseURL = src.substring(0, src.lastIndexOf("/"));
            }
          }
          self2.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
          self2.documentBaseURL = documentBaseURL;
          self2.baseURI = new URI(self2.baseURL);
          self2.suffix = suffix;
          setup$l(self2);
        },
        overrideDefaults: function(defaultSettings) {
          var baseUrl = defaultSettings.base_url;
          if (baseUrl) {
            this._setBaseUrl(baseUrl);
          }
          var suffix = defaultSettings.suffix;
          if (defaultSettings.suffix) {
            this.suffix = suffix;
          }
          this.defaultSettings = defaultSettings;
          var pluginBaseUrls = defaultSettings.plugin_base_urls;
          if (pluginBaseUrls !== void 0) {
            each$j(pluginBaseUrls, function(pluginBaseUrl, pluginName) {
              AddOnManager.PluginManager.urls[pluginName] = pluginBaseUrl;
            });
          }
        },
        init: function(settings) {
          var self2 = this;
          var result;
          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", " ");
          var isInvalidInlineTarget = function(settings2, elm) {
            return settings2.inline && elm.tagName.toLowerCase() in invalidInlineTargets;
          };
          var createId = function(elm) {
            var id = elm.id;
            if (!id) {
              id = get$9(elm, "name").filter(function(name2) {
                return !DOM.get(name2);
              }).getOrThunk(DOM.uniqueId);
              elm.setAttribute("id", id);
            }
            return id;
          };
          var execCallback = function(name2) {
            var callback = settings[name2];
            if (!callback) {
              return;
            }
            return callback.apply(self2, []);
          };
          var hasClass2 = function(elm, className) {
            return className.constructor === RegExp ? className.test(elm.className) : DOM.hasClass(elm, className);
          };
          var findTargets = function(settings2) {
            var targets = [];
            if (Env.browser.isIE() && Env.browser.version.major < 11) {
              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/");
              return [];
            } else if (isQuirksMode) {
              initError("Failed to initialize the editor as the document is not in standards mode. TinyMCE requires standards mode.");
              return [];
            }
            if (settings2.types) {
              each$1(settings2.types, function(type2) {
                targets = targets.concat(DOM.select(type2.selector));
              });
              return targets;
            } else if (settings2.selector) {
              return DOM.select(settings2.selector);
            } else if (settings2.target) {
              return [settings2.target];
            }
            switch (settings2.mode) {
              case "exact":
                var l = settings2.elements || "";
                if (l.length > 0) {
                  each$1(explode(l), function(id) {
                    var elm = DOM.get(id);
                    if (elm) {
                      targets.push(elm);
                    } else {
                      each$1(document.forms, function(f) {
                        each$1(f.elements, function(e) {
                          if (e.name === id) {
                            id = "mce_editor_" + instanceCounter++;
                            DOM.setAttrib(e, "id", id);
                            targets.push(e);
                          }
                        });
                      });
                    }
                  });
                }
                break;
              case "textareas":
              case "specific_textareas":
                each$1(DOM.select("textarea"), function(elm) {
                  if (settings2.editor_deselector && hasClass2(elm, settings2.editor_deselector)) {
                    return;
                  }
                  if (!settings2.editor_selector || hasClass2(elm, settings2.editor_selector)) {
                    targets.push(elm);
                  }
                });
                break;
            }
            return targets;
          };
          var provideResults = function(editors2) {
            result = editors2;
          };
          var initEditors = function() {
            var initCount = 0;
            var editors2 = [];
            var targets;
            var createEditor = function(id, settings2, targetElm) {
              var editor = new Editor(id, settings2, self2);
              editors2.push(editor);
              editor.on("init", function() {
                if (++initCount === targets.length) {
                  provideResults(editors2);
                }
              });
              editor.targetElm = editor.targetElm || targetElm;
              editor.render();
            };
            DOM.unbind(window, "ready", initEditors);
            execCallback("onpageload");
            targets = DomQuery.unique(findTargets(settings));
            if (settings.types) {
              each$1(settings.types, function(type2) {
                Tools.each(targets, function(elm) {
                  if (DOM.is(elm, type2.selector)) {
                    createEditor(createId(elm), extend$2({}, settings, type2), elm);
                    return false;
                  }
                  return true;
                });
              });
              return;
            }
            Tools.each(targets, function(elm) {
              purgeDestroyedEditor(self2.get(elm.id));
            });
            targets = Tools.grep(targets, function(elm) {
              return !self2.get(elm.id);
            });
            if (targets.length === 0) {
              provideResults([]);
            } else {
              each$1(targets, function(elm) {
                if (isInvalidInlineTarget(settings, elm)) {
                  initError("Could not initialize inline editor on invalid inline target element", elm);
                } else {
                  createEditor(createId(elm), settings, elm);
                }
              });
            }
          };
          self2.settings = settings;
          DOM.bind(window, "ready", initEditors);
          return new promiseObj(function(resolve2) {
            if (result) {
              resolve2(result);
            } else {
              provideResults = function(editors2) {
                resolve2(editors2);
              };
            }
          });
        },
        get: function(id) {
          if (arguments.length === 0) {
            return editors.slice(0);
          } else if (isString$1(id)) {
            return find$3(editors, function(editor) {
              return editor.id === id;
            }).getOr(null);
          } else if (isNumber(id)) {
            return editors[id] ? editors[id] : null;
          } else {
            return null;
          }
        },
        add: function(editor) {
          var self2 = this;
          var existingEditor = legacyEditors[editor.id];
          if (existingEditor === editor) {
            return editor;
          }
          if (self2.get(editor.id) === null) {
            if (isValidLegacyKey(editor.id)) {
              legacyEditors[editor.id] = editor;
            }
            legacyEditors.push(editor);
            editors.push(editor);
          }
          toggleGlobalEvents(true);
          self2.activeEditor = editor;
          self2.fire("AddEditor", { editor });
          if (!beforeUnloadDelegate) {
            beforeUnloadDelegate = function(e) {
              var event = self2.fire("BeforeUnload");
              if (event.returnValue) {
                e.preventDefault();
                e.returnValue = event.returnValue;
                return event.returnValue;
              }
            };
            window.addEventListener("beforeunload", beforeUnloadDelegate);
          }
          return editor;
        },
        createEditor: function(id, settings) {
          return this.add(new Editor(id, settings, this));
        },
        remove: function(selector) {
          var self2 = this;
          var i, editor;
          if (!selector) {
            for (i = editors.length - 1; i >= 0; i--) {
              self2.remove(editors[i]);
            }
            return;
          }
          if (isString$1(selector)) {
            each$1(DOM.select(selector), function(elm) {
              editor = self2.get(elm.id);
              if (editor) {
                self2.remove(editor);
              }
            });
            return;
          }
          editor = selector;
          if (isNull(self2.get(editor.id))) {
            return null;
          }
          if (removeEditorFromList(editor)) {
            self2.fire("RemoveEditor", { editor });
          }
          if (editors.length === 0) {
            window.removeEventListener("beforeunload", beforeUnloadDelegate);
          }
          editor.remove();
          toggleGlobalEvents(editors.length > 0);
          return editor;
        },
        execCommand: function(cmd, ui, value2) {
          var self2 = this, editor = self2.get(value2);
          switch (cmd) {
            case "mceAddEditor":
              if (!self2.get(value2)) {
                new Editor(value2, self2.settings, self2).render();
              }
              return true;
            case "mceRemoveEditor":
              if (editor) {
                editor.remove();
              }
              return true;
            case "mceToggleEditor":
              if (!editor) {
                self2.execCommand("mceAddEditor", false, value2);
                return true;
              }
              if (editor.isHidden()) {
                editor.show();
              } else {
                editor.hide();
              }
              return true;
          }
          if (self2.activeEditor) {
            return self2.activeEditor.execCommand(cmd, ui, value2);
          }
          return false;
        },
        triggerSave: function() {
          each$1(editors, function(editor) {
            editor.save();
          });
        },
        addI18n: function(code, items) {
          I18n.add(code, items);
        },
        translate: function(text) {
          return I18n.translate(text);
        },
        setActive: function(editor) {
          var activeEditor = this.activeEditor;
          if (this.activeEditor !== editor) {
            if (activeEditor) {
              activeEditor.fire("deactivate", { relatedTarget: editor });
            }
            editor.fire("activate", { relatedTarget: activeEditor });
          }
          this.activeEditor = editor;
        },
        _setBaseUrl: function(baseUrl) {
          this.baseURL = new URI(this.documentBaseURL).toAbsolute(baseUrl.replace(/\/+$/, ""));
          this.baseURI = new URI(this.baseURL);
        }
      });
      EditorManager.setup();
      var min$1 = Math.min, max$1 = Math.max, round$1 = Math.round;
      var relativePosition = function(rect, targetRect, rel) {
        var x = targetRect.x;
        var y = targetRect.y;
        var w = rect.w;
        var h = rect.h;
        var targetW = targetRect.w;
        var targetH = targetRect.h;
        var relChars = (rel || "").split("");
        if (relChars[0] === "b") {
          y += targetH;
        }
        if (relChars[1] === "r") {
          x += targetW;
        }
        if (relChars[0] === "c") {
          y += round$1(targetH / 2);
        }
        if (relChars[1] === "c") {
          x += round$1(targetW / 2);
        }
        if (relChars[3] === "b") {
          y -= h;
        }
        if (relChars[4] === "r") {
          x -= w;
        }
        if (relChars[3] === "c") {
          y -= round$1(h / 2);
        }
        if (relChars[4] === "c") {
          x -= round$1(w / 2);
        }
        return create$2(x, y, w, h);
      };
      var findBestRelativePosition = function(rect, targetRect, constrainRect, rels) {
        var pos, i;
        for (i = 0; i < rels.length; i++) {
          pos = relativePosition(rect, targetRect, rels[i]);
          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) {
            return rels[i];
          }
        }
        return null;
      };
      var inflate = function(rect, w, h) {
        return create$2(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2);
      };
      var intersect = function(rect, cropRect) {
        var x1 = max$1(rect.x, cropRect.x);
        var y1 = max$1(rect.y, cropRect.y);
        var x2 = min$1(rect.x + rect.w, cropRect.x + cropRect.w);
        var y2 = min$1(rect.y + rect.h, cropRect.y + cropRect.h);
        if (x2 - x1 < 0 || y2 - y1 < 0) {
          return null;
        }
        return create$2(x1, y1, x2 - x1, y2 - y1);
      };
      var clamp = function(rect, clampRect, fixedSize) {
        var x1 = rect.x;
        var y1 = rect.y;
        var x2 = rect.x + rect.w;
        var y2 = rect.y + rect.h;
        var cx2 = clampRect.x + clampRect.w;
        var cy2 = clampRect.y + clampRect.h;
        var underflowX1 = max$1(0, clampRect.x - x1);
        var underflowY1 = max$1(0, clampRect.y - y1);
        var overflowX2 = max$1(0, x2 - cx2);
        var overflowY2 = max$1(0, y2 - cy2);
        x1 += underflowX1;
        y1 += underflowY1;
        if (fixedSize) {
          x2 += underflowX1;
          y2 += underflowY1;
          x1 -= overflowX2;
          y1 -= overflowY2;
        }
        x2 -= overflowX2;
        y2 -= overflowY2;
        return create$2(x1, y1, x2 - x1, y2 - y1);
      };
      var create$2 = function(x, y, w, h) {
        return {
          x,
          y,
          w,
          h
        };
      };
      var fromClientRect = function(clientRect) {
        return create$2(clientRect.left, clientRect.top, clientRect.width, clientRect.height);
      };
      var Rect = {
        inflate,
        relativePosition,
        findBestRelativePosition,
        intersect,
        clamp,
        create: create$2,
        fromClientRect
      };
      var awaiter = function(resolveCb, rejectCb, timeout) {
        if (timeout === void 0) {
          timeout = 1e3;
        }
        var done2 = false;
        var timer = null;
        var complete = function(completer) {
          return function() {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
              args[_i] = arguments[_i];
            }
            if (!done2) {
              done2 = true;
              if (timer !== null) {
                clearTimeout(timer);
                timer = null;
              }
              completer.apply(null, args);
            }
          };
        };
        var resolve2 = complete(resolveCb);
        var reject = complete(rejectCb);
        var start2 = function() {
          var args = [];
          for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
          }
          if (!done2 && timer === null) {
            timer = setTimeout(function() {
              return reject.apply(null, args);
            }, timeout);
          }
        };
        return {
          start: start2,
          resolve: resolve2,
          reject
        };
      };
      var create$1 = function() {
        var tasks = {};
        var resultFns = {};
        var load = function(id, url) {
          var loadErrMsg = 'Script at URL "' + url + '" failed to load';
          var runErrMsg = 'Script at URL "' + url + "\" did not call `tinymce.Resource.add('" + id + "', data)` within 1 second";
          if (tasks[id] !== void 0) {
            return tasks[id];
          } else {
            var task = new promiseObj(function(resolve2, reject) {
              var waiter = awaiter(resolve2, reject);
              resultFns[id] = waiter.resolve;
              ScriptLoader.ScriptLoader.loadScript(url, function() {
                return waiter.start(runErrMsg);
              }, function() {
                return waiter.reject(loadErrMsg);
              });
            });
            tasks[id] = task;
            return task;
          }
        };
        var add2 = function(id, data2) {
          if (resultFns[id] !== void 0) {
            resultFns[id](data2);
            delete resultFns[id];
          }
          tasks[id] = promiseObj.resolve(data2);
        };
        return {
          load,
          add: add2
        };
      };
      var Resource = create$1();
      var each = Tools.each, extend$1 = Tools.extend;
      var extendClass, initializing;
      var Class = function() {
      };
      Class.extend = extendClass = function(props) {
        var self2 = this;
        var _super = self2.prototype;
        var Class2 = function() {
          var i, mixins, mixin;
          var self3 = this;
          if (!initializing) {
            if (self3.init) {
              self3.init.apply(self3, arguments);
            }
            mixins = self3.Mixins;
            if (mixins) {
              i = mixins.length;
              while (i--) {
                mixin = mixins[i];
                if (mixin.init) {
                  mixin.init.apply(self3, arguments);
                }
              }
            }
          }
        };
        var dummy = function() {
          return this;
        };
        var createMethod = function(name2, fn) {
          return function() {
            var self3 = this;
            var tmp = self3._super;
            self3._super = _super[name2];
            var ret = fn.apply(self3, arguments);
            self3._super = tmp;
            return ret;
          };
        };
        initializing = true;
        var prototype = new self2();
        initializing = false;
        if (props.Mixins) {
          each(props.Mixins, function(mixin) {
            for (var name_1 in mixin) {
              if (name_1 !== "init") {
                props[name_1] = mixin[name_1];
              }
            }
          });
          if (_super.Mixins) {
            props.Mixins = _super.Mixins.concat(props.Mixins);
          }
        }
        if (props.Methods) {
          each(props.Methods.split(","), function(name2) {
            props[name2] = dummy;
          });
        }
        if (props.Properties) {
          each(props.Properties.split(","), function(name2) {
            var fieldName = "_" + name2;
            props[name2] = function(value2) {
              var self3 = this;
              if (value2 !== void 0) {
                self3[fieldName] = value2;
                return self3;
              }
              return self3[fieldName];
            };
          });
        }
        if (props.Statics) {
          each(props.Statics, function(func, name2) {
            Class2[name2] = func;
          });
        }
        if (props.Defaults && _super.Defaults) {
          props.Defaults = extend$1({}, _super.Defaults, props.Defaults);
        }
        each$j(props, function(member, name2) {
          if (typeof member === "function" && _super[name2]) {
            prototype[name2] = createMethod(name2, member);
          } else {
            prototype[name2] = member;
          }
        });
        Class2.prototype = prototype;
        Class2.constructor = Class2;
        Class2.extend = extendClass;
        return Class2;
      };
      var min = Math.min, max = Math.max, round = Math.round;
      var Color = function(value2) {
        var self2 = {};
        var r2 = 0, g = 0, b = 0;
        var rgb2hsv = function(r3, g2, b2) {
          var h, s, v;
          h = 0;
          s = 0;
          v = 0;
          r3 = r3 / 255;
          g2 = g2 / 255;
          b2 = b2 / 255;
          var minRGB = min(r3, min(g2, b2));
          var maxRGB = max(r3, max(g2, b2));
          if (minRGB === maxRGB) {
            v = minRGB;
            return {
              h: 0,
              s: 0,
              v: v * 100
            };
          }
          var d = r3 === minRGB ? g2 - b2 : b2 === minRGB ? r3 - g2 : b2 - r3;
          h = r3 === minRGB ? 3 : b2 === minRGB ? 1 : 5;
          h = 60 * (h - d / (maxRGB - minRGB));
          s = (maxRGB - minRGB) / maxRGB;
          v = maxRGB;
          return {
            h: round(h),
            s: round(s * 100),
            v: round(v * 100)
          };
        };
        var hsvToRgb = function(hue, saturation, brightness) {
          hue = (parseInt(hue, 10) || 0) % 360;
          saturation = parseInt(saturation, 10) / 100;
          brightness = parseInt(brightness, 10) / 100;
          saturation = max(0, min(saturation, 1));
          brightness = max(0, min(brightness, 1));
          if (saturation === 0) {
            r2 = g = b = round(255 * brightness);
            return;
          }
          var side = hue / 60;
          var chroma = brightness * saturation;
          var x = chroma * (1 - Math.abs(side % 2 - 1));
          var match2 = brightness - chroma;
          switch (Math.floor(side)) {
            case 0:
              r2 = chroma;
              g = x;
              b = 0;
              break;
            case 1:
              r2 = x;
              g = chroma;
              b = 0;
              break;
            case 2:
              r2 = 0;
              g = chroma;
              b = x;
              break;
            case 3:
              r2 = 0;
              g = x;
              b = chroma;
              break;
            case 4:
              r2 = x;
              g = 0;
              b = chroma;
              break;
            case 5:
              r2 = chroma;
              g = 0;
              b = x;
              break;
            default:
              r2 = g = b = 0;
          }
          r2 = round(255 * (r2 + match2));
          g = round(255 * (g + match2));
          b = round(255 * (b + match2));
        };
        var toHex2 = function() {
          var hex = function(val) {
            val = parseInt(val, 10).toString(16);
            return val.length > 1 ? val : "0" + val;
          };
          return "#" + hex(r2) + hex(g) + hex(b);
        };
        var toRgb = function() {
          return {
            r: r2,
            g,
            b
          };
        };
        var toHsv = function() {
          return rgb2hsv(r2, g, b);
        };
        var parse = function(value3) {
          var matches2;
          if (typeof value3 === "object") {
            if ("r" in value3) {
              r2 = value3.r;
              g = value3.g;
              b = value3.b;
            } else if ("v" in value3) {
              hsvToRgb(value3.h, value3.s, value3.v);
            }
          } else {
            if (matches2 = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)[^\)]*\)/gi.exec(value3)) {
              r2 = parseInt(matches2[1], 10);
              g = parseInt(matches2[2], 10);
              b = parseInt(matches2[3], 10);
            } else if (matches2 = /#([0-F]{2})([0-F]{2})([0-F]{2})/gi.exec(value3)) {
              r2 = parseInt(matches2[1], 16);
              g = parseInt(matches2[2], 16);
              b = parseInt(matches2[3], 16);
            } else if (matches2 = /#([0-F])([0-F])([0-F])/gi.exec(value3)) {
              r2 = parseInt(matches2[1] + matches2[1], 16);
              g = parseInt(matches2[2] + matches2[2], 16);
              b = parseInt(matches2[3] + matches2[3], 16);
            }
          }
          r2 = r2 < 0 ? 0 : r2 > 255 ? 255 : r2;
          g = g < 0 ? 0 : g > 255 ? 255 : g;
          b = b < 0 ? 0 : b > 255 ? 255 : b;
          return self2;
        };
        if (value2) {
          parse(value2);
        }
        self2.toRgb = toRgb;
        self2.toHsv = toHsv;
        self2.toHex = toHex2;
        self2.parse = parse;
        return self2;
      };
      var serialize = function(obj) {
        var data2 = JSON.stringify(obj);
        if (!isString$1(data2)) {
          return data2;
        }
        return data2.replace(/[\u0080-\uFFFF]/g, function(match2) {
          var hexCode = match2.charCodeAt(0).toString(16);
          return "\\u" + "0000".substring(hexCode.length) + hexCode;
        });
      };
      var JSONUtils = {
        serialize,
        parse: function(text) {
          try {
            return JSON.parse(text);
          } catch (ex) {
          }
        }
      };
      var JSONP = {
        callbacks: {},
        count: 0,
        send: function(settings) {
          var self2 = this, dom2 = DOMUtils.DOM, count2 = settings.count !== void 0 ? settings.count : self2.count;
          var id = "tinymce_jsonp_" + count2;
          self2.callbacks[count2] = function(json) {
            dom2.remove(id);
            delete self2.callbacks[count2];
            settings.callback(json);
          };
          dom2.add(dom2.doc.body, "script", {
            id,
            src: settings.url,
            type: "text/javascript"
          });
          self2.count++;
        }
      };
      var XHR = __assign(__assign({}, Observable), {
        send: function(settings) {
          var xhr, count2 = 0;
          var ready = function() {
            if (!settings.async || xhr.readyState === 4 || count2++ > 1e4) {
              if (settings.success && count2 < 1e4 && xhr.status === 200) {
                settings.success.call(settings.success_scope, "" + xhr.responseText, xhr, settings);
              } else if (settings.error) {
                settings.error.call(settings.error_scope, count2 > 1e4 ? "TIMED_OUT" : "GENERAL", xhr, settings);
              }
              xhr = null;
            } else {
              Delay.setTimeout(ready, 10);
            }
          };
          settings.scope = settings.scope || this;
          settings.success_scope = settings.success_scope || settings.scope;
          settings.error_scope = settings.error_scope || settings.scope;
          settings.async = settings.async !== false;
          settings.data = settings.data || "";
          XHR.fire("beforeInitialize", { settings });
          xhr = new XMLHttpRequest();
          if (xhr.overrideMimeType) {
            xhr.overrideMimeType(settings.content_type);
          }
          xhr.open(settings.type || (settings.data ? "POST" : "GET"), settings.url, settings.async);
          if (settings.crossDomain) {
            xhr.withCredentials = true;
          }
          if (settings.content_type) {
            xhr.setRequestHeader("Content-Type", settings.content_type);
          }
          if (settings.requestheaders) {
            Tools.each(settings.requestheaders, function(header) {
              xhr.setRequestHeader(header.key, header.value);
            });
          }
          xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
          xhr = XHR.fire("beforeSend", {
            xhr,
            settings
          }).xhr;
          xhr.send(settings.data);
          if (!settings.async) {
            return ready();
          }
          Delay.setTimeout(ready, 10);
        }
      });
      var extend = Tools.extend;
      var JSONRequest = function() {
        function JSONRequest2(settings) {
          this.settings = extend({}, settings);
          this.count = 0;
        }
        JSONRequest2.sendRPC = function(o) {
          return new JSONRequest2().send(o);
        };
        JSONRequest2.prototype.send = function(args) {
          var ecb = args.error, scb = args.success;
          var xhrArgs = extend(this.settings, args);
          xhrArgs.success = function(c, x) {
            c = JSONUtils.parse(c);
            if (typeof c === "undefined") {
              c = { error: "JSON Parse error." };
            }
            if (c.error) {
              ecb.call(xhrArgs.error_scope || xhrArgs.scope, c.error, x);
            } else {
              scb.call(xhrArgs.success_scope || xhrArgs.scope, c.result);
            }
          };
          xhrArgs.error = function(ty, x) {
            if (ecb) {
              ecb.call(xhrArgs.error_scope || xhrArgs.scope, ty, x);
            }
          };
          xhrArgs.data = JSONUtils.serialize({
            id: args.id || "c" + this.count++,
            method: args.method,
            params: args.params
          });
          xhrArgs.content_type = "application/json";
          XHR.send(xhrArgs);
        };
        return JSONRequest2;
      }();
      var create = function() {
        return function() {
          var data2 = {};
          var keys2 = [];
          var storage = {
            getItem: function(key) {
              var item = data2[key];
              return item ? item : null;
            },
            setItem: function(key, value2) {
              keys2.push(key);
              data2[key] = String(value2);
            },
            key: function(index) {
              return keys2[index];
            },
            removeItem: function(key) {
              keys2 = keys2.filter(function(k) {
                return k === key;
              });
              delete data2[key];
            },
            clear: function() {
              keys2 = [];
              data2 = {};
            },
            length: 0
          };
          Object.defineProperty(storage, "length", {
            get: function() {
              return keys2.length;
            },
            configurable: false,
            enumerable: false
          });
          return storage;
        }();
      };
      var localStorage;
      try {
        var test = "__storage_test__";
        localStorage = window.localStorage;
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
      } catch (e) {
        localStorage = create();
      }
      var LocalStorage = localStorage;
      var publicApi = {
        geom: { Rect },
        util: {
          Promise: promiseObj,
          Delay,
          Tools,
          VK,
          URI,
          Class,
          EventDispatcher,
          Observable,
          I18n,
          XHR,
          JSON: JSONUtils,
          JSONRequest,
          JSONP,
          LocalStorage,
          Color,
          ImageUploader
        },
        dom: {
          EventUtils,
          Sizzle,
          DomQuery,
          TreeWalker: DomTreeWalker,
          TextSeeker,
          DOMUtils,
          ScriptLoader,
          RangeUtils,
          Serializer: DomSerializer,
          StyleSheetLoader,
          ControlSelection,
          BookmarkManager,
          Selection: EditorSelection,
          Event: EventUtils.Event
        },
        html: {
          Styles,
          Entities,
          Node: AstNode,
          Schema,
          SaxParser,
          DomParser,
          Writer,
          Serializer: HtmlSerializer
        },
        Env,
        AddOnManager,
        Annotator,
        Formatter,
        UndoManager,
        EditorCommands,
        WindowManager,
        NotificationManager,
        EditorObservable,
        Shortcuts,
        Editor,
        FocusManager,
        EditorManager,
        DOM: DOMUtils.DOM,
        ScriptLoader: ScriptLoader.ScriptLoader,
        PluginManager,
        ThemeManager,
        IconManager,
        Resource,
        trim: Tools.trim,
        isArray: Tools.isArray,
        is: Tools.is,
        toArray: Tools.toArray,
        makeMap: Tools.makeMap,
        each: Tools.each,
        map: Tools.map,
        grep: Tools.grep,
        inArray: Tools.inArray,
        extend: Tools.extend,
        create: Tools.create,
        walk: Tools.walk,
        createNS: Tools.createNS,
        resolve: Tools.resolve,
        explode: Tools.explode,
        _addCacheSuffix: Tools._addCacheSuffix,
        isOpera: Env.opera,
        isWebKit: Env.webkit,
        isIE: Env.ie,
        isGecko: Env.gecko,
        isMac: Env.mac
      };
      var tinymce = Tools.extend(EditorManager, publicApi);
      var exportToModuleLoaders = function(tinymce2) {
        if (typeof module === "object") {
          try {
            module.exports = tinymce2;
          } catch (_) {
          }
        }
      };
      var exportToWindowGlobal = function(tinymce2) {
        window.tinymce = tinymce2;
        window.tinyMCE = tinymce2;
      };
      exportToWindowGlobal(tinymce);
      exportToModuleLoaders(tinymce);
    })();
  }
});

// dep:tinymce_tinymce
init_define_APP_INFO();
var tinymce_tinymce_default = require_tinymce();
export {
  tinymce_tinymce_default as default
};
//# sourceMappingURL=tinymce_tinymce.js.map
