Subversion Repositories oidplus

Rev

Rev 1422 | View as "text/javascript" | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /**
  2.  * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3.  * Licensed under the LGPL or a commercial license.
  4.  * For LGPL see License.txt in the project root for license information.
  5.  * For commercial licenses see https://www.tiny.cloud/
  6.  *
  7.  * Version: 5.10.9 (2023-11-15)
  8.  */
  9. (function () {
  10.     'use strict';
  11.  
  12.     var typeOf = function (x) {
  13.       var t = typeof x;
  14.       if (x === null) {
  15.         return 'null';
  16.       } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  17.         return 'array';
  18.       } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  19.         return 'string';
  20.       } else {
  21.         return t;
  22.       }
  23.     };
  24.     var isType$1 = function (type) {
  25.       return function (value) {
  26.         return typeOf(value) === type;
  27.       };
  28.     };
  29.     var isSimpleType = function (type) {
  30.       return function (value) {
  31.         return typeof value === type;
  32.       };
  33.     };
  34.     var eq$1 = function (t) {
  35.       return function (a) {
  36.         return t === a;
  37.       };
  38.     };
  39.     var isString = isType$1('string');
  40.     var isObject = isType$1('object');
  41.     var isArray = isType$1('array');
  42.     var isNull = eq$1(null);
  43.     var isBoolean = isSimpleType('boolean');
  44.     var isUndefined = eq$1(undefined);
  45.     var isNullable = function (a) {
  46.       return a === null || a === undefined;
  47.     };
  48.     var isNonNullable = function (a) {
  49.       return !isNullable(a);
  50.     };
  51.     var isFunction = isSimpleType('function');
  52.     var isNumber = isSimpleType('number');
  53.     var isArrayOf = function (value, pred) {
  54.       if (isArray(value)) {
  55.         for (var i = 0, len = value.length; i < len; ++i) {
  56.           if (!pred(value[i])) {
  57.             return false;
  58.           }
  59.         }
  60.         return true;
  61.       }
  62.       return false;
  63.     };
  64.  
  65.     var noop = function () {
  66.     };
  67.     var noarg = function (f) {
  68.       return function () {
  69.         return f();
  70.       };
  71.     };
  72.     var compose = function (fa, fb) {
  73.       return function () {
  74.         var args = [];
  75.         for (var _i = 0; _i < arguments.length; _i++) {
  76.           args[_i] = arguments[_i];
  77.         }
  78.         return fa(fb.apply(null, args));
  79.       };
  80.     };
  81.     var compose1 = function (fbc, fab) {
  82.       return function (a) {
  83.         return fbc(fab(a));
  84.       };
  85.     };
  86.     var constant$1 = function (value) {
  87.       return function () {
  88.         return value;
  89.       };
  90.     };
  91.     var identity$1 = function (x) {
  92.       return x;
  93.     };
  94.     var tripleEquals = function (a, b) {
  95.       return a === b;
  96.     };
  97.     function curry(fn) {
  98.       var initialArgs = [];
  99.       for (var _i = 1; _i < arguments.length; _i++) {
  100.         initialArgs[_i - 1] = arguments[_i];
  101.       }
  102.       return function () {
  103.         var restArgs = [];
  104.         for (var _i = 0; _i < arguments.length; _i++) {
  105.           restArgs[_i] = arguments[_i];
  106.         }
  107.         var all = initialArgs.concat(restArgs);
  108.         return fn.apply(null, all);
  109.       };
  110.     }
  111.     var not = function (f) {
  112.       return function (t) {
  113.         return !f(t);
  114.       };
  115.     };
  116.     var die = function (msg) {
  117.       return function () {
  118.         throw new Error(msg);
  119.       };
  120.     };
  121.     var never = constant$1(false);
  122.     var always = constant$1(true);
  123.  
  124.     var global$g = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  125.  
  126.     var __assign = function () {
  127.       __assign = Object.assign || function __assign(t) {
  128.         for (var s, i = 1, n = arguments.length; i < n; i++) {
  129.           s = arguments[i];
  130.           for (var p in s)
  131.             if (Object.prototype.hasOwnProperty.call(s, p))
  132.               t[p] = s[p];
  133.         }
  134.         return t;
  135.       };
  136.       return __assign.apply(this, arguments);
  137.     };
  138.     function __rest(s, e) {
  139.       var t = {};
  140.       for (var p in s)
  141.         if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  142.           t[p] = s[p];
  143.       if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  144.         for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  145.           if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  146.             t[p[i]] = s[p[i]];
  147.         }
  148.       return t;
  149.     }
  150.     function __spreadArray(to, from, pack) {
  151.       if (pack || arguments.length === 2)
  152.         for (var i = 0, l = from.length, ar; i < l; i++) {
  153.           if (ar || !(i in from)) {
  154.             if (!ar)
  155.               ar = Array.prototype.slice.call(from, 0, i);
  156.             ar[i] = from[i];
  157.           }
  158.         }
  159.       return to.concat(ar || Array.prototype.slice.call(from));
  160.     }
  161.  
  162.     var none = function () {
  163.       return NONE;
  164.     };
  165.     var NONE = function () {
  166.       var call = function (thunk) {
  167.         return thunk();
  168.       };
  169.       var id = identity$1;
  170.       var me = {
  171.         fold: function (n, _s) {
  172.           return n();
  173.         },
  174.         isSome: never,
  175.         isNone: always,
  176.         getOr: id,
  177.         getOrThunk: call,
  178.         getOrDie: function (msg) {
  179.           throw new Error(msg || 'error: getOrDie called on none.');
  180.         },
  181.         getOrNull: constant$1(null),
  182.         getOrUndefined: constant$1(undefined),
  183.         or: id,
  184.         orThunk: call,
  185.         map: none,
  186.         each: noop,
  187.         bind: none,
  188.         exists: never,
  189.         forall: always,
  190.         filter: function () {
  191.           return none();
  192.         },
  193.         toArray: function () {
  194.           return [];
  195.         },
  196.         toString: constant$1('none()')
  197.       };
  198.       return me;
  199.     }();
  200.     var some = function (a) {
  201.       var constant_a = constant$1(a);
  202.       var self = function () {
  203.         return me;
  204.       };
  205.       var bind = function (f) {
  206.         return f(a);
  207.       };
  208.       var me = {
  209.         fold: function (n, s) {
  210.           return s(a);
  211.         },
  212.         isSome: always,
  213.         isNone: never,
  214.         getOr: constant_a,
  215.         getOrThunk: constant_a,
  216.         getOrDie: constant_a,
  217.         getOrNull: constant_a,
  218.         getOrUndefined: constant_a,
  219.         or: self,
  220.         orThunk: self,
  221.         map: function (f) {
  222.           return some(f(a));
  223.         },
  224.         each: function (f) {
  225.           f(a);
  226.         },
  227.         bind: bind,
  228.         exists: bind,
  229.         forall: bind,
  230.         filter: function (f) {
  231.           return f(a) ? me : NONE;
  232.         },
  233.         toArray: function () {
  234.           return [a];
  235.         },
  236.         toString: function () {
  237.           return 'some(' + a + ')';
  238.         }
  239.       };
  240.       return me;
  241.     };
  242.     var from$1 = function (value) {
  243.       return value === null || value === undefined ? NONE : some(value);
  244.     };
  245.     var Optional = {
  246.       some: some,
  247.       none: none,
  248.       from: from$1
  249.     };
  250.  
  251.     var nativeSlice = Array.prototype.slice;
  252.     var nativeIndexOf = Array.prototype.indexOf;
  253.     var nativePush = Array.prototype.push;
  254.     var rawIndexOf = function (ts, t) {
  255.       return nativeIndexOf.call(ts, t);
  256.     };
  257.     var indexOf = function (xs, x) {
  258.       var r = rawIndexOf(xs, x);
  259.       return r === -1 ? Optional.none() : Optional.some(r);
  260.     };
  261.     var contains$2 = function (xs, x) {
  262.       return rawIndexOf(xs, x) > -1;
  263.     };
  264.     var exists = function (xs, pred) {
  265.       for (var i = 0, len = xs.length; i < len; i++) {
  266.         var x = xs[i];
  267.         if (pred(x, i)) {
  268.           return true;
  269.         }
  270.       }
  271.       return false;
  272.     };
  273.     var range$2 = function (num, f) {
  274.       var r = [];
  275.       for (var i = 0; i < num; i++) {
  276.         r.push(f(i));
  277.       }
  278.       return r;
  279.     };
  280.     var chunk$1 = function (array, size) {
  281.       var r = [];
  282.       for (var i = 0; i < array.length; i += size) {
  283.         var s = nativeSlice.call(array, i, i + size);
  284.         r.push(s);
  285.       }
  286.       return r;
  287.     };
  288.     var map$2 = function (xs, f) {
  289.       var len = xs.length;
  290.       var r = new Array(len);
  291.       for (var i = 0; i < len; i++) {
  292.         var x = xs[i];
  293.         r[i] = f(x, i);
  294.       }
  295.       return r;
  296.     };
  297.     var each$1 = function (xs, f) {
  298.       for (var i = 0, len = xs.length; i < len; i++) {
  299.         var x = xs[i];
  300.         f(x, i);
  301.       }
  302.     };
  303.     var eachr = function (xs, f) {
  304.       for (var i = xs.length - 1; i >= 0; i--) {
  305.         var x = xs[i];
  306.         f(x, i);
  307.       }
  308.     };
  309.     var partition$3 = function (xs, pred) {
  310.       var pass = [];
  311.       var fail = [];
  312.       for (var i = 0, len = xs.length; i < len; i++) {
  313.         var x = xs[i];
  314.         var arr = pred(x, i) ? pass : fail;
  315.         arr.push(x);
  316.       }
  317.       return {
  318.         pass: pass,
  319.         fail: fail
  320.       };
  321.     };
  322.     var filter$2 = function (xs, pred) {
  323.       var r = [];
  324.       for (var i = 0, len = xs.length; i < len; i++) {
  325.         var x = xs[i];
  326.         if (pred(x, i)) {
  327.           r.push(x);
  328.         }
  329.       }
  330.       return r;
  331.     };
  332.     var foldr = function (xs, f, acc) {
  333.       eachr(xs, function (x, i) {
  334.         acc = f(acc, x, i);
  335.       });
  336.       return acc;
  337.     };
  338.     var foldl = function (xs, f, acc) {
  339.       each$1(xs, function (x, i) {
  340.         acc = f(acc, x, i);
  341.       });
  342.       return acc;
  343.     };
  344.     var findUntil = function (xs, pred, until) {
  345.       for (var i = 0, len = xs.length; i < len; i++) {
  346.         var x = xs[i];
  347.         if (pred(x, i)) {
  348.           return Optional.some(x);
  349.         } else if (until(x, i)) {
  350.           break;
  351.         }
  352.       }
  353.       return Optional.none();
  354.     };
  355.     var find$5 = function (xs, pred) {
  356.       return findUntil(xs, pred, never);
  357.     };
  358.     var findIndex$1 = function (xs, pred) {
  359.       for (var i = 0, len = xs.length; i < len; i++) {
  360.         var x = xs[i];
  361.         if (pred(x, i)) {
  362.           return Optional.some(i);
  363.         }
  364.       }
  365.       return Optional.none();
  366.     };
  367.     var flatten = function (xs) {
  368.       var r = [];
  369.       for (var i = 0, len = xs.length; i < len; ++i) {
  370.         if (!isArray(xs[i])) {
  371.           throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  372.         }
  373.         nativePush.apply(r, xs[i]);
  374.       }
  375.       return r;
  376.     };
  377.     var bind$3 = function (xs, f) {
  378.       return flatten(map$2(xs, f));
  379.     };
  380.     var forall = function (xs, pred) {
  381.       for (var i = 0, len = xs.length; i < len; ++i) {
  382.         var x = xs[i];
  383.         if (pred(x, i) !== true) {
  384.           return false;
  385.         }
  386.       }
  387.       return true;
  388.     };
  389.     var reverse = function (xs) {
  390.       var r = nativeSlice.call(xs, 0);
  391.       r.reverse();
  392.       return r;
  393.     };
  394.     var difference = function (a1, a2) {
  395.       return filter$2(a1, function (x) {
  396.         return !contains$2(a2, x);
  397.       });
  398.     };
  399.     var mapToObject = function (xs, f) {
  400.       var r = {};
  401.       for (var i = 0, len = xs.length; i < len; i++) {
  402.         var x = xs[i];
  403.         r[String(x)] = f(x, i);
  404.       }
  405.       return r;
  406.     };
  407.     var pure$2 = function (x) {
  408.       return [x];
  409.     };
  410.     var sort = function (xs, comparator) {
  411.       var copy = nativeSlice.call(xs, 0);
  412.       copy.sort(comparator);
  413.       return copy;
  414.     };
  415.     var get$f = function (xs, i) {
  416.       return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  417.     };
  418.     var head = function (xs) {
  419.       return get$f(xs, 0);
  420.     };
  421.     var last$2 = function (xs) {
  422.       return get$f(xs, xs.length - 1);
  423.     };
  424.     var from = isFunction(Array.from) ? Array.from : function (x) {
  425.       return nativeSlice.call(x);
  426.     };
  427.     var findMap = function (arr, f) {
  428.       for (var i = 0; i < arr.length; i++) {
  429.         var r = f(arr[i], i);
  430.         if (r.isSome()) {
  431.           return r;
  432.         }
  433.       }
  434.       return Optional.none();
  435.     };
  436.  
  437.     var keys = Object.keys;
  438.     var hasOwnProperty$1 = Object.hasOwnProperty;
  439.     var each = function (obj, f) {
  440.       var props = keys(obj);
  441.       for (var k = 0, len = props.length; k < len; k++) {
  442.         var i = props[k];
  443.         var x = obj[i];
  444.         f(x, i);
  445.       }
  446.     };
  447.     var map$1 = function (obj, f) {
  448.       return tupleMap(obj, function (x, i) {
  449.         return {
  450.           k: i,
  451.           v: f(x, i)
  452.         };
  453.       });
  454.     };
  455.     var tupleMap = function (obj, f) {
  456.       var r = {};
  457.       each(obj, function (x, i) {
  458.         var tuple = f(x, i);
  459.         r[tuple.k] = tuple.v;
  460.       });
  461.       return r;
  462.     };
  463.     var objAcc = function (r) {
  464.       return function (x, i) {
  465.         r[i] = x;
  466.       };
  467.     };
  468.     var internalFilter = function (obj, pred, onTrue, onFalse) {
  469.       var r = {};
  470.       each(obj, function (x, i) {
  471.         (pred(x, i) ? onTrue : onFalse)(x, i);
  472.       });
  473.       return r;
  474.     };
  475.     var filter$1 = function (obj, pred) {
  476.       var t = {};
  477.       internalFilter(obj, pred, objAcc(t), noop);
  478.       return t;
  479.     };
  480.     var mapToArray = function (obj, f) {
  481.       var r = [];
  482.       each(obj, function (value, name) {
  483.         r.push(f(value, name));
  484.       });
  485.       return r;
  486.     };
  487.     var find$4 = function (obj, pred) {
  488.       var props = keys(obj);
  489.       for (var k = 0, len = props.length; k < len; k++) {
  490.         var i = props[k];
  491.         var x = obj[i];
  492.         if (pred(x, i, obj)) {
  493.           return Optional.some(x);
  494.         }
  495.       }
  496.       return Optional.none();
  497.     };
  498.     var values = function (obj) {
  499.       return mapToArray(obj, identity$1);
  500.     };
  501.     var get$e = function (obj, key) {
  502.       return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  503.     };
  504.     var has$2 = function (obj, key) {
  505.       return hasOwnProperty$1.call(obj, key);
  506.     };
  507.     var hasNonNullableKey = function (obj, key) {
  508.       return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  509.     };
  510.  
  511.     var is$1 = function (lhs, rhs, comparator) {
  512.       if (comparator === void 0) {
  513.         comparator = tripleEquals;
  514.       }
  515.       return lhs.exists(function (left) {
  516.         return comparator(left, rhs);
  517.       });
  518.     };
  519.     var equals = function (lhs, rhs, comparator) {
  520.       if (comparator === void 0) {
  521.         comparator = tripleEquals;
  522.       }
  523.       return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
  524.     };
  525.     var cat = function (arr) {
  526.       var r = [];
  527.       var push = function (x) {
  528.         r.push(x);
  529.       };
  530.       for (var i = 0; i < arr.length; i++) {
  531.         arr[i].each(push);
  532.       }
  533.       return r;
  534.     };
  535.     var sequence = function (arr) {
  536.       var r = [];
  537.       for (var i = 0; i < arr.length; i++) {
  538.         var x = arr[i];
  539.         if (x.isSome()) {
  540.           r.push(x.getOrDie());
  541.         } else {
  542.           return Optional.none();
  543.         }
  544.       }
  545.       return Optional.some(r);
  546.     };
  547.     var lift2 = function (oa, ob, f) {
  548.       return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  549.     };
  550.     var lift3 = function (oa, ob, oc, f) {
  551.       return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  552.     };
  553.     var mapFrom = function (a, f) {
  554.       return a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none();
  555.     };
  556.     var someIf = function (b, a) {
  557.       return b ? Optional.some(a) : Optional.none();
  558.     };
  559.  
  560.     var addToEnd = function (str, suffix) {
  561.       return str + suffix;
  562.     };
  563.     var removeFromStart = function (str, numChars) {
  564.       return str.substring(numChars);
  565.     };
  566.  
  567.     var checkRange = function (str, substr, start) {
  568.       return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  569.     };
  570.     var removeLeading = function (str, prefix) {
  571.       return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  572.     };
  573.     var ensureTrailing = function (str, suffix) {
  574.       return endsWith(str, suffix) ? str : addToEnd(str, suffix);
  575.     };
  576.     var contains$1 = function (str, substr) {
  577.       return str.indexOf(substr) !== -1;
  578.     };
  579.     var startsWith = function (str, prefix) {
  580.       return checkRange(str, prefix, 0);
  581.     };
  582.     var endsWith = function (str, suffix) {
  583.       return checkRange(str, suffix, str.length - suffix.length);
  584.     };
  585.     var blank = function (r) {
  586.       return function (s) {
  587.         return s.replace(r, '');
  588.       };
  589.     };
  590.     var trim$1 = blank(/^\s+|\s+$/g);
  591.     var isNotEmpty = function (s) {
  592.       return s.length > 0;
  593.     };
  594.     var isEmpty = function (s) {
  595.       return !isNotEmpty(s);
  596.     };
  597.  
  598.     var isSupported$1 = function (dom) {
  599.       return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  600.     };
  601.  
  602.     var fromHtml$2 = function (html, scope) {
  603.       var doc = scope || document;
  604.       var div = doc.createElement('div');
  605.       div.innerHTML = html;
  606.       if (!div.hasChildNodes() || div.childNodes.length > 1) {
  607.         console.error('HTML does not have a single root node', html);
  608.         throw new Error('HTML must have a single root node');
  609.       }
  610.       return fromDom(div.childNodes[0]);
  611.     };
  612.     var fromTag = function (tag, scope) {
  613.       var doc = scope || document;
  614.       var node = doc.createElement(tag);
  615.       return fromDom(node);
  616.     };
  617.     var fromText = function (text, scope) {
  618.       var doc = scope || document;
  619.       var node = doc.createTextNode(text);
  620.       return fromDom(node);
  621.     };
  622.     var fromDom = function (node) {
  623.       if (node === null || node === undefined) {
  624.         throw new Error('Node cannot be null or undefined');
  625.       }
  626.       return { dom: node };
  627.     };
  628.     var fromPoint = function (docElm, x, y) {
  629.       return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  630.     };
  631.     var SugarElement = {
  632.       fromHtml: fromHtml$2,
  633.       fromTag: fromTag,
  634.       fromText: fromText,
  635.       fromDom: fromDom,
  636.       fromPoint: fromPoint
  637.     };
  638.  
  639.     typeof window !== 'undefined' ? window : Function('return this;')();
  640.  
  641.     var DOCUMENT = 9;
  642.     var DOCUMENT_FRAGMENT = 11;
  643.     var ELEMENT = 1;
  644.     var TEXT = 3;
  645.  
  646.     var name$2 = function (element) {
  647.       var r = element.dom.nodeName;
  648.       return r.toLowerCase();
  649.     };
  650.     var type = function (element) {
  651.       return element.dom.nodeType;
  652.     };
  653.     var isType = function (t) {
  654.       return function (element) {
  655.         return type(element) === t;
  656.       };
  657.     };
  658.     var isElement$2 = isType(ELEMENT);
  659.     var isText$1 = isType(TEXT);
  660.     var isDocument = isType(DOCUMENT);
  661.     var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  662.  
  663.     var cached = function (f) {
  664.       var called = false;
  665.       var r;
  666.       return function () {
  667.         var args = [];
  668.         for (var _i = 0; _i < arguments.length; _i++) {
  669.           args[_i] = arguments[_i];
  670.         }
  671.         if (!called) {
  672.           called = true;
  673.           r = f.apply(null, args);
  674.         }
  675.         return r;
  676.       };
  677.     };
  678.  
  679.     var DeviceType = function (os, browser, userAgent, mediaMatch) {
  680.       var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  681.       var isiPhone = os.isiOS() && !isiPad;
  682.       var isMobile = os.isiOS() || os.isAndroid();
  683.       var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  684.       var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  685.       var isPhone = isiPhone || isMobile && !isTablet;
  686.       var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  687.       var isDesktop = !isPhone && !isTablet && !iOSwebview;
  688.       return {
  689.         isiPad: constant$1(isiPad),
  690.         isiPhone: constant$1(isiPhone),
  691.         isTablet: constant$1(isTablet),
  692.         isPhone: constant$1(isPhone),
  693.         isTouch: constant$1(isTouch),
  694.         isAndroid: os.isAndroid,
  695.         isiOS: os.isiOS,
  696.         isWebView: constant$1(iOSwebview),
  697.         isDesktop: constant$1(isDesktop)
  698.       };
  699.     };
  700.  
  701.     var firstMatch = function (regexes, s) {
  702.       for (var i = 0; i < regexes.length; i++) {
  703.         var x = regexes[i];
  704.         if (x.test(s)) {
  705.           return x;
  706.         }
  707.       }
  708.       return undefined;
  709.     };
  710.     var find$3 = function (regexes, agent) {
  711.       var r = firstMatch(regexes, agent);
  712.       if (!r) {
  713.         return {
  714.           major: 0,
  715.           minor: 0
  716.         };
  717.       }
  718.       var group = function (i) {
  719.         return Number(agent.replace(r, '$' + i));
  720.       };
  721.       return nu$d(group(1), group(2));
  722.     };
  723.     var detect$4 = function (versionRegexes, agent) {
  724.       var cleanedAgent = String(agent).toLowerCase();
  725.       if (versionRegexes.length === 0) {
  726.         return unknown$3();
  727.       }
  728.       return find$3(versionRegexes, cleanedAgent);
  729.     };
  730.     var unknown$3 = function () {
  731.       return nu$d(0, 0);
  732.     };
  733.     var nu$d = function (major, minor) {
  734.       return {
  735.         major: major,
  736.         minor: minor
  737.       };
  738.     };
  739.     var Version = {
  740.       nu: nu$d,
  741.       detect: detect$4,
  742.       unknown: unknown$3
  743.     };
  744.  
  745.     var detectBrowser$1 = function (browsers, userAgentData) {
  746.       return findMap(userAgentData.brands, function (uaBrand) {
  747.         var lcBrand = uaBrand.brand.toLowerCase();
  748.         return find$5(browsers, function (browser) {
  749.           var _a;
  750.           return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  751.         }).map(function (info) {
  752.           return {
  753.             current: info.name,
  754.             version: Version.nu(parseInt(uaBrand.version, 10), 0)
  755.           };
  756.         });
  757.       });
  758.     };
  759.  
  760.     var detect$3 = function (candidates, userAgent) {
  761.       var agent = String(userAgent).toLowerCase();
  762.       return find$5(candidates, function (candidate) {
  763.         return candidate.search(agent);
  764.       });
  765.     };
  766.     var detectBrowser = function (browsers, userAgent) {
  767.       return detect$3(browsers, userAgent).map(function (browser) {
  768.         var version = Version.detect(browser.versionRegexes, userAgent);
  769.         return {
  770.           current: browser.name,
  771.           version: version
  772.         };
  773.       });
  774.     };
  775.     var detectOs = function (oses, userAgent) {
  776.       return detect$3(oses, userAgent).map(function (os) {
  777.         var version = Version.detect(os.versionRegexes, userAgent);
  778.         return {
  779.           current: os.name,
  780.           version: version
  781.         };
  782.       });
  783.     };
  784.  
  785.     var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  786.     var checkContains = function (target) {
  787.       return function (uastring) {
  788.         return contains$1(uastring, target);
  789.       };
  790.     };
  791.     var browsers = [
  792.       {
  793.         name: 'Edge',
  794.         versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  795.         search: function (uastring) {
  796.           return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  797.         }
  798.       },
  799.       {
  800.         name: 'Chrome',
  801.         brand: 'Chromium',
  802.         versionRegexes: [
  803.           /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  804.           normalVersionRegex
  805.         ],
  806.         search: function (uastring) {
  807.           return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  808.         }
  809.       },
  810.       {
  811.         name: 'IE',
  812.         versionRegexes: [
  813.           /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  814.           /.*?rv:([0-9]+)\.([0-9]+).*/
  815.         ],
  816.         search: function (uastring) {
  817.           return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  818.         }
  819.       },
  820.       {
  821.         name: 'Opera',
  822.         versionRegexes: [
  823.           normalVersionRegex,
  824.           /.*?opera\/([0-9]+)\.([0-9]+).*/
  825.         ],
  826.         search: checkContains('opera')
  827.       },
  828.       {
  829.         name: 'Firefox',
  830.         versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  831.         search: checkContains('firefox')
  832.       },
  833.       {
  834.         name: 'Safari',
  835.         versionRegexes: [
  836.           normalVersionRegex,
  837.           /.*?cpu os ([0-9]+)_([0-9]+).*/
  838.         ],
  839.         search: function (uastring) {
  840.           return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  841.         }
  842.       }
  843.     ];
  844.     var oses = [
  845.       {
  846.         name: 'Windows',
  847.         search: checkContains('win'),
  848.         versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  849.       },
  850.       {
  851.         name: 'iOS',
  852.         search: function (uastring) {
  853.           return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  854.         },
  855.         versionRegexes: [
  856.           /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  857.           /.*cpu os ([0-9]+)_([0-9]+).*/,
  858.           /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  859.         ]
  860.       },
  861.       {
  862.         name: 'Android',
  863.         search: checkContains('android'),
  864.         versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  865.       },
  866.       {
  867.         name: 'OSX',
  868.         search: checkContains('mac os x'),
  869.         versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  870.       },
  871.       {
  872.         name: 'Linux',
  873.         search: checkContains('linux'),
  874.         versionRegexes: []
  875.       },
  876.       {
  877.         name: 'Solaris',
  878.         search: checkContains('sunos'),
  879.         versionRegexes: []
  880.       },
  881.       {
  882.         name: 'FreeBSD',
  883.         search: checkContains('freebsd'),
  884.         versionRegexes: []
  885.       },
  886.       {
  887.         name: 'ChromeOS',
  888.         search: checkContains('cros'),
  889.         versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  890.       }
  891.     ];
  892.     var PlatformInfo = {
  893.       browsers: constant$1(browsers),
  894.       oses: constant$1(oses)
  895.     };
  896.  
  897.     var edge = 'Edge';
  898.     var chrome = 'Chrome';
  899.     var ie = 'IE';
  900.     var opera = 'Opera';
  901.     var firefox = 'Firefox';
  902.     var safari = 'Safari';
  903.     var unknown$2 = function () {
  904.       return nu$c({
  905.         current: undefined,
  906.         version: Version.unknown()
  907.       });
  908.     };
  909.     var nu$c = function (info) {
  910.       var current = info.current;
  911.       var version = info.version;
  912.       var isBrowser = function (name) {
  913.         return function () {
  914.           return current === name;
  915.         };
  916.       };
  917.       return {
  918.         current: current,
  919.         version: version,
  920.         isEdge: isBrowser(edge),
  921.         isChrome: isBrowser(chrome),
  922.         isIE: isBrowser(ie),
  923.         isOpera: isBrowser(opera),
  924.         isFirefox: isBrowser(firefox),
  925.         isSafari: isBrowser(safari)
  926.       };
  927.     };
  928.     var Browser = {
  929.       unknown: unknown$2,
  930.       nu: nu$c,
  931.       edge: constant$1(edge),
  932.       chrome: constant$1(chrome),
  933.       ie: constant$1(ie),
  934.       opera: constant$1(opera),
  935.       firefox: constant$1(firefox),
  936.       safari: constant$1(safari)
  937.     };
  938.  
  939.     var windows = 'Windows';
  940.     var ios = 'iOS';
  941.     var android = 'Android';
  942.     var linux = 'Linux';
  943.     var osx = 'OSX';
  944.     var solaris = 'Solaris';
  945.     var freebsd = 'FreeBSD';
  946.     var chromeos = 'ChromeOS';
  947.     var unknown$1 = function () {
  948.       return nu$b({
  949.         current: undefined,
  950.         version: Version.unknown()
  951.       });
  952.     };
  953.     var nu$b = function (info) {
  954.       var current = info.current;
  955.       var version = info.version;
  956.       var isOS = function (name) {
  957.         return function () {
  958.           return current === name;
  959.         };
  960.       };
  961.       return {
  962.         current: current,
  963.         version: version,
  964.         isWindows: isOS(windows),
  965.         isiOS: isOS(ios),
  966.         isAndroid: isOS(android),
  967.         isOSX: isOS(osx),
  968.         isLinux: isOS(linux),
  969.         isSolaris: isOS(solaris),
  970.         isFreeBSD: isOS(freebsd),
  971.         isChromeOS: isOS(chromeos)
  972.       };
  973.     };
  974.     var OperatingSystem = {
  975.       unknown: unknown$1,
  976.       nu: nu$b,
  977.       windows: constant$1(windows),
  978.       ios: constant$1(ios),
  979.       android: constant$1(android),
  980.       linux: constant$1(linux),
  981.       osx: constant$1(osx),
  982.       solaris: constant$1(solaris),
  983.       freebsd: constant$1(freebsd),
  984.       chromeos: constant$1(chromeos)
  985.     };
  986.  
  987.     var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  988.       var browsers = PlatformInfo.browsers();
  989.       var oses = PlatformInfo.oses();
  990.       var browser = userAgentDataOpt.bind(function (userAgentData) {
  991.         return detectBrowser$1(browsers, userAgentData);
  992.       }).orThunk(function () {
  993.         return detectBrowser(browsers, userAgent);
  994.       }).fold(Browser.unknown, Browser.nu);
  995.       var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  996.       var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  997.       return {
  998.         browser: browser,
  999.         os: os,
  1000.         deviceType: deviceType
  1001.       };
  1002.     };
  1003.     var PlatformDetection = { detect: detect$2 };
  1004.  
  1005.     var mediaMatch = function (query) {
  1006.       return window.matchMedia(query).matches;
  1007.     };
  1008.     var platform = cached(function () {
  1009.       return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  1010.     });
  1011.     var detect$1 = function () {
  1012.       return platform();
  1013.     };
  1014.  
  1015.     var compareDocumentPosition = function (a, b, match) {
  1016.       return (a.compareDocumentPosition(b) & match) !== 0;
  1017.     };
  1018.     var documentPositionContainedBy = function (a, b) {
  1019.       return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1020.     };
  1021.  
  1022.     var is = function (element, selector) {
  1023.       var dom = element.dom;
  1024.       if (dom.nodeType !== ELEMENT) {
  1025.         return false;
  1026.       } else {
  1027.         var elem = dom;
  1028.         if (elem.matches !== undefined) {
  1029.           return elem.matches(selector);
  1030.         } else if (elem.msMatchesSelector !== undefined) {
  1031.           return elem.msMatchesSelector(selector);
  1032.         } else if (elem.webkitMatchesSelector !== undefined) {
  1033.           return elem.webkitMatchesSelector(selector);
  1034.         } else if (elem.mozMatchesSelector !== undefined) {
  1035.           return elem.mozMatchesSelector(selector);
  1036.         } else {
  1037.           throw new Error('Browser lacks native selectors');
  1038.         }
  1039.       }
  1040.     };
  1041.     var bypassSelector = function (dom) {
  1042.       return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1043.     };
  1044.     var all$3 = function (selector, scope) {
  1045.       var base = scope === undefined ? document : scope.dom;
  1046.       return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  1047.     };
  1048.     var one = function (selector, scope) {
  1049.       var base = scope === undefined ? document : scope.dom;
  1050.       return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1051.     };
  1052.  
  1053.     var eq = function (e1, e2) {
  1054.       return e1.dom === e2.dom;
  1055.     };
  1056.     var regularContains = function (e1, e2) {
  1057.       var d1 = e1.dom;
  1058.       var d2 = e2.dom;
  1059.       return d1 === d2 ? false : d1.contains(d2);
  1060.     };
  1061.     var ieContains = function (e1, e2) {
  1062.       return documentPositionContainedBy(e1.dom, e2.dom);
  1063.     };
  1064.     var contains = function (e1, e2) {
  1065.       return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1066.     };
  1067.  
  1068.     var owner$4 = function (element) {
  1069.       return SugarElement.fromDom(element.dom.ownerDocument);
  1070.     };
  1071.     var documentOrOwner = function (dos) {
  1072.       return isDocument(dos) ? dos : owner$4(dos);
  1073.     };
  1074.     var documentElement = function (element) {
  1075.       return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1076.     };
  1077.     var defaultView = function (element) {
  1078.       return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1079.     };
  1080.     var parent = function (element) {
  1081.       return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1082.     };
  1083.     var parentNode = function (element) {
  1084.       return parent(element);
  1085.     };
  1086.     var offsetParent = function (element) {
  1087.       return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  1088.     };
  1089.     var nextSibling = function (element) {
  1090.       return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1091.     };
  1092.     var children = function (element) {
  1093.       return map$2(element.dom.childNodes, SugarElement.fromDom);
  1094.     };
  1095.     var child$2 = function (element, index) {
  1096.       var cs = element.dom.childNodes;
  1097.       return Optional.from(cs[index]).map(SugarElement.fromDom);
  1098.     };
  1099.     var firstChild = function (element) {
  1100.       return child$2(element, 0);
  1101.     };
  1102.     var spot = function (element, offset) {
  1103.       return {
  1104.         element: element,
  1105.         offset: offset
  1106.       };
  1107.     };
  1108.     var leaf = function (element, offset) {
  1109.       var cs = children(element);
  1110.       return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  1111.     };
  1112.  
  1113.     var isShadowRoot = function (dos) {
  1114.       return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  1115.     };
  1116.     var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1117.     var isSupported = constant$1(supported);
  1118.     var getRootNode = supported ? function (e) {
  1119.       return SugarElement.fromDom(e.dom.getRootNode());
  1120.     } : documentOrOwner;
  1121.     var getContentContainer = function (dos) {
  1122.       return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  1123.     };
  1124.     var isInShadowRoot = function (e) {
  1125.       return getShadowRoot(e).isSome();
  1126.     };
  1127.     var getShadowRoot = function (e) {
  1128.       var r = getRootNode(e);
  1129.       return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1130.     };
  1131.     var getShadowHost = function (e) {
  1132.       return SugarElement.fromDom(e.dom.host);
  1133.     };
  1134.     var getOriginalEventTarget = function (event) {
  1135.       if (isSupported() && isNonNullable(event.target)) {
  1136.         var el = SugarElement.fromDom(event.target);
  1137.         if (isElement$2(el) && isOpenShadowHost(el)) {
  1138.           if (event.composed && event.composedPath) {
  1139.             var composedPath = event.composedPath();
  1140.             if (composedPath) {
  1141.               return head(composedPath);
  1142.             }
  1143.           }
  1144.         }
  1145.       }
  1146.       return Optional.from(event.target);
  1147.     };
  1148.     var isOpenShadowHost = function (element) {
  1149.       return isNonNullable(element.dom.shadowRoot);
  1150.     };
  1151.  
  1152.     var inBody = function (element) {
  1153.       var dom = isText$1(element) ? element.dom.parentNode : element.dom;
  1154.       if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1155.         return false;
  1156.       }
  1157.       var doc = dom.ownerDocument;
  1158.       return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1159.         return doc.body.contains(dom);
  1160.       }, compose1(inBody, getShadowHost));
  1161.     };
  1162.     var body = function () {
  1163.       return getBody(SugarElement.fromDom(document));
  1164.     };
  1165.     var getBody = function (doc) {
  1166.       var b = doc.dom.body;
  1167.       if (b === null || b === undefined) {
  1168.         throw new Error('Body is not available yet');
  1169.       }
  1170.       return SugarElement.fromDom(b);
  1171.     };
  1172.  
  1173.     var rawSet = function (dom, key, value) {
  1174.       if (isString(value) || isBoolean(value) || isNumber(value)) {
  1175.         dom.setAttribute(key, value + '');
  1176.       } else {
  1177.         console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1178.         throw new Error('Attribute value was not simple');
  1179.       }
  1180.     };
  1181.     var set$8 = function (element, key, value) {
  1182.       rawSet(element.dom, key, value);
  1183.     };
  1184.     var setAll$1 = function (element, attrs) {
  1185.       var dom = element.dom;
  1186.       each(attrs, function (v, k) {
  1187.         rawSet(dom, k, v);
  1188.       });
  1189.     };
  1190.     var get$d = function (element, key) {
  1191.       var v = element.dom.getAttribute(key);
  1192.       return v === null ? undefined : v;
  1193.     };
  1194.     var getOpt = function (element, key) {
  1195.       return Optional.from(get$d(element, key));
  1196.     };
  1197.     var has$1 = function (element, key) {
  1198.       var dom = element.dom;
  1199.       return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1200.     };
  1201.     var remove$7 = function (element, key) {
  1202.       element.dom.removeAttribute(key);
  1203.     };
  1204.  
  1205.     var internalSet = function (dom, property, value) {
  1206.       if (!isString(value)) {
  1207.         console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1208.         throw new Error('CSS value must be a string: ' + value);
  1209.       }
  1210.       if (isSupported$1(dom)) {
  1211.         dom.style.setProperty(property, value);
  1212.       }
  1213.     };
  1214.     var internalRemove = function (dom, property) {
  1215.       if (isSupported$1(dom)) {
  1216.         dom.style.removeProperty(property);
  1217.       }
  1218.     };
  1219.     var set$7 = function (element, property, value) {
  1220.       var dom = element.dom;
  1221.       internalSet(dom, property, value);
  1222.     };
  1223.     var setAll = function (element, css) {
  1224.       var dom = element.dom;
  1225.       each(css, function (v, k) {
  1226.         internalSet(dom, k, v);
  1227.       });
  1228.     };
  1229.     var setOptions = function (element, css) {
  1230.       var dom = element.dom;
  1231.       each(css, function (v, k) {
  1232.         v.fold(function () {
  1233.           internalRemove(dom, k);
  1234.         }, function (value) {
  1235.           internalSet(dom, k, value);
  1236.         });
  1237.       });
  1238.     };
  1239.     var get$c = function (element, property) {
  1240.       var dom = element.dom;
  1241.       var styles = window.getComputedStyle(dom);
  1242.       var r = styles.getPropertyValue(property);
  1243.       return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1244.     };
  1245.     var getUnsafeProperty = function (dom, property) {
  1246.       return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  1247.     };
  1248.     var getRaw = function (element, property) {
  1249.       var dom = element.dom;
  1250.       var raw = getUnsafeProperty(dom, property);
  1251.       return Optional.from(raw).filter(function (r) {
  1252.         return r.length > 0;
  1253.       });
  1254.     };
  1255.     var getAllRaw = function (element) {
  1256.       var css = {};
  1257.       var dom = element.dom;
  1258.       if (isSupported$1(dom)) {
  1259.         for (var i = 0; i < dom.style.length; i++) {
  1260.           var ruleName = dom.style.item(i);
  1261.           css[ruleName] = dom.style[ruleName];
  1262.         }
  1263.       }
  1264.       return css;
  1265.     };
  1266.     var isValidValue = function (tag, property, value) {
  1267.       var element = SugarElement.fromTag(tag);
  1268.       set$7(element, property, value);
  1269.       var style = getRaw(element, property);
  1270.       return style.isSome();
  1271.     };
  1272.     var remove$6 = function (element, property) {
  1273.       var dom = element.dom;
  1274.       internalRemove(dom, property);
  1275.       if (is$1(getOpt(element, 'style').map(trim$1), '')) {
  1276.         remove$7(element, 'style');
  1277.       }
  1278.     };
  1279.     var reflow = function (e) {
  1280.       return e.dom.offsetWidth;
  1281.     };
  1282.  
  1283.     var Dimension = function (name, getOffset) {
  1284.       var set = function (element, h) {
  1285.         if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  1286.           throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  1287.         }
  1288.         var dom = element.dom;
  1289.         if (isSupported$1(dom)) {
  1290.           dom.style[name] = h + 'px';
  1291.         }
  1292.       };
  1293.       var get = function (element) {
  1294.         var r = getOffset(element);
  1295.         if (r <= 0 || r === null) {
  1296.           var css = get$c(element, name);
  1297.           return parseFloat(css) || 0;
  1298.         }
  1299.         return r;
  1300.       };
  1301.       var getOuter = get;
  1302.       var aggregate = function (element, properties) {
  1303.         return foldl(properties, function (acc, property) {
  1304.           var val = get$c(element, property);
  1305.           var value = val === undefined ? 0 : parseInt(val, 10);
  1306.           return isNaN(value) ? acc : acc + value;
  1307.         }, 0);
  1308.       };
  1309.       var max = function (element, value, properties) {
  1310.         var cumulativeInclusions = aggregate(element, properties);
  1311.         var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  1312.         return absoluteMax;
  1313.       };
  1314.       return {
  1315.         set: set,
  1316.         get: get,
  1317.         getOuter: getOuter,
  1318.         aggregate: aggregate,
  1319.         max: max
  1320.       };
  1321.     };
  1322.  
  1323.     var api$3 = Dimension('height', function (element) {
  1324.       var dom = element.dom;
  1325.       return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  1326.     });
  1327.     var get$b = function (element) {
  1328.       return api$3.get(element);
  1329.     };
  1330.     var getOuter$2 = function (element) {
  1331.       return api$3.getOuter(element);
  1332.     };
  1333.     var setMax$1 = function (element, value) {
  1334.       var inclusions = [
  1335.         'margin-top',
  1336.         'border-top-width',
  1337.         'padding-top',
  1338.         'padding-bottom',
  1339.         'border-bottom-width',
  1340.         'margin-bottom'
  1341.       ];
  1342.       var absMax = api$3.max(element, value, inclusions);
  1343.       set$7(element, 'max-height', absMax + 'px');
  1344.     };
  1345.  
  1346.     var r$1 = function (left, top) {
  1347.       var translate = function (x, y) {
  1348.         return r$1(left + x, top + y);
  1349.       };
  1350.       return {
  1351.         left: left,
  1352.         top: top,
  1353.         translate: translate
  1354.       };
  1355.     };
  1356.     var SugarPosition = r$1;
  1357.  
  1358.     var boxPosition = function (dom) {
  1359.       var box = dom.getBoundingClientRect();
  1360.       return SugarPosition(box.left, box.top);
  1361.     };
  1362.     var firstDefinedOrZero = function (a, b) {
  1363.       if (a !== undefined) {
  1364.         return a;
  1365.       } else {
  1366.         return b !== undefined ? b : 0;
  1367.       }
  1368.     };
  1369.     var absolute$3 = function (element) {
  1370.       var doc = element.dom.ownerDocument;
  1371.       var body = doc.body;
  1372.       var win = doc.defaultView;
  1373.       var html = doc.documentElement;
  1374.       if (body === element.dom) {
  1375.         return SugarPosition(body.offsetLeft, body.offsetTop);
  1376.       }
  1377.       var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1378.       var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1379.       var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1380.       var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1381.       return viewport$1(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1382.     };
  1383.     var viewport$1 = function (element) {
  1384.       var dom = element.dom;
  1385.       var doc = dom.ownerDocument;
  1386.       var body = doc.body;
  1387.       if (body === dom) {
  1388.         return SugarPosition(body.offsetLeft, body.offsetTop);
  1389.       }
  1390.       if (!inBody(element)) {
  1391.         return SugarPosition(0, 0);
  1392.       }
  1393.       return boxPosition(dom);
  1394.     };
  1395.  
  1396.     var api$2 = Dimension('width', function (element) {
  1397.       return element.dom.offsetWidth;
  1398.     });
  1399.     var set$6 = function (element, h) {
  1400.       return api$2.set(element, h);
  1401.     };
  1402.     var get$a = function (element) {
  1403.       return api$2.get(element);
  1404.     };
  1405.     var getOuter$1 = function (element) {
  1406.       return api$2.getOuter(element);
  1407.     };
  1408.     var setMax = function (element, value) {
  1409.       var inclusions = [
  1410.         'margin-left',
  1411.         'border-left-width',
  1412.         'padding-left',
  1413.         'padding-right',
  1414.         'border-right-width',
  1415.         'margin-right'
  1416.       ];
  1417.       var absMax = api$2.max(element, value, inclusions);
  1418.       set$7(element, 'max-width', absMax + 'px');
  1419.     };
  1420.  
  1421.     var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  1422.       return {
  1423.         target: target,
  1424.         x: x,
  1425.         y: y,
  1426.         stop: stop,
  1427.         prevent: prevent,
  1428.         kill: kill,
  1429.         raw: raw
  1430.       };
  1431.     };
  1432.     var fromRawEvent$1 = function (rawEvent) {
  1433.       var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  1434.       var stop = function () {
  1435.         return rawEvent.stopPropagation();
  1436.       };
  1437.       var prevent = function () {
  1438.         return rawEvent.preventDefault();
  1439.       };
  1440.       var kill = compose(prevent, stop);
  1441.       return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  1442.     };
  1443.     var handle = function (filter, handler) {
  1444.       return function (rawEvent) {
  1445.         if (filter(rawEvent)) {
  1446.           handler(fromRawEvent$1(rawEvent));
  1447.         }
  1448.       };
  1449.     };
  1450.     var binder = function (element, event, filter, handler, useCapture) {
  1451.       var wrapped = handle(filter, handler);
  1452.       element.dom.addEventListener(event, wrapped, useCapture);
  1453.       return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  1454.     };
  1455.     var bind$2 = function (element, event, filter, handler) {
  1456.       return binder(element, event, filter, handler, false);
  1457.     };
  1458.     var capture$1 = function (element, event, filter, handler) {
  1459.       return binder(element, event, filter, handler, true);
  1460.     };
  1461.     var unbind = function (element, event, handler, useCapture) {
  1462.       element.dom.removeEventListener(event, handler, useCapture);
  1463.     };
  1464.  
  1465.     var before$2 = function (marker, element) {
  1466.       var parent$1 = parent(marker);
  1467.       parent$1.each(function (v) {
  1468.         v.dom.insertBefore(element.dom, marker.dom);
  1469.       });
  1470.     };
  1471.     var after$2 = function (marker, element) {
  1472.       var sibling = nextSibling(marker);
  1473.       sibling.fold(function () {
  1474.         var parent$1 = parent(marker);
  1475.         parent$1.each(function (v) {
  1476.           append$2(v, element);
  1477.         });
  1478.       }, function (v) {
  1479.         before$2(v, element);
  1480.       });
  1481.     };
  1482.     var prepend$1 = function (parent, element) {
  1483.       var firstChild$1 = firstChild(parent);
  1484.       firstChild$1.fold(function () {
  1485.         append$2(parent, element);
  1486.       }, function (v) {
  1487.         parent.dom.insertBefore(element.dom, v.dom);
  1488.       });
  1489.     };
  1490.     var append$2 = function (parent, element) {
  1491.       parent.dom.appendChild(element.dom);
  1492.     };
  1493.     var appendAt = function (parent, element, index) {
  1494.       child$2(parent, index).fold(function () {
  1495.         append$2(parent, element);
  1496.       }, function (v) {
  1497.         before$2(v, element);
  1498.       });
  1499.     };
  1500.  
  1501.     var before$1 = function (marker, elements) {
  1502.       each$1(elements, function (x) {
  1503.         before$2(marker, x);
  1504.       });
  1505.     };
  1506.     var append$1 = function (parent, elements) {
  1507.       each$1(elements, function (x) {
  1508.         append$2(parent, x);
  1509.       });
  1510.     };
  1511.  
  1512.     var empty = function (element) {
  1513.       element.dom.textContent = '';
  1514.       each$1(children(element), function (rogue) {
  1515.         remove$5(rogue);
  1516.       });
  1517.     };
  1518.     var remove$5 = function (element) {
  1519.       var dom = element.dom;
  1520.       if (dom.parentNode !== null) {
  1521.         dom.parentNode.removeChild(dom);
  1522.       }
  1523.     };
  1524.     var unwrap = function (wrapper) {
  1525.       var children$1 = children(wrapper);
  1526.       if (children$1.length > 0) {
  1527.         before$1(wrapper, children$1);
  1528.       }
  1529.       remove$5(wrapper);
  1530.     };
  1531.  
  1532.     var get$9 = function (_DOC) {
  1533.       var doc = _DOC !== undefined ? _DOC.dom : document;
  1534.       var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1535.       var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1536.       return SugarPosition(x, y);
  1537.     };
  1538.     var to = function (x, y, _DOC) {
  1539.       var doc = _DOC !== undefined ? _DOC.dom : document;
  1540.       var win = doc.defaultView;
  1541.       if (win) {
  1542.         win.scrollTo(x, y);
  1543.       }
  1544.     };
  1545.  
  1546.     var get$8 = function (_win) {
  1547.       var win = _win === undefined ? window : _win;
  1548.       if (detect$1().browser.isFirefox()) {
  1549.         return Optional.none();
  1550.       } else {
  1551.         return Optional.from(win['visualViewport']);
  1552.       }
  1553.     };
  1554.     var bounds$1 = function (x, y, width, height) {
  1555.       return {
  1556.         x: x,
  1557.         y: y,
  1558.         width: width,
  1559.         height: height,
  1560.         right: x + width,
  1561.         bottom: y + height
  1562.       };
  1563.     };
  1564.     var getBounds$3 = function (_win) {
  1565.       var win = _win === undefined ? window : _win;
  1566.       var doc = win.document;
  1567.       var scroll = get$9(SugarElement.fromDom(doc));
  1568.       return get$8(win).fold(function () {
  1569.         var html = win.document.documentElement;
  1570.         var width = html.clientWidth;
  1571.         var height = html.clientHeight;
  1572.         return bounds$1(scroll.left, scroll.top, width, height);
  1573.       }, function (visualViewport) {
  1574.         return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1575.       });
  1576.     };
  1577.  
  1578.     var walkUp = function (navigation, doc) {
  1579.       var frame = navigation.view(doc);
  1580.       return frame.fold(constant$1([]), function (f) {
  1581.         var parent = navigation.owner(f);
  1582.         var rest = walkUp(navigation, parent);
  1583.         return [f].concat(rest);
  1584.       });
  1585.     };
  1586.     var pathTo = function (element, navigation) {
  1587.       var d = navigation.owner(element);
  1588.       var paths = walkUp(navigation, d);
  1589.       return Optional.some(paths);
  1590.     };
  1591.  
  1592.     var view = function (doc) {
  1593.       var _a;
  1594.       var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  1595.       return element.map(SugarElement.fromDom);
  1596.     };
  1597.     var owner$3 = function (element) {
  1598.       return owner$4(element);
  1599.     };
  1600.  
  1601.     var Navigation = /*#__PURE__*/Object.freeze({
  1602.         __proto__: null,
  1603.         view: view,
  1604.         owner: owner$3
  1605.     });
  1606.  
  1607.     var find$2 = function (element) {
  1608.       var doc = SugarElement.fromDom(document);
  1609.       var scroll = get$9(doc);
  1610.       var path = pathTo(element, Navigation);
  1611.       return path.fold(curry(absolute$3, element), function (frames) {
  1612.         var offset = viewport$1(element);
  1613.         var r = foldr(frames, function (b, a) {
  1614.           var loc = viewport$1(a);
  1615.           return {
  1616.             left: b.left + loc.left,
  1617.             top: b.top + loc.top
  1618.           };
  1619.         }, {
  1620.           left: 0,
  1621.           top: 0
  1622.         });
  1623.         return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  1624.       });
  1625.     };
  1626.  
  1627.     var pointed = function (point, width, height) {
  1628.       return {
  1629.         point: point,
  1630.         width: width,
  1631.         height: height
  1632.       };
  1633.     };
  1634.     var rect = function (x, y, width, height) {
  1635.       return {
  1636.         x: x,
  1637.         y: y,
  1638.         width: width,
  1639.         height: height
  1640.       };
  1641.     };
  1642.     var bounds = function (x, y, width, height) {
  1643.       return {
  1644.         x: x,
  1645.         y: y,
  1646.         width: width,
  1647.         height: height,
  1648.         right: x + width,
  1649.         bottom: y + height
  1650.       };
  1651.     };
  1652.     var box$1 = function (element) {
  1653.       var xy = absolute$3(element);
  1654.       var w = getOuter$1(element);
  1655.       var h = getOuter$2(element);
  1656.       return bounds(xy.left, xy.top, w, h);
  1657.     };
  1658.     var absolute$2 = function (element) {
  1659.       var position = find$2(element);
  1660.       var width = getOuter$1(element);
  1661.       var height = getOuter$2(element);
  1662.       return bounds(position.left, position.top, width, height);
  1663.     };
  1664.     var win = function () {
  1665.       return getBounds$3(window);
  1666.     };
  1667.  
  1668.     var value$3 = function (o) {
  1669.       var or = function (_opt) {
  1670.         return value$3(o);
  1671.       };
  1672.       var orThunk = function (_f) {
  1673.         return value$3(o);
  1674.       };
  1675.       var map = function (f) {
  1676.         return value$3(f(o));
  1677.       };
  1678.       var mapError = function (_f) {
  1679.         return value$3(o);
  1680.       };
  1681.       var each = function (f) {
  1682.         f(o);
  1683.       };
  1684.       var bind = function (f) {
  1685.         return f(o);
  1686.       };
  1687.       var fold = function (_, onValue) {
  1688.         return onValue(o);
  1689.       };
  1690.       var exists = function (f) {
  1691.         return f(o);
  1692.       };
  1693.       var forall = function (f) {
  1694.         return f(o);
  1695.       };
  1696.       var toOptional = function () {
  1697.         return Optional.some(o);
  1698.       };
  1699.       return {
  1700.         isValue: always,
  1701.         isError: never,
  1702.         getOr: constant$1(o),
  1703.         getOrThunk: constant$1(o),
  1704.         getOrDie: constant$1(o),
  1705.         or: or,
  1706.         orThunk: orThunk,
  1707.         fold: fold,
  1708.         map: map,
  1709.         mapError: mapError,
  1710.         each: each,
  1711.         bind: bind,
  1712.         exists: exists,
  1713.         forall: forall,
  1714.         toOptional: toOptional
  1715.       };
  1716.     };
  1717.     var error$1 = function (message) {
  1718.       var getOrThunk = function (f) {
  1719.         return f();
  1720.       };
  1721.       var getOrDie = function () {
  1722.         return die(String(message))();
  1723.       };
  1724.       var or = identity$1;
  1725.       var orThunk = function (f) {
  1726.         return f();
  1727.       };
  1728.       var map = function (_f) {
  1729.         return error$1(message);
  1730.       };
  1731.       var mapError = function (f) {
  1732.         return error$1(f(message));
  1733.       };
  1734.       var bind = function (_f) {
  1735.         return error$1(message);
  1736.       };
  1737.       var fold = function (onError, _) {
  1738.         return onError(message);
  1739.       };
  1740.       return {
  1741.         isValue: never,
  1742.         isError: always,
  1743.         getOr: identity$1,
  1744.         getOrThunk: getOrThunk,
  1745.         getOrDie: getOrDie,
  1746.         or: or,
  1747.         orThunk: orThunk,
  1748.         fold: fold,
  1749.         map: map,
  1750.         mapError: mapError,
  1751.         each: noop,
  1752.         bind: bind,
  1753.         exists: never,
  1754.         forall: always,
  1755.         toOptional: Optional.none
  1756.       };
  1757.     };
  1758.     var fromOption = function (opt, err) {
  1759.       return opt.fold(function () {
  1760.         return error$1(err);
  1761.       }, value$3);
  1762.     };
  1763.     var Result = {
  1764.       value: value$3,
  1765.       error: error$1,
  1766.       fromOption: fromOption
  1767.     };
  1768.  
  1769.     var SimpleResultType;
  1770.     (function (SimpleResultType) {
  1771.       SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1772.       SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1773.     }(SimpleResultType || (SimpleResultType = {})));
  1774.     var fold$1 = function (res, onError, onValue) {
  1775.       return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1776.     };
  1777.     var partition$2 = function (results) {
  1778.       var values = [];
  1779.       var errors = [];
  1780.       each$1(results, function (obj) {
  1781.         fold$1(obj, function (err) {
  1782.           return errors.push(err);
  1783.         }, function (val) {
  1784.           return values.push(val);
  1785.         });
  1786.       });
  1787.       return {
  1788.         values: values,
  1789.         errors: errors
  1790.       };
  1791.     };
  1792.     var mapError = function (res, f) {
  1793.       if (res.stype === SimpleResultType.Error) {
  1794.         return {
  1795.           stype: SimpleResultType.Error,
  1796.           serror: f(res.serror)
  1797.         };
  1798.       } else {
  1799.         return res;
  1800.       }
  1801.     };
  1802.     var map = function (res, f) {
  1803.       if (res.stype === SimpleResultType.Value) {
  1804.         return {
  1805.           stype: SimpleResultType.Value,
  1806.           svalue: f(res.svalue)
  1807.         };
  1808.       } else {
  1809.         return res;
  1810.       }
  1811.     };
  1812.     var bind$1 = function (res, f) {
  1813.       if (res.stype === SimpleResultType.Value) {
  1814.         return f(res.svalue);
  1815.       } else {
  1816.         return res;
  1817.       }
  1818.     };
  1819.     var bindError = function (res, f) {
  1820.       if (res.stype === SimpleResultType.Error) {
  1821.         return f(res.serror);
  1822.       } else {
  1823.         return res;
  1824.       }
  1825.     };
  1826.     var svalue = function (v) {
  1827.       return {
  1828.         stype: SimpleResultType.Value,
  1829.         svalue: v
  1830.       };
  1831.     };
  1832.     var serror = function (e) {
  1833.       return {
  1834.         stype: SimpleResultType.Error,
  1835.         serror: e
  1836.       };
  1837.     };
  1838.     var toResult$1 = function (res) {
  1839.       return fold$1(res, Result.error, Result.value);
  1840.     };
  1841.     var fromResult$1 = function (res) {
  1842.       return res.fold(serror, svalue);
  1843.     };
  1844.     var SimpleResult = {
  1845.       fromResult: fromResult$1,
  1846.       toResult: toResult$1,
  1847.       svalue: svalue,
  1848.       partition: partition$2,
  1849.       serror: serror,
  1850.       bind: bind$1,
  1851.       bindError: bindError,
  1852.       map: map,
  1853.       mapError: mapError,
  1854.       fold: fold$1
  1855.     };
  1856.  
  1857.     var field$2 = function (key, newKey, presence, prop) {
  1858.       return {
  1859.         tag: 'field',
  1860.         key: key,
  1861.         newKey: newKey,
  1862.         presence: presence,
  1863.         prop: prop
  1864.       };
  1865.     };
  1866.     var customField$1 = function (newKey, instantiator) {
  1867.       return {
  1868.         tag: 'custom',
  1869.         newKey: newKey,
  1870.         instantiator: instantiator
  1871.       };
  1872.     };
  1873.     var fold = function (value, ifField, ifCustom) {
  1874.       switch (value.tag) {
  1875.       case 'field':
  1876.         return ifField(value.key, value.newKey, value.presence, value.prop);
  1877.       case 'custom':
  1878.         return ifCustom(value.newKey, value.instantiator);
  1879.       }
  1880.     };
  1881.  
  1882.     var shallow$1 = function (old, nu) {
  1883.       return nu;
  1884.     };
  1885.     var deep = function (old, nu) {
  1886.       var bothObjects = isObject(old) && isObject(nu);
  1887.       return bothObjects ? deepMerge(old, nu) : nu;
  1888.     };
  1889.     var baseMerge = function (merger) {
  1890.       return function () {
  1891.         var objects = [];
  1892.         for (var _i = 0; _i < arguments.length; _i++) {
  1893.           objects[_i] = arguments[_i];
  1894.         }
  1895.         if (objects.length === 0) {
  1896.           throw new Error('Can\'t merge zero objects');
  1897.         }
  1898.         var ret = {};
  1899.         for (var j = 0; j < objects.length; j++) {
  1900.           var curObject = objects[j];
  1901.           for (var key in curObject) {
  1902.             if (has$2(curObject, key)) {
  1903.               ret[key] = merger(ret[key], curObject[key]);
  1904.             }
  1905.           }
  1906.         }
  1907.         return ret;
  1908.       };
  1909.     };
  1910.     var deepMerge = baseMerge(deep);
  1911.     var merge$1 = baseMerge(shallow$1);
  1912.  
  1913.     var required$2 = function () {
  1914.       return {
  1915.         tag: 'required',
  1916.         process: {}
  1917.       };
  1918.     };
  1919.     var defaultedThunk = function (fallbackThunk) {
  1920.       return {
  1921.         tag: 'defaultedThunk',
  1922.         process: fallbackThunk
  1923.       };
  1924.     };
  1925.     var defaulted$1 = function (fallback) {
  1926.       return defaultedThunk(constant$1(fallback));
  1927.     };
  1928.     var asOption = function () {
  1929.       return {
  1930.         tag: 'option',
  1931.         process: {}
  1932.       };
  1933.     };
  1934.     var mergeWithThunk = function (baseThunk) {
  1935.       return {
  1936.         tag: 'mergeWithThunk',
  1937.         process: baseThunk
  1938.       };
  1939.     };
  1940.     var mergeWith = function (base) {
  1941.       return mergeWithThunk(constant$1(base));
  1942.     };
  1943.  
  1944.     var mergeValues$1 = function (values, base) {
  1945.       return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1946.     };
  1947.     var mergeErrors$1 = function (errors) {
  1948.       return compose(SimpleResult.serror, flatten)(errors);
  1949.     };
  1950.     var consolidateObj = function (objects, base) {
  1951.       var partition = SimpleResult.partition(objects);
  1952.       return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1953.     };
  1954.     var consolidateArr = function (objects) {
  1955.       var partitions = SimpleResult.partition(objects);
  1956.       return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1957.     };
  1958.     var ResultCombine = {
  1959.       consolidateObj: consolidateObj,
  1960.       consolidateArr: consolidateArr
  1961.     };
  1962.  
  1963.     var formatObj = function (input) {
  1964.       return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1965.     };
  1966.     var formatErrors = function (errors) {
  1967.       var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1968.           path: [],
  1969.           getErrorInfo: constant$1('... (only showing first ten failures)')
  1970.         }]) : errors;
  1971.       return map$2(es, function (e) {
  1972.         return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1973.       });
  1974.     };
  1975.  
  1976.     var nu$a = function (path, getErrorInfo) {
  1977.       return SimpleResult.serror([{
  1978.           path: path,
  1979.           getErrorInfo: getErrorInfo
  1980.         }]);
  1981.     };
  1982.     var missingRequired = function (path, key, obj) {
  1983.       return nu$a(path, function () {
  1984.         return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  1985.       });
  1986.     };
  1987.     var missingKey = function (path, key) {
  1988.       return nu$a(path, function () {
  1989.         return 'Choice schema did not contain choice key: "' + key + '"';
  1990.       });
  1991.     };
  1992.     var missingBranch = function (path, branches, branch) {
  1993.       return nu$a(path, function () {
  1994.         return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1995.       });
  1996.     };
  1997.     var unsupportedFields = function (path, unsupported) {
  1998.       return nu$a(path, function () {
  1999.         return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  2000.       });
  2001.     };
  2002.     var custom = function (path, err) {
  2003.       return nu$a(path, constant$1(err));
  2004.     };
  2005.  
  2006.     var value$2 = function (validator) {
  2007.       var extract = function (path, val) {
  2008.         return SimpleResult.bindError(validator(val), function (err) {
  2009.           return custom(path, err);
  2010.         });
  2011.       };
  2012.       var toString = constant$1('val');
  2013.       return {
  2014.         extract: extract,
  2015.         toString: toString
  2016.       };
  2017.     };
  2018.     var anyValue$1 = value$2(SimpleResult.svalue);
  2019.  
  2020.     var requiredAccess = function (path, obj, key, bundle) {
  2021.       return get$e(obj, key).fold(function () {
  2022.         return missingRequired(path, key, obj);
  2023.       }, bundle);
  2024.     };
  2025.     var fallbackAccess = function (obj, key, fallback, bundle) {
  2026.       var v = get$e(obj, key).getOrThunk(function () {
  2027.         return fallback(obj);
  2028.       });
  2029.       return bundle(v);
  2030.     };
  2031.     var optionAccess = function (obj, key, bundle) {
  2032.       return bundle(get$e(obj, key));
  2033.     };
  2034.     var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  2035.       var opt = get$e(obj, key).map(function (val) {
  2036.         return val === true ? fallback(obj) : val;
  2037.       });
  2038.       return bundle(opt);
  2039.     };
  2040.     var extractField = function (field, path, obj, key, prop) {
  2041.       var bundle = function (av) {
  2042.         return prop.extract(path.concat([key]), av);
  2043.       };
  2044.       var bundleAsOption = function (optValue) {
  2045.         return optValue.fold(function () {
  2046.           return SimpleResult.svalue(Optional.none());
  2047.         }, function (ov) {
  2048.           var result = prop.extract(path.concat([key]), ov);
  2049.           return SimpleResult.map(result, Optional.some);
  2050.         });
  2051.       };
  2052.       switch (field.tag) {
  2053.       case 'required':
  2054.         return requiredAccess(path, obj, key, bundle);
  2055.       case 'defaultedThunk':
  2056.         return fallbackAccess(obj, key, field.process, bundle);
  2057.       case 'option':
  2058.         return optionAccess(obj, key, bundleAsOption);
  2059.       case 'defaultedOptionThunk':
  2060.         return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  2061.       case 'mergeWithThunk': {
  2062.           return fallbackAccess(obj, key, constant$1({}), function (v) {
  2063.             var result = deepMerge(field.process(obj), v);
  2064.             return bundle(result);
  2065.           });
  2066.         }
  2067.       }
  2068.     };
  2069.     var extractFields = function (path, obj, fields) {
  2070.       var success = {};
  2071.       var errors = [];
  2072.       for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  2073.         var field = fields_1[_i];
  2074.         fold(field, function (key, newKey, presence, prop) {
  2075.           var result = extractField(presence, path, obj, key, prop);
  2076.           SimpleResult.fold(result, function (err) {
  2077.             errors.push.apply(errors, err);
  2078.           }, function (res) {
  2079.             success[newKey] = res;
  2080.           });
  2081.         }, function (newKey, instantiator) {
  2082.           success[newKey] = instantiator(obj);
  2083.         });
  2084.       }
  2085.       return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  2086.     };
  2087.     var valueThunk = function (getDelegate) {
  2088.       var extract = function (path, val) {
  2089.         return getDelegate().extract(path, val);
  2090.       };
  2091.       var toString = function () {
  2092.         return getDelegate().toString();
  2093.       };
  2094.       return {
  2095.         extract: extract,
  2096.         toString: toString
  2097.       };
  2098.     };
  2099.     var getSetKeys = function (obj) {
  2100.       return keys(filter$1(obj, isNonNullable));
  2101.     };
  2102.     var objOfOnly = function (fields) {
  2103.       var delegate = objOf(fields);
  2104.       var fieldNames = foldr(fields, function (acc, value) {
  2105.         return fold(value, function (key) {
  2106.           var _a;
  2107.           return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  2108.         }, constant$1(acc));
  2109.       }, {});
  2110.       var extract = function (path, o) {
  2111.         var keys = isBoolean(o) ? [] : getSetKeys(o);
  2112.         var extra = filter$2(keys, function (k) {
  2113.           return !hasNonNullableKey(fieldNames, k);
  2114.         });
  2115.         return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  2116.       };
  2117.       return {
  2118.         extract: extract,
  2119.         toString: delegate.toString
  2120.       };
  2121.     };
  2122.     var objOf = function (values) {
  2123.       var extract = function (path, o) {
  2124.         return extractFields(path, o, values);
  2125.       };
  2126.       var toString = function () {
  2127.         var fieldStrings = map$2(values, function (value) {
  2128.           return fold(value, function (key, _okey, _presence, prop) {
  2129.             return key + ' -> ' + prop.toString();
  2130.           }, function (newKey, _instantiator) {
  2131.             return 'state(' + newKey + ')';
  2132.           });
  2133.         });
  2134.         return 'obj{\n' + fieldStrings.join('\n') + '}';
  2135.       };
  2136.       return {
  2137.         extract: extract,
  2138.         toString: toString
  2139.       };
  2140.     };
  2141.     var arrOf = function (prop) {
  2142.       var extract = function (path, array) {
  2143.         var results = map$2(array, function (a, i) {
  2144.           return prop.extract(path.concat(['[' + i + ']']), a);
  2145.         });
  2146.         return ResultCombine.consolidateArr(results);
  2147.       };
  2148.       var toString = function () {
  2149.         return 'array(' + prop.toString() + ')';
  2150.       };
  2151.       return {
  2152.         extract: extract,
  2153.         toString: toString
  2154.       };
  2155.     };
  2156.     var oneOf = function (props) {
  2157.       var extract = function (path, val) {
  2158.         var errors = [];
  2159.         for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  2160.           var prop = props_1[_i];
  2161.           var res = prop.extract(path, val);
  2162.           if (res.stype === SimpleResultType.Value) {
  2163.             return res;
  2164.           }
  2165.           errors.push(res);
  2166.         }
  2167.         return ResultCombine.consolidateArr(errors);
  2168.       };
  2169.       var toString = function () {
  2170.         return 'oneOf(' + map$2(props, function (prop) {
  2171.           return prop.toString();
  2172.         }).join(', ') + ')';
  2173.       };
  2174.       return {
  2175.         extract: extract,
  2176.         toString: toString
  2177.       };
  2178.     };
  2179.     var setOf$1 = function (validator, prop) {
  2180.       var validateKeys = function (path, keys) {
  2181.         return arrOf(value$2(validator)).extract(path, keys);
  2182.       };
  2183.       var extract = function (path, o) {
  2184.         var keys$1 = keys(o);
  2185.         var validatedKeys = validateKeys(path, keys$1);
  2186.         return SimpleResult.bind(validatedKeys, function (validKeys) {
  2187.           var schema = map$2(validKeys, function (vk) {
  2188.             return field$2(vk, vk, required$2(), prop);
  2189.           });
  2190.           return objOf(schema).extract(path, o);
  2191.         });
  2192.       };
  2193.       var toString = function () {
  2194.         return 'setOf(' + prop.toString() + ')';
  2195.       };
  2196.       return {
  2197.         extract: extract,
  2198.         toString: toString
  2199.       };
  2200.     };
  2201.     var thunk = function (_desc, processor) {
  2202.       var getP = cached(processor);
  2203.       var extract = function (path, val) {
  2204.         return getP().extract(path, val);
  2205.       };
  2206.       var toString = function () {
  2207.         return getP().toString();
  2208.       };
  2209.       return {
  2210.         extract: extract,
  2211.         toString: toString
  2212.       };
  2213.     };
  2214.     var arrOfObj = compose(arrOf, objOf);
  2215.  
  2216.     var anyValue = constant$1(anyValue$1);
  2217.     var typedValue = function (validator, expectedType) {
  2218.       return value$2(function (a) {
  2219.         var actualType = typeof a;
  2220.         return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  2221.       });
  2222.     };
  2223.     var number = typedValue(isNumber, 'number');
  2224.     var string = typedValue(isString, 'string');
  2225.     var boolean = typedValue(isBoolean, 'boolean');
  2226.     var functionProcessor = typedValue(isFunction, 'function');
  2227.     var isPostMessageable = function (val) {
  2228.       if (Object(val) !== val) {
  2229.         return true;
  2230.       }
  2231.       switch ({}.toString.call(val).slice(8, -1)) {
  2232.       case 'Boolean':
  2233.       case 'Number':
  2234.       case 'String':
  2235.       case 'Date':
  2236.       case 'RegExp':
  2237.       case 'Blob':
  2238.       case 'FileList':
  2239.       case 'ImageData':
  2240.       case 'ImageBitmap':
  2241.       case 'ArrayBuffer':
  2242.         return true;
  2243.       case 'Array':
  2244.       case 'Object':
  2245.         return Object.keys(val).every(function (prop) {
  2246.           return isPostMessageable(val[prop]);
  2247.         });
  2248.       default:
  2249.         return false;
  2250.       }
  2251.     };
  2252.     var postMessageable = value$2(function (a) {
  2253.       if (isPostMessageable(a)) {
  2254.         return SimpleResult.svalue(a);
  2255.       } else {
  2256.         return SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  2257.       }
  2258.     });
  2259.  
  2260.     var chooseFrom = function (path, input, branches, ch) {
  2261.       var fields = get$e(branches, ch);
  2262.       return fields.fold(function () {
  2263.         return missingBranch(path, branches, ch);
  2264.       }, function (vp) {
  2265.         return vp.extract(path.concat(['branch: ' + ch]), input);
  2266.       });
  2267.     };
  2268.     var choose$2 = function (key, branches) {
  2269.       var extract = function (path, input) {
  2270.         var choice = get$e(input, key);
  2271.         return choice.fold(function () {
  2272.           return missingKey(path, key);
  2273.         }, function (chosen) {
  2274.           return chooseFrom(path, input, branches, chosen);
  2275.         });
  2276.       };
  2277.       var toString = function () {
  2278.         return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  2279.       };
  2280.       return {
  2281.         extract: extract,
  2282.         toString: toString
  2283.       };
  2284.     };
  2285.  
  2286.     var arrOfVal = function () {
  2287.       return arrOf(anyValue$1);
  2288.     };
  2289.     var valueOf = function (validator) {
  2290.       return value$2(function (v) {
  2291.         return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  2292.       });
  2293.     };
  2294.     var setOf = function (validator, prop) {
  2295.       return setOf$1(function (v) {
  2296.         return SimpleResult.fromResult(validator(v));
  2297.       }, prop);
  2298.     };
  2299.     var extractValue = function (label, prop, obj) {
  2300.       var res = prop.extract([label], obj);
  2301.       return SimpleResult.mapError(res, function (errs) {
  2302.         return {
  2303.           input: obj,
  2304.           errors: errs
  2305.         };
  2306.       });
  2307.     };
  2308.     var asRaw = function (label, prop, obj) {
  2309.       return SimpleResult.toResult(extractValue(label, prop, obj));
  2310.     };
  2311.     var getOrDie = function (extraction) {
  2312.       return extraction.fold(function (errInfo) {
  2313.         throw new Error(formatError(errInfo));
  2314.       }, identity$1);
  2315.     };
  2316.     var asRawOrDie$1 = function (label, prop, obj) {
  2317.       return getOrDie(asRaw(label, prop, obj));
  2318.     };
  2319.     var formatError = function (errInfo) {
  2320.       return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  2321.     };
  2322.     var choose$1 = function (key, branches) {
  2323.       return choose$2(key, map$1(branches, objOf));
  2324.     };
  2325.     var thunkOf = function (desc, schema) {
  2326.       return thunk(desc, schema);
  2327.     };
  2328.  
  2329.     var field$1 = field$2;
  2330.     var customField = customField$1;
  2331.     var validateEnum = function (values) {
  2332.       return valueOf(function (value) {
  2333.         return contains$2(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  2334.       });
  2335.     };
  2336.     var required$1 = function (key) {
  2337.       return field$1(key, key, required$2(), anyValue());
  2338.     };
  2339.     var requiredOf = function (key, schema) {
  2340.       return field$1(key, key, required$2(), schema);
  2341.     };
  2342.     var requiredNumber = function (key) {
  2343.       return requiredOf(key, number);
  2344.     };
  2345.     var requiredString = function (key) {
  2346.       return requiredOf(key, string);
  2347.     };
  2348.     var requiredStringEnum = function (key, values) {
  2349.       return field$1(key, key, required$2(), validateEnum(values));
  2350.     };
  2351.     var requiredBoolean = function (key) {
  2352.       return requiredOf(key, boolean);
  2353.     };
  2354.     var requiredFunction = function (key) {
  2355.       return requiredOf(key, functionProcessor);
  2356.     };
  2357.     var forbid = function (key, message) {
  2358.       return field$1(key, key, asOption(), value$2(function (_v) {
  2359.         return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  2360.       }));
  2361.     };
  2362.     var requiredObjOf = function (key, objSchema) {
  2363.       return field$1(key, key, required$2(), objOf(objSchema));
  2364.     };
  2365.     var requiredArrayOfObj = function (key, objFields) {
  2366.       return field$1(key, key, required$2(), arrOfObj(objFields));
  2367.     };
  2368.     var requiredArrayOf = function (key, schema) {
  2369.       return field$1(key, key, required$2(), arrOf(schema));
  2370.     };
  2371.     var option = function (key) {
  2372.       return field$1(key, key, asOption(), anyValue());
  2373.     };
  2374.     var optionOf = function (key, schema) {
  2375.       return field$1(key, key, asOption(), schema);
  2376.     };
  2377.     var optionNumber = function (key) {
  2378.       return optionOf(key, number);
  2379.     };
  2380.     var optionString = function (key) {
  2381.       return optionOf(key, string);
  2382.     };
  2383.     var optionFunction = function (key) {
  2384.       return optionOf(key, functionProcessor);
  2385.     };
  2386.     var optionArrayOf = function (key, schema) {
  2387.       return optionOf(key, arrOf(schema));
  2388.     };
  2389.     var optionObjOf = function (key, objSchema) {
  2390.       return optionOf(key, objOf(objSchema));
  2391.     };
  2392.     var optionObjOfOnly = function (key, objSchema) {
  2393.       return optionOf(key, objOfOnly(objSchema));
  2394.     };
  2395.     var defaulted = function (key, fallback) {
  2396.       return field$1(key, key, defaulted$1(fallback), anyValue());
  2397.     };
  2398.     var defaultedOf = function (key, fallback, schema) {
  2399.       return field$1(key, key, defaulted$1(fallback), schema);
  2400.     };
  2401.     var defaultedNumber = function (key, fallback) {
  2402.       return defaultedOf(key, fallback, number);
  2403.     };
  2404.     var defaultedString = function (key, fallback) {
  2405.       return defaultedOf(key, fallback, string);
  2406.     };
  2407.     var defaultedStringEnum = function (key, fallback, values) {
  2408.       return defaultedOf(key, fallback, validateEnum(values));
  2409.     };
  2410.     var defaultedBoolean = function (key, fallback) {
  2411.       return defaultedOf(key, fallback, boolean);
  2412.     };
  2413.     var defaultedFunction = function (key, fallback) {
  2414.       return defaultedOf(key, fallback, functionProcessor);
  2415.     };
  2416.     var defaultedPostMsg = function (key, fallback) {
  2417.       return defaultedOf(key, fallback, postMessageable);
  2418.     };
  2419.     var defaultedArrayOf = function (key, fallback, schema) {
  2420.       return defaultedOf(key, fallback, arrOf(schema));
  2421.     };
  2422.     var defaultedObjOf = function (key, fallback, objSchema) {
  2423.       return defaultedOf(key, fallback, objOf(objSchema));
  2424.     };
  2425.  
  2426.     var Cell = function (initial) {
  2427.       var value = initial;
  2428.       var get = function () {
  2429.         return value;
  2430.       };
  2431.       var set = function (v) {
  2432.         value = v;
  2433.       };
  2434.       return {
  2435.         get: get,
  2436.         set: set
  2437.       };
  2438.     };
  2439.  
  2440.     var generate$7 = function (cases) {
  2441.       if (!isArray(cases)) {
  2442.         throw new Error('cases must be an array');
  2443.       }
  2444.       if (cases.length === 0) {
  2445.         throw new Error('there must be at least one case');
  2446.       }
  2447.       var constructors = [];
  2448.       var adt = {};
  2449.       each$1(cases, function (acase, count) {
  2450.         var keys$1 = keys(acase);
  2451.         if (keys$1.length !== 1) {
  2452.           throw new Error('one and only one name per case');
  2453.         }
  2454.         var key = keys$1[0];
  2455.         var value = acase[key];
  2456.         if (adt[key] !== undefined) {
  2457.           throw new Error('duplicate key detected:' + key);
  2458.         } else if (key === 'cata') {
  2459.           throw new Error('cannot have a case named cata (sorry)');
  2460.         } else if (!isArray(value)) {
  2461.           throw new Error('case arguments must be an array');
  2462.         }
  2463.         constructors.push(key);
  2464.         adt[key] = function () {
  2465.           var args = [];
  2466.           for (var _i = 0; _i < arguments.length; _i++) {
  2467.             args[_i] = arguments[_i];
  2468.           }
  2469.           var argLength = args.length;
  2470.           if (argLength !== value.length) {
  2471.             throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2472.           }
  2473.           var match = function (branches) {
  2474.             var branchKeys = keys(branches);
  2475.             if (constructors.length !== branchKeys.length) {
  2476.               throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2477.             }
  2478.             var allReqd = forall(constructors, function (reqKey) {
  2479.               return contains$2(branchKeys, reqKey);
  2480.             });
  2481.             if (!allReqd) {
  2482.               throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2483.             }
  2484.             return branches[key].apply(null, args);
  2485.           };
  2486.           return {
  2487.             fold: function () {
  2488.               var foldArgs = [];
  2489.               for (var _i = 0; _i < arguments.length; _i++) {
  2490.                 foldArgs[_i] = arguments[_i];
  2491.               }
  2492.               if (foldArgs.length !== cases.length) {
  2493.                 throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2494.               }
  2495.               var target = foldArgs[count];
  2496.               return target.apply(null, args);
  2497.             },
  2498.             match: match,
  2499.             log: function (label) {
  2500.               console.log(label, {
  2501.                 constructors: constructors,
  2502.                 constructor: key,
  2503.                 params: args
  2504.               });
  2505.             }
  2506.           };
  2507.         };
  2508.       });
  2509.       return adt;
  2510.     };
  2511.     var Adt = { generate: generate$7 };
  2512.  
  2513.     Adt.generate([
  2514.       {
  2515.         bothErrors: [
  2516.           'error1',
  2517.           'error2'
  2518.         ]
  2519.       },
  2520.       {
  2521.         firstError: [
  2522.           'error1',
  2523.           'value2'
  2524.         ]
  2525.       },
  2526.       {
  2527.         secondError: [
  2528.           'value1',
  2529.           'error2'
  2530.         ]
  2531.       },
  2532.       {
  2533.         bothValues: [
  2534.           'value1',
  2535.           'value2'
  2536.         ]
  2537.       }
  2538.     ]);
  2539.     var partition$1 = function (results) {
  2540.       var errors = [];
  2541.       var values = [];
  2542.       each$1(results, function (result) {
  2543.         result.fold(function (err) {
  2544.           errors.push(err);
  2545.         }, function (value) {
  2546.           values.push(value);
  2547.         });
  2548.       });
  2549.       return {
  2550.         errors: errors,
  2551.         values: values
  2552.       };
  2553.     };
  2554.  
  2555.     var exclude$1 = function (obj, fields) {
  2556.       var r = {};
  2557.       each(obj, function (v, k) {
  2558.         if (!contains$2(fields, k)) {
  2559.           r[k] = v;
  2560.         }
  2561.       });
  2562.       return r;
  2563.     };
  2564.  
  2565.     var wrap$2 = function (key, value) {
  2566.       var _a;
  2567.       return _a = {}, _a[key] = value, _a;
  2568.     };
  2569.     var wrapAll$1 = function (keyvalues) {
  2570.       var r = {};
  2571.       each$1(keyvalues, function (kv) {
  2572.         r[kv.key] = kv.value;
  2573.       });
  2574.       return r;
  2575.     };
  2576.  
  2577.     var exclude = function (obj, fields) {
  2578.       return exclude$1(obj, fields);
  2579.     };
  2580.     var wrap$1 = function (key, value) {
  2581.       return wrap$2(key, value);
  2582.     };
  2583.     var wrapAll = function (keyvalues) {
  2584.       return wrapAll$1(keyvalues);
  2585.     };
  2586.     var mergeValues = function (values, base) {
  2587.       return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  2588.     };
  2589.     var mergeErrors = function (errors) {
  2590.       return Result.error(flatten(errors));
  2591.     };
  2592.     var consolidate = function (objs, base) {
  2593.       var partitions = partition$1(objs);
  2594.       return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2595.     };
  2596.  
  2597.     var ensureIsRoot = function (isRoot) {
  2598.       return isFunction(isRoot) ? isRoot : never;
  2599.     };
  2600.     var ancestor$2 = function (scope, transform, isRoot) {
  2601.       var element = scope.dom;
  2602.       var stop = ensureIsRoot(isRoot);
  2603.       while (element.parentNode) {
  2604.         element = element.parentNode;
  2605.         var el = SugarElement.fromDom(element);
  2606.         var transformed = transform(el);
  2607.         if (transformed.isSome()) {
  2608.           return transformed;
  2609.         } else if (stop(el)) {
  2610.           break;
  2611.         }
  2612.       }
  2613.       return Optional.none();
  2614.     };
  2615.     var closest$4 = function (scope, transform, isRoot) {
  2616.       var current = transform(scope);
  2617.       var stop = ensureIsRoot(isRoot);
  2618.       return current.orThunk(function () {
  2619.         return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  2620.       });
  2621.     };
  2622.  
  2623.     var isSource = function (component, simulatedEvent) {
  2624.       return eq(component.element, simulatedEvent.event.target);
  2625.     };
  2626.  
  2627.     var defaultEventHandler = {
  2628.       can: always,
  2629.       abort: never,
  2630.       run: noop
  2631.     };
  2632.     var nu$9 = function (parts) {
  2633.       if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2634.         throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2635.       }
  2636.       return __assign(__assign({}, defaultEventHandler), parts);
  2637.     };
  2638.     var all$2 = function (handlers, f) {
  2639.       return function () {
  2640.         var args = [];
  2641.         for (var _i = 0; _i < arguments.length; _i++) {
  2642.           args[_i] = arguments[_i];
  2643.         }
  2644.         return foldl(handlers, function (acc, handler) {
  2645.           return acc && f(handler).apply(undefined, args);
  2646.         }, true);
  2647.       };
  2648.     };
  2649.     var any = function (handlers, f) {
  2650.       return function () {
  2651.         var args = [];
  2652.         for (var _i = 0; _i < arguments.length; _i++) {
  2653.           args[_i] = arguments[_i];
  2654.         }
  2655.         return foldl(handlers, function (acc, handler) {
  2656.           return acc || f(handler).apply(undefined, args);
  2657.         }, false);
  2658.       };
  2659.     };
  2660.     var read$2 = function (handler) {
  2661.       return isFunction(handler) ? {
  2662.         can: always,
  2663.         abort: never,
  2664.         run: handler
  2665.       } : handler;
  2666.     };
  2667.     var fuse$1 = function (handlers) {
  2668.       var can = all$2(handlers, function (handler) {
  2669.         return handler.can;
  2670.       });
  2671.       var abort = any(handlers, function (handler) {
  2672.         return handler.abort;
  2673.       });
  2674.       var run = function () {
  2675.         var args = [];
  2676.         for (var _i = 0; _i < arguments.length; _i++) {
  2677.           args[_i] = arguments[_i];
  2678.         }
  2679.         each$1(handlers, function (handler) {
  2680.           handler.run.apply(undefined, args);
  2681.         });
  2682.       };
  2683.       return {
  2684.         can: can,
  2685.         abort: abort,
  2686.         run: run
  2687.       };
  2688.     };
  2689.  
  2690.     var constant = constant$1;
  2691.     var touchstart = constant('touchstart');
  2692.     var touchmove = constant('touchmove');
  2693.     var touchend = constant('touchend');
  2694.     var touchcancel = constant('touchcancel');
  2695.     var mousedown = constant('mousedown');
  2696.     var mousemove = constant('mousemove');
  2697.     var mouseout = constant('mouseout');
  2698.     var mouseup = constant('mouseup');
  2699.     var mouseover = constant('mouseover');
  2700.     var focusin = constant('focusin');
  2701.     var focusout = constant('focusout');
  2702.     var keydown = constant('keydown');
  2703.     var keyup = constant('keyup');
  2704.     var input = constant('input');
  2705.     var change = constant('change');
  2706.     var click = constant('click');
  2707.     var transitioncancel = constant('transitioncancel');
  2708.     var transitionend = constant('transitionend');
  2709.     var transitionstart = constant('transitionstart');
  2710.     var selectstart = constant('selectstart');
  2711.  
  2712.     var prefixName = function (name) {
  2713.       return constant$1('alloy.' + name);
  2714.     };
  2715.     var alloy = { tap: prefixName('tap') };
  2716.     var focus$4 = prefixName('focus');
  2717.     var postBlur = prefixName('blur.post');
  2718.     var postPaste = prefixName('paste.post');
  2719.     var receive = prefixName('receive');
  2720.     var execute$5 = prefixName('execute');
  2721.     var focusItem = prefixName('focus.item');
  2722.     var tap = alloy.tap;
  2723.     var longpress = prefixName('longpress');
  2724.     var sandboxClose = prefixName('sandbox.close');
  2725.     var typeaheadCancel = prefixName('typeahead.cancel');
  2726.     var systemInit = prefixName('system.init');
  2727.     var documentTouchmove = prefixName('system.touchmove');
  2728.     var documentTouchend = prefixName('system.touchend');
  2729.     var windowScroll = prefixName('system.scroll');
  2730.     var windowResize = prefixName('system.resize');
  2731.     var attachedToDom = prefixName('system.attached');
  2732.     var detachedFromDom = prefixName('system.detached');
  2733.     var dismissRequested = prefixName('system.dismissRequested');
  2734.     var repositionRequested = prefixName('system.repositionRequested');
  2735.     var focusShifted = prefixName('focusmanager.shifted');
  2736.     var slotVisibility = prefixName('slotcontainer.visibility');
  2737.     var changeTab = prefixName('change.tab');
  2738.     var dismissTab = prefixName('dismiss.tab');
  2739.     var highlight$1 = prefixName('highlight');
  2740.     var dehighlight$1 = prefixName('dehighlight');
  2741.  
  2742.     var emit = function (component, event) {
  2743.       dispatchWith(component, component.element, event, {});
  2744.     };
  2745.     var emitWith = function (component, event, properties) {
  2746.       dispatchWith(component, component.element, event, properties);
  2747.     };
  2748.     var emitExecute = function (component) {
  2749.       emit(component, execute$5());
  2750.     };
  2751.     var dispatch = function (component, target, event) {
  2752.       dispatchWith(component, target, event, {});
  2753.     };
  2754.     var dispatchWith = function (component, target, event, properties) {
  2755.       var data = __assign({ target: target }, properties);
  2756.       component.getSystem().triggerEvent(event, target, data);
  2757.     };
  2758.     var dispatchEvent = function (component, target, event, simulatedEvent) {
  2759.       component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  2760.     };
  2761.  
  2762.     var derive$2 = function (configs) {
  2763.       return wrapAll(configs);
  2764.     };
  2765.     var abort = function (name, predicate) {
  2766.       return {
  2767.         key: name,
  2768.         value: nu$9({ abort: predicate })
  2769.       };
  2770.     };
  2771.     var can = function (name, predicate) {
  2772.       return {
  2773.         key: name,
  2774.         value: nu$9({ can: predicate })
  2775.       };
  2776.     };
  2777.     var preventDefault = function (name) {
  2778.       return {
  2779.         key: name,
  2780.         value: nu$9({
  2781.           run: function (component, simulatedEvent) {
  2782.             simulatedEvent.event.prevent();
  2783.           }
  2784.         })
  2785.       };
  2786.     };
  2787.     var run$1 = function (name, handler) {
  2788.       return {
  2789.         key: name,
  2790.         value: nu$9({ run: handler })
  2791.       };
  2792.     };
  2793.     var runActionExtra = function (name, action, extra) {
  2794.       return {
  2795.         key: name,
  2796.         value: nu$9({
  2797.           run: function (component, simulatedEvent) {
  2798.             action.apply(undefined, [
  2799.               component,
  2800.               simulatedEvent
  2801.             ].concat(extra));
  2802.           }
  2803.         })
  2804.       };
  2805.     };
  2806.     var runOnName = function (name) {
  2807.       return function (handler) {
  2808.         return run$1(name, handler);
  2809.       };
  2810.     };
  2811.     var runOnSourceName = function (name) {
  2812.       return function (handler) {
  2813.         return {
  2814.           key: name,
  2815.           value: nu$9({
  2816.             run: function (component, simulatedEvent) {
  2817.               if (isSource(component, simulatedEvent)) {
  2818.                 handler(component, simulatedEvent);
  2819.               }
  2820.             }
  2821.           })
  2822.         };
  2823.       };
  2824.     };
  2825.     var redirectToUid = function (name, uid) {
  2826.       return run$1(name, function (component, simulatedEvent) {
  2827.         component.getSystem().getByUid(uid).each(function (redirectee) {
  2828.           dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2829.         });
  2830.       });
  2831.     };
  2832.     var redirectToPart = function (name, detail, partName) {
  2833.       var uid = detail.partUids[partName];
  2834.       return redirectToUid(name, uid);
  2835.     };
  2836.     var runWithTarget = function (name, f) {
  2837.       return run$1(name, function (component, simulatedEvent) {
  2838.         var ev = simulatedEvent.event;
  2839.         var target = component.getSystem().getByDom(ev.target).getOrThunk(function () {
  2840.           var closest = closest$4(ev.target, function (el) {
  2841.             return component.getSystem().getByDom(el).toOptional();
  2842.           }, never);
  2843.           return closest.getOr(component);
  2844.         });
  2845.         f(component, target, simulatedEvent);
  2846.       });
  2847.     };
  2848.     var cutter = function (name) {
  2849.       return run$1(name, function (component, simulatedEvent) {
  2850.         simulatedEvent.cut();
  2851.       });
  2852.     };
  2853.     var stopper = function (name) {
  2854.       return run$1(name, function (component, simulatedEvent) {
  2855.         simulatedEvent.stop();
  2856.       });
  2857.     };
  2858.     var runOnSource = function (name, f) {
  2859.       return runOnSourceName(name)(f);
  2860.     };
  2861.     var runOnAttached = runOnSourceName(attachedToDom());
  2862.     var runOnDetached = runOnSourceName(detachedFromDom());
  2863.     var runOnInit = runOnSourceName(systemInit());
  2864.     var runOnExecute$1 = runOnName(execute$5());
  2865.  
  2866.     var fromHtml$1 = function (html, scope) {
  2867.       var doc = scope || document;
  2868.       var div = doc.createElement('div');
  2869.       div.innerHTML = html;
  2870.       return children(SugarElement.fromDom(div));
  2871.     };
  2872.  
  2873.     var get$7 = function (element) {
  2874.       return element.dom.innerHTML;
  2875.     };
  2876.     var set$5 = function (element, content) {
  2877.       var owner = owner$4(element);
  2878.       var docDom = owner.dom;
  2879.       var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2880.       var contentElements = fromHtml$1(content, docDom);
  2881.       append$1(fragment, contentElements);
  2882.       empty(element);
  2883.       append$2(element, fragment);
  2884.     };
  2885.     var getOuter = function (element) {
  2886.       var container = SugarElement.fromTag('div');
  2887.       var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2888.       append$2(container, clone);
  2889.       return get$7(container);
  2890.     };
  2891.  
  2892.     var clone$2 = function (original, isDeep) {
  2893.       return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2894.     };
  2895.     var shallow = function (original) {
  2896.       return clone$2(original, false);
  2897.     };
  2898.  
  2899.     var getHtml = function (element) {
  2900.       if (isShadowRoot(element)) {
  2901.         return '#shadow-root';
  2902.       } else {
  2903.         var clone = shallow(element);
  2904.         return getOuter(clone);
  2905.       }
  2906.     };
  2907.  
  2908.     var element = function (elem) {
  2909.       return getHtml(elem);
  2910.     };
  2911.  
  2912.     var isRecursive = function (component, originator, target) {
  2913.       return eq(originator, component.element) && !eq(originator, target);
  2914.     };
  2915.     var events$i = derive$2([can(focus$4(), function (component, simulatedEvent) {
  2916.         var event = simulatedEvent.event;
  2917.         var originator = event.originator;
  2918.         var target = event.target;
  2919.         if (isRecursive(component, originator, target)) {
  2920.           console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  2921.           return false;
  2922.         } else {
  2923.           return true;
  2924.         }
  2925.       })]);
  2926.  
  2927.     var DefaultEvents = /*#__PURE__*/Object.freeze({
  2928.         __proto__: null,
  2929.         events: events$i
  2930.     });
  2931.  
  2932.     var unique = 0;
  2933.     var generate$6 = function (prefix) {
  2934.       var date = new Date();
  2935.       var time = date.getTime();
  2936.       var random = Math.floor(Math.random() * 1000000000);
  2937.       unique++;
  2938.       return prefix + '_' + random + unique + String(time);
  2939.     };
  2940.  
  2941.     var prefix$1 = constant$1('alloy-id-');
  2942.     var idAttr$1 = constant$1('data-alloy-id');
  2943.  
  2944.     var prefix = prefix$1();
  2945.     var idAttr = idAttr$1();
  2946.     var write = function (label, elem) {
  2947.       var id = generate$6(prefix + label);
  2948.       writeOnly(elem, id);
  2949.       return id;
  2950.     };
  2951.     var writeOnly = function (elem, uid) {
  2952.       Object.defineProperty(elem.dom, idAttr, {
  2953.         value: uid,
  2954.         writable: true
  2955.       });
  2956.     };
  2957.     var read$1 = function (elem) {
  2958.       var id = isElement$2(elem) ? elem.dom[idAttr] : null;
  2959.       return Optional.from(id);
  2960.     };
  2961.     var generate$5 = function (prefix) {
  2962.       return generate$6(prefix);
  2963.     };
  2964.  
  2965.     var make$8 = identity$1;
  2966.  
  2967.     var NoContextApi = function (getComp) {
  2968.       var getMessage = function (event) {
  2969.         return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  2970.       };
  2971.       var fail = function (event) {
  2972.         return function () {
  2973.           throw new Error(getMessage(event));
  2974.         };
  2975.       };
  2976.       var warn = function (event) {
  2977.         return function () {
  2978.           console.warn(getMessage(event));
  2979.         };
  2980.       };
  2981.       return {
  2982.         debugInfo: constant$1('fake'),
  2983.         triggerEvent: warn('triggerEvent'),
  2984.         triggerFocus: warn('triggerFocus'),
  2985.         triggerEscape: warn('triggerEscape'),
  2986.         broadcast: warn('broadcast'),
  2987.         broadcastOn: warn('broadcastOn'),
  2988.         broadcastEvent: warn('broadcastEvent'),
  2989.         build: fail('build'),
  2990.         addToWorld: fail('addToWorld'),
  2991.         removeFromWorld: fail('removeFromWorld'),
  2992.         addToGui: fail('addToGui'),
  2993.         removeFromGui: fail('removeFromGui'),
  2994.         getByUid: fail('getByUid'),
  2995.         getByDom: fail('getByDom'),
  2996.         isConnected: never
  2997.       };
  2998.     };
  2999.     var singleton$1 = NoContextApi();
  3000.  
  3001.     var markAsBehaviourApi = function (f, apiName, apiFunction) {
  3002.       var delegate = apiFunction.toString();
  3003.       var endIndex = delegate.indexOf(')') + 1;
  3004.       var openBracketIndex = delegate.indexOf('(');
  3005.       var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  3006.       f.toFunctionAnnotation = function () {
  3007.         return {
  3008.           name: apiName,
  3009.           parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  3010.         };
  3011.       };
  3012.       return f;
  3013.     };
  3014.     var cleanParameters = function (parameters) {
  3015.       return map$2(parameters, function (p) {
  3016.         return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  3017.       });
  3018.     };
  3019.     var markAsExtraApi = function (f, extraName) {
  3020.       var delegate = f.toString();
  3021.       var endIndex = delegate.indexOf(')') + 1;
  3022.       var openBracketIndex = delegate.indexOf('(');
  3023.       var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  3024.       f.toFunctionAnnotation = function () {
  3025.         return {
  3026.           name: extraName,
  3027.           parameters: cleanParameters(parameters)
  3028.         };
  3029.       };
  3030.       return f;
  3031.     };
  3032.     var markAsSketchApi = function (f, apiFunction) {
  3033.       var delegate = apiFunction.toString();
  3034.       var endIndex = delegate.indexOf(')') + 1;
  3035.       var openBracketIndex = delegate.indexOf('(');
  3036.       var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  3037.       f.toFunctionAnnotation = function () {
  3038.         return {
  3039.           name: 'OVERRIDE',
  3040.           parameters: cleanParameters(parameters.slice(1))
  3041.         };
  3042.       };
  3043.       return f;
  3044.     };
  3045.  
  3046.     var premadeTag = generate$6('alloy-premade');
  3047.     var premade$1 = function (comp) {
  3048.       return wrap$1(premadeTag, comp);
  3049.     };
  3050.     var getPremade = function (spec) {
  3051.       return get$e(spec, premadeTag);
  3052.     };
  3053.     var makeApi = function (f) {
  3054.       return markAsSketchApi(function (component) {
  3055.         var rest = [];
  3056.         for (var _i = 1; _i < arguments.length; _i++) {
  3057.           rest[_i - 1] = arguments[_i];
  3058.         }
  3059.         return f.apply(void 0, __spreadArray([
  3060.           component.getApis(),
  3061.           component
  3062.         ], rest, false));
  3063.       }, f);
  3064.     };
  3065.  
  3066.     var NoState = {
  3067.       init: function () {
  3068.         return nu$8({ readState: constant$1('No State required') });
  3069.       }
  3070.     };
  3071.     var nu$8 = function (spec) {
  3072.       return spec;
  3073.     };
  3074.  
  3075.     var generateFrom$1 = function (spec, all) {
  3076.       var schema = map$2(all, function (a) {
  3077.         return optionObjOf(a.name(), [
  3078.           required$1('config'),
  3079.           defaulted('state', NoState)
  3080.         ]);
  3081.       });
  3082.       var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  3083.         throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  3084.       }, identity$1);
  3085.       return {
  3086.         list: all,
  3087.         data: map$1(validated, function (optBlobThunk) {
  3088.           var output = optBlobThunk.map(function (blob) {
  3089.             return {
  3090.               config: blob.config,
  3091.               state: blob.state.init(blob.config)
  3092.             };
  3093.           });
  3094.           return constant$1(output);
  3095.         })
  3096.       };
  3097.     };
  3098.     var getBehaviours$3 = function (bData) {
  3099.       return bData.list;
  3100.     };
  3101.     var getData$2 = function (bData) {
  3102.       return bData.data;
  3103.     };
  3104.  
  3105.     var byInnerKey = function (data, tuple) {
  3106.       var r = {};
  3107.       each(data, function (detail, key) {
  3108.         each(detail, function (value, indexKey) {
  3109.           var chain = get$e(r, indexKey).getOr([]);
  3110.           r[indexKey] = chain.concat([tuple(key, value)]);
  3111.         });
  3112.       });
  3113.       return r;
  3114.     };
  3115.  
  3116.     var nu$7 = function (s) {
  3117.       return {
  3118.         classes: isUndefined(s.classes) ? [] : s.classes,
  3119.         attributes: isUndefined(s.attributes) ? {} : s.attributes,
  3120.         styles: isUndefined(s.styles) ? {} : s.styles
  3121.       };
  3122.     };
  3123.     var merge = function (defnA, mod) {
  3124.       return __assign(__assign({}, defnA), {
  3125.         attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  3126.         styles: __assign(__assign({}, defnA.styles), mod.styles),
  3127.         classes: defnA.classes.concat(mod.classes)
  3128.       });
  3129.     };
  3130.  
  3131.     var combine$2 = function (info, baseMod, behaviours, base) {
  3132.       var modsByBehaviour = __assign({}, baseMod);
  3133.       each$1(behaviours, function (behaviour) {
  3134.         modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  3135.       });
  3136.       var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  3137.         return {
  3138.           name: name,
  3139.           modification: modification
  3140.         };
  3141.       });
  3142.       var combineObjects = function (objects) {
  3143.         return foldr(objects, function (b, a) {
  3144.           return __assign(__assign({}, a.modification), b);
  3145.         }, {});
  3146.       };
  3147.       var combinedClasses = foldr(byAspect.classes, function (b, a) {
  3148.         return a.modification.concat(b);
  3149.       }, []);
  3150.       var combinedAttributes = combineObjects(byAspect.attributes);
  3151.       var combinedStyles = combineObjects(byAspect.styles);
  3152.       return nu$7({
  3153.         classes: combinedClasses,
  3154.         attributes: combinedAttributes,
  3155.         styles: combinedStyles
  3156.       });
  3157.     };
  3158.  
  3159.     var sortKeys = function (label, keyName, array, order) {
  3160.       try {
  3161.         var sorted = sort(array, function (a, b) {
  3162.           var aKey = a[keyName];
  3163.           var bKey = b[keyName];
  3164.           var aIndex = order.indexOf(aKey);
  3165.           var bIndex = order.indexOf(bKey);
  3166.           if (aIndex === -1) {
  3167.             throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  3168.           }
  3169.           if (bIndex === -1) {
  3170.             throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  3171.           }
  3172.           if (aIndex < bIndex) {
  3173.             return -1;
  3174.           } else if (bIndex < aIndex) {
  3175.             return 1;
  3176.           } else {
  3177.             return 0;
  3178.           }
  3179.         });
  3180.         return Result.value(sorted);
  3181.       } catch (err) {
  3182.         return Result.error([err]);
  3183.       }
  3184.     };
  3185.  
  3186.     var uncurried = function (handler, purpose) {
  3187.       return {
  3188.         handler: handler,
  3189.         purpose: purpose
  3190.       };
  3191.     };
  3192.     var curried = function (handler, purpose) {
  3193.       return {
  3194.         cHandler: handler,
  3195.         purpose: purpose
  3196.       };
  3197.     };
  3198.     var curryArgs = function (descHandler, extraArgs) {
  3199.       return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  3200.     };
  3201.     var getCurried = function (descHandler) {
  3202.       return descHandler.cHandler;
  3203.     };
  3204.  
  3205.     var behaviourTuple = function (name, handler) {
  3206.       return {
  3207.         name: name,
  3208.         handler: handler
  3209.       };
  3210.     };
  3211.     var nameToHandlers = function (behaviours, info) {
  3212.       var r = {};
  3213.       each$1(behaviours, function (behaviour) {
  3214.         r[behaviour.name()] = behaviour.handlers(info);
  3215.       });
  3216.       return r;
  3217.     };
  3218.     var groupByEvents = function (info, behaviours, base) {
  3219.       var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  3220.       return byInnerKey(behaviourEvents, behaviourTuple);
  3221.     };
  3222.     var combine$1 = function (info, eventOrder, behaviours, base) {
  3223.       var byEventName = groupByEvents(info, behaviours, base);
  3224.       return combineGroups(byEventName, eventOrder);
  3225.     };
  3226.     var assemble = function (rawHandler) {
  3227.       var handler = read$2(rawHandler);
  3228.       return function (component, simulatedEvent) {
  3229.         var rest = [];
  3230.         for (var _i = 2; _i < arguments.length; _i++) {
  3231.           rest[_i - 2] = arguments[_i];
  3232.         }
  3233.         var args = [
  3234.           component,
  3235.           simulatedEvent
  3236.         ].concat(rest);
  3237.         if (handler.abort.apply(undefined, args)) {
  3238.           simulatedEvent.stop();
  3239.         } else if (handler.can.apply(undefined, args)) {
  3240.           handler.run.apply(undefined, args);
  3241.         }
  3242.       };
  3243.     };
  3244.     var missingOrderError = function (eventName, tuples) {
  3245.       return Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map$2(tuples, function (c) {
  3246.           return c.name;
  3247.         }), null, 2)]);
  3248.     };
  3249.     var fuse = function (tuples, eventOrder, eventName) {
  3250.       var order = eventOrder[eventName];
  3251.       if (!order) {
  3252.         return missingOrderError(eventName, tuples);
  3253.       } else {
  3254.         return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  3255.           var handlers = map$2(sortedTuples, function (tuple) {
  3256.             return tuple.handler;
  3257.           });
  3258.           return fuse$1(handlers);
  3259.         });
  3260.       }
  3261.     };
  3262.     var combineGroups = function (byEventName, eventOrder) {
  3263.       var r = mapToArray(byEventName, function (tuples, eventName) {
  3264.         var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  3265.         return combined.map(function (handler) {
  3266.           var assembled = assemble(handler);
  3267.           var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  3268.             return exists(tuples, function (t) {
  3269.               return t.name === o;
  3270.             });
  3271.           }).join(' > ') : tuples[0].name;
  3272.           return wrap$1(eventName, uncurried(assembled, purpose));
  3273.         });
  3274.       });
  3275.       return consolidate(r, {});
  3276.     };
  3277.  
  3278.     var _a$2;
  3279.     var baseBehaviour = 'alloy.base.behaviour';
  3280.     var schema$z = objOf([
  3281.       field$1('dom', 'dom', required$2(), objOf([
  3282.         required$1('tag'),
  3283.         defaulted('styles', {}),
  3284.         defaulted('classes', []),
  3285.         defaulted('attributes', {}),
  3286.         option('value'),
  3287.         option('innerHtml')
  3288.       ])),
  3289.       required$1('components'),
  3290.       required$1('uid'),
  3291.       defaulted('events', {}),
  3292.       defaulted('apis', {}),
  3293.       field$1('eventOrder', 'eventOrder', mergeWith((_a$2 = {}, _a$2[execute$5()] = [
  3294.         'disabling',
  3295.         baseBehaviour,
  3296.         'toggling',
  3297.         'typeaheadevents'
  3298.       ], _a$2[focus$4()] = [
  3299.         baseBehaviour,
  3300.         'focusing',
  3301.         'keying'
  3302.       ], _a$2[systemInit()] = [
  3303.         baseBehaviour,
  3304.         'disabling',
  3305.         'toggling',
  3306.         'representing'
  3307.       ], _a$2[input()] = [
  3308.         baseBehaviour,
  3309.         'representing',
  3310.         'streaming',
  3311.         'invalidating'
  3312.       ], _a$2[detachedFromDom()] = [
  3313.         baseBehaviour,
  3314.         'representing',
  3315.         'item-events',
  3316.         'tooltipping'
  3317.       ], _a$2[mousedown()] = [
  3318.         'focusing',
  3319.         baseBehaviour,
  3320.         'item-type-events'
  3321.       ], _a$2[touchstart()] = [
  3322.         'focusing',
  3323.         baseBehaviour,
  3324.         'item-type-events'
  3325.       ], _a$2[mouseover()] = [
  3326.         'item-type-events',
  3327.         'tooltipping'
  3328.       ], _a$2[receive()] = [
  3329.         'receiving',
  3330.         'reflecting',
  3331.         'tooltipping'
  3332.       ], _a$2)), anyValue()),
  3333.       option('domModification')
  3334.     ]);
  3335.     var toInfo = function (spec) {
  3336.       return asRaw('custom.definition', schema$z, spec);
  3337.     };
  3338.     var toDefinition = function (detail) {
  3339.       return __assign(__assign({}, detail.dom), {
  3340.         uid: detail.uid,
  3341.         domChildren: map$2(detail.components, function (comp) {
  3342.           return comp.element;
  3343.         })
  3344.       });
  3345.     };
  3346.     var toModification = function (detail) {
  3347.       return detail.domModification.fold(function () {
  3348.         return nu$7({});
  3349.       }, nu$7);
  3350.     };
  3351.     var toEvents = function (info) {
  3352.       return info.events;
  3353.     };
  3354.  
  3355.     var read = function (element, attr) {
  3356.       var value = get$d(element, attr);
  3357.       return value === undefined || value === '' ? [] : value.split(' ');
  3358.     };
  3359.     var add$4 = function (element, attr, id) {
  3360.       var old = read(element, attr);
  3361.       var nu = old.concat([id]);
  3362.       set$8(element, attr, nu.join(' '));
  3363.       return true;
  3364.     };
  3365.     var remove$4 = function (element, attr, id) {
  3366.       var nu = filter$2(read(element, attr), function (v) {
  3367.         return v !== id;
  3368.       });
  3369.       if (nu.length > 0) {
  3370.         set$8(element, attr, nu.join(' '));
  3371.       } else {
  3372.         remove$7(element, attr);
  3373.       }
  3374.       return false;
  3375.     };
  3376.  
  3377.     var supports = function (element) {
  3378.       return element.dom.classList !== undefined;
  3379.     };
  3380.     var get$6 = function (element) {
  3381.       return read(element, 'class');
  3382.     };
  3383.     var add$3 = function (element, clazz) {
  3384.       return add$4(element, 'class', clazz);
  3385.     };
  3386.     var remove$3 = function (element, clazz) {
  3387.       return remove$4(element, 'class', clazz);
  3388.     };
  3389.  
  3390.     var add$2 = function (element, clazz) {
  3391.       if (supports(element)) {
  3392.         element.dom.classList.add(clazz);
  3393.       } else {
  3394.         add$3(element, clazz);
  3395.       }
  3396.     };
  3397.     var cleanClass = function (element) {
  3398.       var classList = supports(element) ? element.dom.classList : get$6(element);
  3399.       if (classList.length === 0) {
  3400.         remove$7(element, 'class');
  3401.       }
  3402.     };
  3403.     var remove$2 = function (element, clazz) {
  3404.       if (supports(element)) {
  3405.         var classList = element.dom.classList;
  3406.         classList.remove(clazz);
  3407.       } else {
  3408.         remove$3(element, clazz);
  3409.       }
  3410.       cleanClass(element);
  3411.     };
  3412.     var has = function (element, clazz) {
  3413.       return supports(element) && element.dom.classList.contains(clazz);
  3414.     };
  3415.  
  3416.     var add$1 = function (element, classes) {
  3417.       each$1(classes, function (x) {
  3418.         add$2(element, x);
  3419.       });
  3420.     };
  3421.     var remove$1 = function (element, classes) {
  3422.       each$1(classes, function (x) {
  3423.         remove$2(element, x);
  3424.       });
  3425.     };
  3426.     var hasAll = function (element, classes) {
  3427.       return forall(classes, function (clazz) {
  3428.         return has(element, clazz);
  3429.       });
  3430.     };
  3431.  
  3432.     var get$5 = function (element) {
  3433.       return element.dom.value;
  3434.     };
  3435.     var set$4 = function (element, value) {
  3436.       if (value === undefined) {
  3437.         throw new Error('Value.set was undefined');
  3438.       }
  3439.       element.dom.value = value;
  3440.     };
  3441.  
  3442.     var renderToDom = function (definition) {
  3443.       var subject = SugarElement.fromTag(definition.tag);
  3444.       setAll$1(subject, definition.attributes);
  3445.       add$1(subject, definition.classes);
  3446.       setAll(subject, definition.styles);
  3447.       definition.innerHtml.each(function (html) {
  3448.         return set$5(subject, html);
  3449.       });
  3450.       var children = definition.domChildren;
  3451.       append$1(subject, children);
  3452.       definition.value.each(function (value) {
  3453.         set$4(subject, value);
  3454.       });
  3455.       if (!definition.uid) {
  3456.         debugger;
  3457.       }
  3458.       writeOnly(subject, definition.uid);
  3459.       return subject;
  3460.     };
  3461.  
  3462.     var getBehaviours$2 = function (spec) {
  3463.       var behaviours = get$e(spec, 'behaviours').getOr({});
  3464.       return bind$3(keys(behaviours), function (name) {
  3465.         var behaviour = behaviours[name];
  3466.         return isNonNullable(behaviour) ? [behaviour.me] : [];
  3467.       });
  3468.     };
  3469.     var generateFrom = function (spec, all) {
  3470.       return generateFrom$1(spec, all);
  3471.     };
  3472.     var generate$4 = function (spec) {
  3473.       var all = getBehaviours$2(spec);
  3474.       return generateFrom(spec, all);
  3475.     };
  3476.  
  3477.     var getDomDefinition = function (info, bList, bData) {
  3478.       var definition = toDefinition(info);
  3479.       var infoModification = toModification(info);
  3480.       var baseModification = { 'alloy.base.modification': infoModification };
  3481.       var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
  3482.       return merge(definition, modification);
  3483.     };
  3484.     var getEvents = function (info, bList, bData) {
  3485.       var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  3486.       return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  3487.     };
  3488.     var build$2 = function (spec) {
  3489.       var getMe = function () {
  3490.         return me;
  3491.       };
  3492.       var systemApi = Cell(singleton$1);
  3493.       var info = getOrDie(toInfo(spec));
  3494.       var bBlob = generate$4(spec);
  3495.       var bList = getBehaviours$3(bBlob);
  3496.       var bData = getData$2(bBlob);
  3497.       var modDefinition = getDomDefinition(info, bList, bData);
  3498.       var item = renderToDom(modDefinition);
  3499.       var events = getEvents(info, bList, bData);
  3500.       var subcomponents = Cell(info.components);
  3501.       var connect = function (newApi) {
  3502.         systemApi.set(newApi);
  3503.       };
  3504.       var disconnect = function () {
  3505.         systemApi.set(NoContextApi(getMe));
  3506.       };
  3507.       var syncComponents = function () {
  3508.         var children$1 = children(item);
  3509.         var subs = bind$3(children$1, function (child) {
  3510.           return systemApi.get().getByDom(child).fold(function () {
  3511.             return [];
  3512.           }, pure$2);
  3513.         });
  3514.         subcomponents.set(subs);
  3515.       };
  3516.       var config = function (behaviour) {
  3517.         var b = bData;
  3518.         var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3519.           throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3520.         };
  3521.         return f();
  3522.       };
  3523.       var hasConfigured = function (behaviour) {
  3524.         return isFunction(bData[behaviour.name()]);
  3525.       };
  3526.       var getApis = function () {
  3527.         return info.apis;
  3528.       };
  3529.       var readState = function (behaviourName) {
  3530.         return bData[behaviourName]().map(function (b) {
  3531.           return b.state.readState();
  3532.         }).getOr('not enabled');
  3533.       };
  3534.       var me = {
  3535.         uid: spec.uid,
  3536.         getSystem: systemApi.get,
  3537.         config: config,
  3538.         hasConfigured: hasConfigured,
  3539.         spec: spec,
  3540.         readState: readState,
  3541.         getApis: getApis,
  3542.         connect: connect,
  3543.         disconnect: disconnect,
  3544.         element: item,
  3545.         syncComponents: syncComponents,
  3546.         components: subcomponents.get,
  3547.         events: events
  3548.       };
  3549.       return me;
  3550.     };
  3551.  
  3552.     var buildSubcomponents = function (spec) {
  3553.       var components = get$e(spec, 'components').getOr([]);
  3554.       return map$2(components, build$1);
  3555.     };
  3556.     var buildFromSpec = function (userSpec) {
  3557.       var _a = make$8(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3558.       var components = buildSubcomponents(spec);
  3559.       var completeSpec = __assign(__assign({}, spec), {
  3560.         events: __assign(__assign({}, DefaultEvents), specEvents),
  3561.         components: components
  3562.       });
  3563.       return Result.value(build$2(completeSpec));
  3564.     };
  3565.     var text$1 = function (textContent) {
  3566.       var element = SugarElement.fromText(textContent);
  3567.       return external$2({ element: element });
  3568.     };
  3569.     var external$2 = function (spec) {
  3570.       var extSpec = asRawOrDie$1('external.component', objOfOnly([
  3571.         required$1('element'),
  3572.         option('uid')
  3573.       ]), spec);
  3574.       var systemApi = Cell(NoContextApi());
  3575.       var connect = function (newApi) {
  3576.         systemApi.set(newApi);
  3577.       };
  3578.       var disconnect = function () {
  3579.         systemApi.set(NoContextApi(function () {
  3580.           return me;
  3581.         }));
  3582.       };
  3583.       var uid = extSpec.uid.getOrThunk(function () {
  3584.         return generate$5('external');
  3585.       });
  3586.       writeOnly(extSpec.element, uid);
  3587.       var me = {
  3588.         uid: uid,
  3589.         getSystem: systemApi.get,
  3590.         config: Optional.none,
  3591.         hasConfigured: never,
  3592.         connect: connect,
  3593.         disconnect: disconnect,
  3594.         getApis: function () {
  3595.           return {};
  3596.         },
  3597.         element: extSpec.element,
  3598.         spec: spec,
  3599.         readState: constant$1('No state'),
  3600.         syncComponents: noop,
  3601.         components: constant$1([]),
  3602.         events: {}
  3603.       };
  3604.       return premade$1(me);
  3605.     };
  3606.     var uids = generate$5;
  3607.     var isSketchSpec$1 = function (spec) {
  3608.       return has$2(spec, 'uid');
  3609.     };
  3610.     var build$1 = function (spec) {
  3611.       return getPremade(spec).getOrThunk(function () {
  3612.         var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids('') }, spec);
  3613.         return buildFromSpec(userSpecWithUid).getOrDie();
  3614.       });
  3615.     };
  3616.     var premade = premade$1;
  3617.  
  3618.     function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3619.       if (is(scope, a)) {
  3620.         return Optional.some(scope);
  3621.       } else if (isFunction(isRoot) && isRoot(scope)) {
  3622.         return Optional.none();
  3623.       } else {
  3624.         return ancestor(scope, a, isRoot);
  3625.       }
  3626.     }
  3627.  
  3628.     var ancestor$1 = function (scope, predicate, isRoot) {
  3629.       var element = scope.dom;
  3630.       var stop = isFunction(isRoot) ? isRoot : never;
  3631.       while (element.parentNode) {
  3632.         element = element.parentNode;
  3633.         var el = SugarElement.fromDom(element);
  3634.         if (predicate(el)) {
  3635.           return Optional.some(el);
  3636.         } else if (stop(el)) {
  3637.           break;
  3638.         }
  3639.       }
  3640.       return Optional.none();
  3641.     };
  3642.     var closest$3 = function (scope, predicate, isRoot) {
  3643.       var is = function (s, test) {
  3644.         return test(s);
  3645.       };
  3646.       return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3647.     };
  3648.     var child$1 = function (scope, predicate) {
  3649.       var pred = function (node) {
  3650.         return predicate(SugarElement.fromDom(node));
  3651.       };
  3652.       var result = find$5(scope.dom.childNodes, pred);
  3653.       return result.map(SugarElement.fromDom);
  3654.     };
  3655.     var descendant$1 = function (scope, predicate) {
  3656.       var descend = function (node) {
  3657.         for (var i = 0; i < node.childNodes.length; i++) {
  3658.           var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3659.           if (predicate(child_1)) {
  3660.             return Optional.some(child_1);
  3661.           }
  3662.           var res = descend(node.childNodes[i]);
  3663.           if (res.isSome()) {
  3664.             return res;
  3665.           }
  3666.         }
  3667.         return Optional.none();
  3668.       };
  3669.       return descend(scope.dom);
  3670.     };
  3671.  
  3672.     var closest$2 = function (scope, predicate, isRoot) {
  3673.       return closest$3(scope, predicate, isRoot).isSome();
  3674.     };
  3675.  
  3676.     var ancestor = function (scope, selector, isRoot) {
  3677.       return ancestor$1(scope, function (e) {
  3678.         return is(e, selector);
  3679.       }, isRoot);
  3680.     };
  3681.     var child = function (scope, selector) {
  3682.       return child$1(scope, function (e) {
  3683.         return is(e, selector);
  3684.       });
  3685.     };
  3686.     var descendant = function (scope, selector) {
  3687.       return one(selector, scope);
  3688.     };
  3689.     var closest$1 = function (scope, selector, isRoot) {
  3690.       var is$1 = function (element, selector) {
  3691.         return is(element, selector);
  3692.       };
  3693.       return ClosestOrAncestor(is$1, ancestor, scope, selector, isRoot);
  3694.     };
  3695.  
  3696.     var find$1 = function (queryElem) {
  3697.       var dependent = closest$3(queryElem, function (elem) {
  3698.         if (!isElement$2(elem)) {
  3699.           return false;
  3700.         }
  3701.         var id = get$d(elem, 'id');
  3702.         return id !== undefined && id.indexOf('aria-owns') > -1;
  3703.       });
  3704.       return dependent.bind(function (dep) {
  3705.         var id = get$d(dep, 'id');
  3706.         var dos = getRootNode(dep);
  3707.         return descendant(dos, '[aria-owns="' + id + '"]');
  3708.       });
  3709.     };
  3710.     var manager = function () {
  3711.       var ariaId = generate$6('aria-owns');
  3712.       var link = function (elem) {
  3713.         set$8(elem, 'aria-owns', ariaId);
  3714.       };
  3715.       var unlink = function (elem) {
  3716.         remove$7(elem, 'aria-owns');
  3717.       };
  3718.       return {
  3719.         id: ariaId,
  3720.         link: link,
  3721.         unlink: unlink
  3722.       };
  3723.     };
  3724.  
  3725.     var isAriaPartOf = function (component, queryElem) {
  3726.       return find$1(queryElem).exists(function (owner) {
  3727.         return isPartOf$1(component, owner);
  3728.       });
  3729.     };
  3730.     var isPartOf$1 = function (component, queryElem) {
  3731.       return closest$2(queryElem, function (el) {
  3732.         return eq(el, component.element);
  3733.       }, never) || isAriaPartOf(component, queryElem);
  3734.     };
  3735.  
  3736.     var unknown = 'unknown';
  3737.     var EventConfiguration;
  3738.     (function (EventConfiguration) {
  3739.       EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3740.       EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3741.       EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3742.     }(EventConfiguration || (EventConfiguration = {})));
  3743.     var eventConfig = Cell({});
  3744.     var makeEventLogger = function (eventName, initialTarget) {
  3745.       var sequence = [];
  3746.       var startTime = new Date().getTime();
  3747.       return {
  3748.         logEventCut: function (_name, target, purpose) {
  3749.           sequence.push({
  3750.             outcome: 'cut',
  3751.             target: target,
  3752.             purpose: purpose
  3753.           });
  3754.         },
  3755.         logEventStopped: function (_name, target, purpose) {
  3756.           sequence.push({
  3757.             outcome: 'stopped',
  3758.             target: target,
  3759.             purpose: purpose
  3760.           });
  3761.         },
  3762.         logNoParent: function (_name, target, purpose) {
  3763.           sequence.push({
  3764.             outcome: 'no-parent',
  3765.             target: target,
  3766.             purpose: purpose
  3767.           });
  3768.         },
  3769.         logEventNoHandlers: function (_name, target) {
  3770.           sequence.push({
  3771.             outcome: 'no-handlers-left',
  3772.             target: target
  3773.           });
  3774.         },
  3775.         logEventResponse: function (_name, target, purpose) {
  3776.           sequence.push({
  3777.             outcome: 'response',
  3778.             purpose: purpose,
  3779.             target: target
  3780.           });
  3781.         },
  3782.         write: function () {
  3783.           var finishTime = new Date().getTime();
  3784.           if (contains$2([
  3785.               'mousemove',
  3786.               'mouseover',
  3787.               'mouseout',
  3788.               systemInit()
  3789.             ], eventName)) {
  3790.             return;
  3791.           }
  3792.           console.log(eventName, {
  3793.             event: eventName,
  3794.             time: finishTime - startTime,
  3795.             target: initialTarget.dom,
  3796.             sequence: map$2(sequence, function (s) {
  3797.               if (!contains$2([
  3798.                   'cut',
  3799.                   'stopped',
  3800.                   'response'
  3801.                 ], s.outcome)) {
  3802.                 return s.outcome;
  3803.               } else {
  3804.                 return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3805.               }
  3806.             })
  3807.           });
  3808.         }
  3809.       };
  3810.     };
  3811.     var processEvent = function (eventName, initialTarget, f) {
  3812.       var status = get$e(eventConfig.get(), eventName).orThunk(function () {
  3813.         var patterns = keys(eventConfig.get());
  3814.         return findMap(patterns, function (p) {
  3815.           return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  3816.         });
  3817.       }).getOr(EventConfiguration.NORMAL);
  3818.       switch (status) {
  3819.       case EventConfiguration.NORMAL:
  3820.         return f(noLogger());
  3821.       case EventConfiguration.LOGGING: {
  3822.           var logger = makeEventLogger(eventName, initialTarget);
  3823.           var output = f(logger);
  3824.           logger.write();
  3825.           return output;
  3826.         }
  3827.       case EventConfiguration.STOP:
  3828.         return true;
  3829.       }
  3830.     };
  3831.     var path = [
  3832.       'alloy/data/Fields',
  3833.       'alloy/debugging/Debugging'
  3834.     ];
  3835.     var getTrace = function () {
  3836.       var err = new Error();
  3837.       if (err.stack !== undefined) {
  3838.         var lines = err.stack.split('\n');
  3839.         return find$5(lines, function (line) {
  3840.           return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3841.             return line.indexOf(p) > -1;
  3842.           });
  3843.         }).getOr(unknown);
  3844.       } else {
  3845.         return unknown;
  3846.       }
  3847.     };
  3848.     var ignoreEvent = {
  3849.       logEventCut: noop,
  3850.       logEventStopped: noop,
  3851.       logNoParent: noop,
  3852.       logEventNoHandlers: noop,
  3853.       logEventResponse: noop,
  3854.       write: noop
  3855.     };
  3856.     var monitorEvent = function (eventName, initialTarget, f) {
  3857.       return processEvent(eventName, initialTarget, f);
  3858.     };
  3859.     var noLogger = constant$1(ignoreEvent);
  3860.  
  3861.     var menuFields = constant$1([
  3862.       required$1('menu'),
  3863.       required$1('selectedMenu')
  3864.     ]);
  3865.     var itemFields = constant$1([
  3866.       required$1('item'),
  3867.       required$1('selectedItem')
  3868.     ]);
  3869.     constant$1(objOf(itemFields().concat(menuFields())));
  3870.     var itemSchema$3 = constant$1(objOf(itemFields()));
  3871.  
  3872.     var _initSize = requiredObjOf('initSize', [
  3873.       required$1('numColumns'),
  3874.       required$1('numRows')
  3875.     ]);
  3876.     var itemMarkers = function () {
  3877.       return requiredOf('markers', itemSchema$3());
  3878.     };
  3879.     var tieredMenuMarkers = function () {
  3880.       return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3881.     };
  3882.     var markers$1 = function (required) {
  3883.       return requiredObjOf('markers', map$2(required, required$1));
  3884.     };
  3885.     var onPresenceHandler = function (label, fieldName, presence) {
  3886.       getTrace();
  3887.       return field$1(fieldName, fieldName, presence, valueOf(function (f) {
  3888.         return Result.value(function () {
  3889.           var args = [];
  3890.           for (var _i = 0; _i < arguments.length; _i++) {
  3891.             args[_i] = arguments[_i];
  3892.           }
  3893.           return f.apply(undefined, args);
  3894.         });
  3895.       }));
  3896.     };
  3897.     var onHandler = function (fieldName) {
  3898.       return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  3899.     };
  3900.     var onKeyboardHandler = function (fieldName) {
  3901.       return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  3902.     };
  3903.     var onStrictHandler = function (fieldName) {
  3904.       return onPresenceHandler('onHandler', fieldName, required$2());
  3905.     };
  3906.     var onStrictKeyboardHandler = function (fieldName) {
  3907.       return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  3908.     };
  3909.     var output$1 = function (name, value) {
  3910.       return customField(name, constant$1(value));
  3911.     };
  3912.     var snapshot = function (name) {
  3913.       return customField(name, identity$1);
  3914.     };
  3915.     var initSize = constant$1(_initSize);
  3916.  
  3917.     var nu$6 = function (x, y, bubble, direction, placement, boundsRestriction, labelPrefix, alwaysFit) {
  3918.       if (alwaysFit === void 0) {
  3919.         alwaysFit = false;
  3920.       }
  3921.       return {
  3922.         x: x,
  3923.         y: y,
  3924.         bubble: bubble,
  3925.         direction: direction,
  3926.         placement: placement,
  3927.         restriction: boundsRestriction,
  3928.         label: labelPrefix + '-' + placement,
  3929.         alwaysFit: alwaysFit
  3930.       };
  3931.     };
  3932.  
  3933.     var adt$a = Adt.generate([
  3934.       { southeast: [] },
  3935.       { southwest: [] },
  3936.       { northeast: [] },
  3937.       { northwest: [] },
  3938.       { south: [] },
  3939.       { north: [] },
  3940.       { east: [] },
  3941.       { west: [] }
  3942.     ]);
  3943.     var cata$2 = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3944.       return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3945.     };
  3946.     var cataVertical = function (subject, south, middle, north) {
  3947.       return subject.fold(south, south, north, north, south, north, middle, middle);
  3948.     };
  3949.     var cataHorizontal = function (subject, east, middle, west) {
  3950.       return subject.fold(east, west, east, west, middle, middle, east, west);
  3951.     };
  3952.     var southeast$3 = adt$a.southeast;
  3953.     var southwest$3 = adt$a.southwest;
  3954.     var northeast$3 = adt$a.northeast;
  3955.     var northwest$3 = adt$a.northwest;
  3956.     var south$3 = adt$a.south;
  3957.     var north$3 = adt$a.north;
  3958.     var east$3 = adt$a.east;
  3959.     var west$3 = adt$a.west;
  3960.  
  3961.     var cycleBy = function (value, delta, min, max) {
  3962.       var r = value + delta;
  3963.       if (r > max) {
  3964.         return min;
  3965.       } else if (r < min) {
  3966.         return max;
  3967.       } else {
  3968.         return r;
  3969.       }
  3970.     };
  3971.     var clamp$1 = function (value, min, max) {
  3972.       return Math.min(Math.max(value, min), max);
  3973.     };
  3974.  
  3975.     var getRestriction = function (anchor, restriction) {
  3976.       switch (restriction) {
  3977.       case 1:
  3978.         return anchor.x;
  3979.       case 0:
  3980.         return anchor.x + anchor.width;
  3981.       case 2:
  3982.         return anchor.y;
  3983.       case 3:
  3984.         return anchor.y + anchor.height;
  3985.       }
  3986.     };
  3987.     var boundsRestriction = function (anchor, restrictions) {
  3988.       return mapToObject([
  3989.         'left',
  3990.         'right',
  3991.         'top',
  3992.         'bottom'
  3993.       ], function (dir) {
  3994.         return get$e(restrictions, dir).map(function (restriction) {
  3995.           return getRestriction(anchor, restriction);
  3996.         });
  3997.       });
  3998.     };
  3999.     var adjustBounds = function (bounds$1, restriction, bubbleOffset) {
  4000.       var applyRestriction = function (dir, current) {
  4001.         return restriction[dir].map(function (pos) {
  4002.           var isVerticalAxis = dir === 'top' || dir === 'bottom';
  4003.           var offset = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
  4004.           var comparator = dir === 'left' || dir === 'top' ? Math.max : Math.min;
  4005.           var newPos = comparator(pos, current) + offset;
  4006.           return isVerticalAxis ? clamp$1(newPos, bounds$1.y, bounds$1.bottom) : clamp$1(newPos, bounds$1.x, bounds$1.right);
  4007.         }).getOr(current);
  4008.       };
  4009.       var adjustedLeft = applyRestriction('left', bounds$1.x);
  4010.       var adjustedTop = applyRestriction('top', bounds$1.y);
  4011.       var adjustedRight = applyRestriction('right', bounds$1.right);
  4012.       var adjustedBottom = applyRestriction('bottom', bounds$1.bottom);
  4013.       return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  4014.     };
  4015.  
  4016.     var labelPrefix$2 = 'layout';
  4017.     var eastX$1 = function (anchor) {
  4018.       return anchor.x;
  4019.     };
  4020.     var middleX$1 = function (anchor, element) {
  4021.       return anchor.x + anchor.width / 2 - element.width / 2;
  4022.     };
  4023.     var westX$1 = function (anchor, element) {
  4024.       return anchor.x + anchor.width - element.width;
  4025.     };
  4026.     var northY$2 = function (anchor, element) {
  4027.       return anchor.y - element.height;
  4028.     };
  4029.     var southY$2 = function (anchor) {
  4030.       return anchor.y + anchor.height;
  4031.     };
  4032.     var centreY$1 = function (anchor, element) {
  4033.       return anchor.y + anchor.height / 2 - element.height / 2;
  4034.     };
  4035.     var eastEdgeX$1 = function (anchor) {
  4036.       return anchor.x + anchor.width;
  4037.     };
  4038.     var westEdgeX$1 = function (anchor, element) {
  4039.       return anchor.x - element.width;
  4040.     };
  4041.     var southeast$2 = function (anchor, element, bubbles) {
  4042.       return nu$6(eastX$1(anchor), southY$2(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  4043.         left: 1,
  4044.         top: 3
  4045.       }), labelPrefix$2);
  4046.     };
  4047.     var southwest$2 = function (anchor, element, bubbles) {
  4048.       return nu$6(westX$1(anchor, element), southY$2(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  4049.         right: 0,
  4050.         top: 3
  4051.       }), labelPrefix$2);
  4052.     };
  4053.     var northeast$2 = function (anchor, element, bubbles) {
  4054.       return nu$6(eastX$1(anchor), northY$2(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  4055.         left: 1,
  4056.         bottom: 2
  4057.       }), labelPrefix$2);
  4058.     };
  4059.     var northwest$2 = function (anchor, element, bubbles) {
  4060.       return nu$6(westX$1(anchor, element), northY$2(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  4061.         right: 0,
  4062.         bottom: 2
  4063.       }), labelPrefix$2);
  4064.     };
  4065.     var north$2 = function (anchor, element, bubbles) {
  4066.       return nu$6(middleX$1(anchor, element), northY$2(anchor, element), bubbles.north(), north$3(), 'north', boundsRestriction(anchor, { bottom: 2 }), labelPrefix$2);
  4067.     };
  4068.     var south$2 = function (anchor, element, bubbles) {
  4069.       return nu$6(middleX$1(anchor, element), southY$2(anchor), bubbles.south(), south$3(), 'south', boundsRestriction(anchor, { top: 3 }), labelPrefix$2);
  4070.     };
  4071.     var east$2 = function (anchor, element, bubbles) {
  4072.       return nu$6(eastEdgeX$1(anchor), centreY$1(anchor, element), bubbles.east(), east$3(), 'east', boundsRestriction(anchor, { left: 0 }), labelPrefix$2);
  4073.     };
  4074.     var west$2 = function (anchor, element, bubbles) {
  4075.       return nu$6(westEdgeX$1(anchor, element), centreY$1(anchor, element), bubbles.west(), west$3(), 'west', boundsRestriction(anchor, { right: 1 }), labelPrefix$2);
  4076.     };
  4077.     var all$1 = function () {
  4078.       return [
  4079.         southeast$2,
  4080.         southwest$2,
  4081.         northeast$2,
  4082.         northwest$2,
  4083.         south$2,
  4084.         north$2,
  4085.         east$2,
  4086.         west$2
  4087.       ];
  4088.     };
  4089.     var allRtl$1 = function () {
  4090.       return [
  4091.         southwest$2,
  4092.         southeast$2,
  4093.         northwest$2,
  4094.         northeast$2,
  4095.         south$2,
  4096.         north$2,
  4097.         east$2,
  4098.         west$2
  4099.       ];
  4100.     };
  4101.     var aboveOrBelow = function () {
  4102.       return [
  4103.         northeast$2,
  4104.         northwest$2,
  4105.         southeast$2,
  4106.         southwest$2,
  4107.         north$2,
  4108.         south$2
  4109.       ];
  4110.     };
  4111.     var aboveOrBelowRtl = function () {
  4112.       return [
  4113.         northwest$2,
  4114.         northeast$2,
  4115.         southwest$2,
  4116.         southeast$2,
  4117.         north$2,
  4118.         south$2
  4119.       ];
  4120.     };
  4121.     var belowOrAbove = function () {
  4122.       return [
  4123.         southeast$2,
  4124.         southwest$2,
  4125.         northeast$2,
  4126.         northwest$2,
  4127.         south$2,
  4128.         north$2
  4129.       ];
  4130.     };
  4131.     var belowOrAboveRtl = function () {
  4132.       return [
  4133.         southwest$2,
  4134.         southeast$2,
  4135.         northwest$2,
  4136.         northeast$2,
  4137.         south$2,
  4138.         north$2
  4139.       ];
  4140.     };
  4141.  
  4142.     var chooseChannels = function (channels, message) {
  4143.       return message.universal ? channels : filter$2(channels, function (ch) {
  4144.         return contains$2(message.channels, ch);
  4145.       });
  4146.     };
  4147.     var events$h = function (receiveConfig) {
  4148.       return derive$2([run$1(receive(), function (component, message) {
  4149.           var channelMap = receiveConfig.channels;
  4150.           var channels = keys(channelMap);
  4151.           var receivingData = message;
  4152.           var targetChannels = chooseChannels(channels, receivingData);
  4153.           each$1(targetChannels, function (ch) {
  4154.             var channelInfo = channelMap[ch];
  4155.             var channelSchema = channelInfo.schema;
  4156.             var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  4157.             channelInfo.onReceive(component, data);
  4158.           });
  4159.         })]);
  4160.     };
  4161.  
  4162.     var ActiveReceiving = /*#__PURE__*/Object.freeze({
  4163.         __proto__: null,
  4164.         events: events$h
  4165.     });
  4166.  
  4167.     var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  4168.         onStrictHandler('onReceive'),
  4169.         defaulted('schema', anyValue())
  4170.       ])))];
  4171.  
  4172.     var executeEvent = function (bConfig, bState, executor) {
  4173.       return runOnExecute$1(function (component) {
  4174.         executor(component, bConfig, bState);
  4175.       });
  4176.     };
  4177.     var loadEvent = function (bConfig, bState, f) {
  4178.       return runOnInit(function (component, _simulatedEvent) {
  4179.         f(component, bConfig, bState);
  4180.       });
  4181.     };
  4182.     var create$9 = function (schema, name, active, apis, extra, state) {
  4183.       var configSchema = objOfOnly(schema);
  4184.       var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  4185.       return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4186.     };
  4187.     var createModes$1 = function (modes, name, active, apis, extra, state) {
  4188.       var configSchema = modes;
  4189.       var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  4190.       return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4191.     };
  4192.     var wrapApi = function (bName, apiFunction, apiName) {
  4193.       var f = function (component) {
  4194.         var rest = [];
  4195.         for (var _i = 1; _i < arguments.length; _i++) {
  4196.           rest[_i - 1] = arguments[_i];
  4197.         }
  4198.         var args = [component].concat(rest);
  4199.         return component.config({ name: constant$1(bName) }).fold(function () {
  4200.           throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  4201.         }, function (info) {
  4202.           var rest = Array.prototype.slice.call(args, 1);
  4203.           return apiFunction.apply(undefined, [
  4204.             component,
  4205.             info.config,
  4206.             info.state
  4207.           ].concat(rest));
  4208.         });
  4209.       };
  4210.       return markAsBehaviourApi(f, apiName, apiFunction);
  4211.     };
  4212.     var revokeBehaviour = function (name) {
  4213.       return {
  4214.         key: name,
  4215.         value: undefined
  4216.       };
  4217.     };
  4218.     var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  4219.       var getConfig = function (info) {
  4220.         return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  4221.       };
  4222.       var wrappedApis = map$1(apis, function (apiF, apiName) {
  4223.         return wrapApi(name, apiF, apiName);
  4224.       });
  4225.       var wrappedExtra = map$1(extra, function (extraF, extraName) {
  4226.         return markAsExtraApi(extraF, extraName);
  4227.       });
  4228.       var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  4229.         revoke: curry(revokeBehaviour, name),
  4230.         config: function (spec) {
  4231.           var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  4232.           return {
  4233.             key: name,
  4234.             value: {
  4235.               config: prepared,
  4236.               me: me,
  4237.               configAsRaw: cached(function () {
  4238.                 return asRawOrDie$1(name + '-config', configSchema, spec);
  4239.               }),
  4240.               initialConfig: spec,
  4241.               state: state
  4242.             }
  4243.           };
  4244.         },
  4245.         schema: constant$1(schemaSchema),
  4246.         exhibit: function (info, base) {
  4247.           return lift2(getConfig(info), get$e(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  4248.             return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  4249.           }).getOrThunk(function () {
  4250.             return nu$7({});
  4251.           });
  4252.         },
  4253.         name: constant$1(name),
  4254.         handlers: function (info) {
  4255.           return getConfig(info).map(function (behaviourInfo) {
  4256.             var getEvents = get$e(active, 'events').getOr(function () {
  4257.               return {};
  4258.             });
  4259.             return getEvents(behaviourInfo.config, behaviourInfo.state);
  4260.           }).getOr({});
  4261.         }
  4262.       });
  4263.       return me;
  4264.     };
  4265.  
  4266.     var derive$1 = function (capabilities) {
  4267.       return wrapAll(capabilities);
  4268.     };
  4269.     var simpleSchema = objOfOnly([
  4270.       required$1('fields'),
  4271.       required$1('name'),
  4272.       defaulted('active', {}),
  4273.       defaulted('apis', {}),
  4274.       defaulted('state', NoState),
  4275.       defaulted('extra', {})
  4276.     ]);
  4277.     var create$8 = function (data) {
  4278.       var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  4279.       return create$9(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  4280.     };
  4281.     var modeSchema = objOfOnly([
  4282.       required$1('branchKey'),
  4283.       required$1('branches'),
  4284.       required$1('name'),
  4285.       defaulted('active', {}),
  4286.       defaulted('apis', {}),
  4287.       defaulted('state', NoState),
  4288.       defaulted('extra', {})
  4289.     ]);
  4290.     var createModes = function (data) {
  4291.       var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  4292.       return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  4293.     };
  4294.     var revoke = constant$1(undefined);
  4295.  
  4296.     var Receiving = create$8({
  4297.       fields: ReceivingSchema,
  4298.       name: 'receiving',
  4299.       active: ActiveReceiving
  4300.     });
  4301.  
  4302.     var exhibit$6 = function (base, posConfig) {
  4303.       return nu$7({
  4304.         classes: [],
  4305.         styles: posConfig.useFixed() ? {} : { position: 'relative' }
  4306.       });
  4307.     };
  4308.  
  4309.     var ActivePosition = /*#__PURE__*/Object.freeze({
  4310.         __proto__: null,
  4311.         exhibit: exhibit$6
  4312.     });
  4313.  
  4314.     var getDocument = function () {
  4315.       return SugarElement.fromDom(document);
  4316.     };
  4317.  
  4318.     var focus$3 = function (element) {
  4319.       return element.dom.focus();
  4320.     };
  4321.     var blur$1 = function (element) {
  4322.       return element.dom.blur();
  4323.     };
  4324.     var hasFocus = function (element) {
  4325.       var root = getRootNode(element).dom;
  4326.       return element.dom === root.activeElement;
  4327.     };
  4328.     var active = function (root) {
  4329.       if (root === void 0) {
  4330.         root = getDocument();
  4331.       }
  4332.       return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  4333.     };
  4334.     var search = function (element) {
  4335.       return active(getRootNode(element)).filter(function (e) {
  4336.         return element.dom.contains(e.dom);
  4337.       });
  4338.     };
  4339.  
  4340.     var preserve$1 = function (f, container) {
  4341.       var dos = getRootNode(container);
  4342.       var refocus = active(dos).bind(function (focused) {
  4343.         var hasFocus = function (elem) {
  4344.           return eq(focused, elem);
  4345.         };
  4346.         return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  4347.       });
  4348.       var result = f(container);
  4349.       refocus.each(function (oldFocus) {
  4350.         active(dos).filter(function (newFocus) {
  4351.           return eq(newFocus, oldFocus);
  4352.         }).fold(function () {
  4353.           focus$3(oldFocus);
  4354.         }, noop);
  4355.       });
  4356.       return result;
  4357.     };
  4358.  
  4359.     var NuPositionCss = function (position, left, top, right, bottom) {
  4360.       var toPx = function (num) {
  4361.         return num + 'px';
  4362.       };
  4363.       return {
  4364.         position: position,
  4365.         left: left.map(toPx),
  4366.         top: top.map(toPx),
  4367.         right: right.map(toPx),
  4368.         bottom: bottom.map(toPx)
  4369.       };
  4370.     };
  4371.     var toOptions = function (position) {
  4372.       return __assign(__assign({}, position), { position: Optional.some(position.position) });
  4373.     };
  4374.     var applyPositionCss = function (element, position) {
  4375.       setOptions(element, toOptions(position));
  4376.     };
  4377.  
  4378.     var adt$9 = Adt.generate([
  4379.       { none: [] },
  4380.       {
  4381.         relative: [
  4382.           'x',
  4383.           'y',
  4384.           'width',
  4385.           'height'
  4386.         ]
  4387.       },
  4388.       {
  4389.         fixed: [
  4390.           'x',
  4391.           'y',
  4392.           'width',
  4393.           'height'
  4394.         ]
  4395.       }
  4396.     ]);
  4397.     var positionWithDirection = function (posName, decision, x, y, width, height) {
  4398.       var decisionRect = decision.rect;
  4399.       var decisionX = decisionRect.x - x;
  4400.       var decisionY = decisionRect.y - y;
  4401.       var decisionWidth = decisionRect.width;
  4402.       var decisionHeight = decisionRect.height;
  4403.       var decisionRight = width - (decisionX + decisionWidth);
  4404.       var decisionBottom = height - (decisionY + decisionHeight);
  4405.       var left = Optional.some(decisionX);
  4406.       var top = Optional.some(decisionY);
  4407.       var right = Optional.some(decisionRight);
  4408.       var bottom = Optional.some(decisionBottom);
  4409.       var none = Optional.none();
  4410.       return cata$2(decision.direction, function () {
  4411.         return NuPositionCss(posName, left, top, none, none);
  4412.       }, function () {
  4413.         return NuPositionCss(posName, none, top, right, none);
  4414.       }, function () {
  4415.         return NuPositionCss(posName, left, none, none, bottom);
  4416.       }, function () {
  4417.         return NuPositionCss(posName, none, none, right, bottom);
  4418.       }, function () {
  4419.         return NuPositionCss(posName, left, top, none, none);
  4420.       }, function () {
  4421.         return NuPositionCss(posName, left, none, none, bottom);
  4422.       }, function () {
  4423.         return NuPositionCss(posName, left, top, none, none);
  4424.       }, function () {
  4425.         return NuPositionCss(posName, none, top, right, none);
  4426.       });
  4427.     };
  4428.     var reposition = function (origin, decision) {
  4429.       return origin.fold(function () {
  4430.         var decisionRect = decision.rect;
  4431.         return NuPositionCss('absolute', Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
  4432.       }, function (x, y, width, height) {
  4433.         return positionWithDirection('absolute', decision, x, y, width, height);
  4434.       }, function (x, y, width, height) {
  4435.         return positionWithDirection('fixed', decision, x, y, width, height);
  4436.       });
  4437.     };
  4438.     var toBox = function (origin, element) {
  4439.       var rel = curry(find$2, element);
  4440.       var position = origin.fold(rel, rel, function () {
  4441.         var scroll = get$9();
  4442.         return find$2(element).translate(-scroll.left, -scroll.top);
  4443.       });
  4444.       var width = getOuter$1(element);
  4445.       var height = getOuter$2(element);
  4446.       return bounds(position.left, position.top, width, height);
  4447.     };
  4448.     var viewport = function (origin, getBounds) {
  4449.       return getBounds.fold(function () {
  4450.         return origin.fold(win, win, bounds);
  4451.       }, function (b) {
  4452.         return origin.fold(b, b, function () {
  4453.           var bounds$1 = b();
  4454.           var pos = translate$2(origin, bounds$1.x, bounds$1.y);
  4455.           return bounds(pos.left, pos.top, bounds$1.width, bounds$1.height);
  4456.         });
  4457.       });
  4458.     };
  4459.     var translate$2 = function (origin, x, y) {
  4460.       var pos = SugarPosition(x, y);
  4461.       var removeScroll = function () {
  4462.         var outerScroll = get$9();
  4463.         return pos.translate(-outerScroll.left, -outerScroll.top);
  4464.       };
  4465.       return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
  4466.     };
  4467.     var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4468.       return subject.fold(onNone, onRelative, onFixed);
  4469.     };
  4470.     adt$9.none;
  4471.     var relative$1 = adt$9.relative;
  4472.     var fixed$1 = adt$9.fixed;
  4473.  
  4474.     var anchor = function (anchorBox, origin) {
  4475.       return {
  4476.         anchorBox: anchorBox,
  4477.         origin: origin
  4478.       };
  4479.     };
  4480.     var box = function (anchorBox, origin) {
  4481.       return anchor(anchorBox, origin);
  4482.     };
  4483.  
  4484.     var placementAttribute = 'data-alloy-placement';
  4485.     var setPlacement$1 = function (element, placement) {
  4486.       set$8(element, placementAttribute, placement);
  4487.     };
  4488.     var getPlacement = function (element) {
  4489.       return getOpt(element, placementAttribute);
  4490.     };
  4491.     var reset$2 = function (element) {
  4492.       return remove$7(element, placementAttribute);
  4493.     };
  4494.  
  4495.     var adt$8 = Adt.generate([
  4496.       { fit: ['reposition'] },
  4497.       {
  4498.         nofit: [
  4499.           'reposition',
  4500.           'visibleW',
  4501.           'visibleH',
  4502.           'isVisible'
  4503.         ]
  4504.       }
  4505.     ]);
  4506.     var determinePosition = function (box, bounds) {
  4507.       var boundsX = bounds.x, boundsY = bounds.y, boundsRight = bounds.right, boundsBottom = bounds.bottom;
  4508.       var x = box.x, y = box.y, right = box.right, bottom = box.bottom, width = box.width, height = box.height;
  4509.       var xInBounds = x >= boundsX && x <= boundsRight;
  4510.       var yInBounds = y >= boundsY && y <= boundsBottom;
  4511.       var originInBounds = xInBounds && yInBounds;
  4512.       var rightInBounds = right <= boundsRight && right >= boundsX;
  4513.       var bottomInBounds = bottom <= boundsBottom && bottom >= boundsY;
  4514.       var sizeInBounds = rightInBounds && bottomInBounds;
  4515.       var visibleW = Math.min(width, x >= boundsX ? boundsRight - x : right - boundsX);
  4516.       var visibleH = Math.min(height, y >= boundsY ? boundsBottom - y : bottom - boundsY);
  4517.       return {
  4518.         originInBounds: originInBounds,
  4519.         sizeInBounds: sizeInBounds,
  4520.         visibleW: visibleW,
  4521.         visibleH: visibleH
  4522.       };
  4523.     };
  4524.     var calcReposition = function (box, bounds$1) {
  4525.       var boundsX = bounds$1.x, boundsY = bounds$1.y, boundsRight = bounds$1.right, boundsBottom = bounds$1.bottom;
  4526.       var x = box.x, y = box.y, width = box.width, height = box.height;
  4527.       var maxX = Math.max(boundsX, boundsRight - width);
  4528.       var maxY = Math.max(boundsY, boundsBottom - height);
  4529.       var restrictedX = clamp$1(x, boundsX, maxX);
  4530.       var restrictedY = clamp$1(y, boundsY, maxY);
  4531.       var restrictedWidth = Math.min(restrictedX + width, boundsRight) - restrictedX;
  4532.       var restrictedHeight = Math.min(restrictedY + height, boundsBottom) - restrictedY;
  4533.       return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
  4534.     };
  4535.     var calcMaxSizes = function (direction, box, bounds) {
  4536.       var upAvailable = constant$1(box.bottom - bounds.y);
  4537.       var downAvailable = constant$1(bounds.bottom - box.y);
  4538.       var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
  4539.       var westAvailable = constant$1(box.right - bounds.x);
  4540.       var eastAvailable = constant$1(bounds.right - box.x);
  4541.       var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
  4542.       return {
  4543.         maxWidth: maxWidth,
  4544.         maxHeight: maxHeight
  4545.       };
  4546.     };
  4547.     var attempt = function (candidate, width, height, bounds$1) {
  4548.       var bubble = candidate.bubble;
  4549.       var bubbleOffset = bubble.offset;
  4550.       var adjustedBounds = adjustBounds(bounds$1, candidate.restriction, bubbleOffset);
  4551.       var newX = candidate.x + bubbleOffset.left;
  4552.       var newY = candidate.y + bubbleOffset.top;
  4553.       var box = bounds(newX, newY, width, height);
  4554.       var _a = determinePosition(box, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, visibleW = _a.visibleW, visibleH = _a.visibleH;
  4555.       var fits = originInBounds && sizeInBounds;
  4556.       var fittedBox = fits ? box : calcReposition(box, adjustedBounds);
  4557.       var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
  4558.       var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$1), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight;
  4559.       var reposition = {
  4560.         rect: fittedBox,
  4561.         maxHeight: maxHeight,
  4562.         maxWidth: maxWidth,
  4563.         direction: candidate.direction,
  4564.         placement: candidate.placement,
  4565.         classes: {
  4566.           on: bubble.classesOn,
  4567.           off: bubble.classesOff
  4568.         },
  4569.         layout: candidate.label,
  4570.         testY: newY
  4571.       };
  4572.       return fits || candidate.alwaysFit ? adt$8.fit(reposition) : adt$8.nofit(reposition, visibleW, visibleH, isPartlyVisible);
  4573.     };
  4574.     var attempts = function (element, candidates, anchorBox, elementBox, bubbles, bounds) {
  4575.       var panelWidth = elementBox.width;
  4576.       var panelHeight = elementBox.height;
  4577.       var attemptBestFit = function (layout, reposition, visibleW, visibleH, isVisible) {
  4578.         var next = layout(anchorBox, elementBox, bubbles, element, bounds);
  4579.         var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4580.         return attemptLayout.fold(constant$1(attemptLayout), function (newReposition, newVisibleW, newVisibleH, newIsVisible) {
  4581.           var improved = isVisible === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible && newIsVisible;
  4582.           return improved ? attemptLayout : adt$8.nofit(reposition, visibleW, visibleH, isVisible);
  4583.         });
  4584.       };
  4585.       var abc = foldl(candidates, function (b, a) {
  4586.         var bestNext = curry(attemptBestFit, a);
  4587.         return b.fold(constant$1(b), bestNext);
  4588.       }, adt$8.nofit({
  4589.         rect: anchorBox,
  4590.         maxHeight: elementBox.height,
  4591.         maxWidth: elementBox.width,
  4592.         direction: southeast$3(),
  4593.         placement: 'southeast',
  4594.         classes: {
  4595.           on: [],
  4596.           off: []
  4597.         },
  4598.         layout: 'none',
  4599.         testY: anchorBox.y
  4600.       }, -1, -1, false));
  4601.       return abc.fold(identity$1, identity$1);
  4602.     };
  4603.  
  4604.     var singleton = function (doRevoke) {
  4605.       var subject = Cell(Optional.none());
  4606.       var revoke = function () {
  4607.         return subject.get().each(doRevoke);
  4608.       };
  4609.       var clear = function () {
  4610.         revoke();
  4611.         subject.set(Optional.none());
  4612.       };
  4613.       var isSet = function () {
  4614.         return subject.get().isSome();
  4615.       };
  4616.       var get = function () {
  4617.         return subject.get();
  4618.       };
  4619.       var set = function (s) {
  4620.         revoke();
  4621.         subject.set(Optional.some(s));
  4622.       };
  4623.       return {
  4624.         clear: clear,
  4625.         isSet: isSet,
  4626.         get: get,
  4627.         set: set
  4628.       };
  4629.     };
  4630.     var destroyable = function () {
  4631.       return singleton(function (s) {
  4632.         return s.destroy();
  4633.       });
  4634.     };
  4635.     var unbindable = function () {
  4636.       return singleton(function (s) {
  4637.         return s.unbind();
  4638.       });
  4639.     };
  4640.     var api$1 = function () {
  4641.       var subject = destroyable();
  4642.       var run = function (f) {
  4643.         return subject.get().each(f);
  4644.       };
  4645.       return __assign(__assign({}, subject), { run: run });
  4646.     };
  4647.     var value$1 = function () {
  4648.       var subject = singleton(noop);
  4649.       var on = function (f) {
  4650.         return subject.get().each(f);
  4651.       };
  4652.       return __assign(__assign({}, subject), { on: on });
  4653.     };
  4654.  
  4655.     var filter = always;
  4656.     var bind = function (element, event, handler) {
  4657.       return bind$2(element, event, filter, handler);
  4658.     };
  4659.     var capture = function (element, event, handler) {
  4660.       return capture$1(element, event, filter, handler);
  4661.     };
  4662.     var fromRawEvent = fromRawEvent$1;
  4663.  
  4664.     var properties = [
  4665.       'top',
  4666.       'bottom',
  4667.       'right',
  4668.       'left'
  4669.     ];
  4670.     var timerAttr = 'data-alloy-transition-timer';
  4671.     var isTransitioning$1 = function (element, transition) {
  4672.       return hasAll(element, transition.classes);
  4673.     };
  4674.     var shouldApplyTransitionCss = function (transition, decision, lastPlacement) {
  4675.       return lastPlacement.exists(function (placer) {
  4676.         var mode = transition.mode;
  4677.         return mode === 'all' ? true : placer[mode] !== decision[mode];
  4678.       });
  4679.     };
  4680.     var hasChanges = function (position, intermediate) {
  4681.       var round = function (value) {
  4682.         return parseFloat(value).toFixed(3);
  4683.       };
  4684.       return find$4(intermediate, function (value, key) {
  4685.         var newValue = position[key].map(round);
  4686.         var val = value.map(round);
  4687.         return !equals(newValue, val);
  4688.       }).isSome();
  4689.     };
  4690.     var getTransitionDuration = function (element) {
  4691.       var get = function (name) {
  4692.         var style = get$c(element, name);
  4693.         var times = isString(style) ? style.split(/\s*,\s*/) : [];
  4694.         return filter$2(times, isNotEmpty);
  4695.       };
  4696.       var parse = function (value) {
  4697.         if (isString(value) && /^[\d.]+/.test(value)) {
  4698.           var num = parseFloat(value);
  4699.           return endsWith(value, 'ms') ? num : num * 1000;
  4700.         } else {
  4701.           return 0;
  4702.         }
  4703.       };
  4704.       var delay = get('transition-delay');
  4705.       var duration = get('transition-duration');
  4706.       return foldl(duration, function (acc, dur, i) {
  4707.         var time = parse(delay[i]) + parse(dur);
  4708.         return Math.max(acc, time);
  4709.       }, 0);
  4710.     };
  4711.     var setupTransitionListeners = function (element, transition) {
  4712.       var transitionEnd = unbindable();
  4713.       var transitionCancel = unbindable();
  4714.       var timer;
  4715.       var isSourceTransition = function (e) {
  4716.         var _a;
  4717.         var pseudoElement = (_a = e.raw.pseudoElement) !== null && _a !== void 0 ? _a : '';
  4718.         return eq(e.target, element) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName);
  4719.       };
  4720.       var transitionDone = function (e) {
  4721.         if (isNullable(e) || isSourceTransition(e)) {
  4722.           transitionEnd.clear();
  4723.           transitionCancel.clear();
  4724.           var type = e === null || e === void 0 ? void 0 : e.raw.type;
  4725.           if (isNullable(type) || type === transitionend()) {
  4726.             clearTimeout(timer);
  4727.             remove$7(element, timerAttr);
  4728.             remove$1(element, transition.classes);
  4729.           }
  4730.         }
  4731.       };
  4732.       var transitionStarted = function () {
  4733.         transitionEnd.set(bind(element, transitionend(), transitionDone));
  4734.         transitionCancel.set(bind(element, transitioncancel(), transitionDone));
  4735.       };
  4736.       if ('ontransitionstart' in element.dom) {
  4737.         var transitionStart_1 = bind(element, transitionstart(), function (e) {
  4738.           if (isSourceTransition(e)) {
  4739.             transitionStart_1.unbind();
  4740.             transitionStarted();
  4741.           }
  4742.         });
  4743.       } else {
  4744.         transitionStarted();
  4745.       }
  4746.       var duration = getTransitionDuration(element);
  4747.       requestAnimationFrame(function () {
  4748.         timer = setTimeout(transitionDone, duration + 17);
  4749.         set$8(element, timerAttr, timer);
  4750.       });
  4751.     };
  4752.     var startTransitioning = function (element, transition) {
  4753.       add$1(element, transition.classes);
  4754.       getOpt(element, timerAttr).each(function (timerId) {
  4755.         clearTimeout(parseInt(timerId, 10));
  4756.         remove$7(element, timerAttr);
  4757.       });
  4758.       setupTransitionListeners(element, transition);
  4759.     };
  4760.     var applyTransitionCss = function (element, origin, position, transition, decision, lastPlacement) {
  4761.       var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
  4762.       if (shouldTransition || isTransitioning$1(element, transition)) {
  4763.         set$7(element, 'position', position.position);
  4764.         var rect = toBox(origin, element);
  4765.         var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect }));
  4766.         var intermediateCssOptions = mapToObject(properties, function (prop) {
  4767.           return intermediatePosition_1[prop];
  4768.         });
  4769.         if (hasChanges(position, intermediateCssOptions)) {
  4770.           setOptions(element, intermediateCssOptions);
  4771.           if (shouldTransition) {
  4772.             startTransitioning(element, transition);
  4773.           }
  4774.           reflow(element);
  4775.         }
  4776.       } else {
  4777.         remove$1(element, transition.classes);
  4778.       }
  4779.     };
  4780.  
  4781.     var elementSize = function (p) {
  4782.       return {
  4783.         width: getOuter$1(p),
  4784.         height: getOuter$2(p)
  4785.       };
  4786.     };
  4787.     var layout = function (anchorBox, element, bubbles, options) {
  4788.       remove$6(element, 'max-height');
  4789.       remove$6(element, 'max-width');
  4790.       var elementBox = elementSize(element);
  4791.       return attempts(element, options.preference, anchorBox, elementBox, bubbles, options.bounds);
  4792.     };
  4793.     var setClasses = function (element, decision) {
  4794.       var classInfo = decision.classes;
  4795.       remove$1(element, classInfo.off);
  4796.       add$1(element, classInfo.on);
  4797.     };
  4798.     var setHeight = function (element, decision, options) {
  4799.       var maxHeightFunction = options.maxHeightFunction;
  4800.       maxHeightFunction(element, decision.maxHeight);
  4801.     };
  4802.     var setWidth = function (element, decision, options) {
  4803.       var maxWidthFunction = options.maxWidthFunction;
  4804.       maxWidthFunction(element, decision.maxWidth);
  4805.     };
  4806.     var position$2 = function (element, decision, options) {
  4807.       var positionCss = reposition(options.origin, decision);
  4808.       options.transition.each(function (transition) {
  4809.         applyTransitionCss(element, options.origin, positionCss, transition, decision, options.lastPlacement);
  4810.       });
  4811.       applyPositionCss(element, positionCss);
  4812.     };
  4813.     var setPlacement = function (element, decision) {
  4814.       setPlacement$1(element, decision.placement);
  4815.     };
  4816.  
  4817.     var setMaxHeight = function (element, maxHeight) {
  4818.       setMax$1(element, Math.floor(maxHeight));
  4819.     };
  4820.     var anchored = constant$1(function (element, available) {
  4821.       setMaxHeight(element, available);
  4822.       setAll(element, {
  4823.         'overflow-x': 'hidden',
  4824.         'overflow-y': 'auto'
  4825.       });
  4826.     });
  4827.     var expandable$1 = constant$1(function (element, available) {
  4828.       setMaxHeight(element, available);
  4829.     });
  4830.  
  4831.     var defaultOr = function (options, key, dephault) {
  4832.       return options[key] === undefined ? dephault : options[key];
  4833.     };
  4834.     var simple = function (anchor, element, bubble, layouts, lastPlacement, getBounds, overrideOptions, transition) {
  4835.       var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4836.       var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4837.       var anchorBox = anchor.anchorBox;
  4838.       var origin = anchor.origin;
  4839.       var options = {
  4840.         bounds: viewport(origin, getBounds),
  4841.         origin: origin,
  4842.         preference: layouts,
  4843.         maxHeightFunction: maxHeightFunction,
  4844.         maxWidthFunction: maxWidthFunction,
  4845.         lastPlacement: lastPlacement,
  4846.         transition: transition
  4847.       };
  4848.       return go(anchorBox, element, bubble, options);
  4849.     };
  4850.     var go = function (anchorBox, element, bubble, options) {
  4851.       var decision = layout(anchorBox, element, bubble, options);
  4852.       position$2(element, decision, options);
  4853.       setPlacement(element, decision);
  4854.       setClasses(element, decision);
  4855.       setHeight(element, decision, options);
  4856.       setWidth(element, decision, options);
  4857.       return {
  4858.         layout: decision.layout,
  4859.         placement: decision.placement
  4860.       };
  4861.     };
  4862.  
  4863.     var allAlignments = [
  4864.       'valignCentre',
  4865.       'alignLeft',
  4866.       'alignRight',
  4867.       'alignCentre',
  4868.       'top',
  4869.       'bottom',
  4870.       'left',
  4871.       'right',
  4872.       'inset'
  4873.     ];
  4874.     var nu$5 = function (xOffset, yOffset, classes, insetModifier) {
  4875.       if (insetModifier === void 0) {
  4876.         insetModifier = 1;
  4877.       }
  4878.       var insetXOffset = xOffset * insetModifier;
  4879.       var insetYOffset = yOffset * insetModifier;
  4880.       var getClasses = function (prop) {
  4881.         return get$e(classes, prop).getOr([]);
  4882.       };
  4883.       var make = function (xDelta, yDelta, alignmentsOn) {
  4884.         var alignmentsOff = difference(allAlignments, alignmentsOn);
  4885.         return {
  4886.           offset: SugarPosition(xDelta, yDelta),
  4887.           classesOn: bind$3(alignmentsOn, getClasses),
  4888.           classesOff: bind$3(alignmentsOff, getClasses)
  4889.         };
  4890.       };
  4891.       return {
  4892.         southeast: function () {
  4893.           return make(-xOffset, yOffset, [
  4894.             'top',
  4895.             'alignLeft'
  4896.           ]);
  4897.         },
  4898.         southwest: function () {
  4899.           return make(xOffset, yOffset, [
  4900.             'top',
  4901.             'alignRight'
  4902.           ]);
  4903.         },
  4904.         south: function () {
  4905.           return make(-xOffset / 2, yOffset, [
  4906.             'top',
  4907.             'alignCentre'
  4908.           ]);
  4909.         },
  4910.         northeast: function () {
  4911.           return make(-xOffset, -yOffset, [
  4912.             'bottom',
  4913.             'alignLeft'
  4914.           ]);
  4915.         },
  4916.         northwest: function () {
  4917.           return make(xOffset, -yOffset, [
  4918.             'bottom',
  4919.             'alignRight'
  4920.           ]);
  4921.         },
  4922.         north: function () {
  4923.           return make(-xOffset / 2, -yOffset, [
  4924.             'bottom',
  4925.             'alignCentre'
  4926.           ]);
  4927.         },
  4928.         east: function () {
  4929.           return make(xOffset, -yOffset / 2, [
  4930.             'valignCentre',
  4931.             'left'
  4932.           ]);
  4933.         },
  4934.         west: function () {
  4935.           return make(-xOffset, -yOffset / 2, [
  4936.             'valignCentre',
  4937.             'right'
  4938.           ]);
  4939.         },
  4940.         insetNortheast: function () {
  4941.           return make(insetXOffset, insetYOffset, [
  4942.             'top',
  4943.             'alignLeft',
  4944.             'inset'
  4945.           ]);
  4946.         },
  4947.         insetNorthwest: function () {
  4948.           return make(-insetXOffset, insetYOffset, [
  4949.             'top',
  4950.             'alignRight',
  4951.             'inset'
  4952.           ]);
  4953.         },
  4954.         insetNorth: function () {
  4955.           return make(-insetXOffset / 2, insetYOffset, [
  4956.             'top',
  4957.             'alignCentre',
  4958.             'inset'
  4959.           ]);
  4960.         },
  4961.         insetSoutheast: function () {
  4962.           return make(insetXOffset, -insetYOffset, [
  4963.             'bottom',
  4964.             'alignLeft',
  4965.             'inset'
  4966.           ]);
  4967.         },
  4968.         insetSouthwest: function () {
  4969.           return make(-insetXOffset, -insetYOffset, [
  4970.             'bottom',
  4971.             'alignRight',
  4972.             'inset'
  4973.           ]);
  4974.         },
  4975.         insetSouth: function () {
  4976.           return make(-insetXOffset / 2, -insetYOffset, [
  4977.             'bottom',
  4978.             'alignCentre',
  4979.             'inset'
  4980.           ]);
  4981.         },
  4982.         insetEast: function () {
  4983.           return make(-insetXOffset, -insetYOffset / 2, [
  4984.             'valignCentre',
  4985.             'right',
  4986.             'inset'
  4987.           ]);
  4988.         },
  4989.         insetWest: function () {
  4990.           return make(insetXOffset, -insetYOffset / 2, [
  4991.             'valignCentre',
  4992.             'left',
  4993.             'inset'
  4994.           ]);
  4995.         }
  4996.       };
  4997.     };
  4998.     var fallback = function () {
  4999.       return nu$5(0, 0, {});
  5000.     };
  5001.  
  5002.     var nu$4 = identity$1;
  5003.  
  5004.     var onDirection = function (isLtr, isRtl) {
  5005.       return function (element) {
  5006.         return getDirection(element) === 'rtl' ? isRtl : isLtr;
  5007.       };
  5008.     };
  5009.     var getDirection = function (element) {
  5010.       return get$c(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  5011.     };
  5012.  
  5013.     var AttributeValue;
  5014.     (function (AttributeValue) {
  5015.       AttributeValue['TopToBottom'] = 'toptobottom';
  5016.       AttributeValue['BottomToTop'] = 'bottomtotop';
  5017.     }(AttributeValue || (AttributeValue = {})));
  5018.     var Attribute = 'data-alloy-vertical-dir';
  5019.     var isBottomToTopDir = function (el) {
  5020.       return closest$2(el, function (current) {
  5021.         return isElement$2(current) && get$d(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop;
  5022.       });
  5023.     };
  5024.  
  5025.     var schema$y = function () {
  5026.       return optionObjOf('layouts', [
  5027.         required$1('onLtr'),
  5028.         required$1('onRtl'),
  5029.         option('onBottomLtr'),
  5030.         option('onBottomRtl')
  5031.       ]);
  5032.     };
  5033.     var get$4 = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  5034.       var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  5035.       var customLtr = info.layouts.map(function (ls) {
  5036.         return ls.onLtr(elem);
  5037.       });
  5038.       var customRtl = info.layouts.map(function (ls) {
  5039.         return ls.onRtl(elem);
  5040.       });
  5041.       var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  5042.         return ls.onBottomLtr.map(function (f) {
  5043.           return f(elem);
  5044.         });
  5045.       }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  5046.       var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  5047.         return ls.onBottomRtl.map(function (f) {
  5048.           return f(elem);
  5049.         });
  5050.       }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  5051.       var f = onDirection(ltr, rtl);
  5052.       return f(elem);
  5053.     };
  5054.  
  5055.     var placement$4 = function (component, anchorInfo, origin) {
  5056.       var hotspot = anchorInfo.hotspot;
  5057.       var anchorBox = toBox(origin, hotspot.element);
  5058.       var layouts = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
  5059.       return Optional.some(nu$4({
  5060.         anchorBox: anchorBox,
  5061.         bubble: anchorInfo.bubble.getOr(fallback()),
  5062.         overrides: anchorInfo.overrides,
  5063.         layouts: layouts,
  5064.         placer: Optional.none()
  5065.       }));
  5066.     };
  5067.     var HotspotAnchor = [
  5068.       required$1('hotspot'),
  5069.       option('bubble'),
  5070.       defaulted('overrides', {}),
  5071.       schema$y(),
  5072.       output$1('placement', placement$4)
  5073.     ];
  5074.  
  5075.     var placement$3 = function (component, anchorInfo, origin) {
  5076.       var pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
  5077.       var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
  5078.       var layouts = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
  5079.       return Optional.some(nu$4({
  5080.         anchorBox: anchorBox,
  5081.         bubble: anchorInfo.bubble,
  5082.         overrides: anchorInfo.overrides,
  5083.         layouts: layouts,
  5084.         placer: Optional.none()
  5085.       }));
  5086.     };
  5087.     var MakeshiftAnchor = [
  5088.       required$1('x'),
  5089.       required$1('y'),
  5090.       defaulted('height', 0),
  5091.       defaulted('width', 0),
  5092.       defaulted('bubble', fallback()),
  5093.       defaulted('overrides', {}),
  5094.       schema$y(),
  5095.       output$1('placement', placement$3)
  5096.     ];
  5097.  
  5098.     var adt$7 = Adt.generate([
  5099.       { screen: ['point'] },
  5100.       {
  5101.         absolute: [
  5102.           'point',
  5103.           'scrollLeft',
  5104.           'scrollTop'
  5105.         ]
  5106.       }
  5107.     ]);
  5108.     var toFixed = function (pos) {
  5109.       return pos.fold(identity$1, function (point, scrollLeft, scrollTop) {
  5110.         return point.translate(-scrollLeft, -scrollTop);
  5111.       });
  5112.     };
  5113.     var toAbsolute = function (pos) {
  5114.       return pos.fold(identity$1, identity$1);
  5115.     };
  5116.     var sum = function (points) {
  5117.       return foldl(points, function (b, a) {
  5118.         return b.translate(a.left, a.top);
  5119.       }, SugarPosition(0, 0));
  5120.     };
  5121.     var sumAsFixed = function (positions) {
  5122.       var points = map$2(positions, toFixed);
  5123.       return sum(points);
  5124.     };
  5125.     var sumAsAbsolute = function (positions) {
  5126.       var points = map$2(positions, toAbsolute);
  5127.       return sum(points);
  5128.     };
  5129.     var screen = adt$7.screen;
  5130.     var absolute$1 = adt$7.absolute;
  5131.  
  5132.     var getOffset = function (component, origin, anchorInfo) {
  5133.       var win = defaultView(anchorInfo.root).dom;
  5134.       var hasSameOwner = function (frame) {
  5135.         var frameOwner = owner$4(frame);
  5136.         var compOwner = owner$4(component.element);
  5137.         return eq(frameOwner, compOwner);
  5138.       };
  5139.       return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
  5140.     };
  5141.     var getRootPoint = function (component, origin, anchorInfo) {
  5142.       var doc = owner$4(component.element);
  5143.       var outerScroll = get$9(doc);
  5144.       var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  5145.       return absolute$1(offset, outerScroll.left, outerScroll.top);
  5146.     };
  5147.  
  5148.     var getBox = function (left, top, width, height) {
  5149.       var point = screen(SugarPosition(left, top));
  5150.       return Optional.some(pointed(point, width, height));
  5151.     };
  5152.     var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  5153.       return optBox.map(function (box) {
  5154.         var points = [
  5155.           rootPoint,
  5156.           box.point
  5157.         ];
  5158.         var topLeft = cata$1(origin, function () {
  5159.           return sumAsAbsolute(points);
  5160.         }, function () {
  5161.           return sumAsAbsolute(points);
  5162.         }, function () {
  5163.           return sumAsFixed(points);
  5164.         });
  5165.         var anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height);
  5166.         var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  5167.         var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
  5168.         var layouts = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
  5169.         return nu$4({
  5170.           anchorBox: anchorBox,
  5171.           bubble: anchorInfo.bubble.getOr(fallback()),
  5172.           overrides: anchorInfo.overrides,
  5173.           layouts: layouts,
  5174.           placer: Optional.none()
  5175.         });
  5176.       });
  5177.     };
  5178.  
  5179.     var placement$2 = function (component, anchorInfo, origin) {
  5180.       var rootPoint = getRootPoint(component, origin, anchorInfo);
  5181.       return anchorInfo.node.filter(inBody).bind(function (target) {
  5182.         var rect = target.dom.getBoundingClientRect();
  5183.         var nodeBox = getBox(rect.left, rect.top, rect.width, rect.height);
  5184.         var elem = anchorInfo.node.getOr(component.element);
  5185.         return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5186.       });
  5187.     };
  5188.     var NodeAnchor = [
  5189.       required$1('node'),
  5190.       required$1('root'),
  5191.       option('bubble'),
  5192.       schema$y(),
  5193.       defaulted('overrides', {}),
  5194.       defaulted('showAbove', false),
  5195.       output$1('placement', placement$2)
  5196.     ];
  5197.  
  5198.     var zeroWidth = '\uFEFF';
  5199.     var nbsp = '\xA0';
  5200.  
  5201.     var create$7 = function (start, soffset, finish, foffset) {
  5202.       return {
  5203.         start: start,
  5204.         soffset: soffset,
  5205.         finish: finish,
  5206.         foffset: foffset
  5207.       };
  5208.     };
  5209.     var SimRange = { create: create$7 };
  5210.  
  5211.     var adt$6 = Adt.generate([
  5212.       { before: ['element'] },
  5213.       {
  5214.         on: [
  5215.           'element',
  5216.           'offset'
  5217.         ]
  5218.       },
  5219.       { after: ['element'] }
  5220.     ]);
  5221.     var cata = function (subject, onBefore, onOn, onAfter) {
  5222.       return subject.fold(onBefore, onOn, onAfter);
  5223.     };
  5224.     var getStart$1 = function (situ) {
  5225.       return situ.fold(identity$1, identity$1, identity$1);
  5226.     };
  5227.     var before = adt$6.before;
  5228.     var on$1 = adt$6.on;
  5229.     var after$1 = adt$6.after;
  5230.     var Situ = {
  5231.       before: before,
  5232.       on: on$1,
  5233.       after: after$1,
  5234.       cata: cata,
  5235.       getStart: getStart$1
  5236.     };
  5237.  
  5238.     var adt$5 = Adt.generate([
  5239.       { domRange: ['rng'] },
  5240.       {
  5241.         relative: [
  5242.           'startSitu',
  5243.           'finishSitu'
  5244.         ]
  5245.       },
  5246.       {
  5247.         exact: [
  5248.           'start',
  5249.           'soffset',
  5250.           'finish',
  5251.           'foffset'
  5252.         ]
  5253.       }
  5254.     ]);
  5255.     var exactFromRange = function (simRange) {
  5256.       return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  5257.     };
  5258.     var getStart = function (selection) {
  5259.       return selection.match({
  5260.         domRange: function (rng) {
  5261.           return SugarElement.fromDom(rng.startContainer);
  5262.         },
  5263.         relative: function (startSitu, _finishSitu) {
  5264.           return Situ.getStart(startSitu);
  5265.         },
  5266.         exact: function (start, _soffset, _finish, _foffset) {
  5267.           return start;
  5268.         }
  5269.       });
  5270.     };
  5271.     var domRange = adt$5.domRange;
  5272.     var relative = adt$5.relative;
  5273.     var exact = adt$5.exact;
  5274.     var getWin = function (selection) {
  5275.       var start = getStart(selection);
  5276.       return defaultView(start);
  5277.     };
  5278.     var range$1 = SimRange.create;
  5279.     var SimSelection = {
  5280.       domRange: domRange,
  5281.       relative: relative,
  5282.       exact: exact,
  5283.       exactFromRange: exactFromRange,
  5284.       getWin: getWin,
  5285.       range: range$1
  5286.     };
  5287.  
  5288.     var setStart = function (rng, situ) {
  5289.       situ.fold(function (e) {
  5290.         rng.setStartBefore(e.dom);
  5291.       }, function (e, o) {
  5292.         rng.setStart(e.dom, o);
  5293.       }, function (e) {
  5294.         rng.setStartAfter(e.dom);
  5295.       });
  5296.     };
  5297.     var setFinish = function (rng, situ) {
  5298.       situ.fold(function (e) {
  5299.         rng.setEndBefore(e.dom);
  5300.       }, function (e, o) {
  5301.         rng.setEnd(e.dom, o);
  5302.       }, function (e) {
  5303.         rng.setEndAfter(e.dom);
  5304.       });
  5305.     };
  5306.     var relativeToNative = function (win, startSitu, finishSitu) {
  5307.       var range = win.document.createRange();
  5308.       setStart(range, startSitu);
  5309.       setFinish(range, finishSitu);
  5310.       return range;
  5311.     };
  5312.     var exactToNative = function (win, start, soffset, finish, foffset) {
  5313.       var rng = win.document.createRange();
  5314.       rng.setStart(start.dom, soffset);
  5315.       rng.setEnd(finish.dom, foffset);
  5316.       return rng;
  5317.     };
  5318.     var toRect = function (rect) {
  5319.       return {
  5320.         left: rect.left,
  5321.         top: rect.top,
  5322.         right: rect.right,
  5323.         bottom: rect.bottom,
  5324.         width: rect.width,
  5325.         height: rect.height
  5326.       };
  5327.     };
  5328.     var getFirstRect$1 = function (rng) {
  5329.       var rects = rng.getClientRects();
  5330.       var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  5331.       return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5332.     };
  5333.     var getBounds$2 = function (rng) {
  5334.       var rect = rng.getBoundingClientRect();
  5335.       return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5336.     };
  5337.  
  5338.     var adt$4 = Adt.generate([
  5339.       {
  5340.         ltr: [
  5341.           'start',
  5342.           'soffset',
  5343.           'finish',
  5344.           'foffset'
  5345.         ]
  5346.       },
  5347.       {
  5348.         rtl: [
  5349.           'start',
  5350.           'soffset',
  5351.           'finish',
  5352.           'foffset'
  5353.         ]
  5354.       }
  5355.     ]);
  5356.     var fromRange = function (win, type, range) {
  5357.       return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  5358.     };
  5359.     var getRanges = function (win, selection) {
  5360.       return selection.match({
  5361.         domRange: function (rng) {
  5362.           return {
  5363.             ltr: constant$1(rng),
  5364.             rtl: Optional.none
  5365.           };
  5366.         },
  5367.         relative: function (startSitu, finishSitu) {
  5368.           return {
  5369.             ltr: cached(function () {
  5370.               return relativeToNative(win, startSitu, finishSitu);
  5371.             }),
  5372.             rtl: cached(function () {
  5373.               return Optional.some(relativeToNative(win, finishSitu, startSitu));
  5374.             })
  5375.           };
  5376.         },
  5377.         exact: function (start, soffset, finish, foffset) {
  5378.           return {
  5379.             ltr: cached(function () {
  5380.               return exactToNative(win, start, soffset, finish, foffset);
  5381.             }),
  5382.             rtl: cached(function () {
  5383.               return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  5384.             })
  5385.           };
  5386.         }
  5387.       });
  5388.     };
  5389.     var doDiagnose = function (win, ranges) {
  5390.       var rng = ranges.ltr();
  5391.       if (rng.collapsed) {
  5392.         var reversed = ranges.rtl().filter(function (rev) {
  5393.           return rev.collapsed === false;
  5394.         });
  5395.         return reversed.map(function (rev) {
  5396.           return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  5397.         }).getOrThunk(function () {
  5398.           return fromRange(win, adt$4.ltr, rng);
  5399.         });
  5400.       } else {
  5401.         return fromRange(win, adt$4.ltr, rng);
  5402.       }
  5403.     };
  5404.     var diagnose = function (win, selection) {
  5405.       var ranges = getRanges(win, selection);
  5406.       return doDiagnose(win, ranges);
  5407.     };
  5408.     var asLtrRange = function (win, selection) {
  5409.       var diagnosis = diagnose(win, selection);
  5410.       return diagnosis.match({
  5411.         ltr: function (start, soffset, finish, foffset) {
  5412.           var rng = win.document.createRange();
  5413.           rng.setStart(start.dom, soffset);
  5414.           rng.setEnd(finish.dom, foffset);
  5415.           return rng;
  5416.         },
  5417.         rtl: function (start, soffset, finish, foffset) {
  5418.           var rng = win.document.createRange();
  5419.           rng.setStart(finish.dom, foffset);
  5420.           rng.setEnd(start.dom, soffset);
  5421.           return rng;
  5422.         }
  5423.       });
  5424.     };
  5425.     adt$4.ltr;
  5426.     adt$4.rtl;
  5427.  
  5428.     var NodeValue = function (is, name) {
  5429.       var get = function (element) {
  5430.         if (!is(element)) {
  5431.           throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  5432.         }
  5433.         return getOption(element).getOr('');
  5434.       };
  5435.       var getOption = function (element) {
  5436.         return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  5437.       };
  5438.       var set = function (element, value) {
  5439.         if (!is(element)) {
  5440.           throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  5441.         }
  5442.         element.dom.nodeValue = value;
  5443.       };
  5444.       return {
  5445.         get: get,
  5446.         getOption: getOption,
  5447.         set: set
  5448.       };
  5449.     };
  5450.  
  5451.     var api = NodeValue(isText$1, 'text');
  5452.     var get$3 = function (element) {
  5453.       return api.get(element);
  5454.     };
  5455.     var getOption = function (element) {
  5456.       return api.getOption(element);
  5457.     };
  5458.  
  5459.     var getEnd = function (element) {
  5460.       return name$2(element) === 'img' ? 1 : getOption(element).fold(function () {
  5461.         return children(element).length;
  5462.       }, function (v) {
  5463.         return v.length;
  5464.       });
  5465.     };
  5466.     var isTextNodeWithCursorPosition = function (el) {
  5467.       return getOption(el).filter(function (text) {
  5468.         return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  5469.       }).isSome();
  5470.     };
  5471.     var elementsWithCursorPosition = [
  5472.       'img',
  5473.       'br'
  5474.     ];
  5475.     var isCursorPosition = function (elem) {
  5476.       var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  5477.       return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem));
  5478.     };
  5479.  
  5480.     var last$1 = function (element) {
  5481.       return descendantRtl(element, isCursorPosition);
  5482.     };
  5483.     var descendantRtl = function (scope, predicate) {
  5484.       var descend = function (element) {
  5485.         var children$1 = children(element);
  5486.         for (var i = children$1.length - 1; i >= 0; i--) {
  5487.           var child = children$1[i];
  5488.           if (predicate(child)) {
  5489.             return Optional.some(child);
  5490.           }
  5491.           var res = descend(child);
  5492.           if (res.isSome()) {
  5493.             return res;
  5494.           }
  5495.         }
  5496.         return Optional.none();
  5497.       };
  5498.       return descend(scope);
  5499.     };
  5500.  
  5501.     var descendants = function (scope, selector) {
  5502.       return all$3(selector, scope);
  5503.     };
  5504.  
  5505.     var makeRange = function (start, soffset, finish, foffset) {
  5506.       var doc = owner$4(start);
  5507.       var rng = doc.dom.createRange();
  5508.       rng.setStart(start.dom, soffset);
  5509.       rng.setEnd(finish.dom, foffset);
  5510.       return rng;
  5511.     };
  5512.     var after = function (start, soffset, finish, foffset) {
  5513.       var r = makeRange(start, soffset, finish, foffset);
  5514.       var same = eq(start, finish) && soffset === foffset;
  5515.       return r.collapsed && !same;
  5516.     };
  5517.  
  5518.     var getNativeSelection = function (win) {
  5519.       return Optional.from(win.getSelection());
  5520.     };
  5521.     var readRange = function (selection) {
  5522.       if (selection.rangeCount > 0) {
  5523.         var firstRng = selection.getRangeAt(0);
  5524.         var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  5525.         return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  5526.       } else {
  5527.         return Optional.none();
  5528.       }
  5529.     };
  5530.     var doGetExact = function (selection) {
  5531.       if (selection.anchorNode === null || selection.focusNode === null) {
  5532.         return readRange(selection);
  5533.       } else {
  5534.         var anchor = SugarElement.fromDom(selection.anchorNode);
  5535.         var focus_1 = SugarElement.fromDom(selection.focusNode);
  5536.         return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  5537.       }
  5538.     };
  5539.     var getExact = function (win) {
  5540.       return getNativeSelection(win).filter(function (sel) {
  5541.         return sel.rangeCount > 0;
  5542.       }).bind(doGetExact);
  5543.     };
  5544.     var getFirstRect = function (win, selection) {
  5545.       var rng = asLtrRange(win, selection);
  5546.       return getFirstRect$1(rng);
  5547.     };
  5548.     var getBounds$1 = function (win, selection) {
  5549.       var rng = asLtrRange(win, selection);
  5550.       return getBounds$2(rng);
  5551.     };
  5552.  
  5553.     var point$1 = function (element, offset) {
  5554.       return {
  5555.         element: element,
  5556.         offset: offset
  5557.       };
  5558.     };
  5559.     var descendOnce$1 = function (element, offset) {
  5560.       var children$1 = children(element);
  5561.       if (children$1.length === 0) {
  5562.         return point$1(element, offset);
  5563.       } else if (offset < children$1.length) {
  5564.         return point$1(children$1[offset], 0);
  5565.       } else {
  5566.         var last = children$1[children$1.length - 1];
  5567.         var len = isText$1(last) ? get$3(last).length : children(last).length;
  5568.         return point$1(last, len);
  5569.       }
  5570.     };
  5571.  
  5572.     var descendOnce = function (element, offset) {
  5573.       return isText$1(element) ? point$1(element, offset) : descendOnce$1(element, offset);
  5574.     };
  5575.     var getAnchorSelection = function (win, anchorInfo) {
  5576.       var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  5577.         return function () {
  5578.           return getExact(win);
  5579.         };
  5580.       });
  5581.       return getSelection().map(function (sel) {
  5582.         var modStart = descendOnce(sel.start, sel.soffset);
  5583.         var modFinish = descendOnce(sel.finish, sel.foffset);
  5584.         return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  5585.       });
  5586.     };
  5587.     var placement$1 = function (component, anchorInfo, origin) {
  5588.       var win = defaultView(anchorInfo.root).dom;
  5589.       var rootPoint = getRootPoint(component, origin, anchorInfo);
  5590.       var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5591.         var optRect = getBounds$1(win, SimSelection.exactFromRange(sel)).orThunk(function () {
  5592.           var x = SugarElement.fromText(zeroWidth);
  5593.           before$2(sel.start, x);
  5594.           var rect = getFirstRect(win, SimSelection.exact(x, 0, x, 1));
  5595.           remove$5(x);
  5596.           return rect;
  5597.         });
  5598.         return optRect.bind(function (rawRect) {
  5599.           return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
  5600.         });
  5601.       });
  5602.       var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5603.         return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
  5604.       });
  5605.       var elem = targetElement.getOr(component.element);
  5606.       return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  5607.     };
  5608.     var SelectionAnchor = [
  5609.       option('getSelection'),
  5610.       required$1('root'),
  5611.       option('bubble'),
  5612.       schema$y(),
  5613.       defaulted('overrides', {}),
  5614.       defaulted('showAbove', false),
  5615.       output$1('placement', placement$1)
  5616.     ];
  5617.  
  5618.     var labelPrefix$1 = 'link-layout';
  5619.     var eastX = function (anchor) {
  5620.       return anchor.x + anchor.width;
  5621.     };
  5622.     var westX = function (anchor, element) {
  5623.       return anchor.x - element.width;
  5624.     };
  5625.     var northY$1 = function (anchor, element) {
  5626.       return anchor.y - element.height + anchor.height;
  5627.     };
  5628.     var southY$1 = function (anchor) {
  5629.       return anchor.y;
  5630.     };
  5631.     var southeast$1 = function (anchor, element, bubbles) {
  5632.       return nu$6(eastX(anchor), southY$1(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  5633.         left: 0,
  5634.         top: 2
  5635.       }), labelPrefix$1);
  5636.     };
  5637.     var southwest$1 = function (anchor, element, bubbles) {
  5638.       return nu$6(westX(anchor, element), southY$1(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  5639.         right: 1,
  5640.         top: 2
  5641.       }), labelPrefix$1);
  5642.     };
  5643.     var northeast$1 = function (anchor, element, bubbles) {
  5644.       return nu$6(eastX(anchor), northY$1(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  5645.         left: 0,
  5646.         bottom: 3
  5647.       }), labelPrefix$1);
  5648.     };
  5649.     var northwest$1 = function (anchor, element, bubbles) {
  5650.       return nu$6(westX(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  5651.         right: 1,
  5652.         bottom: 3
  5653.       }), labelPrefix$1);
  5654.     };
  5655.     var all = function () {
  5656.       return [
  5657.         southeast$1,
  5658.         southwest$1,
  5659.         northeast$1,
  5660.         northwest$1
  5661.       ];
  5662.     };
  5663.     var allRtl = function () {
  5664.       return [
  5665.         southwest$1,
  5666.         southeast$1,
  5667.         northwest$1,
  5668.         northeast$1
  5669.       ];
  5670.     };
  5671.  
  5672.     var placement = function (component, submenuInfo, origin) {
  5673.       var anchorBox = toBox(origin, submenuInfo.item.element);
  5674.       var layouts = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
  5675.       return Optional.some(nu$4({
  5676.         anchorBox: anchorBox,
  5677.         bubble: fallback(),
  5678.         overrides: submenuInfo.overrides,
  5679.         layouts: layouts,
  5680.         placer: Optional.none()
  5681.       }));
  5682.     };
  5683.     var SubmenuAnchor = [
  5684.       required$1('item'),
  5685.       schema$y(),
  5686.       defaulted('overrides', {}),
  5687.       output$1('placement', placement)
  5688.     ];
  5689.  
  5690.     var AnchorSchema = choose$1('type', {
  5691.       selection: SelectionAnchor,
  5692.       node: NodeAnchor,
  5693.       hotspot: HotspotAnchor,
  5694.       submenu: SubmenuAnchor,
  5695.       makeshift: MakeshiftAnchor
  5696.     });
  5697.  
  5698.     var TransitionSchema = [
  5699.       requiredArrayOf('classes', string),
  5700.       defaultedStringEnum('mode', 'all', [
  5701.         'all',
  5702.         'layout',
  5703.         'placement'
  5704.       ])
  5705.     ];
  5706.     var PositionSchema = [
  5707.       defaulted('useFixed', never),
  5708.       option('getBounds')
  5709.     ];
  5710.     var PlacementSchema = [
  5711.       requiredOf('anchor', AnchorSchema),
  5712.       optionObjOf('transition', TransitionSchema)
  5713.     ];
  5714.  
  5715.     var getFixedOrigin = function () {
  5716.       var html = document.documentElement;
  5717.       return fixed$1(0, 0, html.clientWidth, html.clientHeight);
  5718.     };
  5719.     var getRelativeOrigin = function (component) {
  5720.       var position = absolute$3(component.element);
  5721.       var bounds = component.element.dom.getBoundingClientRect();
  5722.       return relative$1(position.left, position.top, bounds.width, bounds.height);
  5723.     };
  5724.     var place = function (component, origin, anchoring, getBounds, placee, lastPlace, transition) {
  5725.       var anchor = box(anchoring.anchorBox, origin);
  5726.       return simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds, anchoring.overrides, transition);
  5727.     };
  5728.     var position$1 = function (component, posConfig, posState, placee, placementSpec) {
  5729.       positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
  5730.     };
  5731.     var positionWithin = function (component, posConfig, posState, placee, placementSpec, boxElement) {
  5732.       var boundsBox = boxElement.map(box$1);
  5733.       return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
  5734.     };
  5735.     var positionWithinBounds = function (component, posConfig, posState, placee, placementSpec, bounds) {
  5736.       var placeeDetail = asRawOrDie$1('placement.info', objOf(PlacementSchema), placementSpec);
  5737.       var anchorage = placeeDetail.anchor;
  5738.       var element = placee.element;
  5739.       var placeeState = posState.get(placee.uid);
  5740.       preserve$1(function () {
  5741.         set$7(element, 'position', 'fixed');
  5742.         var oldVisibility = getRaw(element, 'visibility');
  5743.         set$7(element, 'visibility', 'hidden');
  5744.         var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5745.         var placer = anchorage.placement;
  5746.         var getBounds = bounds.map(constant$1).or(posConfig.getBounds);
  5747.         placer(component, anchorage, origin).each(function (anchoring) {
  5748.           var doPlace = anchoring.placer.getOr(place);
  5749.           var newState = doPlace(component, origin, anchoring, getBounds, placee, placeeState, placeeDetail.transition);
  5750.           posState.set(placee.uid, newState);
  5751.         });
  5752.         oldVisibility.fold(function () {
  5753.           remove$6(element, 'visibility');
  5754.         }, function (vis) {
  5755.           set$7(element, 'visibility', vis);
  5756.         });
  5757.         if (getRaw(element, 'left').isNone() && getRaw(element, 'top').isNone() && getRaw(element, 'right').isNone() && getRaw(element, 'bottom').isNone() && is$1(getRaw(element, 'position'), 'fixed')) {
  5758.           remove$6(element, 'position');
  5759.         }
  5760.       }, element);
  5761.     };
  5762.     var getMode = function (component, pConfig, _pState) {
  5763.       return pConfig.useFixed() ? 'fixed' : 'absolute';
  5764.     };
  5765.     var reset$1 = function (component, pConfig, posState, placee) {
  5766.       var element = placee.element;
  5767.       each$1([
  5768.         'position',
  5769.         'left',
  5770.         'right',
  5771.         'top',
  5772.         'bottom'
  5773.       ], function (prop) {
  5774.         return remove$6(element, prop);
  5775.       });
  5776.       reset$2(element);
  5777.       posState.clear(placee.uid);
  5778.     };
  5779.  
  5780.     var PositionApis = /*#__PURE__*/Object.freeze({
  5781.         __proto__: null,
  5782.         position: position$1,
  5783.         positionWithin: positionWithin,
  5784.         positionWithinBounds: positionWithinBounds,
  5785.         getMode: getMode,
  5786.         reset: reset$1
  5787.     });
  5788.  
  5789.     var init$g = function () {
  5790.       var state = {};
  5791.       var set = function (id, data) {
  5792.         state[id] = data;
  5793.       };
  5794.       var get = function (id) {
  5795.         return get$e(state, id);
  5796.       };
  5797.       var clear = function (id) {
  5798.         if (isNonNullable(id)) {
  5799.           delete state[id];
  5800.         } else {
  5801.           state = {};
  5802.         }
  5803.       };
  5804.       return nu$8({
  5805.         readState: function () {
  5806.           return state;
  5807.         },
  5808.         clear: clear,
  5809.         set: set,
  5810.         get: get
  5811.       });
  5812.     };
  5813.  
  5814.     var PositioningState = /*#__PURE__*/Object.freeze({
  5815.         __proto__: null,
  5816.         init: init$g
  5817.     });
  5818.  
  5819.     var Positioning = create$8({
  5820.       fields: PositionSchema,
  5821.       name: 'positioning',
  5822.       active: ActivePosition,
  5823.       apis: PositionApis,
  5824.       state: PositioningState
  5825.     });
  5826.  
  5827.     var fireDetaching = function (component) {
  5828.       emit(component, detachedFromDom());
  5829.       var children = component.components();
  5830.       each$1(children, fireDetaching);
  5831.     };
  5832.     var fireAttaching = function (component) {
  5833.       var children = component.components();
  5834.       each$1(children, fireAttaching);
  5835.       emit(component, attachedToDom());
  5836.     };
  5837.     var attach$1 = function (parent, child) {
  5838.       append$2(parent.element, child.element);
  5839.     };
  5840.     var detachChildren$1 = function (component) {
  5841.       each$1(component.components(), function (childComp) {
  5842.         return remove$5(childComp.element);
  5843.       });
  5844.       empty(component.element);
  5845.       component.syncComponents();
  5846.     };
  5847.     var replaceChildren = function (component, newChildren) {
  5848.       var subs = component.components();
  5849.       detachChildren$1(component);
  5850.       var deleted = difference(subs, newChildren);
  5851.       each$1(deleted, function (comp) {
  5852.         fireDetaching(comp);
  5853.         component.getSystem().removeFromWorld(comp);
  5854.       });
  5855.       each$1(newChildren, function (childComp) {
  5856.         if (!childComp.getSystem().isConnected()) {
  5857.           component.getSystem().addToWorld(childComp);
  5858.           attach$1(component, childComp);
  5859.           if (inBody(component.element)) {
  5860.             fireAttaching(childComp);
  5861.           }
  5862.         } else {
  5863.           attach$1(component, childComp);
  5864.         }
  5865.         component.syncComponents();
  5866.       });
  5867.     };
  5868.  
  5869.     var attach = function (parent, child) {
  5870.       attachWith(parent, child, append$2);
  5871.     };
  5872.     var attachWith = function (parent, child, insertion) {
  5873.       parent.getSystem().addToWorld(child);
  5874.       insertion(parent.element, child.element);
  5875.       if (inBody(parent.element)) {
  5876.         fireAttaching(child);
  5877.       }
  5878.       parent.syncComponents();
  5879.     };
  5880.     var doDetach = function (component) {
  5881.       fireDetaching(component);
  5882.       remove$5(component.element);
  5883.       component.getSystem().removeFromWorld(component);
  5884.     };
  5885.     var detach = function (component) {
  5886.       var parent$1 = parent(component.element).bind(function (p) {
  5887.         return component.getSystem().getByDom(p).toOptional();
  5888.       });
  5889.       doDetach(component);
  5890.       parent$1.each(function (p) {
  5891.         p.syncComponents();
  5892.       });
  5893.     };
  5894.     var detachChildren = function (component) {
  5895.       var subs = component.components();
  5896.       each$1(subs, doDetach);
  5897.       empty(component.element);
  5898.       component.syncComponents();
  5899.     };
  5900.     var attachSystem = function (element, guiSystem) {
  5901.       attachSystemWith(element, guiSystem, append$2);
  5902.     };
  5903.     var attachSystemAfter = function (element, guiSystem) {
  5904.       attachSystemWith(element, guiSystem, after$2);
  5905.     };
  5906.     var attachSystemWith = function (element, guiSystem, inserter) {
  5907.       inserter(element, guiSystem.element);
  5908.       var children$1 = children(guiSystem.element);
  5909.       each$1(children$1, function (child) {
  5910.         guiSystem.getByDom(child).each(fireAttaching);
  5911.       });
  5912.     };
  5913.     var detachSystem = function (guiSystem) {
  5914.       var children$1 = children(guiSystem.element);
  5915.       each$1(children$1, function (child) {
  5916.         guiSystem.getByDom(child).each(fireDetaching);
  5917.       });
  5918.       remove$5(guiSystem.element);
  5919.     };
  5920.  
  5921.     var rebuild = function (sandbox, sConfig, sState, data) {
  5922.       sState.get().each(function (_data) {
  5923.         detachChildren(sandbox);
  5924.       });
  5925.       var point = sConfig.getAttachPoint(sandbox);
  5926.       attach(point, sandbox);
  5927.       var built = sandbox.getSystem().build(data);
  5928.       attach(sandbox, built);
  5929.       sState.set(built);
  5930.       return built;
  5931.     };
  5932.     var open$1 = function (sandbox, sConfig, sState, data) {
  5933.       var newState = rebuild(sandbox, sConfig, sState, data);
  5934.       sConfig.onOpen(sandbox, newState);
  5935.       return newState;
  5936.     };
  5937.     var setContent = function (sandbox, sConfig, sState, data) {
  5938.       return sState.get().map(function () {
  5939.         return rebuild(sandbox, sConfig, sState, data);
  5940.       });
  5941.     };
  5942.     var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5943.       cloak(sandbox, sConfig);
  5944.       open$1(sandbox, sConfig, sState, data);
  5945.       transaction();
  5946.       decloak(sandbox, sConfig);
  5947.     };
  5948.     var close$1 = function (sandbox, sConfig, sState) {
  5949.       sState.get().each(function (data) {
  5950.         detachChildren(sandbox);
  5951.         detach(sandbox);
  5952.         sConfig.onClose(sandbox, data);
  5953.         sState.clear();
  5954.       });
  5955.     };
  5956.     var isOpen$1 = function (_sandbox, _sConfig, sState) {
  5957.       return sState.isOpen();
  5958.     };
  5959.     var isPartOf = function (sandbox, sConfig, sState, queryElem) {
  5960.       return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5961.         return sConfig.isPartOf(sandbox, data, queryElem);
  5962.       });
  5963.     };
  5964.     var getState$2 = function (_sandbox, _sConfig, sState) {
  5965.       return sState.get();
  5966.     };
  5967.     var store = function (sandbox, cssKey, attr, newValue) {
  5968.       getRaw(sandbox.element, cssKey).fold(function () {
  5969.         remove$7(sandbox.element, attr);
  5970.       }, function (v) {
  5971.         set$8(sandbox.element, attr, v);
  5972.       });
  5973.       set$7(sandbox.element, cssKey, newValue);
  5974.     };
  5975.     var restore = function (sandbox, cssKey, attr) {
  5976.       getOpt(sandbox.element, attr).fold(function () {
  5977.         return remove$6(sandbox.element, cssKey);
  5978.       }, function (oldValue) {
  5979.         return set$7(sandbox.element, cssKey, oldValue);
  5980.       });
  5981.     };
  5982.     var cloak = function (sandbox, sConfig, _sState) {
  5983.       var sink = sConfig.getAttachPoint(sandbox);
  5984.       set$7(sandbox.element, 'position', Positioning.getMode(sink));
  5985.       store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5986.     };
  5987.     var hasPosition = function (element) {
  5988.       return exists([
  5989.         'top',
  5990.         'left',
  5991.         'right',
  5992.         'bottom'
  5993.       ], function (pos) {
  5994.         return getRaw(element, pos).isSome();
  5995.       });
  5996.     };
  5997.     var decloak = function (sandbox, sConfig, _sState) {
  5998.       if (!hasPosition(sandbox.element)) {
  5999.         remove$6(sandbox.element, 'position');
  6000.       }
  6001.       restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  6002.     };
  6003.  
  6004.     var SandboxApis = /*#__PURE__*/Object.freeze({
  6005.         __proto__: null,
  6006.         cloak: cloak,
  6007.         decloak: decloak,
  6008.         open: open$1,
  6009.         openWhileCloaked: openWhileCloaked,
  6010.         close: close$1,
  6011.         isOpen: isOpen$1,
  6012.         isPartOf: isPartOf,
  6013.         getState: getState$2,
  6014.         setContent: setContent
  6015.     });
  6016.  
  6017.     var events$g = function (sandboxConfig, sandboxState) {
  6018.       return derive$2([run$1(sandboxClose(), function (sandbox, _simulatedEvent) {
  6019.           close$1(sandbox, sandboxConfig, sandboxState);
  6020.         })]);
  6021.     };
  6022.  
  6023.     var ActiveSandbox = /*#__PURE__*/Object.freeze({
  6024.         __proto__: null,
  6025.         events: events$g
  6026.     });
  6027.  
  6028.     var SandboxSchema = [
  6029.       onHandler('onOpen'),
  6030.       onHandler('onClose'),
  6031.       required$1('isPartOf'),
  6032.       required$1('getAttachPoint'),
  6033.       defaulted('cloakVisibilityAttr', 'data-precloak-visibility')
  6034.     ];
  6035.  
  6036.     var init$f = function () {
  6037.       var contents = value$1();
  6038.       var readState = constant$1('not-implemented');
  6039.       return nu$8({
  6040.         readState: readState,
  6041.         isOpen: contents.isSet,
  6042.         clear: contents.clear,
  6043.         set: contents.set,
  6044.         get: contents.get
  6045.       });
  6046.     };
  6047.  
  6048.     var SandboxState = /*#__PURE__*/Object.freeze({
  6049.         __proto__: null,
  6050.         init: init$f
  6051.     });
  6052.  
  6053.     var Sandboxing = create$8({
  6054.       fields: SandboxSchema,
  6055.       name: 'sandboxing',
  6056.       active: ActiveSandbox,
  6057.       apis: SandboxApis,
  6058.       state: SandboxState
  6059.     });
  6060.  
  6061.     var dismissPopups = constant$1('dismiss.popups');
  6062.     var repositionPopups = constant$1('reposition.popups');
  6063.     var mouseReleased = constant$1('mouse.released');
  6064.  
  6065.     var schema$x = objOfOnly([
  6066.       defaulted('isExtraPart', never),
  6067.       optionObjOf('fireEventInstead', [defaulted('event', dismissRequested())])
  6068.     ]);
  6069.     var receivingChannel$1 = function (rawSpec) {
  6070.       var _a;
  6071.       var detail = asRawOrDie$1('Dismissal', schema$x, rawSpec);
  6072.       return _a = {}, _a[dismissPopups()] = {
  6073.         schema: objOfOnly([required$1('target')]),
  6074.         onReceive: function (sandbox, data) {
  6075.           if (Sandboxing.isOpen(sandbox)) {
  6076.             var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  6077.             if (!isPart) {
  6078.               detail.fireEventInstead.fold(function () {
  6079.                 return Sandboxing.close(sandbox);
  6080.               }, function (fe) {
  6081.                 return emit(sandbox, fe.event);
  6082.               });
  6083.             }
  6084.           }
  6085.         }
  6086.       }, _a;
  6087.     };
  6088.  
  6089.     var schema$w = objOfOnly([
  6090.       optionObjOf('fireEventInstead', [defaulted('event', repositionRequested())]),
  6091.       requiredFunction('doReposition')
  6092.     ]);
  6093.     var receivingChannel = function (rawSpec) {
  6094.       var _a;
  6095.       var detail = asRawOrDie$1('Reposition', schema$w, rawSpec);
  6096.       return _a = {}, _a[repositionPopups()] = {
  6097.         onReceive: function (sandbox) {
  6098.           if (Sandboxing.isOpen(sandbox)) {
  6099.             detail.fireEventInstead.fold(function () {
  6100.               return detail.doReposition(sandbox);
  6101.             }, function (fe) {
  6102.               return emit(sandbox, fe.event);
  6103.             });
  6104.           }
  6105.         }
  6106.       }, _a;
  6107.     };
  6108.  
  6109.     var onLoad$5 = function (component, repConfig, repState) {
  6110.       repConfig.store.manager.onLoad(component, repConfig, repState);
  6111.     };
  6112.     var onUnload$2 = function (component, repConfig, repState) {
  6113.       repConfig.store.manager.onUnload(component, repConfig, repState);
  6114.     };
  6115.     var setValue$3 = function (component, repConfig, repState, data) {
  6116.       repConfig.store.manager.setValue(component, repConfig, repState, data);
  6117.     };
  6118.     var getValue$3 = function (component, repConfig, repState) {
  6119.       return repConfig.store.manager.getValue(component, repConfig, repState);
  6120.     };
  6121.     var getState$1 = function (component, repConfig, repState) {
  6122.       return repState;
  6123.     };
  6124.  
  6125.     var RepresentApis = /*#__PURE__*/Object.freeze({
  6126.         __proto__: null,
  6127.         onLoad: onLoad$5,
  6128.         onUnload: onUnload$2,
  6129.         setValue: setValue$3,
  6130.         getValue: getValue$3,
  6131.         getState: getState$1
  6132.     });
  6133.  
  6134.     var events$f = function (repConfig, repState) {
  6135.       var es = repConfig.resetOnDom ? [
  6136.         runOnAttached(function (comp, _se) {
  6137.           onLoad$5(comp, repConfig, repState);
  6138.         }),
  6139.         runOnDetached(function (comp, _se) {
  6140.           onUnload$2(comp, repConfig, repState);
  6141.         })
  6142.       ] : [loadEvent(repConfig, repState, onLoad$5)];
  6143.       return derive$2(es);
  6144.     };
  6145.  
  6146.     var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  6147.         __proto__: null,
  6148.         events: events$f
  6149.     });
  6150.  
  6151.     var memory$1 = function () {
  6152.       var data = Cell(null);
  6153.       var readState = function () {
  6154.         return {
  6155.           mode: 'memory',
  6156.           value: data.get()
  6157.         };
  6158.       };
  6159.       var isNotSet = function () {
  6160.         return data.get() === null;
  6161.       };
  6162.       var clear = function () {
  6163.         data.set(null);
  6164.       };
  6165.       return nu$8({
  6166.         set: data.set,
  6167.         get: data.get,
  6168.         isNotSet: isNotSet,
  6169.         clear: clear,
  6170.         readState: readState
  6171.       });
  6172.     };
  6173.     var manual = function () {
  6174.       var readState = noop;
  6175.       return nu$8({ readState: readState });
  6176.     };
  6177.     var dataset = function () {
  6178.       var dataByValue = Cell({});
  6179.       var dataByText = Cell({});
  6180.       var readState = function () {
  6181.         return {
  6182.           mode: 'dataset',
  6183.           dataByValue: dataByValue.get(),
  6184.           dataByText: dataByText.get()
  6185.         };
  6186.       };
  6187.       var clear = function () {
  6188.         dataByValue.set({});
  6189.         dataByText.set({});
  6190.       };
  6191.       var lookup = function (itemString) {
  6192.         return get$e(dataByValue.get(), itemString).orThunk(function () {
  6193.           return get$e(dataByText.get(), itemString);
  6194.         });
  6195.       };
  6196.       var update = function (items) {
  6197.         var currentDataByValue = dataByValue.get();
  6198.         var currentDataByText = dataByText.get();
  6199.         var newDataByValue = {};
  6200.         var newDataByText = {};
  6201.         each$1(items, function (item) {
  6202.           newDataByValue[item.value] = item;
  6203.           get$e(item, 'meta').each(function (meta) {
  6204.             get$e(meta, 'text').each(function (text) {
  6205.               newDataByText[text] = item;
  6206.             });
  6207.           });
  6208.         });
  6209.         dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  6210.         dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  6211.       };
  6212.       return nu$8({
  6213.         readState: readState,
  6214.         lookup: lookup,
  6215.         update: update,
  6216.         clear: clear
  6217.       });
  6218.     };
  6219.     var init$e = function (spec) {
  6220.       return spec.store.manager.state(spec);
  6221.     };
  6222.  
  6223.     var RepresentState = /*#__PURE__*/Object.freeze({
  6224.         __proto__: null,
  6225.         memory: memory$1,
  6226.         dataset: dataset,
  6227.         manual: manual,
  6228.         init: init$e
  6229.     });
  6230.  
  6231.     var setValue$2 = function (component, repConfig, repState, data) {
  6232.       var store = repConfig.store;
  6233.       repState.update([data]);
  6234.       store.setValue(component, data);
  6235.       repConfig.onSetValue(component, data);
  6236.     };
  6237.     var getValue$2 = function (component, repConfig, repState) {
  6238.       var store = repConfig.store;
  6239.       var key = store.getDataKey(component);
  6240.       return repState.lookup(key).getOrThunk(function () {
  6241.         return store.getFallbackEntry(key);
  6242.       });
  6243.     };
  6244.     var onLoad$4 = function (component, repConfig, repState) {
  6245.       var store = repConfig.store;
  6246.       store.initialValue.each(function (data) {
  6247.         setValue$2(component, repConfig, repState, data);
  6248.       });
  6249.     };
  6250.     var onUnload$1 = function (component, repConfig, repState) {
  6251.       repState.clear();
  6252.     };
  6253.     var DatasetStore = [
  6254.       option('initialValue'),
  6255.       required$1('getFallbackEntry'),
  6256.       required$1('getDataKey'),
  6257.       required$1('setValue'),
  6258.       output$1('manager', {
  6259.         setValue: setValue$2,
  6260.         getValue: getValue$2,
  6261.         onLoad: onLoad$4,
  6262.         onUnload: onUnload$1,
  6263.         state: dataset
  6264.       })
  6265.     ];
  6266.  
  6267.     var getValue$1 = function (component, repConfig, _repState) {
  6268.       return repConfig.store.getValue(component);
  6269.     };
  6270.     var setValue$1 = function (component, repConfig, _repState, data) {
  6271.       repConfig.store.setValue(component, data);
  6272.       repConfig.onSetValue(component, data);
  6273.     };
  6274.     var onLoad$3 = function (component, repConfig, _repState) {
  6275.       repConfig.store.initialValue.each(function (data) {
  6276.         repConfig.store.setValue(component, data);
  6277.       });
  6278.     };
  6279.     var ManualStore = [
  6280.       required$1('getValue'),
  6281.       defaulted('setValue', noop),
  6282.       option('initialValue'),
  6283.       output$1('manager', {
  6284.         setValue: setValue$1,
  6285.         getValue: getValue$1,
  6286.         onLoad: onLoad$3,
  6287.         onUnload: noop,
  6288.         state: NoState.init
  6289.       })
  6290.     ];
  6291.  
  6292.     var setValue = function (component, repConfig, repState, data) {
  6293.       repState.set(data);
  6294.       repConfig.onSetValue(component, data);
  6295.     };
  6296.     var getValue = function (component, repConfig, repState) {
  6297.       return repState.get();
  6298.     };
  6299.     var onLoad$2 = function (component, repConfig, repState) {
  6300.       repConfig.store.initialValue.each(function (initVal) {
  6301.         if (repState.isNotSet()) {
  6302.           repState.set(initVal);
  6303.         }
  6304.       });
  6305.     };
  6306.     var onUnload = function (component, repConfig, repState) {
  6307.       repState.clear();
  6308.     };
  6309.     var MemoryStore = [
  6310.       option('initialValue'),
  6311.       output$1('manager', {
  6312.         setValue: setValue,
  6313.         getValue: getValue,
  6314.         onLoad: onLoad$2,
  6315.         onUnload: onUnload,
  6316.         state: memory$1
  6317.       })
  6318.     ];
  6319.  
  6320.     var RepresentSchema = [
  6321.       defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  6322.         memory: MemoryStore,
  6323.         manual: ManualStore,
  6324.         dataset: DatasetStore
  6325.       })),
  6326.       onHandler('onSetValue'),
  6327.       defaulted('resetOnDom', false)
  6328.     ];
  6329.  
  6330.     var Representing = create$8({
  6331.       fields: RepresentSchema,
  6332.       name: 'representing',
  6333.       active: ActiveRepresenting,
  6334.       apis: RepresentApis,
  6335.       extra: {
  6336.         setValueFrom: function (component, source) {
  6337.           var value = Representing.getValue(source);
  6338.           Representing.setValue(component, value);
  6339.         }
  6340.       },
  6341.       state: RepresentState
  6342.     });
  6343.  
  6344.     var field = function (name, forbidden) {
  6345.       return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  6346.         return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  6347.       }).concat([customField('dump', identity$1)]));
  6348.     };
  6349.     var get$2 = function (data) {
  6350.       return data.dump;
  6351.     };
  6352.     var augment = function (data, original) {
  6353.       return __assign(__assign({}, derive$1(original)), data.dump);
  6354.     };
  6355.     var SketchBehaviours = {
  6356.       field: field,
  6357.       augment: augment,
  6358.       get: get$2
  6359.     };
  6360.  
  6361.     var _placeholder = 'placeholder';
  6362.     var adt$3 = Adt.generate([
  6363.       {
  6364.         single: [
  6365.           'required',
  6366.           'valueThunk'
  6367.         ]
  6368.       },
  6369.       {
  6370.         multiple: [
  6371.           'required',
  6372.           'valueThunks'
  6373.         ]
  6374.       }
  6375.     ]);
  6376.     var isSubstituted = function (spec) {
  6377.       return has$2(spec, 'uiType');
  6378.     };
  6379.     var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  6380.       if (owner.exists(function (o) {
  6381.           return o !== compSpec.owner;
  6382.         })) {
  6383.         return adt$3.single(true, constant$1(compSpec));
  6384.       }
  6385.       return get$e(placeholders, compSpec.name).fold(function () {
  6386.         throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  6387.       }, function (newSpec) {
  6388.         return newSpec.replace();
  6389.       });
  6390.     };
  6391.     var scan = function (owner, detail, compSpec, placeholders) {
  6392.       if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  6393.         return subPlaceholder(owner, detail, compSpec, placeholders);
  6394.       } else {
  6395.         return adt$3.single(false, constant$1(compSpec));
  6396.       }
  6397.     };
  6398.     var substitute = function (owner, detail, compSpec, placeholders) {
  6399.       var base = scan(owner, detail, compSpec, placeholders);
  6400.       return base.fold(function (req, valueThunk) {
  6401.         var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  6402.         var childSpecs = get$e(value, 'components').getOr([]);
  6403.         var substituted = bind$3(childSpecs, function (c) {
  6404.           return substitute(owner, detail, c, placeholders);
  6405.         });
  6406.         return [__assign(__assign({}, value), { components: substituted })];
  6407.       }, function (req, valuesThunk) {
  6408.         if (isSubstituted(compSpec)) {
  6409.           var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  6410.           var preprocessor = compSpec.validated.preprocess.getOr(identity$1);
  6411.           return preprocessor(values);
  6412.         } else {
  6413.           return valuesThunk(detail);
  6414.         }
  6415.       });
  6416.     };
  6417.     var substituteAll = function (owner, detail, components, placeholders) {
  6418.       return bind$3(components, function (c) {
  6419.         return substitute(owner, detail, c, placeholders);
  6420.       });
  6421.     };
  6422.     var oneReplace = function (label, replacements) {
  6423.       var called = false;
  6424.       var used = function () {
  6425.         return called;
  6426.       };
  6427.       var replace = function () {
  6428.         if (called) {
  6429.           throw new Error('Trying to use the same placeholder more than once: ' + label);
  6430.         }
  6431.         called = true;
  6432.         return replacements;
  6433.       };
  6434.       var required = function () {
  6435.         return replacements.fold(function (req, _) {
  6436.           return req;
  6437.         }, function (req, _) {
  6438.           return req;
  6439.         });
  6440.       };
  6441.       return {
  6442.         name: constant$1(label),
  6443.         required: required,
  6444.         used: used,
  6445.         replace: replace
  6446.       };
  6447.     };
  6448.     var substitutePlaces = function (owner, detail, components, placeholders) {
  6449.       var ps = map$1(placeholders, function (ph, name) {
  6450.         return oneReplace(name, ph);
  6451.       });
  6452.       var outcome = substituteAll(owner, detail, components, ps);
  6453.       each(ps, function (p) {
  6454.         if (p.used() === false && p.required()) {
  6455.           throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  6456.         }
  6457.       });
  6458.       return outcome;
  6459.     };
  6460.     var single$2 = adt$3.single;
  6461.     var multiple = adt$3.multiple;
  6462.     var placeholder = constant$1(_placeholder);
  6463.  
  6464.     var adt$2 = Adt.generate([
  6465.       { required: ['data'] },
  6466.       { external: ['data'] },
  6467.       { optional: ['data'] },
  6468.       { group: ['data'] }
  6469.     ]);
  6470.     var fFactory = defaulted('factory', { sketch: identity$1 });
  6471.     var fSchema = defaulted('schema', []);
  6472.     var fName = required$1('name');
  6473.     var fPname = field$1('pname', 'pname', defaultedThunk(function (typeSpec) {
  6474.       return '<alloy.' + generate$6(typeSpec.name) + '>';
  6475.     }), anyValue());
  6476.     var fGroupSchema = customField('schema', function () {
  6477.       return [option('preprocess')];
  6478.     });
  6479.     var fDefaults = defaulted('defaults', constant$1({}));
  6480.     var fOverrides = defaulted('overrides', constant$1({}));
  6481.     var requiredSpec = objOf([
  6482.       fFactory,
  6483.       fSchema,
  6484.       fName,
  6485.       fPname,
  6486.       fDefaults,
  6487.       fOverrides
  6488.     ]);
  6489.     var externalSpec = objOf([
  6490.       fFactory,
  6491.       fSchema,
  6492.       fName,
  6493.       fDefaults,
  6494.       fOverrides
  6495.     ]);
  6496.     var optionalSpec = objOf([
  6497.       fFactory,
  6498.       fSchema,
  6499.       fName,
  6500.       fPname,
  6501.       fDefaults,
  6502.       fOverrides
  6503.     ]);
  6504.     var groupSpec = objOf([
  6505.       fFactory,
  6506.       fGroupSchema,
  6507.       fName,
  6508.       required$1('unit'),
  6509.       fPname,
  6510.       fDefaults,
  6511.       fOverrides
  6512.     ]);
  6513.     var asNamedPart = function (part) {
  6514.       return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  6515.     };
  6516.     var name$1 = function (part) {
  6517.       var get = function (data) {
  6518.         return data.name;
  6519.       };
  6520.       return part.fold(get, get, get, get);
  6521.     };
  6522.     var asCommon = function (part) {
  6523.       return part.fold(identity$1, identity$1, identity$1, identity$1);
  6524.     };
  6525.     var convert = function (adtConstructor, partSchema) {
  6526.       return function (spec) {
  6527.         var data = asRawOrDie$1('Converting part type', partSchema, spec);
  6528.         return adtConstructor(data);
  6529.       };
  6530.     };
  6531.     var required = convert(adt$2.required, requiredSpec);
  6532.     var external$1 = convert(adt$2.external, externalSpec);
  6533.     var optional = convert(adt$2.optional, optionalSpec);
  6534.     var group = convert(adt$2.group, groupSpec);
  6535.     var original = constant$1('entirety');
  6536.  
  6537.     var PartType = /*#__PURE__*/Object.freeze({
  6538.         __proto__: null,
  6539.         required: required,
  6540.         external: external$1,
  6541.         optional: optional,
  6542.         group: group,
  6543.         asNamedPart: asNamedPart,
  6544.         name: name$1,
  6545.         asCommon: asCommon,
  6546.         original: original
  6547.     });
  6548.  
  6549.     var combine = function (detail, data, partSpec, partValidated) {
  6550.       return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  6551.     };
  6552.     var subs = function (owner, detail, parts) {
  6553.       var internals = {};
  6554.       var externals = {};
  6555.       each$1(parts, function (part) {
  6556.         part.fold(function (data) {
  6557.           internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  6558.             return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6559.           });
  6560.         }, function (data) {
  6561.           var partSpec = detail.parts[data.name];
  6562.           externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  6563.         }, function (data) {
  6564.           internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  6565.             return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6566.           });
  6567.         }, function (data) {
  6568.           internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  6569.             var units = detail[data.name];
  6570.             return map$2(units, function (u) {
  6571.               return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  6572.             });
  6573.           });
  6574.         });
  6575.       });
  6576.       return {
  6577.         internals: constant$1(internals),
  6578.         externals: constant$1(externals)
  6579.       };
  6580.     };
  6581.  
  6582.     var generate$3 = function (owner, parts) {
  6583.       var r = {};
  6584.       each$1(parts, function (part) {
  6585.         asNamedPart(part).each(function (np) {
  6586.           var g = doGenerateOne(owner, np.pname);
  6587.           r[np.name] = function (config) {
  6588.             var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  6589.             return __assign(__assign({}, g), {
  6590.               config: config,
  6591.               validated: validated
  6592.             });
  6593.           };
  6594.         });
  6595.       });
  6596.       return r;
  6597.     };
  6598.     var doGenerateOne = function (owner, pname) {
  6599.       return {
  6600.         uiType: placeholder(),
  6601.         owner: owner,
  6602.         name: pname
  6603.       };
  6604.     };
  6605.     var generateOne$1 = function (owner, pname, config) {
  6606.       return {
  6607.         uiType: placeholder(),
  6608.         owner: owner,
  6609.         name: pname,
  6610.         config: config,
  6611.         validated: {}
  6612.       };
  6613.     };
  6614.     var schemas = function (parts) {
  6615.       return bind$3(parts, function (part) {
  6616.         return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  6617.           return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  6618.         }).toArray();
  6619.       });
  6620.     };
  6621.     var names = function (parts) {
  6622.       return map$2(parts, name$1);
  6623.     };
  6624.     var substitutes = function (owner, detail, parts) {
  6625.       return subs(owner, detail, parts);
  6626.     };
  6627.     var components$1 = function (owner, detail, internals) {
  6628.       return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  6629.     };
  6630.     var getPart = function (component, detail, partKey) {
  6631.       var uid = detail.partUids[partKey];
  6632.       return component.getSystem().getByUid(uid).toOptional();
  6633.     };
  6634.     var getPartOrDie = function (component, detail, partKey) {
  6635.       return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  6636.     };
  6637.     var getParts = function (component, detail, partKeys) {
  6638.       var r = {};
  6639.       var uids = detail.partUids;
  6640.       var system = component.getSystem();
  6641.       each$1(partKeys, function (pk) {
  6642.         r[pk] = constant$1(system.getByUid(uids[pk]));
  6643.       });
  6644.       return r;
  6645.     };
  6646.     var getAllParts = function (component, detail) {
  6647.       var system = component.getSystem();
  6648.       return map$1(detail.partUids, function (pUid, _k) {
  6649.         return constant$1(system.getByUid(pUid));
  6650.       });
  6651.     };
  6652.     var getAllPartNames = function (detail) {
  6653.       return keys(detail.partUids);
  6654.     };
  6655.     var getPartsOrDie = function (component, detail, partKeys) {
  6656.       var r = {};
  6657.       var uids = detail.partUids;
  6658.       var system = component.getSystem();
  6659.       each$1(partKeys, function (pk) {
  6660.         r[pk] = constant$1(system.getByUid(uids[pk]).getOrDie());
  6661.       });
  6662.       return r;
  6663.     };
  6664.     var defaultUids = function (baseUid, partTypes) {
  6665.       var partNames = names(partTypes);
  6666.       return wrapAll(map$2(partNames, function (pn) {
  6667.         return {
  6668.           key: pn,
  6669.           value: baseUid + '-' + pn
  6670.         };
  6671.       }));
  6672.     };
  6673.     var defaultUidsSchema = function (partTypes) {
  6674.       return field$1('partUids', 'partUids', mergeWithThunk(function (spec) {
  6675.         return defaultUids(spec.uid, partTypes);
  6676.       }), anyValue());
  6677.     };
  6678.  
  6679.     var AlloyParts = /*#__PURE__*/Object.freeze({
  6680.         __proto__: null,
  6681.         generate: generate$3,
  6682.         generateOne: generateOne$1,
  6683.         schemas: schemas,
  6684.         names: names,
  6685.         substitutes: substitutes,
  6686.         components: components$1,
  6687.         defaultUids: defaultUids,
  6688.         defaultUidsSchema: defaultUidsSchema,
  6689.         getAllParts: getAllParts,
  6690.         getAllPartNames: getAllPartNames,
  6691.         getPart: getPart,
  6692.         getPartOrDie: getPartOrDie,
  6693.         getParts: getParts,
  6694.         getPartsOrDie: getPartsOrDie
  6695.     });
  6696.  
  6697.     var base = function (partSchemas, partUidsSchemas) {
  6698.       var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  6699.       return ps.concat([
  6700.         required$1('uid'),
  6701.         defaulted('dom', {}),
  6702.         defaulted('components', []),
  6703.         snapshot('originalSpec'),
  6704.         defaulted('debug.sketcher', {})
  6705.       ]).concat(partUidsSchemas);
  6706.     };
  6707.     var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6708.       var baseS = base(partSchemas, partUidsSchemas);
  6709.       return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6710.     };
  6711.  
  6712.     var single$1 = function (owner, schema, factory, spec) {
  6713.       var specWithUid = supplyUid(spec);
  6714.       var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  6715.       return factory(detail, specWithUid);
  6716.     };
  6717.     var composite$1 = function (owner, schema, partTypes, factory, spec) {
  6718.       var specWithUid = supplyUid(spec);
  6719.       var partSchemas = schemas(partTypes);
  6720.       var partUidsSchema = defaultUidsSchema(partTypes);
  6721.       var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6722.       var subs = substitutes(owner, detail, partTypes);
  6723.       var components = components$1(owner, detail, subs.internals());
  6724.       return factory(detail, components, specWithUid, subs.externals());
  6725.     };
  6726.     var hasUid = function (spec) {
  6727.       return has$2(spec, 'uid');
  6728.     };
  6729.     var supplyUid = function (spec) {
  6730.       return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5('uid') });
  6731.     };
  6732.  
  6733.     var isSketchSpec = function (spec) {
  6734.       return spec.uid !== undefined;
  6735.     };
  6736.     var singleSchema = objOfOnly([
  6737.       required$1('name'),
  6738.       required$1('factory'),
  6739.       required$1('configFields'),
  6740.       defaulted('apis', {}),
  6741.       defaulted('extraApis', {})
  6742.     ]);
  6743.     var compositeSchema = objOfOnly([
  6744.       required$1('name'),
  6745.       required$1('factory'),
  6746.       required$1('configFields'),
  6747.       required$1('partFields'),
  6748.       defaulted('apis', {}),
  6749.       defaulted('extraApis', {})
  6750.     ]);
  6751.     var single = function (rawConfig) {
  6752.       var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6753.       var sketch = function (spec) {
  6754.         return single$1(config.name, config.configFields, config.factory, spec);
  6755.       };
  6756.       var apis = map$1(config.apis, makeApi);
  6757.       var extraApis = map$1(config.extraApis, function (f, k) {
  6758.         return markAsExtraApi(f, k);
  6759.       });
  6760.       return __assign(__assign({
  6761.         name: config.name,
  6762.         configFields: config.configFields,
  6763.         sketch: sketch
  6764.       }, apis), extraApis);
  6765.     };
  6766.     var composite = function (rawConfig) {
  6767.       var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6768.       var sketch = function (spec) {
  6769.         return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  6770.       };
  6771.       var parts = generate$3(config.name, config.partFields);
  6772.       var apis = map$1(config.apis, makeApi);
  6773.       var extraApis = map$1(config.extraApis, function (f, k) {
  6774.         return markAsExtraApi(f, k);
  6775.       });
  6776.       return __assign(__assign({
  6777.         name: config.name,
  6778.         partFields: config.partFields,
  6779.         configFields: config.configFields,
  6780.         sketch: sketch,
  6781.         parts: parts
  6782.       }, apis), extraApis);
  6783.     };
  6784.  
  6785.     var inside = function (target) {
  6786.       return name$2(target) === 'input' && get$d(target, 'type') !== 'radio' || name$2(target) === 'textarea';
  6787.     };
  6788.  
  6789.     var getCurrent = function (component, composeConfig, _composeState) {
  6790.       return composeConfig.find(component);
  6791.     };
  6792.  
  6793.     var ComposeApis = /*#__PURE__*/Object.freeze({
  6794.         __proto__: null,
  6795.         getCurrent: getCurrent
  6796.     });
  6797.  
  6798.     var ComposeSchema = [required$1('find')];
  6799.  
  6800.     var Composing = create$8({
  6801.       fields: ComposeSchema,
  6802.       name: 'composing',
  6803.       apis: ComposeApis
  6804.     });
  6805.  
  6806.     var nativeDisabled = [
  6807.       'input',
  6808.       'button',
  6809.       'textarea',
  6810.       'select'
  6811.     ];
  6812.     var onLoad$1 = function (component, disableConfig, disableState) {
  6813.       var f = disableConfig.disabled() ? disable$1 : enable$1;
  6814.       f(component, disableConfig);
  6815.     };
  6816.     var hasNative = function (component, config) {
  6817.       return config.useNative === true && contains$2(nativeDisabled, name$2(component.element));
  6818.     };
  6819.     var nativeIsDisabled = function (component) {
  6820.       return has$1(component.element, 'disabled');
  6821.     };
  6822.     var nativeDisable = function (component) {
  6823.       set$8(component.element, 'disabled', 'disabled');
  6824.     };
  6825.     var nativeEnable = function (component) {
  6826.       remove$7(component.element, 'disabled');
  6827.     };
  6828.     var ariaIsDisabled = function (component) {
  6829.       return get$d(component.element, 'aria-disabled') === 'true';
  6830.     };
  6831.     var ariaDisable = function (component) {
  6832.       set$8(component.element, 'aria-disabled', 'true');
  6833.     };
  6834.     var ariaEnable = function (component) {
  6835.       set$8(component.element, 'aria-disabled', 'false');
  6836.     };
  6837.     var disable$1 = function (component, disableConfig, _disableState) {
  6838.       disableConfig.disableClass.each(function (disableClass) {
  6839.         add$2(component.element, disableClass);
  6840.       });
  6841.       var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6842.       f(component);
  6843.       disableConfig.onDisabled(component);
  6844.     };
  6845.     var enable$1 = function (component, disableConfig, _disableState) {
  6846.       disableConfig.disableClass.each(function (disableClass) {
  6847.         remove$2(component.element, disableClass);
  6848.       });
  6849.       var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6850.       f(component);
  6851.       disableConfig.onEnabled(component);
  6852.     };
  6853.     var isDisabled = function (component, disableConfig) {
  6854.       return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6855.     };
  6856.     var set$3 = function (component, disableConfig, disableState, disabled) {
  6857.       var f = disabled ? disable$1 : enable$1;
  6858.       f(component, disableConfig);
  6859.     };
  6860.  
  6861.     var DisableApis = /*#__PURE__*/Object.freeze({
  6862.         __proto__: null,
  6863.         enable: enable$1,
  6864.         disable: disable$1,
  6865.         isDisabled: isDisabled,
  6866.         onLoad: onLoad$1,
  6867.         set: set$3
  6868.     });
  6869.  
  6870.     var exhibit$5 = function (base, disableConfig) {
  6871.       return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6872.     };
  6873.     var events$e = function (disableConfig, disableState) {
  6874.       return derive$2([
  6875.         abort(execute$5(), function (component, _simulatedEvent) {
  6876.           return isDisabled(component, disableConfig);
  6877.         }),
  6878.         loadEvent(disableConfig, disableState, onLoad$1)
  6879.       ]);
  6880.     };
  6881.  
  6882.     var ActiveDisable = /*#__PURE__*/Object.freeze({
  6883.         __proto__: null,
  6884.         exhibit: exhibit$5,
  6885.         events: events$e
  6886.     });
  6887.  
  6888.     var DisableSchema = [
  6889.       defaultedFunction('disabled', never),
  6890.       defaulted('useNative', true),
  6891.       option('disableClass'),
  6892.       onHandler('onDisabled'),
  6893.       onHandler('onEnabled')
  6894.     ];
  6895.  
  6896.     var Disabling = create$8({
  6897.       fields: DisableSchema,
  6898.       name: 'disabling',
  6899.       active: ActiveDisable,
  6900.       apis: DisableApis
  6901.     });
  6902.  
  6903.     var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6904.       var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  6905.       each$1(highlighted, function (h) {
  6906.         if (!exists(skip, function (skipComp) {
  6907.             return skipComp.element === h;
  6908.           })) {
  6909.           remove$2(h, hConfig.highlightClass);
  6910.           component.getSystem().getByDom(h).each(function (target) {
  6911.             hConfig.onDehighlight(component, target);
  6912.             emit(target, dehighlight$1());
  6913.           });
  6914.         }
  6915.       });
  6916.     };
  6917.     var dehighlightAll = function (component, hConfig, hState) {
  6918.       return dehighlightAllExcept(component, hConfig, hState, []);
  6919.     };
  6920.     var dehighlight = function (component, hConfig, hState, target) {
  6921.       if (isHighlighted(component, hConfig, hState, target)) {
  6922.         remove$2(target.element, hConfig.highlightClass);
  6923.         hConfig.onDehighlight(component, target);
  6924.         emit(target, dehighlight$1());
  6925.       }
  6926.     };
  6927.     var highlight = function (component, hConfig, hState, target) {
  6928.       dehighlightAllExcept(component, hConfig, hState, [target]);
  6929.       if (!isHighlighted(component, hConfig, hState, target)) {
  6930.         add$2(target.element, hConfig.highlightClass);
  6931.         hConfig.onHighlight(component, target);
  6932.         emit(target, highlight$1());
  6933.       }
  6934.     };
  6935.     var highlightFirst = function (component, hConfig, hState) {
  6936.       getFirst(component, hConfig).each(function (firstComp) {
  6937.         highlight(component, hConfig, hState, firstComp);
  6938.       });
  6939.     };
  6940.     var highlightLast = function (component, hConfig, hState) {
  6941.       getLast(component, hConfig).each(function (lastComp) {
  6942.         highlight(component, hConfig, hState, lastComp);
  6943.       });
  6944.     };
  6945.     var highlightAt = function (component, hConfig, hState, index) {
  6946.       getByIndex(component, hConfig, hState, index).fold(function (err) {
  6947.         throw err;
  6948.       }, function (firstComp) {
  6949.         highlight(component, hConfig, hState, firstComp);
  6950.       });
  6951.     };
  6952.     var highlightBy = function (component, hConfig, hState, predicate) {
  6953.       var candidates = getCandidates(component, hConfig);
  6954.       var targetComp = find$5(candidates, predicate);
  6955.       targetComp.each(function (c) {
  6956.         highlight(component, hConfig, hState, c);
  6957.       });
  6958.     };
  6959.     var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6960.       return has(queryTarget.element, hConfig.highlightClass);
  6961.     };
  6962.     var getHighlighted = function (component, hConfig, _hState) {
  6963.       return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  6964.         return component.getSystem().getByDom(e).toOptional();
  6965.       });
  6966.     };
  6967.     var getByIndex = function (component, hConfig, hState, index) {
  6968.       var items = descendants(component.element, '.' + hConfig.itemClass);
  6969.       return Optional.from(items[index]).fold(function () {
  6970.         return Result.error(new Error('No element found with index ' + index));
  6971.       }, component.getSystem().getByDom);
  6972.     };
  6973.     var getFirst = function (component, hConfig, _hState) {
  6974.       return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  6975.         return component.getSystem().getByDom(e).toOptional();
  6976.       });
  6977.     };
  6978.     var getLast = function (component, hConfig, _hState) {
  6979.       var items = descendants(component.element, '.' + hConfig.itemClass);
  6980.       var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  6981.       return last.bind(function (c) {
  6982.         return component.getSystem().getByDom(c).toOptional();
  6983.       });
  6984.     };
  6985.     var getDelta$2 = function (component, hConfig, hState, delta) {
  6986.       var items = descendants(component.element, '.' + hConfig.itemClass);
  6987.       var current = findIndex$1(items, function (item) {
  6988.         return has(item, hConfig.highlightClass);
  6989.       });
  6990.       return current.bind(function (selected) {
  6991.         var dest = cycleBy(selected, delta, 0, items.length - 1);
  6992.         return component.getSystem().getByDom(items[dest]).toOptional();
  6993.       });
  6994.     };
  6995.     var getPrevious = function (component, hConfig, hState) {
  6996.       return getDelta$2(component, hConfig, hState, -1);
  6997.     };
  6998.     var getNext = function (component, hConfig, hState) {
  6999.       return getDelta$2(component, hConfig, hState, +1);
  7000.     };
  7001.     var getCandidates = function (component, hConfig, _hState) {
  7002.       var items = descendants(component.element, '.' + hConfig.itemClass);
  7003.       return cat(map$2(items, function (i) {
  7004.         return component.getSystem().getByDom(i).toOptional();
  7005.       }));
  7006.     };
  7007.  
  7008.     var HighlightApis = /*#__PURE__*/Object.freeze({
  7009.         __proto__: null,
  7010.         dehighlightAll: dehighlightAll,
  7011.         dehighlight: dehighlight,
  7012.         highlight: highlight,
  7013.         highlightFirst: highlightFirst,
  7014.         highlightLast: highlightLast,
  7015.         highlightAt: highlightAt,
  7016.         highlightBy: highlightBy,
  7017.         isHighlighted: isHighlighted,
  7018.         getHighlighted: getHighlighted,
  7019.         getFirst: getFirst,
  7020.         getLast: getLast,
  7021.         getPrevious: getPrevious,
  7022.         getNext: getNext,
  7023.         getCandidates: getCandidates
  7024.     });
  7025.  
  7026.     var HighlightSchema = [
  7027.       required$1('highlightClass'),
  7028.       required$1('itemClass'),
  7029.       onHandler('onHighlight'),
  7030.       onHandler('onDehighlight')
  7031.     ];
  7032.  
  7033.     var Highlighting = create$8({
  7034.       fields: HighlightSchema,
  7035.       name: 'highlighting',
  7036.       apis: HighlightApis
  7037.     });
  7038.  
  7039.     var BACKSPACE = [8];
  7040.     var TAB = [9];
  7041.     var ENTER = [13];
  7042.     var ESCAPE = [27];
  7043.     var SPACE = [32];
  7044.     var LEFT = [37];
  7045.     var UP = [38];
  7046.     var RIGHT = [39];
  7047.     var DOWN = [40];
  7048.  
  7049.     var cyclePrev = function (values, index, predicate) {
  7050.       var before = reverse(values.slice(0, index));
  7051.       var after = reverse(values.slice(index + 1));
  7052.       return find$5(before.concat(after), predicate);
  7053.     };
  7054.     var tryPrev = function (values, index, predicate) {
  7055.       var before = reverse(values.slice(0, index));
  7056.       return find$5(before, predicate);
  7057.     };
  7058.     var cycleNext = function (values, index, predicate) {
  7059.       var before = values.slice(0, index);
  7060.       var after = values.slice(index + 1);
  7061.       return find$5(after.concat(before), predicate);
  7062.     };
  7063.     var tryNext = function (values, index, predicate) {
  7064.       var after = values.slice(index + 1);
  7065.       return find$5(after, predicate);
  7066.     };
  7067.  
  7068.     var inSet = function (keys) {
  7069.       return function (event) {
  7070.         var raw = event.raw;
  7071.         return contains$2(keys, raw.which);
  7072.       };
  7073.     };
  7074.     var and = function (preds) {
  7075.       return function (event) {
  7076.         return forall(preds, function (pred) {
  7077.           return pred(event);
  7078.         });
  7079.       };
  7080.     };
  7081.     var isShift = function (event) {
  7082.       var raw = event.raw;
  7083.       return raw.shiftKey === true;
  7084.     };
  7085.     var isControl = function (event) {
  7086.       var raw = event.raw;
  7087.       return raw.ctrlKey === true;
  7088.     };
  7089.     var isNotShift = not(isShift);
  7090.  
  7091.     var rule = function (matches, action) {
  7092.       return {
  7093.         matches: matches,
  7094.         classification: action
  7095.       };
  7096.     };
  7097.     var choose = function (transitions, event) {
  7098.       var transition = find$5(transitions, function (t) {
  7099.         return t.matches(event);
  7100.       });
  7101.       return transition.map(function (t) {
  7102.         return t.classification;
  7103.       });
  7104.     };
  7105.  
  7106.     var reportFocusShifting = function (component, prevFocus, newFocus) {
  7107.       var noChange = prevFocus.exists(function (p) {
  7108.         return newFocus.exists(function (n) {
  7109.           return eq(n, p);
  7110.         });
  7111.       });
  7112.       if (!noChange) {
  7113.         emitWith(component, focusShifted(), {
  7114.           prevFocus: prevFocus,
  7115.           newFocus: newFocus
  7116.         });
  7117.       }
  7118.     };
  7119.     var dom$2 = function () {
  7120.       var get = function (component) {
  7121.         return search(component.element);
  7122.       };
  7123.       var set = function (component, focusee) {
  7124.         var prevFocus = get(component);
  7125.         component.getSystem().triggerFocus(focusee, component.element);
  7126.         var newFocus = get(component);
  7127.         reportFocusShifting(component, prevFocus, newFocus);
  7128.       };
  7129.       return {
  7130.         get: get,
  7131.         set: set
  7132.       };
  7133.     };
  7134.     var highlights = function () {
  7135.       var get = function (component) {
  7136.         return Highlighting.getHighlighted(component).map(function (item) {
  7137.           return item.element;
  7138.         });
  7139.       };
  7140.       var set = function (component, element) {
  7141.         var prevFocus = get(component);
  7142.         component.getSystem().getByDom(element).fold(noop, function (item) {
  7143.           Highlighting.highlight(component, item);
  7144.         });
  7145.         var newFocus = get(component);
  7146.         reportFocusShifting(component, prevFocus, newFocus);
  7147.       };
  7148.       return {
  7149.         get: get,
  7150.         set: set
  7151.       };
  7152.     };
  7153.  
  7154.     var FocusInsideModes;
  7155.     (function (FocusInsideModes) {
  7156.       FocusInsideModes['OnFocusMode'] = 'onFocus';
  7157.       FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  7158.       FocusInsideModes['OnApiMode'] = 'onApi';
  7159.     }(FocusInsideModes || (FocusInsideModes = {})));
  7160.  
  7161.     var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  7162.       var schema = function () {
  7163.         return infoSchema.concat([
  7164.           defaulted('focusManager', dom$2()),
  7165.           defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  7166.             return contains$2([
  7167.               'onFocus',
  7168.               'onEnterOrSpace',
  7169.               'onApi'
  7170.             ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  7171.           })),
  7172.           output$1('handler', me),
  7173.           output$1('state', stateInit),
  7174.           output$1('sendFocusIn', optFocusIn)
  7175.         ]);
  7176.       };
  7177.       var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  7178.         var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  7179.         return choose(rules, simulatedEvent.event).bind(function (rule) {
  7180.           return rule(component, simulatedEvent, keyingConfig, keyingState);
  7181.         });
  7182.       };
  7183.       var toEvents = function (keyingConfig, keyingState) {
  7184.         var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  7185.           return run$1(focus$4(), function (component, simulatedEvent) {
  7186.             focusIn(component, keyingConfig, keyingState);
  7187.             simulatedEvent.stop();
  7188.           });
  7189.         });
  7190.         var tryGoInsideComponent = function (component, simulatedEvent) {
  7191.           var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  7192.           if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  7193.             optFocusIn(keyingConfig).each(function (focusIn) {
  7194.               focusIn(component, keyingConfig, keyingState);
  7195.               simulatedEvent.stop();
  7196.             });
  7197.           }
  7198.         };
  7199.         var keyboardEvents = [
  7200.           run$1(keydown(), function (component, simulatedEvent) {
  7201.             processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  7202.               tryGoInsideComponent(component, simulatedEvent);
  7203.             }, function (_) {
  7204.               simulatedEvent.stop();
  7205.             });
  7206.           }),
  7207.           run$1(keyup(), function (component, simulatedEvent) {
  7208.             processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  7209.               simulatedEvent.stop();
  7210.             });
  7211.           })
  7212.         ];
  7213.         return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
  7214.       };
  7215.       var me = {
  7216.         schema: schema,
  7217.         processKey: processKey,
  7218.         toEvents: toEvents
  7219.       };
  7220.       return me;
  7221.     };
  7222.  
  7223.     var create$6 = function (cyclicField) {
  7224.       var schema = [
  7225.         option('onEscape'),
  7226.         option('onEnter'),
  7227.         defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  7228.         defaulted('firstTabstop', 0),
  7229.         defaulted('useTabstopAt', always),
  7230.         option('visibilitySelector')
  7231.       ].concat([cyclicField]);
  7232.       var isVisible = function (tabbingConfig, element) {
  7233.         var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  7234.           return closest$1(element, sel);
  7235.         }).getOr(element);
  7236.         return get$b(target) > 0;
  7237.       };
  7238.       var findInitial = function (component, tabbingConfig) {
  7239.         var tabstops = descendants(component.element, tabbingConfig.selector);
  7240.         var visibles = filter$2(tabstops, function (elem) {
  7241.           return isVisible(tabbingConfig, elem);
  7242.         });
  7243.         return Optional.from(visibles[tabbingConfig.firstTabstop]);
  7244.       };
  7245.       var findCurrent = function (component, tabbingConfig) {
  7246.         return tabbingConfig.focusManager.get(component).bind(function (elem) {
  7247.           return closest$1(elem, tabbingConfig.selector);
  7248.         });
  7249.       };
  7250.       var isTabstop = function (tabbingConfig, element) {
  7251.         return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  7252.       };
  7253.       var focusIn = function (component, tabbingConfig, _tabbingState) {
  7254.         findInitial(component, tabbingConfig).each(function (target) {
  7255.           tabbingConfig.focusManager.set(component, target);
  7256.         });
  7257.       };
  7258.       var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  7259.         return cycle(tabstops, stopIndex, function (elem) {
  7260.           return isTabstop(tabbingConfig, elem);
  7261.         }).fold(function () {
  7262.           return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  7263.         }, function (target) {
  7264.           tabbingConfig.focusManager.set(component, target);
  7265.           return Optional.some(true);
  7266.         });
  7267.       };
  7268.       var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  7269.         var tabstops = descendants(component.element, tabbingConfig.selector);
  7270.         return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  7271.           var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  7272.           return optStopIndex.bind(function (stopIndex) {
  7273.             return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  7274.           });
  7275.         });
  7276.       };
  7277.       var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  7278.         var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  7279.         return go(component, simulatedEvent, tabbingConfig, navigate);
  7280.       };
  7281.       var goForwards = function (component, simulatedEvent, tabbingConfig) {
  7282.         var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  7283.         return go(component, simulatedEvent, tabbingConfig, navigate);
  7284.       };
  7285.       var execute = function (component, simulatedEvent, tabbingConfig) {
  7286.         return tabbingConfig.onEnter.bind(function (f) {
  7287.           return f(component, simulatedEvent);
  7288.         });
  7289.       };
  7290.       var exit = function (component, simulatedEvent, tabbingConfig) {
  7291.         return tabbingConfig.onEscape.bind(function (f) {
  7292.           return f(component, simulatedEvent);
  7293.         });
  7294.       };
  7295.       var getKeydownRules = constant$1([
  7296.         rule(and([
  7297.           isShift,
  7298.           inSet(TAB)
  7299.         ]), goBackwards),
  7300.         rule(inSet(TAB), goForwards),
  7301.         rule(inSet(ESCAPE), exit),
  7302.         rule(and([
  7303.           isNotShift,
  7304.           inSet(ENTER)
  7305.         ]), execute)
  7306.       ]);
  7307.       var getKeyupRules = constant$1([]);
  7308.       return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  7309.         return Optional.some(focusIn);
  7310.       });
  7311.     };
  7312.  
  7313.     var AcyclicType = create$6(customField('cyclic', never));
  7314.  
  7315.     var CyclicType = create$6(customField('cyclic', always));
  7316.  
  7317.     var doDefaultExecute = function (component, _simulatedEvent, focused) {
  7318.       dispatch(component, focused, execute$5());
  7319.       return Optional.some(true);
  7320.     };
  7321.     var defaultExecute = function (component, simulatedEvent, focused) {
  7322.       var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  7323.       return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  7324.     };
  7325.     var stopEventForFirefox = function (_component, _simulatedEvent) {
  7326.       return Optional.some(true);
  7327.     };
  7328.  
  7329.     var schema$v = [
  7330.       defaulted('execute', defaultExecute),
  7331.       defaulted('useSpace', false),
  7332.       defaulted('useEnter', true),
  7333.       defaulted('useControlEnter', false),
  7334.       defaulted('useDown', false)
  7335.     ];
  7336.     var execute$4 = function (component, simulatedEvent, executeConfig) {
  7337.       return executeConfig.execute(component, simulatedEvent, component.element);
  7338.     };
  7339.     var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7340.       var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  7341.       var enterExec = executeConfig.useEnter ? ENTER : [];
  7342.       var downExec = executeConfig.useDown ? DOWN : [];
  7343.       var execKeys = spaceExec.concat(enterExec).concat(downExec);
  7344.       return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  7345.           isControl,
  7346.           inSet(ENTER)
  7347.         ]), execute$4)] : []);
  7348.     };
  7349.     var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7350.       return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7351.     };
  7352.     var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  7353.       return Optional.none();
  7354.     });
  7355.  
  7356.     var flatgrid$1 = function () {
  7357.       var dimensions = value$1();
  7358.       var setGridSize = function (numRows, numColumns) {
  7359.         dimensions.set({
  7360.           numRows: numRows,
  7361.           numColumns: numColumns
  7362.         });
  7363.       };
  7364.       var getNumRows = function () {
  7365.         return dimensions.get().map(function (d) {
  7366.           return d.numRows;
  7367.         });
  7368.       };
  7369.       var getNumColumns = function () {
  7370.         return dimensions.get().map(function (d) {
  7371.           return d.numColumns;
  7372.         });
  7373.       };
  7374.       return nu$8({
  7375.         readState: function () {
  7376.           return dimensions.get().map(function (d) {
  7377.             return {
  7378.               numRows: String(d.numRows),
  7379.               numColumns: String(d.numColumns)
  7380.             };
  7381.           }).getOr({
  7382.             numRows: '?',
  7383.             numColumns: '?'
  7384.           });
  7385.         },
  7386.         setGridSize: setGridSize,
  7387.         getNumRows: getNumRows,
  7388.         getNumColumns: getNumColumns
  7389.       });
  7390.     };
  7391.     var init$d = function (spec) {
  7392.       return spec.state(spec);
  7393.     };
  7394.  
  7395.     var KeyingState = /*#__PURE__*/Object.freeze({
  7396.         __proto__: null,
  7397.         flatgrid: flatgrid$1,
  7398.         init: init$d
  7399.     });
  7400.  
  7401.     var useH = function (movement) {
  7402.       return function (component, simulatedEvent, config, state) {
  7403.         var move = movement(component.element);
  7404.         return use(move, component, simulatedEvent, config, state);
  7405.       };
  7406.     };
  7407.     var west$1 = function (moveLeft, moveRight) {
  7408.       var movement = onDirection(moveLeft, moveRight);
  7409.       return useH(movement);
  7410.     };
  7411.     var east$1 = function (moveLeft, moveRight) {
  7412.       var movement = onDirection(moveRight, moveLeft);
  7413.       return useH(movement);
  7414.     };
  7415.     var useV = function (move) {
  7416.       return function (component, simulatedEvent, config, state) {
  7417.         return use(move, component, simulatedEvent, config, state);
  7418.       };
  7419.     };
  7420.     var use = function (move, component, simulatedEvent, config, state) {
  7421.       var outcome = config.focusManager.get(component).bind(function (focused) {
  7422.         return move(component.element, focused, config, state);
  7423.       });
  7424.       return outcome.map(function (newFocus) {
  7425.         config.focusManager.set(component, newFocus);
  7426.         return true;
  7427.       });
  7428.     };
  7429.     var north$1 = useV;
  7430.     var south$1 = useV;
  7431.     var move$1 = useV;
  7432.  
  7433.     var isHidden$1 = function (dom) {
  7434.       return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  7435.     };
  7436.     var isVisible = function (element) {
  7437.       return !isHidden$1(element.dom);
  7438.     };
  7439.  
  7440.     var locate = function (candidates, predicate) {
  7441.       return findIndex$1(candidates, predicate).map(function (index) {
  7442.         return {
  7443.           index: index,
  7444.           candidates: candidates
  7445.         };
  7446.       });
  7447.     };
  7448.  
  7449.     var locateVisible = function (container, current, selector) {
  7450.       var predicate = function (x) {
  7451.         return eq(x, current);
  7452.       };
  7453.       var candidates = descendants(container, selector);
  7454.       var visible = filter$2(candidates, isVisible);
  7455.       return locate(visible, predicate);
  7456.     };
  7457.     var findIndex = function (elements, target) {
  7458.       return findIndex$1(elements, function (elem) {
  7459.         return eq(target, elem);
  7460.       });
  7461.     };
  7462.  
  7463.     var withGrid = function (values, index, numCols, f) {
  7464.       var oldRow = Math.floor(index / numCols);
  7465.       var oldColumn = index % numCols;
  7466.       return f(oldRow, oldColumn).bind(function (address) {
  7467.         var newIndex = address.row * numCols + address.column;
  7468.         return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  7469.       });
  7470.     };
  7471.     var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  7472.       return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7473.         var onLastRow = oldRow === numRows - 1;
  7474.         var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  7475.         var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  7476.         return Optional.some({
  7477.           row: oldRow,
  7478.           column: newColumn
  7479.         });
  7480.       });
  7481.     };
  7482.     var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  7483.       return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7484.         var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  7485.         var onLastRow = newRow === numRows - 1;
  7486.         var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  7487.         var newCol = clamp$1(oldColumn, 0, colsInRow - 1);
  7488.         return Optional.some({
  7489.           row: newRow,
  7490.           column: newCol
  7491.         });
  7492.       });
  7493.     };
  7494.     var cycleRight$1 = function (values, index, numRows, numCols) {
  7495.       return cycleHorizontal$1(values, index, numRows, numCols, +1);
  7496.     };
  7497.     var cycleLeft$1 = function (values, index, numRows, numCols) {
  7498.       return cycleHorizontal$1(values, index, numRows, numCols, -1);
  7499.     };
  7500.     var cycleUp$1 = function (values, index, numRows, numCols) {
  7501.       return cycleVertical$1(values, index, numRows, numCols, -1);
  7502.     };
  7503.     var cycleDown$1 = function (values, index, numRows, numCols) {
  7504.       return cycleVertical$1(values, index, numRows, numCols, +1);
  7505.     };
  7506.  
  7507.     var schema$u = [
  7508.       required$1('selector'),
  7509.       defaulted('execute', defaultExecute),
  7510.       onKeyboardHandler('onEscape'),
  7511.       defaulted('captureTab', false),
  7512.       initSize()
  7513.     ];
  7514.     var focusIn$3 = function (component, gridConfig, _gridState) {
  7515.       descendant(component.element, gridConfig.selector).each(function (first) {
  7516.         gridConfig.focusManager.set(component, first);
  7517.       });
  7518.     };
  7519.     var findCurrent$1 = function (component, gridConfig) {
  7520.       return gridConfig.focusManager.get(component).bind(function (elem) {
  7521.         return closest$1(elem, gridConfig.selector);
  7522.       });
  7523.     };
  7524.     var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  7525.       return findCurrent$1(component, gridConfig).bind(function (focused) {
  7526.         return gridConfig.execute(component, simulatedEvent, focused);
  7527.       });
  7528.     };
  7529.     var doMove$2 = function (cycle) {
  7530.       return function (element, focused, gridConfig, gridState) {
  7531.         return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  7532.           return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  7533.         });
  7534.       };
  7535.     };
  7536.     var handleTab = function (_component, _simulatedEvent, gridConfig) {
  7537.       return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  7538.     };
  7539.     var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  7540.       return gridConfig.onEscape(component, simulatedEvent);
  7541.     };
  7542.     var moveLeft$3 = doMove$2(cycleLeft$1);
  7543.     var moveRight$3 = doMove$2(cycleRight$1);
  7544.     var moveNorth$1 = doMove$2(cycleUp$1);
  7545.     var moveSouth$1 = doMove$2(cycleDown$1);
  7546.     var getKeydownRules$4 = constant$1([
  7547.       rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
  7548.       rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
  7549.       rule(inSet(UP), north$1(moveNorth$1)),
  7550.       rule(inSet(DOWN), south$1(moveSouth$1)),
  7551.       rule(and([
  7552.         isShift,
  7553.         inSet(TAB)
  7554.       ]), handleTab),
  7555.       rule(and([
  7556.         isNotShift,
  7557.         inSet(TAB)
  7558.       ]), handleTab),
  7559.       rule(inSet(ESCAPE), doEscape$1),
  7560.       rule(inSet(SPACE.concat(ENTER)), execute$3)
  7561.     ]);
  7562.     var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7563.     var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  7564.       return Optional.some(focusIn$3);
  7565.     });
  7566.  
  7567.     var horizontal = function (container, selector, current, delta) {
  7568.       var isDisabledButton = function (candidate) {
  7569.         return name$2(candidate) === 'button' && get$d(candidate, 'disabled') === 'disabled';
  7570.       };
  7571.       var tryCycle = function (initial, index, candidates) {
  7572.         var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  7573.         if (newIndex === initial) {
  7574.           return Optional.none();
  7575.         } else {
  7576.           return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  7577.         }
  7578.       };
  7579.       return locateVisible(container, current, selector).bind(function (identified) {
  7580.         var index = identified.index;
  7581.         var candidates = identified.candidates;
  7582.         return tryCycle(index, index, candidates);
  7583.       });
  7584.     };
  7585.  
  7586.     var schema$t = [
  7587.       required$1('selector'),
  7588.       defaulted('getInitial', Optional.none),
  7589.       defaulted('execute', defaultExecute),
  7590.       onKeyboardHandler('onEscape'),
  7591.       defaulted('executeOnMove', false),
  7592.       defaulted('allowVertical', true)
  7593.     ];
  7594.     var findCurrent = function (component, flowConfig) {
  7595.       return flowConfig.focusManager.get(component).bind(function (elem) {
  7596.         return closest$1(elem, flowConfig.selector);
  7597.       });
  7598.     };
  7599.     var execute$2 = function (component, simulatedEvent, flowConfig) {
  7600.       return findCurrent(component, flowConfig).bind(function (focused) {
  7601.         return flowConfig.execute(component, simulatedEvent, focused);
  7602.       });
  7603.     };
  7604.     var focusIn$2 = function (component, flowConfig, _state) {
  7605.       flowConfig.getInitial(component).orThunk(function () {
  7606.         return descendant(component.element, flowConfig.selector);
  7607.       }).each(function (first) {
  7608.         flowConfig.focusManager.set(component, first);
  7609.       });
  7610.     };
  7611.     var moveLeft$2 = function (element, focused, info) {
  7612.       return horizontal(element, info.selector, focused, -1);
  7613.     };
  7614.     var moveRight$2 = function (element, focused, info) {
  7615.       return horizontal(element, info.selector, focused, +1);
  7616.     };
  7617.     var doMove$1 = function (movement) {
  7618.       return function (component, simulatedEvent, flowConfig, flowState) {
  7619.         return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  7620.           return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  7621.         });
  7622.       };
  7623.     };
  7624.     var doEscape = function (component, simulatedEvent, flowConfig) {
  7625.       return flowConfig.onEscape(component, simulatedEvent);
  7626.     };
  7627.     var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  7628.       var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  7629.       var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  7630.       return [
  7631.         rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
  7632.         rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
  7633.         rule(inSet(ENTER), execute$2),
  7634.         rule(inSet(SPACE), execute$2),
  7635.         rule(inSet(ESCAPE), doEscape)
  7636.       ];
  7637.     };
  7638.     var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7639.     var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7640.       return Optional.some(focusIn$2);
  7641.     });
  7642.  
  7643.     var toCell = function (matrix, rowIndex, columnIndex) {
  7644.       return Optional.from(matrix[rowIndex]).bind(function (row) {
  7645.         return Optional.from(row[columnIndex]).map(function (cell) {
  7646.           return {
  7647.             rowIndex: rowIndex,
  7648.             columnIndex: columnIndex,
  7649.             cell: cell
  7650.           };
  7651.         });
  7652.       });
  7653.     };
  7654.     var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7655.       var row = matrix[rowIndex];
  7656.       var colsInRow = row.length;
  7657.       var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  7658.       return toCell(matrix, rowIndex, newColIndex);
  7659.     };
  7660.     var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  7661.       var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  7662.       var colsInNextRow = matrix[nextRowIndex].length;
  7663.       var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7664.       return toCell(matrix, nextRowIndex, nextColIndex);
  7665.     };
  7666.     var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7667.       var row = matrix[rowIndex];
  7668.       var colsInRow = row.length;
  7669.       var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1);
  7670.       return toCell(matrix, rowIndex, newColIndex);
  7671.     };
  7672.     var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  7673.       var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix.length - 1);
  7674.       var colsInNextRow = matrix[nextRowIndex].length;
  7675.       var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7676.       return toCell(matrix, nextRowIndex, nextColIndex);
  7677.     };
  7678.     var cycleRight = function (matrix, startRow, startCol) {
  7679.       return cycleHorizontal(matrix, startRow, startCol, +1);
  7680.     };
  7681.     var cycleLeft = function (matrix, startRow, startCol) {
  7682.       return cycleHorizontal(matrix, startRow, startCol, -1);
  7683.     };
  7684.     var cycleUp = function (matrix, startRow, startCol) {
  7685.       return cycleVertical(matrix, startCol, startRow, -1);
  7686.     };
  7687.     var cycleDown = function (matrix, startRow, startCol) {
  7688.       return cycleVertical(matrix, startCol, startRow, +1);
  7689.     };
  7690.     var moveLeft$1 = function (matrix, startRow, startCol) {
  7691.       return moveHorizontal(matrix, startRow, startCol, -1);
  7692.     };
  7693.     var moveRight$1 = function (matrix, startRow, startCol) {
  7694.       return moveHorizontal(matrix, startRow, startCol, +1);
  7695.     };
  7696.     var moveUp$1 = function (matrix, startRow, startCol) {
  7697.       return moveVertical(matrix, startCol, startRow, -1);
  7698.     };
  7699.     var moveDown$1 = function (matrix, startRow, startCol) {
  7700.       return moveVertical(matrix, startCol, startRow, +1);
  7701.     };
  7702.  
  7703.     var schema$s = [
  7704.       requiredObjOf('selectors', [
  7705.         required$1('row'),
  7706.         required$1('cell')
  7707.       ]),
  7708.       defaulted('cycles', true),
  7709.       defaulted('previousSelector', Optional.none),
  7710.       defaulted('execute', defaultExecute)
  7711.     ];
  7712.     var focusIn$1 = function (component, matrixConfig, _state) {
  7713.       var focused = matrixConfig.previousSelector(component).orThunk(function () {
  7714.         var selectors = matrixConfig.selectors;
  7715.         return descendant(component.element, selectors.cell);
  7716.       });
  7717.       focused.each(function (cell) {
  7718.         matrixConfig.focusManager.set(component, cell);
  7719.       });
  7720.     };
  7721.     var execute$1 = function (component, simulatedEvent, matrixConfig) {
  7722.       return search(component.element).bind(function (focused) {
  7723.         return matrixConfig.execute(component, simulatedEvent, focused);
  7724.       });
  7725.     };
  7726.     var toMatrix = function (rows, matrixConfig) {
  7727.       return map$2(rows, function (row) {
  7728.         return descendants(row, matrixConfig.selectors.cell);
  7729.       });
  7730.     };
  7731.     var doMove = function (ifCycle, ifMove) {
  7732.       return function (element, focused, matrixConfig) {
  7733.         var move = matrixConfig.cycles ? ifCycle : ifMove;
  7734.         return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  7735.           var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  7736.           return findIndex(cellsInRow, focused).bind(function (colIndex) {
  7737.             var allRows = descendants(element, matrixConfig.selectors.row);
  7738.             return findIndex(allRows, inRow).bind(function (rowIndex) {
  7739.               var matrix = toMatrix(allRows, matrixConfig);
  7740.               return move(matrix, rowIndex, colIndex).map(function (next) {
  7741.                 return next.cell;
  7742.               });
  7743.             });
  7744.           });
  7745.         });
  7746.       };
  7747.     };
  7748.     var moveLeft = doMove(cycleLeft, moveLeft$1);
  7749.     var moveRight = doMove(cycleRight, moveRight$1);
  7750.     var moveNorth = doMove(cycleUp, moveUp$1);
  7751.     var moveSouth = doMove(cycleDown, moveDown$1);
  7752.     var getKeydownRules$2 = constant$1([
  7753.       rule(inSet(LEFT), west$1(moveLeft, moveRight)),
  7754.       rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
  7755.       rule(inSet(UP), north$1(moveNorth)),
  7756.       rule(inSet(DOWN), south$1(moveSouth)),
  7757.       rule(inSet(SPACE.concat(ENTER)), execute$1)
  7758.     ]);
  7759.     var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7760.     var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  7761.       return Optional.some(focusIn$1);
  7762.     });
  7763.  
  7764.     var schema$r = [
  7765.       required$1('selector'),
  7766.       defaulted('execute', defaultExecute),
  7767.       defaulted('moveOnTab', false)
  7768.     ];
  7769.     var execute = function (component, simulatedEvent, menuConfig) {
  7770.       return menuConfig.focusManager.get(component).bind(function (focused) {
  7771.         return menuConfig.execute(component, simulatedEvent, focused);
  7772.       });
  7773.     };
  7774.     var focusIn = function (component, menuConfig, _state) {
  7775.       descendant(component.element, menuConfig.selector).each(function (first) {
  7776.         menuConfig.focusManager.set(component, first);
  7777.       });
  7778.     };
  7779.     var moveUp = function (element, focused, info) {
  7780.       return horizontal(element, info.selector, focused, -1);
  7781.     };
  7782.     var moveDown = function (element, focused, info) {
  7783.       return horizontal(element, info.selector, focused, +1);
  7784.     };
  7785.     var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7786.       return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7787.     };
  7788.     var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7789.       return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7790.     };
  7791.     var getKeydownRules$1 = constant$1([
  7792.       rule(inSet(UP), move$1(moveUp)),
  7793.       rule(inSet(DOWN), move$1(moveDown)),
  7794.       rule(and([
  7795.         isShift,
  7796.         inSet(TAB)
  7797.       ]), fireShiftTab),
  7798.       rule(and([
  7799.         isNotShift,
  7800.         inSet(TAB)
  7801.       ]), fireTab),
  7802.       rule(inSet(ENTER), execute),
  7803.       rule(inSet(SPACE), execute)
  7804.     ]);
  7805.     var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7806.     var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  7807.       return Optional.some(focusIn);
  7808.     });
  7809.  
  7810.     var schema$q = [
  7811.       onKeyboardHandler('onSpace'),
  7812.       onKeyboardHandler('onEnter'),
  7813.       onKeyboardHandler('onShiftEnter'),
  7814.       onKeyboardHandler('onLeft'),
  7815.       onKeyboardHandler('onRight'),
  7816.       onKeyboardHandler('onTab'),
  7817.       onKeyboardHandler('onShiftTab'),
  7818.       onKeyboardHandler('onUp'),
  7819.       onKeyboardHandler('onDown'),
  7820.       onKeyboardHandler('onEscape'),
  7821.       defaulted('stopSpaceKeyup', false),
  7822.       option('focusIn')
  7823.     ];
  7824.     var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  7825.       return [
  7826.         rule(inSet(SPACE), specialInfo.onSpace),
  7827.         rule(and([
  7828.           isNotShift,
  7829.           inSet(ENTER)
  7830.         ]), specialInfo.onEnter),
  7831.         rule(and([
  7832.           isShift,
  7833.           inSet(ENTER)
  7834.         ]), specialInfo.onShiftEnter),
  7835.         rule(and([
  7836.           isShift,
  7837.           inSet(TAB)
  7838.         ]), specialInfo.onShiftTab),
  7839.         rule(and([
  7840.           isNotShift,
  7841.           inSet(TAB)
  7842.         ]), specialInfo.onTab),
  7843.         rule(inSet(UP), specialInfo.onUp),
  7844.         rule(inSet(DOWN), specialInfo.onDown),
  7845.         rule(inSet(LEFT), specialInfo.onLeft),
  7846.         rule(inSet(RIGHT), specialInfo.onRight),
  7847.         rule(inSet(SPACE), specialInfo.onSpace),
  7848.         rule(inSet(ESCAPE), specialInfo.onEscape)
  7849.       ];
  7850.     };
  7851.     var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  7852.       return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7853.     };
  7854.     var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  7855.       return specialInfo.focusIn;
  7856.     });
  7857.  
  7858.     var acyclic = AcyclicType.schema();
  7859.     var cyclic = CyclicType.schema();
  7860.     var flow = FlowType.schema();
  7861.     var flatgrid = FlatgridType.schema();
  7862.     var matrix = MatrixType.schema();
  7863.     var execution = ExecutionType.schema();
  7864.     var menu = MenuType.schema();
  7865.     var special = SpecialType.schema();
  7866.  
  7867.     var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7868.         __proto__: null,
  7869.         acyclic: acyclic,
  7870.         cyclic: cyclic,
  7871.         flow: flow,
  7872.         flatgrid: flatgrid,
  7873.         matrix: matrix,
  7874.         execution: execution,
  7875.         menu: menu,
  7876.         special: special
  7877.     });
  7878.  
  7879.     var isFlatgridState = function (keyState) {
  7880.       return hasNonNullableKey(keyState, 'setGridSize');
  7881.     };
  7882.     var Keying = createModes({
  7883.       branchKey: 'mode',
  7884.       branches: KeyboardBranches,
  7885.       name: 'keying',
  7886.       active: {
  7887.         events: function (keyingConfig, keyingState) {
  7888.           var handler = keyingConfig.handler;
  7889.           return handler.toEvents(keyingConfig, keyingState);
  7890.         }
  7891.       },
  7892.       apis: {
  7893.         focusIn: function (component, keyConfig, keyState) {
  7894.           keyConfig.sendFocusIn(keyConfig).fold(function () {
  7895.             component.getSystem().triggerFocus(component.element, component.element);
  7896.           }, function (sendFocusIn) {
  7897.             sendFocusIn(component, keyConfig, keyState);
  7898.           });
  7899.         },
  7900.         setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7901.           if (!isFlatgridState(keyState)) {
  7902.             console.error('Layout does not support setGridSize');
  7903.           } else {
  7904.             keyState.setGridSize(numRows, numColumns);
  7905.           }
  7906.         }
  7907.       },
  7908.       state: KeyingState
  7909.     });
  7910.  
  7911.     var set$2 = function (component, replaceConfig, replaceState, data) {
  7912.       preserve$1(function () {
  7913.         var newChildren = map$2(data, component.getSystem().build);
  7914.         replaceChildren(component, newChildren);
  7915.       }, component.element);
  7916.     };
  7917.     var insert = function (component, replaceConfig, insertion, childSpec) {
  7918.       var child = component.getSystem().build(childSpec);
  7919.       attachWith(component, child, insertion);
  7920.     };
  7921.     var append = function (component, replaceConfig, replaceState, appendee) {
  7922.       insert(component, replaceConfig, append$2, appendee);
  7923.     };
  7924.     var prepend = function (component, replaceConfig, replaceState, prependee) {
  7925.       insert(component, replaceConfig, prepend$1, prependee);
  7926.     };
  7927.     var remove = function (component, replaceConfig, replaceState, removee) {
  7928.       var children = contents(component);
  7929.       var foundChild = find$5(children, function (child) {
  7930.         return eq(removee.element, child.element);
  7931.       });
  7932.       foundChild.each(detach);
  7933.     };
  7934.     var contents = function (component, _replaceConfig) {
  7935.       return component.components();
  7936.     };
  7937.     var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7938.       var children = contents(component);
  7939.       return Optional.from(children[replaceeIndex]).map(function (replacee) {
  7940.         remove(component, replaceConfig, replaceState, replacee);
  7941.         replacer.each(function (r) {
  7942.           insert(component, replaceConfig, function (p, c) {
  7943.             appendAt(p, c, replaceeIndex);
  7944.           }, r);
  7945.         });
  7946.         return replacee;
  7947.       });
  7948.     };
  7949.     var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7950.       var children = contents(component);
  7951.       return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  7952.         return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7953.       });
  7954.     };
  7955.  
  7956.     var ReplaceApis = /*#__PURE__*/Object.freeze({
  7957.         __proto__: null,
  7958.         append: append,
  7959.         prepend: prepend,
  7960.         remove: remove,
  7961.         replaceAt: replaceAt,
  7962.         replaceBy: replaceBy,
  7963.         set: set$2,
  7964.         contents: contents
  7965.     });
  7966.  
  7967.     var Replacing = create$8({
  7968.       fields: [],
  7969.       name: 'replacing',
  7970.       apis: ReplaceApis
  7971.     });
  7972.  
  7973.     var events$d = function (name, eventHandlers) {
  7974.       var events = derive$2(eventHandlers);
  7975.       return create$8({
  7976.         fields: [required$1('enabled')],
  7977.         name: name,
  7978.         active: { events: constant$1(events) }
  7979.       });
  7980.     };
  7981.     var config = function (name, eventHandlers) {
  7982.       var me = events$d(name, eventHandlers);
  7983.       return {
  7984.         key: name,
  7985.         value: {
  7986.           config: {},
  7987.           me: me,
  7988.           configAsRaw: constant$1({}),
  7989.           initialConfig: {},
  7990.           state: NoState
  7991.         }
  7992.       };
  7993.     };
  7994.  
  7995.     var focus$2 = function (component, focusConfig) {
  7996.       if (!focusConfig.ignore) {
  7997.         focus$3(component.element);
  7998.         focusConfig.onFocus(component);
  7999.       }
  8000.     };
  8001.     var blur = function (component, focusConfig) {
  8002.       if (!focusConfig.ignore) {
  8003.         blur$1(component.element);
  8004.       }
  8005.     };
  8006.     var isFocused = function (component) {
  8007.       return hasFocus(component.element);
  8008.     };
  8009.  
  8010.     var FocusApis = /*#__PURE__*/Object.freeze({
  8011.         __proto__: null,
  8012.         focus: focus$2,
  8013.         blur: blur,
  8014.         isFocused: isFocused
  8015.     });
  8016.  
  8017.     var exhibit$4 = function (base, focusConfig) {
  8018.       var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  8019.       return nu$7(mod);
  8020.     };
  8021.     var events$c = function (focusConfig) {
  8022.       return derive$2([run$1(focus$4(), function (component, simulatedEvent) {
  8023.           focus$2(component, focusConfig);
  8024.           simulatedEvent.stop();
  8025.         })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function (_, simulatedEvent) {
  8026.           simulatedEvent.event.prevent();
  8027.         })] : []));
  8028.     };
  8029.  
  8030.     var ActiveFocus = /*#__PURE__*/Object.freeze({
  8031.         __proto__: null,
  8032.         exhibit: exhibit$4,
  8033.         events: events$c
  8034.     });
  8035.  
  8036.     var FocusSchema = [
  8037.       onHandler('onFocus'),
  8038.       defaulted('stopMousedown', false),
  8039.       defaulted('ignore', false)
  8040.     ];
  8041.  
  8042.     var Focusing = create$8({
  8043.       fields: FocusSchema,
  8044.       name: 'focusing',
  8045.       active: ActiveFocus,
  8046.       apis: FocusApis
  8047.     });
  8048.  
  8049.     var SetupBehaviourCellState = function (initialState) {
  8050.       var init = function () {
  8051.         var cell = Cell(initialState);
  8052.         var get = function () {
  8053.           return cell.get();
  8054.         };
  8055.         var set = function (newState) {
  8056.           return cell.set(newState);
  8057.         };
  8058.         var clear = function () {
  8059.           return cell.set(initialState);
  8060.         };
  8061.         var readState = function () {
  8062.           return cell.get();
  8063.         };
  8064.         return {
  8065.           get: get,
  8066.           set: set,
  8067.           clear: clear,
  8068.           readState: readState
  8069.         };
  8070.       };
  8071.       return { init: init };
  8072.     };
  8073.  
  8074.     var updateAriaState = function (component, toggleConfig, toggleState) {
  8075.       var ariaInfo = toggleConfig.aria;
  8076.       ariaInfo.update(component, ariaInfo, toggleState.get());
  8077.     };
  8078.     var updateClass = function (component, toggleConfig, toggleState) {
  8079.       toggleConfig.toggleClass.each(function (toggleClass) {
  8080.         if (toggleState.get()) {
  8081.           add$2(component.element, toggleClass);
  8082.         } else {
  8083.           remove$2(component.element, toggleClass);
  8084.         }
  8085.       });
  8086.     };
  8087.     var toggle$2 = function (component, toggleConfig, toggleState) {
  8088.       set$1(component, toggleConfig, toggleState, !toggleState.get());
  8089.     };
  8090.     var on = function (component, toggleConfig, toggleState) {
  8091.       toggleState.set(true);
  8092.       updateClass(component, toggleConfig, toggleState);
  8093.       updateAriaState(component, toggleConfig, toggleState);
  8094.     };
  8095.     var off = function (component, toggleConfig, toggleState) {
  8096.       toggleState.set(false);
  8097.       updateClass(component, toggleConfig, toggleState);
  8098.       updateAriaState(component, toggleConfig, toggleState);
  8099.     };
  8100.     var set$1 = function (component, toggleConfig, toggleState, state) {
  8101.       var action = state ? on : off;
  8102.       action(component, toggleConfig, toggleState);
  8103.     };
  8104.     var isOn = function (component, toggleConfig, toggleState) {
  8105.       return toggleState.get();
  8106.     };
  8107.     var onLoad = function (component, toggleConfig, toggleState) {
  8108.       set$1(component, toggleConfig, toggleState, toggleConfig.selected);
  8109.     };
  8110.  
  8111.     var ToggleApis = /*#__PURE__*/Object.freeze({
  8112.         __proto__: null,
  8113.         onLoad: onLoad,
  8114.         toggle: toggle$2,
  8115.         isOn: isOn,
  8116.         on: on,
  8117.         off: off,
  8118.         set: set$1
  8119.     });
  8120.  
  8121.     var exhibit$3 = function () {
  8122.       return nu$7({});
  8123.     };
  8124.     var events$b = function (toggleConfig, toggleState) {
  8125.       var execute = executeEvent(toggleConfig, toggleState, toggle$2);
  8126.       var load = loadEvent(toggleConfig, toggleState, onLoad);
  8127.       return derive$2(flatten([
  8128.         toggleConfig.toggleOnExecute ? [execute] : [],
  8129.         [load]
  8130.       ]));
  8131.     };
  8132.  
  8133.     var ActiveToggle = /*#__PURE__*/Object.freeze({
  8134.         __proto__: null,
  8135.         exhibit: exhibit$3,
  8136.         events: events$b
  8137.     });
  8138.  
  8139.     var updatePressed = function (component, ariaInfo, status) {
  8140.       set$8(component.element, 'aria-pressed', status);
  8141.       if (ariaInfo.syncWithExpanded) {
  8142.         updateExpanded(component, ariaInfo, status);
  8143.       }
  8144.     };
  8145.     var updateSelected = function (component, ariaInfo, status) {
  8146.       set$8(component.element, 'aria-selected', status);
  8147.     };
  8148.     var updateChecked = function (component, ariaInfo, status) {
  8149.       set$8(component.element, 'aria-checked', status);
  8150.     };
  8151.     var updateExpanded = function (component, ariaInfo, status) {
  8152.       set$8(component.element, 'aria-expanded', status);
  8153.     };
  8154.  
  8155.     var ToggleSchema = [
  8156.       defaulted('selected', false),
  8157.       option('toggleClass'),
  8158.       defaulted('toggleOnExecute', true),
  8159.       defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  8160.         pressed: [
  8161.           defaulted('syncWithExpanded', false),
  8162.           output$1('update', updatePressed)
  8163.         ],
  8164.         checked: [output$1('update', updateChecked)],
  8165.         expanded: [output$1('update', updateExpanded)],
  8166.         selected: [output$1('update', updateSelected)],
  8167.         none: [output$1('update', noop)]
  8168.       }))
  8169.     ];
  8170.  
  8171.     var Toggling = create$8({
  8172.       fields: ToggleSchema,
  8173.       name: 'toggling',
  8174.       active: ActiveToggle,
  8175.       apis: ToggleApis,
  8176.       state: SetupBehaviourCellState(false)
  8177.     });
  8178.  
  8179.     var pointerEvents = function () {
  8180.       var onClick = function (component, simulatedEvent) {
  8181.         simulatedEvent.stop();
  8182.         emitExecute(component);
  8183.       };
  8184.       return [
  8185.         run$1(click(), onClick),
  8186.         run$1(tap(), onClick),
  8187.         cutter(touchstart()),
  8188.         cutter(mousedown())
  8189.       ];
  8190.     };
  8191.     var events$a = function (optAction) {
  8192.       var executeHandler = function (action) {
  8193.         return runOnExecute$1(function (component, simulatedEvent) {
  8194.           action(component);
  8195.           simulatedEvent.stop();
  8196.         });
  8197.       };
  8198.       return derive$2(flatten([
  8199.         optAction.map(executeHandler).toArray(),
  8200.         pointerEvents()
  8201.       ]));
  8202.     };
  8203.  
  8204.     var hoverEvent = 'alloy.item-hover';
  8205.     var focusEvent = 'alloy.item-focus';
  8206.     var onHover = function (item) {
  8207.       if (search(item.element).isNone() || Focusing.isFocused(item)) {
  8208.         if (!Focusing.isFocused(item)) {
  8209.           Focusing.focus(item);
  8210.         }
  8211.         emitWith(item, hoverEvent, { item: item });
  8212.       }
  8213.     };
  8214.     var onFocus$1 = function (item) {
  8215.       emitWith(item, focusEvent, { item: item });
  8216.     };
  8217.     var hover = constant$1(hoverEvent);
  8218.     var focus$1 = constant$1(focusEvent);
  8219.  
  8220.     var builder$2 = function (detail) {
  8221.       return {
  8222.         dom: detail.dom,
  8223.         domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes), { 'aria-haspopup': detail.hasSubmenu }), detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  8224.         behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  8225.           detail.toggling.fold(Toggling.revoke, function (tConfig) {
  8226.             return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  8227.           }),
  8228.           Focusing.config({
  8229.             ignore: detail.ignoreFocus,
  8230.             stopMousedown: detail.ignoreFocus,
  8231.             onFocus: function (component) {
  8232.               onFocus$1(component);
  8233.             }
  8234.           }),
  8235.           Keying.config({ mode: 'execution' }),
  8236.           Representing.config({
  8237.             store: {
  8238.               mode: 'memory',
  8239.               initialValue: detail.data
  8240.             }
  8241.           }),
  8242.           config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [
  8243.             run$1(mouseover(), onHover),
  8244.             run$1(focusItem(), Focusing.focus)
  8245.           ], false))
  8246.         ]),
  8247.         components: detail.components,
  8248.         eventOrder: detail.eventOrder
  8249.       };
  8250.     };
  8251.     var schema$p = [
  8252.       required$1('data'),
  8253.       required$1('components'),
  8254.       required$1('dom'),
  8255.       defaulted('hasSubmenu', false),
  8256.       option('toggling'),
  8257.       SketchBehaviours.field('itemBehaviours', [
  8258.         Toggling,
  8259.         Focusing,
  8260.         Keying,
  8261.         Representing
  8262.       ]),
  8263.       defaulted('ignoreFocus', false),
  8264.       defaulted('domModification', {}),
  8265.       output$1('builder', builder$2),
  8266.       defaulted('eventOrder', {})
  8267.     ];
  8268.  
  8269.     var builder$1 = function (detail) {
  8270.       return {
  8271.         dom: detail.dom,
  8272.         components: detail.components,
  8273.         events: derive$2([stopper(focusItem())])
  8274.       };
  8275.     };
  8276.     var schema$o = [
  8277.       required$1('dom'),
  8278.       required$1('components'),
  8279.       output$1('builder', builder$1)
  8280.     ];
  8281.  
  8282.     var owner$2 = constant$1('item-widget');
  8283.     var parts$h = constant$1([required({
  8284.         name: 'widget',
  8285.         overrides: function (detail) {
  8286.           return {
  8287.             behaviours: derive$1([Representing.config({
  8288.                 store: {
  8289.                   mode: 'manual',
  8290.                   getValue: function (_component) {
  8291.                     return detail.data;
  8292.                   },
  8293.                   setValue: noop
  8294.                 }
  8295.               })])
  8296.           };
  8297.         }
  8298.       })]);
  8299.  
  8300.     var builder = function (detail) {
  8301.       var subs = substitutes(owner$2(), detail, parts$h());
  8302.       var components = components$1(owner$2(), detail, subs.internals());
  8303.       var focusWidget = function (component) {
  8304.         return getPart(component, detail, 'widget').map(function (widget) {
  8305.           Keying.focusIn(widget);
  8306.           return widget;
  8307.         });
  8308.       };
  8309.       var onHorizontalArrow = function (component, simulatedEvent) {
  8310.         return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  8311.           if (detail.autofocus) {
  8312.             simulatedEvent.setSource(component.element);
  8313.             return Optional.none();
  8314.           } else {
  8315.             return Optional.none();
  8316.           }
  8317.         }();
  8318.       };
  8319.       return {
  8320.         dom: detail.dom,
  8321.         components: components,
  8322.         domModification: detail.domModification,
  8323.         events: derive$2([
  8324.           runOnExecute$1(function (component, simulatedEvent) {
  8325.             focusWidget(component).each(function (_widget) {
  8326.               simulatedEvent.stop();
  8327.             });
  8328.           }),
  8329.           run$1(mouseover(), onHover),
  8330.           run$1(focusItem(), function (component, _simulatedEvent) {
  8331.             if (detail.autofocus) {
  8332.               focusWidget(component);
  8333.             } else {
  8334.               Focusing.focus(component);
  8335.             }
  8336.           })
  8337.         ]),
  8338.         behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  8339.           Representing.config({
  8340.             store: {
  8341.               mode: 'memory',
  8342.               initialValue: detail.data
  8343.             }
  8344.           }),
  8345.           Focusing.config({
  8346.             ignore: detail.ignoreFocus,
  8347.             onFocus: function (component) {
  8348.               onFocus$1(component);
  8349.             }
  8350.           }),
  8351.           Keying.config({
  8352.             mode: 'special',
  8353.             focusIn: detail.autofocus ? function (component) {
  8354.               focusWidget(component);
  8355.             } : revoke(),
  8356.             onLeft: onHorizontalArrow,
  8357.             onRight: onHorizontalArrow,
  8358.             onEscape: function (component, simulatedEvent) {
  8359.               if (!Focusing.isFocused(component) && !detail.autofocus) {
  8360.                 Focusing.focus(component);
  8361.                 return Optional.some(true);
  8362.               } else if (detail.autofocus) {
  8363.                 simulatedEvent.setSource(component.element);
  8364.                 return Optional.none();
  8365.               } else {
  8366.                 return Optional.none();
  8367.               }
  8368.             }
  8369.           })
  8370.         ])
  8371.       };
  8372.     };
  8373.     var schema$n = [
  8374.       required$1('uid'),
  8375.       required$1('data'),
  8376.       required$1('components'),
  8377.       required$1('dom'),
  8378.       defaulted('autofocus', false),
  8379.       defaulted('ignoreFocus', false),
  8380.       SketchBehaviours.field('widgetBehaviours', [
  8381.         Representing,
  8382.         Focusing,
  8383.         Keying
  8384.       ]),
  8385.       defaulted('domModification', {}),
  8386.       defaultUidsSchema(parts$h()),
  8387.       output$1('builder', builder)
  8388.     ];
  8389.  
  8390.     var itemSchema$2 = choose$1('type', {
  8391.       widget: schema$n,
  8392.       item: schema$p,
  8393.       separator: schema$o
  8394.     });
  8395.     var configureGrid = function (detail, movementInfo) {
  8396.       return {
  8397.         mode: 'flatgrid',
  8398.         selector: '.' + detail.markers.item,
  8399.         initSize: {
  8400.           numColumns: movementInfo.initSize.numColumns,
  8401.           numRows: movementInfo.initSize.numRows
  8402.         },
  8403.         focusManager: detail.focusManager
  8404.       };
  8405.     };
  8406.     var configureMatrix = function (detail, movementInfo) {
  8407.       return {
  8408.         mode: 'matrix',
  8409.         selectors: {
  8410.           row: movementInfo.rowSelector,
  8411.           cell: '.' + detail.markers.item
  8412.         },
  8413.         focusManager: detail.focusManager
  8414.       };
  8415.     };
  8416.     var configureMenu = function (detail, movementInfo) {
  8417.       return {
  8418.         mode: 'menu',
  8419.         selector: '.' + detail.markers.item,
  8420.         moveOnTab: movementInfo.moveOnTab,
  8421.         focusManager: detail.focusManager
  8422.       };
  8423.     };
  8424.     var parts$g = constant$1([group({
  8425.         factory: {
  8426.           sketch: function (spec) {
  8427.             var itemInfo = asRawOrDie$1('menu.spec item', itemSchema$2, spec);
  8428.             return itemInfo.builder(itemInfo);
  8429.           }
  8430.         },
  8431.         name: 'items',
  8432.         unit: 'item',
  8433.         defaults: function (detail, u) {
  8434.           return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$5('item') });
  8435.         },
  8436.         overrides: function (detail, u) {
  8437.           return {
  8438.             type: u.type,
  8439.             ignoreFocus: detail.fakeFocus,
  8440.             domModification: { classes: [detail.markers.item] }
  8441.           };
  8442.         }
  8443.       })]);
  8444.     var schema$m = constant$1([
  8445.       required$1('value'),
  8446.       required$1('items'),
  8447.       required$1('dom'),
  8448.       required$1('components'),
  8449.       defaulted('eventOrder', {}),
  8450.       field('menuBehaviours', [
  8451.         Highlighting,
  8452.         Representing,
  8453.         Composing,
  8454.         Keying
  8455.       ]),
  8456.       defaultedOf('movement', {
  8457.         mode: 'menu',
  8458.         moveOnTab: true
  8459.       }, choose$1('mode', {
  8460.         grid: [
  8461.           initSize(),
  8462.           output$1('config', configureGrid)
  8463.         ],
  8464.         matrix: [
  8465.           output$1('config', configureMatrix),
  8466.           required$1('rowSelector')
  8467.         ],
  8468.         menu: [
  8469.           defaulted('moveOnTab', true),
  8470.           output$1('config', configureMenu)
  8471.         ]
  8472.       })),
  8473.       itemMarkers(),
  8474.       defaulted('fakeFocus', false),
  8475.       defaulted('focusManager', dom$2()),
  8476.       onHandler('onHighlight')
  8477.     ]);
  8478.  
  8479.     var focus = constant$1('alloy.menu-focus');
  8480.  
  8481.     var make$7 = function (detail, components, _spec, _externals) {
  8482.       return {
  8483.         uid: detail.uid,
  8484.         dom: detail.dom,
  8485.         markers: detail.markers,
  8486.         behaviours: augment(detail.menuBehaviours, [
  8487.           Highlighting.config({
  8488.             highlightClass: detail.markers.selectedItem,
  8489.             itemClass: detail.markers.item,
  8490.             onHighlight: detail.onHighlight
  8491.           }),
  8492.           Representing.config({
  8493.             store: {
  8494.               mode: 'memory',
  8495.               initialValue: detail.value
  8496.             }
  8497.           }),
  8498.           Composing.config({ find: Optional.some }),
  8499.           Keying.config(detail.movement.config(detail, detail.movement))
  8500.         ]),
  8501.         events: derive$2([
  8502.           run$1(focus$1(), function (menu, simulatedEvent) {
  8503.             var event = simulatedEvent.event;
  8504.             menu.getSystem().getByDom(event.target).each(function (item) {
  8505.               Highlighting.highlight(menu, item);
  8506.               simulatedEvent.stop();
  8507.               emitWith(menu, focus(), {
  8508.                 menu: menu,
  8509.                 item: item
  8510.               });
  8511.             });
  8512.           }),
  8513.           run$1(hover(), function (menu, simulatedEvent) {
  8514.             var item = simulatedEvent.event.item;
  8515.             Highlighting.highlight(menu, item);
  8516.           })
  8517.         ]),
  8518.         components: components,
  8519.         eventOrder: detail.eventOrder,
  8520.         domModification: { attributes: { role: 'menu' } }
  8521.       };
  8522.     };
  8523.  
  8524.     var Menu = composite({
  8525.       name: 'Menu',
  8526.       configFields: schema$m(),
  8527.       partFields: parts$g(),
  8528.       factory: make$7
  8529.     });
  8530.  
  8531.     var transpose$1 = function (obj) {
  8532.       return tupleMap(obj, function (v, k) {
  8533.         return {
  8534.           k: v,
  8535.           v: k
  8536.         };
  8537.       });
  8538.     };
  8539.     var trace = function (items, byItem, byMenu, finish) {
  8540.       return get$e(byMenu, finish).bind(function (triggerItem) {
  8541.         return get$e(items, triggerItem).bind(function (triggerMenu) {
  8542.           var rest = trace(items, byItem, byMenu, triggerMenu);
  8543.           return Optional.some([triggerMenu].concat(rest));
  8544.         });
  8545.       }).getOr([]);
  8546.     };
  8547.     var generate$2 = function (menus, expansions) {
  8548.       var items = {};
  8549.       each(menus, function (menuItems, menu) {
  8550.         each$1(menuItems, function (item) {
  8551.           items[item] = menu;
  8552.         });
  8553.       });
  8554.       var byItem = expansions;
  8555.       var byMenu = transpose$1(expansions);
  8556.       var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8557.         return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8558.       });
  8559.       return map$1(items, function (menu) {
  8560.         return get$e(menuPaths, menu).getOr([menu]);
  8561.       });
  8562.     };
  8563.  
  8564.     var init$c = function () {
  8565.       var expansions = Cell({});
  8566.       var menus = Cell({});
  8567.       var paths = Cell({});
  8568.       var primary = value$1();
  8569.       var directory = Cell({});
  8570.       var clear = function () {
  8571.         expansions.set({});
  8572.         menus.set({});
  8573.         paths.set({});
  8574.         primary.clear();
  8575.       };
  8576.       var isClear = function () {
  8577.         return primary.get().isNone();
  8578.       };
  8579.       var setMenuBuilt = function (menuName, built) {
  8580.         var _a;
  8581.         menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8582.           type: 'prepared',
  8583.           menu: built
  8584.         }, _a)));
  8585.       };
  8586.       var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8587.         primary.set(sPrimary);
  8588.         expansions.set(sExpansions);
  8589.         menus.set(sMenus);
  8590.         directory.set(dir);
  8591.         var sPaths = generate$2(dir, sExpansions);
  8592.         paths.set(sPaths);
  8593.       };
  8594.       var getTriggeringItem = function (menuValue) {
  8595.         return find$4(expansions.get(), function (v, _k) {
  8596.           return v === menuValue;
  8597.         });
  8598.       };
  8599.       var getTriggerData = function (menuValue, getItemByValue, path) {
  8600.         return getPreparedMenu(menuValue).bind(function (menu) {
  8601.           return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8602.             return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8603.               return {
  8604.                 triggeredMenu: menu,
  8605.                 triggeringItem: triggeredItem,
  8606.                 triggeringPath: path
  8607.               };
  8608.             });
  8609.           });
  8610.         });
  8611.       };
  8612.       var getTriggeringPath = function (itemValue, getItemByValue) {
  8613.         var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8614.           return getPreparedMenu(menuValue).isSome();
  8615.         });
  8616.         return get$e(paths.get(), itemValue).bind(function (path) {
  8617.           var revPath = reverse(extraPath.concat(path));
  8618.           var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8619.             return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8620.               return is$1(primary.get(), menuValue) ? [] : [Optional.none()];
  8621.             }, function (data) {
  8622.               return [Optional.some(data)];
  8623.             });
  8624.           });
  8625.           return sequence(triggers);
  8626.         });
  8627.       };
  8628.       var expand = function (itemValue) {
  8629.         return get$e(expansions.get(), itemValue).map(function (menu) {
  8630.           var current = get$e(paths.get(), itemValue).getOr([]);
  8631.           return [menu].concat(current);
  8632.         });
  8633.       };
  8634.       var collapse = function (itemValue) {
  8635.         return get$e(paths.get(), itemValue).bind(function (path) {
  8636.           return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8637.         });
  8638.       };
  8639.       var refresh = function (itemValue) {
  8640.         return get$e(paths.get(), itemValue);
  8641.       };
  8642.       var getPreparedMenu = function (menuValue) {
  8643.         return lookupMenu(menuValue).bind(extractPreparedMenu);
  8644.       };
  8645.       var lookupMenu = function (menuValue) {
  8646.         return get$e(menus.get(), menuValue);
  8647.       };
  8648.       var lookupItem = function (itemValue) {
  8649.         return get$e(expansions.get(), itemValue);
  8650.       };
  8651.       var otherMenus = function (path) {
  8652.         var menuValues = directory.get();
  8653.         return difference(keys(menuValues), path);
  8654.       };
  8655.       var getPrimary = function () {
  8656.         return primary.get().bind(getPreparedMenu);
  8657.       };
  8658.       var getMenus = function () {
  8659.         return menus.get();
  8660.       };
  8661.       return {
  8662.         setMenuBuilt: setMenuBuilt,
  8663.         setContents: setContents,
  8664.         expand: expand,
  8665.         refresh: refresh,
  8666.         collapse: collapse,
  8667.         lookupMenu: lookupMenu,
  8668.         lookupItem: lookupItem,
  8669.         otherMenus: otherMenus,
  8670.         getPrimary: getPrimary,
  8671.         getMenus: getMenus,
  8672.         clear: clear,
  8673.         isClear: isClear,
  8674.         getTriggeringPath: getTriggeringPath
  8675.       };
  8676.     };
  8677.     var extractPreparedMenu = function (prep) {
  8678.       return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8679.     };
  8680.     var LayeredState = {
  8681.       init: init$c,
  8682.       extractPreparedMenu: extractPreparedMenu
  8683.     };
  8684.  
  8685.     var make$6 = function (detail, _rawUiSpec) {
  8686.       var submenuParentItems = value$1();
  8687.       var buildMenus = function (container, primaryName, menus) {
  8688.         return map$1(menus, function (spec, name) {
  8689.           var makeSketch = function () {
  8690.             return Menu.sketch(__assign(__assign({}, spec), {
  8691.               value: name,
  8692.               markers: detail.markers,
  8693.               fakeFocus: detail.fakeFocus,
  8694.               onHighlight: detail.onHighlight,
  8695.               focusManager: detail.fakeFocus ? highlights() : dom$2()
  8696.             }));
  8697.           };
  8698.           return name === primaryName ? {
  8699.             type: 'prepared',
  8700.             menu: container.getSystem().build(makeSketch())
  8701.           } : {
  8702.             type: 'notbuilt',
  8703.             nbMenu: makeSketch
  8704.           };
  8705.         });
  8706.       };
  8707.       var layeredState = LayeredState.init();
  8708.       var setup = function (container) {
  8709.         var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8710.         var directory = toDirectory();
  8711.         layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8712.         return layeredState.getPrimary();
  8713.       };
  8714.       var getItemValue = function (item) {
  8715.         return Representing.getValue(item).value;
  8716.       };
  8717.       var getItemByValue = function (_container, menus, itemValue) {
  8718.         return findMap(menus, function (menu) {
  8719.           if (!menu.getSystem().isConnected()) {
  8720.             return Optional.none();
  8721.           }
  8722.           var candidates = Highlighting.getCandidates(menu);
  8723.           return find$5(candidates, function (c) {
  8724.             return getItemValue(c) === itemValue;
  8725.           });
  8726.         });
  8727.       };
  8728.       var toDirectory = function (_container) {
  8729.         return map$1(detail.data.menus, function (data, _menuName) {
  8730.           return bind$3(data.items, function (item) {
  8731.             return item.type === 'separator' ? [] : [item.data.value];
  8732.           });
  8733.         });
  8734.       };
  8735.       var setActiveMenu = function (container, menu) {
  8736.         Highlighting.highlight(container, menu);
  8737.         Highlighting.getHighlighted(menu).orThunk(function () {
  8738.           return Highlighting.getFirst(menu);
  8739.         }).each(function (item) {
  8740.           dispatch(container, item.element, focusItem());
  8741.         });
  8742.       };
  8743.       var getMenus = function (state, menuValues) {
  8744.         return cat(map$2(menuValues, function (mv) {
  8745.           return state.lookupMenu(mv).bind(function (prep) {
  8746.             return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8747.           });
  8748.         }));
  8749.       };
  8750.       var closeOthers = function (container, state, path) {
  8751.         var others = getMenus(state, state.otherMenus(path));
  8752.         each$1(others, function (o) {
  8753.           remove$1(o.element, [detail.markers.backgroundMenu]);
  8754.           if (!detail.stayInDom) {
  8755.             Replacing.remove(container, o);
  8756.           }
  8757.         });
  8758.       };
  8759.       var getSubmenuParents = function (container) {
  8760.         return submenuParentItems.get().getOrThunk(function () {
  8761.           var r = {};
  8762.           var items = descendants(container.element, '.' + detail.markers.item);
  8763.           var parentItems = filter$2(items, function (i) {
  8764.             return get$d(i, 'aria-haspopup') === 'true';
  8765.           });
  8766.           each$1(parentItems, function (i) {
  8767.             container.getSystem().getByDom(i).each(function (itemComp) {
  8768.               var key = getItemValue(itemComp);
  8769.               r[key] = itemComp;
  8770.             });
  8771.           });
  8772.           submenuParentItems.set(r);
  8773.           return r;
  8774.         });
  8775.       };
  8776.       var updateAriaExpansions = function (container, path) {
  8777.         var parentItems = getSubmenuParents(container);
  8778.         each(parentItems, function (v, k) {
  8779.           var expanded = contains$2(path, k);
  8780.           set$8(v.element, 'aria-expanded', expanded);
  8781.         });
  8782.       };
  8783.       var updateMenuPath = function (container, state, path) {
  8784.         return Optional.from(path[0]).bind(function (latestMenuName) {
  8785.           return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8786.             if (menuPrep.type === 'notbuilt') {
  8787.               return Optional.none();
  8788.             } else {
  8789.               var activeMenu = menuPrep.menu;
  8790.               var rest = getMenus(state, path.slice(1));
  8791.               each$1(rest, function (r) {
  8792.                 add$2(r.element, detail.markers.backgroundMenu);
  8793.               });
  8794.               if (!inBody(activeMenu.element)) {
  8795.                 Replacing.append(container, premade(activeMenu));
  8796.               }
  8797.               remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  8798.               setActiveMenu(container, activeMenu);
  8799.               closeOthers(container, state, path);
  8800.               return Optional.some(activeMenu);
  8801.             }
  8802.           });
  8803.         });
  8804.       };
  8805.       var ExpandHighlightDecision;
  8806.       (function (ExpandHighlightDecision) {
  8807.         ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8808.         ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8809.       }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8810.       var buildIfRequired = function (container, menuName, menuPrep) {
  8811.         if (menuPrep.type === 'notbuilt') {
  8812.           var menu = container.getSystem().build(menuPrep.nbMenu());
  8813.           layeredState.setMenuBuilt(menuName, menu);
  8814.           return menu;
  8815.         } else {
  8816.           return menuPrep.menu;
  8817.         }
  8818.       };
  8819.       var expandRight = function (container, item, decision) {
  8820.         if (decision === void 0) {
  8821.           decision = ExpandHighlightDecision.HighlightSubmenu;
  8822.         }
  8823.         if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8824.           return Optional.some(item);
  8825.         } else {
  8826.           var value = getItemValue(item);
  8827.           return layeredState.expand(value).bind(function (path) {
  8828.             updateAriaExpansions(container, path);
  8829.             return Optional.from(path[0]).bind(function (menuName) {
  8830.               return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8831.                 var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8832.                 if (!inBody(activeMenu.element)) {
  8833.                   Replacing.append(container, premade(activeMenu));
  8834.                 }
  8835.                 detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8836.                 if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8837.                   Highlighting.highlightFirst(activeMenu);
  8838.                   return updateMenuPath(container, layeredState, path);
  8839.                 } else {
  8840.                   Highlighting.dehighlightAll(activeMenu);
  8841.                   return Optional.some(item);
  8842.                 }
  8843.               });
  8844.             });
  8845.           });
  8846.         }
  8847.       };
  8848.       var collapseLeft = function (container, item) {
  8849.         var value = getItemValue(item);
  8850.         return layeredState.collapse(value).bind(function (path) {
  8851.           updateAriaExpansions(container, path);
  8852.           return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8853.             detail.onCollapseMenu(container, item, activeMenu);
  8854.             return activeMenu;
  8855.           });
  8856.         });
  8857.       };
  8858.       var updateView = function (container, item) {
  8859.         var value = getItemValue(item);
  8860.         return layeredState.refresh(value).bind(function (path) {
  8861.           updateAriaExpansions(container, path);
  8862.           return updateMenuPath(container, layeredState, path);
  8863.         });
  8864.       };
  8865.       var onRight = function (container, item) {
  8866.         return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8867.       };
  8868.       var onLeft = function (container, item) {
  8869.         return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8870.       };
  8871.       var onEscape = function (container, item) {
  8872.         return collapseLeft(container, item).orThunk(function () {
  8873.           return detail.onEscape(container, item).map(function () {
  8874.             return container;
  8875.           });
  8876.         });
  8877.       };
  8878.       var keyOnItem = function (f) {
  8879.         return function (container, simulatedEvent) {
  8880.           return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8881.             return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8882.               return f(container, item).map(always);
  8883.             });
  8884.           });
  8885.         };
  8886.       };
  8887.       var events = derive$2([
  8888.         run$1(focus(), function (sandbox, simulatedEvent) {
  8889.           var item = simulatedEvent.event.item;
  8890.           layeredState.lookupItem(getItemValue(item)).each(function () {
  8891.             var menu = simulatedEvent.event.menu;
  8892.             Highlighting.highlight(sandbox, menu);
  8893.             var value = getItemValue(simulatedEvent.event.item);
  8894.             layeredState.refresh(value).each(function (path) {
  8895.               return closeOthers(sandbox, layeredState, path);
  8896.             });
  8897.           });
  8898.         }),
  8899.         runOnExecute$1(function (component, simulatedEvent) {
  8900.           var target = simulatedEvent.event.target;
  8901.           component.getSystem().getByDom(target).each(function (item) {
  8902.             var itemValue = getItemValue(item);
  8903.             if (itemValue.indexOf('collapse-item') === 0) {
  8904.               collapseLeft(component, item);
  8905.             }
  8906.             expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8907.               detail.onExecute(component, item);
  8908.             }, noop);
  8909.           });
  8910.         }),
  8911.         runOnAttached(function (container, _simulatedEvent) {
  8912.           setup(container).each(function (primary) {
  8913.             Replacing.append(container, premade(primary));
  8914.             detail.onOpenMenu(container, primary);
  8915.             if (detail.highlightImmediately) {
  8916.               setActiveMenu(container, primary);
  8917.             }
  8918.           });
  8919.         })
  8920.       ].concat(detail.navigateOnHover ? [run$1(hover(), function (sandbox, simulatedEvent) {
  8921.           var item = simulatedEvent.event.item;
  8922.           updateView(sandbox, item);
  8923.           expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8924.           detail.onHover(sandbox, item);
  8925.         })] : []));
  8926.       var getActiveItem = function (container) {
  8927.         return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8928.       };
  8929.       var collapseMenuApi = function (container) {
  8930.         getActiveItem(container).each(function (currentItem) {
  8931.           collapseLeft(container, currentItem);
  8932.         });
  8933.       };
  8934.       var highlightPrimary = function (container) {
  8935.         layeredState.getPrimary().each(function (primary) {
  8936.           setActiveMenu(container, primary);
  8937.         });
  8938.       };
  8939.       var extractMenuFromContainer = function (container) {
  8940.         return Optional.from(container.components()[0]).filter(function (comp) {
  8941.           return get$d(comp.element, 'role') === 'menu';
  8942.         });
  8943.       };
  8944.       var repositionMenus = function (container) {
  8945.         var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8946.           return getActiveItem(container).bind(function (currentItem) {
  8947.             var itemValue = getItemValue(currentItem);
  8948.             var allMenus = values(layeredState.getMenus());
  8949.             var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8950.             return layeredState.getTriggeringPath(itemValue, function (v) {
  8951.               return getItemByValue(container, preparedMenus, v);
  8952.             });
  8953.           }).map(function (triggeringPath) {
  8954.             return {
  8955.               primary: primary,
  8956.               triggeringPath: triggeringPath
  8957.             };
  8958.           });
  8959.         });
  8960.         maybeActivePrimary.fold(function () {
  8961.           extractMenuFromContainer(container).each(function (primaryMenu) {
  8962.             detail.onRepositionMenu(container, primaryMenu, []);
  8963.           });
  8964.         }, function (_a) {
  8965.           var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8966.           detail.onRepositionMenu(container, primary, triggeringPath);
  8967.         });
  8968.       };
  8969.       var apis = {
  8970.         collapseMenu: collapseMenuApi,
  8971.         highlightPrimary: highlightPrimary,
  8972.         repositionMenus: repositionMenus
  8973.       };
  8974.       return {
  8975.         uid: detail.uid,
  8976.         dom: detail.dom,
  8977.         markers: detail.markers,
  8978.         behaviours: augment(detail.tmenuBehaviours, [
  8979.           Keying.config({
  8980.             mode: 'special',
  8981.             onRight: keyOnItem(onRight),
  8982.             onLeft: keyOnItem(onLeft),
  8983.             onEscape: keyOnItem(onEscape),
  8984.             focusIn: function (container, _keyInfo) {
  8985.               layeredState.getPrimary().each(function (primary) {
  8986.                 dispatch(container, primary.element, focusItem());
  8987.               });
  8988.             }
  8989.           }),
  8990.           Highlighting.config({
  8991.             highlightClass: detail.markers.selectedMenu,
  8992.             itemClass: detail.markers.menu
  8993.           }),
  8994.           Composing.config({
  8995.             find: function (container) {
  8996.               return Highlighting.getHighlighted(container);
  8997.             }
  8998.           }),
  8999.           Replacing.config({})
  9000.         ]),
  9001.         eventOrder: detail.eventOrder,
  9002.         apis: apis,
  9003.         events: events
  9004.       };
  9005.     };
  9006.     var collapseItem$1 = constant$1('collapse-item');
  9007.  
  9008.     var tieredData = function (primary, menus, expansions) {
  9009.       return {
  9010.         primary: primary,
  9011.         menus: menus,
  9012.         expansions: expansions
  9013.       };
  9014.     };
  9015.     var singleData = function (name, menu) {
  9016.       return {
  9017.         primary: name,
  9018.         menus: wrap$1(name, menu),
  9019.         expansions: {}
  9020.       };
  9021.     };
  9022.     var collapseItem = function (text) {
  9023.       return {
  9024.         value: generate$6(collapseItem$1()),
  9025.         meta: { text: text }
  9026.       };
  9027.     };
  9028.     var tieredMenu = single({
  9029.       name: 'TieredMenu',
  9030.       configFields: [
  9031.         onStrictKeyboardHandler('onExecute'),
  9032.         onStrictKeyboardHandler('onEscape'),
  9033.         onStrictHandler('onOpenMenu'),
  9034.         onStrictHandler('onOpenSubmenu'),
  9035.         onHandler('onRepositionMenu'),
  9036.         onHandler('onCollapseMenu'),
  9037.         defaulted('highlightImmediately', true),
  9038.         requiredObjOf('data', [
  9039.           required$1('primary'),
  9040.           required$1('menus'),
  9041.           required$1('expansions')
  9042.         ]),
  9043.         defaulted('fakeFocus', false),
  9044.         onHandler('onHighlight'),
  9045.         onHandler('onHover'),
  9046.         tieredMenuMarkers(),
  9047.         required$1('dom'),
  9048.         defaulted('navigateOnHover', true),
  9049.         defaulted('stayInDom', false),
  9050.         field('tmenuBehaviours', [
  9051.           Keying,
  9052.           Highlighting,
  9053.           Composing,
  9054.           Replacing
  9055.         ]),
  9056.         defaulted('eventOrder', {})
  9057.       ],
  9058.       apis: {
  9059.         collapseMenu: function (apis, tmenu) {
  9060.           apis.collapseMenu(tmenu);
  9061.         },
  9062.         highlightPrimary: function (apis, tmenu) {
  9063.           apis.highlightPrimary(tmenu);
  9064.         },
  9065.         repositionMenus: function (apis, tmenu) {
  9066.           apis.repositionMenus(tmenu);
  9067.         }
  9068.       },
  9069.       factory: make$6,
  9070.       extraApis: {
  9071.         tieredData: tieredData,
  9072.         singleData: singleData,
  9073.         collapseItem: collapseItem
  9074.       }
  9075.     });
  9076.  
  9077.     var makeMenu = function (detail, menuSandbox, placementSpec, menuSpec, getBounds) {
  9078.       var lazySink = function () {
  9079.         return detail.lazySink(menuSandbox);
  9080.       };
  9081.       var layouts = menuSpec.type === 'horizontal' ? {
  9082.         layouts: {
  9083.           onLtr: function () {
  9084.             return belowOrAbove();
  9085.           },
  9086.           onRtl: function () {
  9087.             return belowOrAboveRtl();
  9088.           }
  9089.         }
  9090.       } : {};
  9091.       var isFirstTierSubmenu = function (triggeringPaths) {
  9092.         return triggeringPaths.length === 2;
  9093.       };
  9094.       var getSubmenuLayouts = function (triggeringPaths) {
  9095.         return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  9096.       };
  9097.       return tieredMenu.sketch({
  9098.         dom: { tag: 'div' },
  9099.         data: menuSpec.data,
  9100.         markers: menuSpec.menu.markers,
  9101.         highlightImmediately: menuSpec.menu.highlightImmediately,
  9102.         onEscape: function () {
  9103.           Sandboxing.close(menuSandbox);
  9104.           detail.onEscape.map(function (handler) {
  9105.             return handler(menuSandbox);
  9106.           });
  9107.           return Optional.some(true);
  9108.         },
  9109.         onExecute: function () {
  9110.           return Optional.some(true);
  9111.         },
  9112.         onOpenMenu: function (tmenu, menu) {
  9113.           Positioning.positionWithinBounds(lazySink().getOrDie(), menu, placementSpec, getBounds());
  9114.         },
  9115.         onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  9116.           var sink = lazySink().getOrDie();
  9117.           Positioning.position(sink, submenu, {
  9118.             anchor: __assign({
  9119.               type: 'submenu',
  9120.               item: item
  9121.             }, getSubmenuLayouts(triggeringPaths))
  9122.           });
  9123.         },
  9124.         onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  9125.           var sink = lazySink().getOrDie();
  9126.           Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds());
  9127.           each$1(submenuTriggers, function (st) {
  9128.             var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  9129.             Positioning.position(sink, st.triggeredMenu, {
  9130.               anchor: __assign({
  9131.                 type: 'submenu',
  9132.                 item: st.triggeringItem
  9133.               }, submenuLayouts)
  9134.             });
  9135.           });
  9136.         }
  9137.       });
  9138.     };
  9139.     var factory$m = function (detail, spec) {
  9140.       var isPartOfRelated = function (sandbox, queryElem) {
  9141.         var related = detail.getRelated(sandbox);
  9142.         return related.exists(function (rel) {
  9143.           return isPartOf$1(rel, queryElem);
  9144.         });
  9145.       };
  9146.       var setContent = function (sandbox, thing) {
  9147.         Sandboxing.setContent(sandbox, thing);
  9148.       };
  9149.       var showAt = function (sandbox, thing, placementSpec) {
  9150.         showWithin(sandbox, thing, placementSpec, Optional.none());
  9151.       };
  9152.       var showWithin = function (sandbox, thing, placementSpec, boxElement) {
  9153.         showWithinBounds(sandbox, thing, placementSpec, function () {
  9154.           return boxElement.map(function (elem) {
  9155.             return box$1(elem);
  9156.           });
  9157.         });
  9158.       };
  9159.       var showWithinBounds = function (sandbox, thing, placementSpec, getBounds) {
  9160.         var sink = detail.lazySink(sandbox).getOrDie();
  9161.         Sandboxing.openWhileCloaked(sandbox, thing, function () {
  9162.           return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds());
  9163.         });
  9164.         Representing.setValue(sandbox, Optional.some({
  9165.           mode: 'position',
  9166.           config: placementSpec,
  9167.           getBounds: getBounds
  9168.         }));
  9169.       };
  9170.       var showMenuAt = function (sandbox, placementSpec, menuSpec) {
  9171.         showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
  9172.       };
  9173.       var showMenuWithinBounds = function (sandbox, placementSpec, menuSpec, getBounds) {
  9174.         var menu = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds);
  9175.         Sandboxing.open(sandbox, menu);
  9176.         Representing.setValue(sandbox, Optional.some({
  9177.           mode: 'menu',
  9178.           menu: menu
  9179.         }));
  9180.       };
  9181.       var hide = function (sandbox) {
  9182.         if (Sandboxing.isOpen(sandbox)) {
  9183.           Representing.setValue(sandbox, Optional.none());
  9184.           Sandboxing.close(sandbox);
  9185.         }
  9186.       };
  9187.       var getContent = function (sandbox) {
  9188.         return Sandboxing.getState(sandbox);
  9189.       };
  9190.       var reposition = function (sandbox) {
  9191.         if (Sandboxing.isOpen(sandbox)) {
  9192.           Representing.getValue(sandbox).each(function (state) {
  9193.             switch (state.mode) {
  9194.             case 'menu':
  9195.               Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
  9196.               break;
  9197.             case 'position':
  9198.               var sink = detail.lazySink(sandbox).getOrDie();
  9199.               Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
  9200.               break;
  9201.             }
  9202.           });
  9203.         }
  9204.       };
  9205.       var apis = {
  9206.         setContent: setContent,
  9207.         showAt: showAt,
  9208.         showWithin: showWithin,
  9209.         showWithinBounds: showWithinBounds,
  9210.         showMenuAt: showMenuAt,
  9211.         showMenuWithinBounds: showMenuWithinBounds,
  9212.         hide: hide,
  9213.         getContent: getContent,
  9214.         reposition: reposition,
  9215.         isOpen: Sandboxing.isOpen
  9216.       };
  9217.       return {
  9218.         uid: detail.uid,
  9219.         dom: detail.dom,
  9220.         behaviours: augment(detail.inlineBehaviours, [
  9221.           Sandboxing.config({
  9222.             isPartOf: function (sandbox, data, queryElem) {
  9223.               return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  9224.             },
  9225.             getAttachPoint: function (sandbox) {
  9226.               return detail.lazySink(sandbox).getOrDie();
  9227.             },
  9228.             onOpen: function (sandbox) {
  9229.               detail.onShow(sandbox);
  9230.             },
  9231.             onClose: function (sandbox) {
  9232.               detail.onHide(sandbox);
  9233.             }
  9234.           }),
  9235.           Representing.config({
  9236.             store: {
  9237.               mode: 'memory',
  9238.               initialValue: Optional.none()
  9239.             }
  9240.           }),
  9241.           Receiving.config({
  9242.             channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) {
  9243.               return { fireEventInstead: { event: fe.event } };
  9244.             }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) {
  9245.               return { fireEventInstead: { event: fe.event } };
  9246.             }).getOr({})), { doReposition: reposition })))
  9247.           })
  9248.         ]),
  9249.         eventOrder: detail.eventOrder,
  9250.         apis: apis
  9251.       };
  9252.     };
  9253.     var InlineView = single({
  9254.       name: 'InlineView',
  9255.       configFields: [
  9256.         required$1('lazySink'),
  9257.         onHandler('onShow'),
  9258.         onHandler('onHide'),
  9259.         optionFunction('onEscape'),
  9260.         field('inlineBehaviours', [
  9261.           Sandboxing,
  9262.           Representing,
  9263.           Receiving
  9264.         ]),
  9265.         optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  9266.         optionObjOf('fireRepositionEventInstead', [defaulted('event', repositionRequested())]),
  9267.         defaulted('getRelated', Optional.none),
  9268.         defaulted('isExtraPart', never),
  9269.         defaulted('eventOrder', Optional.none)
  9270.       ],
  9271.       factory: factory$m,
  9272.       apis: {
  9273.         showAt: function (apis, component, anchor, thing) {
  9274.           apis.showAt(component, anchor, thing);
  9275.         },
  9276.         showWithin: function (apis, component, anchor, thing, boxElement) {
  9277.           apis.showWithin(component, anchor, thing, boxElement);
  9278.         },
  9279.         showWithinBounds: function (apis, component, anchor, thing, bounds) {
  9280.           apis.showWithinBounds(component, anchor, thing, bounds);
  9281.         },
  9282.         showMenuAt: function (apis, component, anchor, menuSpec) {
  9283.           apis.showMenuAt(component, anchor, menuSpec);
  9284.         },
  9285.         showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  9286.           apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  9287.         },
  9288.         hide: function (apis, component) {
  9289.           apis.hide(component);
  9290.         },
  9291.         isOpen: function (apis, component) {
  9292.           return apis.isOpen(component);
  9293.         },
  9294.         getContent: function (apis, component) {
  9295.           return apis.getContent(component);
  9296.         },
  9297.         setContent: function (apis, component, thing) {
  9298.           apis.setContent(component, thing);
  9299.         },
  9300.         reposition: function (apis, component) {
  9301.           apis.reposition(component);
  9302.         }
  9303.       }
  9304.     });
  9305.  
  9306.     var labelPrefix = 'layout-inset';
  9307.     var westEdgeX = function (anchor) {
  9308.       return anchor.x;
  9309.     };
  9310.     var middleX = function (anchor, element) {
  9311.       return anchor.x + anchor.width / 2 - element.width / 2;
  9312.     };
  9313.     var eastEdgeX = function (anchor, element) {
  9314.       return anchor.x + anchor.width - element.width;
  9315.     };
  9316.     var northY = function (anchor) {
  9317.       return anchor.y;
  9318.     };
  9319.     var southY = function (anchor, element) {
  9320.       return anchor.y + anchor.height - element.height;
  9321.     };
  9322.     var centreY = function (anchor, element) {
  9323.       return anchor.y + anchor.height / 2 - element.height / 2;
  9324.     };
  9325.     var southwest = function (anchor, element, bubbles) {
  9326.       return nu$6(eastEdgeX(anchor, element), southY(anchor, element), bubbles.insetSouthwest(), northwest$3(), 'southwest', boundsRestriction(anchor, {
  9327.         right: 0,
  9328.         bottom: 3
  9329.       }), labelPrefix);
  9330.     };
  9331.     var southeast = function (anchor, element, bubbles) {
  9332.       return nu$6(westEdgeX(anchor), southY(anchor, element), bubbles.insetSoutheast(), northeast$3(), 'southeast', boundsRestriction(anchor, {
  9333.         left: 1,
  9334.         bottom: 3
  9335.       }), labelPrefix);
  9336.     };
  9337.     var northwest = function (anchor, element, bubbles) {
  9338.       return nu$6(eastEdgeX(anchor, element), northY(anchor), bubbles.insetNorthwest(), southwest$3(), 'northwest', boundsRestriction(anchor, {
  9339.         right: 0,
  9340.         top: 2
  9341.       }), labelPrefix);
  9342.     };
  9343.     var northeast = function (anchor, element, bubbles) {
  9344.       return nu$6(westEdgeX(anchor), northY(anchor), bubbles.insetNortheast(), southeast$3(), 'northeast', boundsRestriction(anchor, {
  9345.         left: 1,
  9346.         top: 2
  9347.       }), labelPrefix);
  9348.     };
  9349.     var north = function (anchor, element, bubbles) {
  9350.       return nu$6(middleX(anchor, element), northY(anchor), bubbles.insetNorth(), south$3(), 'north', boundsRestriction(anchor, { top: 2 }), labelPrefix);
  9351.     };
  9352.     var south = function (anchor, element, bubbles) {
  9353.       return nu$6(middleX(anchor, element), southY(anchor, element), bubbles.insetSouth(), north$3(), 'south', boundsRestriction(anchor, { bottom: 3 }), labelPrefix);
  9354.     };
  9355.     var east = function (anchor, element, bubbles) {
  9356.       return nu$6(eastEdgeX(anchor, element), centreY(anchor, element), bubbles.insetEast(), west$3(), 'east', boundsRestriction(anchor, { right: 0 }), labelPrefix);
  9357.     };
  9358.     var west = function (anchor, element, bubbles) {
  9359.       return nu$6(westEdgeX(anchor), centreY(anchor, element), bubbles.insetWest(), east$3(), 'west', boundsRestriction(anchor, { left: 1 }), labelPrefix);
  9360.     };
  9361.     var lookupPreserveLayout = function (lastPlacement) {
  9362.       switch (lastPlacement) {
  9363.       case 'north':
  9364.         return north;
  9365.       case 'northeast':
  9366.         return northeast;
  9367.       case 'northwest':
  9368.         return northwest;
  9369.       case 'south':
  9370.         return south;
  9371.       case 'southeast':
  9372.         return southeast;
  9373.       case 'southwest':
  9374.         return southwest;
  9375.       case 'east':
  9376.         return east;
  9377.       case 'west':
  9378.         return west;
  9379.       }
  9380.     };
  9381.     var preserve = function (anchor, element, bubbles, placee, bounds) {
  9382.       var layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
  9383.       return layout(anchor, element, bubbles, placee, bounds);
  9384.     };
  9385.     var lookupFlippedLayout = function (lastPlacement) {
  9386.       switch (lastPlacement) {
  9387.       case 'north':
  9388.         return south;
  9389.       case 'northeast':
  9390.         return southeast;
  9391.       case 'northwest':
  9392.         return southwest;
  9393.       case 'south':
  9394.         return north;
  9395.       case 'southeast':
  9396.         return northeast;
  9397.       case 'southwest':
  9398.         return northwest;
  9399.       case 'east':
  9400.         return west;
  9401.       case 'west':
  9402.         return east;
  9403.       }
  9404.     };
  9405.     var flip$2 = function (anchor, element, bubbles, placee, bounds) {
  9406.       var layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
  9407.       return layout(anchor, element, bubbles, placee, bounds);
  9408.     };
  9409.  
  9410.     var global$f = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9411.  
  9412.     var factory$l = function (detail) {
  9413.       var events = events$a(detail.action);
  9414.       var tag = detail.dom.tag;
  9415.       var lookupAttr = function (attr) {
  9416.         return get$e(detail.dom, 'attributes').bind(function (attrs) {
  9417.           return get$e(attrs, attr);
  9418.         });
  9419.       };
  9420.       var getModAttributes = function () {
  9421.         if (tag === 'button') {
  9422.           var type = lookupAttr('type').getOr('button');
  9423.           var roleAttrs = lookupAttr('role').map(function (role) {
  9424.             return { role: role };
  9425.           }).getOr({});
  9426.           return __assign({ type: type }, roleAttrs);
  9427.         } else {
  9428.           var role = lookupAttr('role').getOr('button');
  9429.           return { role: role };
  9430.         }
  9431.       };
  9432.       return {
  9433.         uid: detail.uid,
  9434.         dom: detail.dom,
  9435.         components: detail.components,
  9436.         events: events,
  9437.         behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  9438.           Focusing.config({}),
  9439.           Keying.config({
  9440.             mode: 'execution',
  9441.             useSpace: true,
  9442.             useEnter: true
  9443.           })
  9444.         ]),
  9445.         domModification: { attributes: getModAttributes() },
  9446.         eventOrder: detail.eventOrder
  9447.       };
  9448.     };
  9449.     var Button = single({
  9450.       name: 'Button',
  9451.       factory: factory$l,
  9452.       configFields: [
  9453.         defaulted('uid', undefined),
  9454.         required$1('dom'),
  9455.         defaulted('components', []),
  9456.         SketchBehaviours.field('buttonBehaviours', [
  9457.           Focusing,
  9458.           Keying
  9459.         ]),
  9460.         option('action'),
  9461.         option('role'),
  9462.         defaulted('eventOrder', {})
  9463.       ]
  9464.     });
  9465.  
  9466.     var getAttrs = function (elem) {
  9467.       var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  9468.       return foldl(attributes, function (b, attr) {
  9469.         var _a;
  9470.         if (attr.name === 'class') {
  9471.           return b;
  9472.         } else {
  9473.           return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  9474.         }
  9475.       }, {});
  9476.     };
  9477.     var getClasses = function (elem) {
  9478.       return Array.prototype.slice.call(elem.dom.classList, 0);
  9479.     };
  9480.     var fromHtml = function (html) {
  9481.       var elem = SugarElement.fromHtml(html);
  9482.       var children$1 = children(elem);
  9483.       var attrs = getAttrs(elem);
  9484.       var classes = getClasses(elem);
  9485.       var contents = children$1.length === 0 ? {} : { innerHtml: get$7(elem) };
  9486.       return __assign({
  9487.         tag: name$2(elem),
  9488.         classes: classes,
  9489.         attributes: attrs
  9490.       }, contents);
  9491.     };
  9492.  
  9493.     var record = function (spec) {
  9494.       var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$5('memento');
  9495.       var get = function (anyInSystem) {
  9496.         return anyInSystem.getSystem().getByUid(uid).getOrDie();
  9497.       };
  9498.       var getOpt = function (anyInSystem) {
  9499.         return anyInSystem.getSystem().getByUid(uid).toOptional();
  9500.       };
  9501.       var asSpec = function () {
  9502.         return __assign(__assign({}, spec), { uid: uid });
  9503.       };
  9504.       return {
  9505.         get: get,
  9506.         getOpt: getOpt,
  9507.         asSpec: asSpec
  9508.       };
  9509.     };
  9510.  
  9511.     function _typeof(obj) {
  9512.       '@babel/helpers - typeof';
  9513.       return _typeof = 'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator ? function (obj) {
  9514.         return typeof obj;
  9515.       } : function (obj) {
  9516.         return obj && 'function' == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? 'symbol' : typeof obj;
  9517.       }, _typeof(obj);
  9518.     }
  9519.     function _setPrototypeOf(o, p) {
  9520.       _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  9521.         o.__proto__ = p;
  9522.         return o;
  9523.       };
  9524.       return _setPrototypeOf(o, p);
  9525.     }
  9526.     function _isNativeReflectConstruct() {
  9527.       if (typeof Reflect === 'undefined' || !Reflect.construct)
  9528.         return false;
  9529.       if (Reflect.construct.sham)
  9530.         return false;
  9531.       if (typeof Proxy === 'function')
  9532.         return true;
  9533.       try {
  9534.         Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {
  9535.         }));
  9536.         return true;
  9537.       } catch (e) {
  9538.         return false;
  9539.       }
  9540.     }
  9541.     function _construct(Parent, args, Class) {
  9542.       if (_isNativeReflectConstruct()) {
  9543.         _construct = Reflect.construct;
  9544.       } else {
  9545.         _construct = function _construct(Parent, args, Class) {
  9546.           var a = [null];
  9547.           a.push.apply(a, args);
  9548.           var Constructor = Function.bind.apply(Parent, a);
  9549.           var instance = new Constructor();
  9550.           if (Class)
  9551.             _setPrototypeOf(instance, Class.prototype);
  9552.           return instance;
  9553.         };
  9554.       }
  9555.       return _construct.apply(null, arguments);
  9556.     }
  9557.     function _toConsumableArray(arr) {
  9558.       return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  9559.     }
  9560.     function _arrayWithoutHoles(arr) {
  9561.       if (Array.isArray(arr))
  9562.         return _arrayLikeToArray(arr);
  9563.     }
  9564.     function _iterableToArray(iter) {
  9565.       if (typeof Symbol !== 'undefined' && iter[Symbol.iterator] != null || iter['@@iterator'] != null)
  9566.         return Array.from(iter);
  9567.     }
  9568.     function _unsupportedIterableToArray(o, minLen) {
  9569.       if (!o)
  9570.         return;
  9571.       if (typeof o === 'string')
  9572.         return _arrayLikeToArray(o, minLen);
  9573.       var n = Object.prototype.toString.call(o).slice(8, -1);
  9574.       if (n === 'Object' && o.constructor)
  9575.         n = o.constructor.name;
  9576.       if (n === 'Map' || n === 'Set')
  9577.         return Array.from(o);
  9578.       if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
  9579.         return _arrayLikeToArray(o, minLen);
  9580.     }
  9581.     function _arrayLikeToArray(arr, len) {
  9582.       if (len == null || len > arr.length)
  9583.         len = arr.length;
  9584.       for (var i = 0, arr2 = new Array(len); i < len; i++)
  9585.         arr2[i] = arr[i];
  9586.       return arr2;
  9587.     }
  9588.     function _nonIterableSpread() {
  9589.       throw new TypeError('Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.');
  9590.     }
  9591.     var hasOwnProperty = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
  9592.     var freeze = Object.freeze, seal = Object.seal, create$5 = Object.create;
  9593.     var _ref = typeof Reflect !== 'undefined' && Reflect, apply$1 = _ref.apply, construct = _ref.construct;
  9594.     if (!apply$1) {
  9595.       apply$1 = function apply(fun, thisValue, args) {
  9596.         return fun.apply(thisValue, args);
  9597.       };
  9598.     }
  9599.     if (!freeze) {
  9600.       freeze = function freeze(x) {
  9601.         return x;
  9602.       };
  9603.     }
  9604.     if (!seal) {
  9605.       seal = function seal(x) {
  9606.         return x;
  9607.       };
  9608.     }
  9609.     if (!construct) {
  9610.       construct = function construct(Func, args) {
  9611.         return _construct(Func, _toConsumableArray(args));
  9612.       };
  9613.     }
  9614.     var arrayForEach = unapply(Array.prototype.forEach);
  9615.     var arrayPop = unapply(Array.prototype.pop);
  9616.     var arrayPush = unapply(Array.prototype.push);
  9617.     var stringToLowerCase = unapply(String.prototype.toLowerCase);
  9618.     var stringMatch = unapply(String.prototype.match);
  9619.     var stringReplace = unapply(String.prototype.replace);
  9620.     var stringIndexOf = unapply(String.prototype.indexOf);
  9621.     var stringTrim = unapply(String.prototype.trim);
  9622.     var regExpTest = unapply(RegExp.prototype.test);
  9623.     var typeErrorCreate = unconstruct(TypeError);
  9624.     function unapply(func) {
  9625.       return function (thisArg) {
  9626.         for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  9627.           args[_key - 1] = arguments[_key];
  9628.         }
  9629.         return apply$1(func, thisArg, args);
  9630.       };
  9631.     }
  9632.     function unconstruct(func) {
  9633.       return function () {
  9634.         for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  9635.           args[_key2] = arguments[_key2];
  9636.         }
  9637.         return construct(func, args);
  9638.       };
  9639.     }
  9640.     function addToSet(set, array) {
  9641.       if (setPrototypeOf) {
  9642.         setPrototypeOf(set, null);
  9643.       }
  9644.       var l = array.length;
  9645.       while (l--) {
  9646.         var element = array[l];
  9647.         if (typeof element === 'string') {
  9648.           var lcElement = stringToLowerCase(element);
  9649.           if (lcElement !== element) {
  9650.             if (!isFrozen(array)) {
  9651.               array[l] = lcElement;
  9652.             }
  9653.             element = lcElement;
  9654.           }
  9655.         }
  9656.         set[element] = true;
  9657.       }
  9658.       return set;
  9659.     }
  9660.     function clone$1(object) {
  9661.       var newObject = create$5(null);
  9662.       var property;
  9663.       for (property in object) {
  9664.         if (apply$1(hasOwnProperty, object, [property])) {
  9665.           newObject[property] = object[property];
  9666.         }
  9667.       }
  9668.       return newObject;
  9669.     }
  9670.     function lookupGetter(object, prop) {
  9671.       while (object !== null) {
  9672.         var desc = getOwnPropertyDescriptor(object, prop);
  9673.         if (desc) {
  9674.           if (desc.get) {
  9675.             return unapply(desc.get);
  9676.           }
  9677.           if (typeof desc.value === 'function') {
  9678.             return unapply(desc.value);
  9679.           }
  9680.         }
  9681.         object = getPrototypeOf(object);
  9682.       }
  9683.       function fallbackValue(element) {
  9684.         console.warn('fallback value for', element);
  9685.         return null;
  9686.       }
  9687.       return fallbackValue;
  9688.     }
  9689.     var html$1 = freeze([
  9690.       'a',
  9691.       'abbr',
  9692.       'acronym',
  9693.       'address',
  9694.       'area',
  9695.       'article',
  9696.       'aside',
  9697.       'audio',
  9698.       'b',
  9699.       'bdi',
  9700.       'bdo',
  9701.       'big',
  9702.       'blink',
  9703.       'blockquote',
  9704.       'body',
  9705.       'br',
  9706.       'button',
  9707.       'canvas',
  9708.       'caption',
  9709.       'center',
  9710.       'cite',
  9711.       'code',
  9712.       'col',
  9713.       'colgroup',
  9714.       'content',
  9715.       'data',
  9716.       'datalist',
  9717.       'dd',
  9718.       'decorator',
  9719.       'del',
  9720.       'details',
  9721.       'dfn',
  9722.       'dialog',
  9723.       'dir',
  9724.       'div',
  9725.       'dl',
  9726.       'dt',
  9727.       'element',
  9728.       'em',
  9729.       'fieldset',
  9730.       'figcaption',
  9731.       'figure',
  9732.       'font',
  9733.       'footer',
  9734.       'form',
  9735.       'h1',
  9736.       'h2',
  9737.       'h3',
  9738.       'h4',
  9739.       'h5',
  9740.       'h6',
  9741.       'head',
  9742.       'header',
  9743.       'hgroup',
  9744.       'hr',
  9745.       'html',
  9746.       'i',
  9747.       'img',
  9748.       'input',
  9749.       'ins',
  9750.       'kbd',
  9751.       'label',
  9752.       'legend',
  9753.       'li',
  9754.       'main',
  9755.       'map',
  9756.       'mark',
  9757.       'marquee',
  9758.       'menu',
  9759.       'menuitem',
  9760.       'meter',
  9761.       'nav',
  9762.       'nobr',
  9763.       'ol',
  9764.       'optgroup',
  9765.       'option',
  9766.       'output',
  9767.       'p',
  9768.       'picture',
  9769.       'pre',
  9770.       'progress',
  9771.       'q',
  9772.       'rp',
  9773.       'rt',
  9774.       'ruby',
  9775.       's',
  9776.       'samp',
  9777.       'section',
  9778.       'select',
  9779.       'shadow',
  9780.       'small',
  9781.       'source',
  9782.       'spacer',
  9783.       'span',
  9784.       'strike',
  9785.       'strong',
  9786.       'style',
  9787.       'sub',
  9788.       'summary',
  9789.       'sup',
  9790.       'table',
  9791.       'tbody',
  9792.       'td',
  9793.       'template',
  9794.       'textarea',
  9795.       'tfoot',
  9796.       'th',
  9797.       'thead',
  9798.       'time',
  9799.       'tr',
  9800.       'track',
  9801.       'tt',
  9802.       'u',
  9803.       'ul',
  9804.       'var',
  9805.       'video',
  9806.       'wbr'
  9807.     ]);
  9808.     var svg$1 = freeze([
  9809.       'svg',
  9810.       'a',
  9811.       'altglyph',
  9812.       'altglyphdef',
  9813.       'altglyphitem',
  9814.       'animatecolor',
  9815.       'animatemotion',
  9816.       'animatetransform',
  9817.       'circle',
  9818.       'clippath',
  9819.       'defs',
  9820.       'desc',
  9821.       'ellipse',
  9822.       'filter',
  9823.       'font',
  9824.       'g',
  9825.       'glyph',
  9826.       'glyphref',
  9827.       'hkern',
  9828.       'image',
  9829.       'line',
  9830.       'lineargradient',
  9831.       'marker',
  9832.       'mask',
  9833.       'metadata',
  9834.       'mpath',
  9835.       'path',
  9836.       'pattern',
  9837.       'polygon',
  9838.       'polyline',
  9839.       'radialgradient',
  9840.       'rect',
  9841.       'stop',
  9842.       'style',
  9843.       'switch',
  9844.       'symbol',
  9845.       'text',
  9846.       'textpath',
  9847.       'title',
  9848.       'tref',
  9849.       'tspan',
  9850.       'view',
  9851.       'vkern'
  9852.     ]);
  9853.     var svgFilters = freeze([
  9854.       'feBlend',
  9855.       'feColorMatrix',
  9856.       'feComponentTransfer',
  9857.       'feComposite',
  9858.       'feConvolveMatrix',
  9859.       'feDiffuseLighting',
  9860.       'feDisplacementMap',
  9861.       'feDistantLight',
  9862.       'feFlood',
  9863.       'feFuncA',
  9864.       'feFuncB',
  9865.       'feFuncG',
  9866.       'feFuncR',
  9867.       'feGaussianBlur',
  9868.       'feImage',
  9869.       'feMerge',
  9870.       'feMergeNode',
  9871.       'feMorphology',
  9872.       'feOffset',
  9873.       'fePointLight',
  9874.       'feSpecularLighting',
  9875.       'feSpotLight',
  9876.       'feTile',
  9877.       'feTurbulence'
  9878.     ]);
  9879.     var svgDisallowed = freeze([
  9880.       'animate',
  9881.       'color-profile',
  9882.       'cursor',
  9883.       'discard',
  9884.       'fedropshadow',
  9885.       'font-face',
  9886.       'font-face-format',
  9887.       'font-face-name',
  9888.       'font-face-src',
  9889.       'font-face-uri',
  9890.       'foreignobject',
  9891.       'hatch',
  9892.       'hatchpath',
  9893.       'mesh',
  9894.       'meshgradient',
  9895.       'meshpatch',
  9896.       'meshrow',
  9897.       'missing-glyph',
  9898.       'script',
  9899.       'set',
  9900.       'solidcolor',
  9901.       'unknown',
  9902.       'use'
  9903.     ]);
  9904.     var mathMl$1 = freeze([
  9905.       'math',
  9906.       'menclose',
  9907.       'merror',
  9908.       'mfenced',
  9909.       'mfrac',
  9910.       'mglyph',
  9911.       'mi',
  9912.       'mlabeledtr',
  9913.       'mmultiscripts',
  9914.       'mn',
  9915.       'mo',
  9916.       'mover',
  9917.       'mpadded',
  9918.       'mphantom',
  9919.       'mroot',
  9920.       'mrow',
  9921.       'ms',
  9922.       'mspace',
  9923.       'msqrt',
  9924.       'mstyle',
  9925.       'msub',
  9926.       'msup',
  9927.       'msubsup',
  9928.       'mtable',
  9929.       'mtd',
  9930.       'mtext',
  9931.       'mtr',
  9932.       'munder',
  9933.       'munderover'
  9934.     ]);
  9935.     var mathMlDisallowed = freeze([
  9936.       'maction',
  9937.       'maligngroup',
  9938.       'malignmark',
  9939.       'mlongdiv',
  9940.       'mscarries',
  9941.       'mscarry',
  9942.       'msgroup',
  9943.       'mstack',
  9944.       'msline',
  9945.       'msrow',
  9946.       'semantics',
  9947.       'annotation',
  9948.       'annotation-xml',
  9949.       'mprescripts',
  9950.       'none'
  9951.     ]);
  9952.     var text = freeze(['#text']);
  9953.     var html = freeze([
  9954.       'accept',
  9955.       'action',
  9956.       'align',
  9957.       'alt',
  9958.       'autocapitalize',
  9959.       'autocomplete',
  9960.       'autopictureinpicture',
  9961.       'autoplay',
  9962.       'background',
  9963.       'bgcolor',
  9964.       'border',
  9965.       'capture',
  9966.       'cellpadding',
  9967.       'cellspacing',
  9968.       'checked',
  9969.       'cite',
  9970.       'class',
  9971.       'clear',
  9972.       'color',
  9973.       'cols',
  9974.       'colspan',
  9975.       'controls',
  9976.       'controlslist',
  9977.       'coords',
  9978.       'crossorigin',
  9979.       'datetime',
  9980.       'decoding',
  9981.       'default',
  9982.       'dir',
  9983.       'disabled',
  9984.       'disablepictureinpicture',
  9985.       'disableremoteplayback',
  9986.       'download',
  9987.       'draggable',
  9988.       'enctype',
  9989.       'enterkeyhint',
  9990.       'face',
  9991.       'for',
  9992.       'headers',
  9993.       'height',
  9994.       'hidden',
  9995.       'high',
  9996.       'href',
  9997.       'hreflang',
  9998.       'id',
  9999.       'inputmode',
  10000.       'integrity',
  10001.       'ismap',
  10002.       'kind',
  10003.       'label',
  10004.       'lang',
  10005.       'list',
  10006.       'loading',
  10007.       'loop',
  10008.       'low',
  10009.       'max',
  10010.       'maxlength',
  10011.       'media',
  10012.       'method',
  10013.       'min',
  10014.       'minlength',
  10015.       'multiple',
  10016.       'muted',
  10017.       'name',
  10018.       'nonce',
  10019.       'noshade',
  10020.       'novalidate',
  10021.       'nowrap',
  10022.       'open',
  10023.       'optimum',
  10024.       'pattern',
  10025.       'placeholder',
  10026.       'playsinline',
  10027.       'poster',
  10028.       'preload',
  10029.       'pubdate',
  10030.       'radiogroup',
  10031.       'readonly',
  10032.       'rel',
  10033.       'required',
  10034.       'rev',
  10035.       'reversed',
  10036.       'role',
  10037.       'rows',
  10038.       'rowspan',
  10039.       'spellcheck',
  10040.       'scope',
  10041.       'selected',
  10042.       'shape',
  10043.       'size',
  10044.       'sizes',
  10045.       'span',
  10046.       'srclang',
  10047.       'start',
  10048.       'src',
  10049.       'srcset',
  10050.       'step',
  10051.       'style',
  10052.       'summary',
  10053.       'tabindex',
  10054.       'title',
  10055.       'translate',
  10056.       'type',
  10057.       'usemap',
  10058.       'valign',
  10059.       'value',
  10060.       'width',
  10061.       'xmlns',
  10062.       'slot'
  10063.     ]);
  10064.     var svg = freeze([
  10065.       'accent-height',
  10066.       'accumulate',
  10067.       'additive',
  10068.       'alignment-baseline',
  10069.       'ascent',
  10070.       'attributename',
  10071.       'attributetype',
  10072.       'azimuth',
  10073.       'basefrequency',
  10074.       'baseline-shift',
  10075.       'begin',
  10076.       'bias',
  10077.       'by',
  10078.       'class',
  10079.       'clip',
  10080.       'clippathunits',
  10081.       'clip-path',
  10082.       'clip-rule',
  10083.       'color',
  10084.       'color-interpolation',
  10085.       'color-interpolation-filters',
  10086.       'color-profile',
  10087.       'color-rendering',
  10088.       'cx',
  10089.       'cy',
  10090.       'd',
  10091.       'dx',
  10092.       'dy',
  10093.       'diffuseconstant',
  10094.       'direction',
  10095.       'display',
  10096.       'divisor',
  10097.       'dur',
  10098.       'edgemode',
  10099.       'elevation',
  10100.       'end',
  10101.       'fill',
  10102.       'fill-opacity',
  10103.       'fill-rule',
  10104.       'filter',
  10105.       'filterunits',
  10106.       'flood-color',
  10107.       'flood-opacity',
  10108.       'font-family',
  10109.       'font-size',
  10110.       'font-size-adjust',
  10111.       'font-stretch',
  10112.       'font-style',
  10113.       'font-variant',
  10114.       'font-weight',
  10115.       'fx',
  10116.       'fy',
  10117.       'g1',
  10118.       'g2',
  10119.       'glyph-name',
  10120.       'glyphref',
  10121.       'gradientunits',
  10122.       'gradienttransform',
  10123.       'height',
  10124.       'href',
  10125.       'id',
  10126.       'image-rendering',
  10127.       'in',
  10128.       'in2',
  10129.       'k',
  10130.       'k1',
  10131.       'k2',
  10132.       'k3',
  10133.       'k4',
  10134.       'kerning',
  10135.       'keypoints',
  10136.       'keysplines',
  10137.       'keytimes',
  10138.       'lang',
  10139.       'lengthadjust',
  10140.       'letter-spacing',
  10141.       'kernelmatrix',
  10142.       'kernelunitlength',
  10143.       'lighting-color',
  10144.       'local',
  10145.       'marker-end',
  10146.       'marker-mid',
  10147.       'marker-start',
  10148.       'markerheight',
  10149.       'markerunits',
  10150.       'markerwidth',
  10151.       'maskcontentunits',
  10152.       'maskunits',
  10153.       'max',
  10154.       'mask',
  10155.       'media',
  10156.       'method',
  10157.       'mode',
  10158.       'min',
  10159.       'name',
  10160.       'numoctaves',
  10161.       'offset',
  10162.       'operator',
  10163.       'opacity',
  10164.       'order',
  10165.       'orient',
  10166.       'orientation',
  10167.       'origin',
  10168.       'overflow',
  10169.       'paint-order',
  10170.       'path',
  10171.       'pathlength',
  10172.       'patterncontentunits',
  10173.       'patterntransform',
  10174.       'patternunits',
  10175.       'points',
  10176.       'preservealpha',
  10177.       'preserveaspectratio',
  10178.       'primitiveunits',
  10179.       'r',
  10180.       'rx',
  10181.       'ry',
  10182.       'radius',
  10183.       'refx',
  10184.       'refy',
  10185.       'repeatcount',
  10186.       'repeatdur',
  10187.       'restart',
  10188.       'result',
  10189.       'rotate',
  10190.       'scale',
  10191.       'seed',
  10192.       'shape-rendering',
  10193.       'specularconstant',
  10194.       'specularexponent',
  10195.       'spreadmethod',
  10196.       'startoffset',
  10197.       'stddeviation',
  10198.       'stitchtiles',
  10199.       'stop-color',
  10200.       'stop-opacity',
  10201.       'stroke-dasharray',
  10202.       'stroke-dashoffset',
  10203.       'stroke-linecap',
  10204.       'stroke-linejoin',
  10205.       'stroke-miterlimit',
  10206.       'stroke-opacity',
  10207.       'stroke',
  10208.       'stroke-width',
  10209.       'style',
  10210.       'surfacescale',
  10211.       'systemlanguage',
  10212.       'tabindex',
  10213.       'targetx',
  10214.       'targety',
  10215.       'transform',
  10216.       'transform-origin',
  10217.       'text-anchor',
  10218.       'text-decoration',
  10219.       'text-rendering',
  10220.       'textlength',
  10221.       'type',
  10222.       'u1',
  10223.       'u2',
  10224.       'unicode',
  10225.       'values',
  10226.       'viewbox',
  10227.       'visibility',
  10228.       'version',
  10229.       'vert-adv-y',
  10230.       'vert-origin-x',
  10231.       'vert-origin-y',
  10232.       'width',
  10233.       'word-spacing',
  10234.       'wrap',
  10235.       'writing-mode',
  10236.       'xchannelselector',
  10237.       'ychannelselector',
  10238.       'x',
  10239.       'x1',
  10240.       'x2',
  10241.       'xmlns',
  10242.       'y',
  10243.       'y1',
  10244.       'y2',
  10245.       'z',
  10246.       'zoomandpan'
  10247.     ]);
  10248.     var mathMl = freeze([
  10249.       'accent',
  10250.       'accentunder',
  10251.       'align',
  10252.       'bevelled',
  10253.       'close',
  10254.       'columnsalign',
  10255.       'columnlines',
  10256.       'columnspan',
  10257.       'denomalign',
  10258.       'depth',
  10259.       'dir',
  10260.       'display',
  10261.       'displaystyle',
  10262.       'encoding',
  10263.       'fence',
  10264.       'frame',
  10265.       'height',
  10266.       'href',
  10267.       'id',
  10268.       'largeop',
  10269.       'length',
  10270.       'linethickness',
  10271.       'lspace',
  10272.       'lquote',
  10273.       'mathbackground',
  10274.       'mathcolor',
  10275.       'mathsize',
  10276.       'mathvariant',
  10277.       'maxsize',
  10278.       'minsize',
  10279.       'movablelimits',
  10280.       'notation',
  10281.       'numalign',
  10282.       'open',
  10283.       'rowalign',
  10284.       'rowlines',
  10285.       'rowspacing',
  10286.       'rowspan',
  10287.       'rspace',
  10288.       'rquote',
  10289.       'scriptlevel',
  10290.       'scriptminsize',
  10291.       'scriptsizemultiplier',
  10292.       'selection',
  10293.       'separator',
  10294.       'separators',
  10295.       'stretchy',
  10296.       'subscriptshift',
  10297.       'supscriptshift',
  10298.       'symmetric',
  10299.       'voffset',
  10300.       'width',
  10301.       'xmlns'
  10302.     ]);
  10303.     var xml = freeze([
  10304.       'xlink:href',
  10305.       'xml:id',
  10306.       'xlink:title',
  10307.       'xml:space',
  10308.       'xmlns:xlink'
  10309.     ]);
  10310.     var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm);
  10311.     var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
  10312.     var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
  10313.     var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
  10314.     var IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i);
  10315.     var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
  10316.     var ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g);
  10317.     var DOCTYPE_NAME = seal(/^html$/i);
  10318.     var getGlobal = function getGlobal() {
  10319.       return typeof window === 'undefined' ? null : window;
  10320.     };
  10321.     var _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {
  10322.       if (_typeof(trustedTypes) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
  10323.         return null;
  10324.       }
  10325.       var suffix = null;
  10326.       var ATTR_NAME = 'data-tt-policy-suffix';
  10327.       if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {
  10328.         suffix = document.currentScript.getAttribute(ATTR_NAME);
  10329.       }
  10330.       var policyName = 'dompurify' + (suffix ? '#' + suffix : '');
  10331.       try {
  10332.         return trustedTypes.createPolicy(policyName, {
  10333.           createHTML: function createHTML(html) {
  10334.             return html;
  10335.           }
  10336.         });
  10337.       } catch (_) {
  10338.         console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
  10339.         return null;
  10340.       }
  10341.     };
  10342.     function createDOMPurify() {
  10343.       var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
  10344.       var DOMPurify = function DOMPurify(root) {
  10345.         return createDOMPurify(root);
  10346.       };
  10347.       DOMPurify.version = '2.3.8';
  10348.       DOMPurify.removed = [];
  10349.       if (!window || !window.document || window.document.nodeType !== 9) {
  10350.         DOMPurify.isSupported = false;
  10351.         return DOMPurify;
  10352.       }
  10353.       var originalDocument = window.document;
  10354.       var document = window.document;
  10355.       var DocumentFragment = window.DocumentFragment, HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter, _window$NamedNodeMap = window.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap, HTMLFormElement = window.HTMLFormElement, DOMParser = window.DOMParser, trustedTypes = window.trustedTypes;
  10356.       var ElementPrototype = Element.prototype;
  10357.       var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
  10358.       var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
  10359.       var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
  10360.       var getParentNode = lookupGetter(ElementPrototype, 'parentNode');
  10361.       if (typeof HTMLTemplateElement === 'function') {
  10362.         var template = document.createElement('template');
  10363.         if (template.content && template.content.ownerDocument) {
  10364.           document = template.content.ownerDocument;
  10365.         }
  10366.       }
  10367.       var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  10368.       var emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML('') : '';
  10369.       var _document = document, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  10370.       var importNode = originalDocument.importNode;
  10371.       var documentMode = {};
  10372.       try {
  10373.         documentMode = clone$1(document).documentMode ? document.documentMode : {};
  10374.       } catch (_) {
  10375.       }
  10376.       var hooks = {};
  10377.       DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;
  10378.       var MUSTACHE_EXPR$1 = MUSTACHE_EXPR, ERB_EXPR$1 = ERB_EXPR, DATA_ATTR$1 = DATA_ATTR, ARIA_ATTR$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$1 = ATTR_WHITESPACE;
  10379.       var IS_ALLOWED_URI$1 = IS_ALLOWED_URI;
  10380.       var ALLOWED_TAGS = null;
  10381.       var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray(html$1), _toConsumableArray(svg$1), _toConsumableArray(svgFilters), _toConsumableArray(mathMl$1), _toConsumableArray(text)));
  10382.       var ALLOWED_ATTR = null;
  10383.       var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray(html), _toConsumableArray(svg), _toConsumableArray(mathMl), _toConsumableArray(xml)));
  10384.       var CUSTOM_ELEMENT_HANDLING = Object.seal(Object.create(null, {
  10385.         tagNameCheck: {
  10386.           writable: true,
  10387.           configurable: false,
  10388.           enumerable: true,
  10389.           value: null
  10390.         },
  10391.         attributeNameCheck: {
  10392.           writable: true,
  10393.           configurable: false,
  10394.           enumerable: true,
  10395.           value: null
  10396.         },
  10397.         allowCustomizedBuiltInElements: {
  10398.           writable: true,
  10399.           configurable: false,
  10400.           enumerable: true,
  10401.           value: false
  10402.         }
  10403.       }));
  10404.       var FORBID_TAGS = null;
  10405.       var FORBID_ATTR = null;
  10406.       var ALLOW_ARIA_ATTR = true;
  10407.       var ALLOW_DATA_ATTR = true;
  10408.       var ALLOW_UNKNOWN_PROTOCOLS = false;
  10409.       var SAFE_FOR_TEMPLATES = false;
  10410.       var WHOLE_DOCUMENT = false;
  10411.       var SET_CONFIG = false;
  10412.       var FORCE_BODY = false;
  10413.       var RETURN_DOM = false;
  10414.       var RETURN_DOM_FRAGMENT = false;
  10415.       var RETURN_TRUSTED_TYPE = false;
  10416.       var SANITIZE_DOM = true;
  10417.       var KEEP_CONTENT = true;
  10418.       var IN_PLACE = false;
  10419.       var USE_PROFILES = {};
  10420.       var FORBID_CONTENTS = null;
  10421.       var DEFAULT_FORBID_CONTENTS = addToSet({}, [
  10422.         'annotation-xml',
  10423.         'audio',
  10424.         'colgroup',
  10425.         'desc',
  10426.         'foreignobject',
  10427.         'head',
  10428.         'iframe',
  10429.         'math',
  10430.         'mi',
  10431.         'mn',
  10432.         'mo',
  10433.         'ms',
  10434.         'mtext',
  10435.         'noembed',
  10436.         'noframes',
  10437.         'noscript',
  10438.         'plaintext',
  10439.         'script',
  10440.         'style',
  10441.         'svg',
  10442.         'template',
  10443.         'thead',
  10444.         'title',
  10445.         'video',
  10446.         'xmp'
  10447.       ]);
  10448.       var DATA_URI_TAGS = null;
  10449.       var DEFAULT_DATA_URI_TAGS = addToSet({}, [
  10450.         'audio',
  10451.         'video',
  10452.         'img',
  10453.         'source',
  10454.         'image',
  10455.         'track'
  10456.       ]);
  10457.       var URI_SAFE_ATTRIBUTES = null;
  10458.       var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [
  10459.         'alt',
  10460.         'class',
  10461.         'for',
  10462.         'id',
  10463.         'label',
  10464.         'name',
  10465.         'pattern',
  10466.         'placeholder',
  10467.         'role',
  10468.         'summary',
  10469.         'title',
  10470.         'value',
  10471.         'style',
  10472.         'xmlns'
  10473.       ]);
  10474.       var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
  10475.       var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
  10476.       var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
  10477.       var NAMESPACE = HTML_NAMESPACE;
  10478.       var IS_EMPTY_INPUT = false;
  10479.       var PARSER_MEDIA_TYPE;
  10480.       var SUPPORTED_PARSER_MEDIA_TYPES = [
  10481.         'application/xhtml+xml',
  10482.         'text/html'
  10483.       ];
  10484.       var DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
  10485.       var transformCaseFunc;
  10486.       var CONFIG = null;
  10487.       var formElement = document.createElement('form');
  10488.       var isRegexOrFunction = function isRegexOrFunction(testValue) {
  10489.         return testValue instanceof RegExp || testValue instanceof Function;
  10490.       };
  10491.       var _parseConfig = function _parseConfig(cfg) {
  10492.         if (CONFIG && CONFIG === cfg) {
  10493.           return;
  10494.         }
  10495.         if (!cfg || _typeof(cfg) !== 'object') {
  10496.           cfg = {};
  10497.         }
  10498.         cfg = clone$1(cfg);
  10499.         ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
  10500.         ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
  10501.         URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone$1(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
  10502.         DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone$1(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
  10503.         FORBID_CONTENTS = 'FORBID_CONTENTS' in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
  10504.         FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
  10505.         FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
  10506.         USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;
  10507.         ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
  10508.         ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
  10509.         ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
  10510.         SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
  10511.         WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
  10512.         RETURN_DOM = cfg.RETURN_DOM || false;
  10513.         RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
  10514.         RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
  10515.         FORCE_BODY = cfg.FORCE_BODY || false;
  10516.         SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
  10517.         KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
  10518.         IN_PLACE = cfg.IN_PLACE || false;
  10519.         IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$1;
  10520.         NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
  10521.         if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
  10522.           CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
  10523.         }
  10524.         if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
  10525.           CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
  10526.         }
  10527.         if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
  10528.           CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
  10529.         }
  10530.         PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
  10531.         transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? function (x) {
  10532.           return x;
  10533.         } : stringToLowerCase;
  10534.         if (SAFE_FOR_TEMPLATES) {
  10535.           ALLOW_DATA_ATTR = false;
  10536.         }
  10537.         if (RETURN_DOM_FRAGMENT) {
  10538.           RETURN_DOM = true;
  10539.         }
  10540.         if (USE_PROFILES) {
  10541.           ALLOWED_TAGS = addToSet({}, _toConsumableArray(text));
  10542.           ALLOWED_ATTR = [];
  10543.           if (USE_PROFILES.html === true) {
  10544.             addToSet(ALLOWED_TAGS, html$1);
  10545.             addToSet(ALLOWED_ATTR, html);
  10546.           }
  10547.           if (USE_PROFILES.svg === true) {
  10548.             addToSet(ALLOWED_TAGS, svg$1);
  10549.             addToSet(ALLOWED_ATTR, svg);
  10550.             addToSet(ALLOWED_ATTR, xml);
  10551.           }
  10552.           if (USE_PROFILES.svgFilters === true) {
  10553.             addToSet(ALLOWED_TAGS, svgFilters);
  10554.             addToSet(ALLOWED_ATTR, svg);
  10555.             addToSet(ALLOWED_ATTR, xml);
  10556.           }
  10557.           if (USE_PROFILES.mathMl === true) {
  10558.             addToSet(ALLOWED_TAGS, mathMl$1);
  10559.             addToSet(ALLOWED_ATTR, mathMl);
  10560.             addToSet(ALLOWED_ATTR, xml);
  10561.           }
  10562.         }
  10563.         if (cfg.ADD_TAGS) {
  10564.           if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
  10565.             ALLOWED_TAGS = clone$1(ALLOWED_TAGS);
  10566.           }
  10567.           addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
  10568.         }
  10569.         if (cfg.ADD_ATTR) {
  10570.           if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
  10571.             ALLOWED_ATTR = clone$1(ALLOWED_ATTR);
  10572.           }
  10573.           addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
  10574.         }
  10575.         if (cfg.ADD_URI_SAFE_ATTR) {
  10576.           addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
  10577.         }
  10578.         if (cfg.FORBID_CONTENTS) {
  10579.           if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
  10580.             FORBID_CONTENTS = clone$1(FORBID_CONTENTS);
  10581.           }
  10582.           addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
  10583.         }
  10584.         if (KEEP_CONTENT) {
  10585.           ALLOWED_TAGS['#text'] = true;
  10586.         }
  10587.         if (WHOLE_DOCUMENT) {
  10588.           addToSet(ALLOWED_TAGS, [
  10589.             'html',
  10590.             'head',
  10591.             'body'
  10592.           ]);
  10593.         }
  10594.         if (ALLOWED_TAGS.table) {
  10595.           addToSet(ALLOWED_TAGS, ['tbody']);
  10596.           delete FORBID_TAGS.tbody;
  10597.         }
  10598.         if (freeze) {
  10599.           freeze(cfg);
  10600.         }
  10601.         CONFIG = cfg;
  10602.       };
  10603.       var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, [
  10604.         'mi',
  10605.         'mo',
  10606.         'mn',
  10607.         'ms',
  10608.         'mtext'
  10609.       ]);
  10610.       var HTML_INTEGRATION_POINTS = addToSet({}, [
  10611.         'foreignobject',
  10612.         'desc',
  10613.         'title',
  10614.         'annotation-xml'
  10615.       ]);
  10616.       var COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [
  10617.         'title',
  10618.         'style',
  10619.         'font',
  10620.         'a',
  10621.         'script'
  10622.       ]);
  10623.       var ALL_SVG_TAGS = addToSet({}, svg$1);
  10624.       addToSet(ALL_SVG_TAGS, svgFilters);
  10625.       addToSet(ALL_SVG_TAGS, svgDisallowed);
  10626.       var ALL_MATHML_TAGS = addToSet({}, mathMl$1);
  10627.       addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  10628.       var _checkValidNamespace = function _checkValidNamespace(element) {
  10629.         var parent = getParentNode(element);
  10630.         if (!parent || !parent.tagName) {
  10631.           parent = {
  10632.             namespaceURI: HTML_NAMESPACE,
  10633.             tagName: 'template'
  10634.           };
  10635.         }
  10636.         var tagName = stringToLowerCase(element.tagName);
  10637.         var parentTagName = stringToLowerCase(parent.tagName);
  10638.         if (element.namespaceURI === SVG_NAMESPACE) {
  10639.           if (parent.namespaceURI === HTML_NAMESPACE) {
  10640.             return tagName === 'svg';
  10641.           }
  10642.           if (parent.namespaceURI === MATHML_NAMESPACE) {
  10643.             return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
  10644.           }
  10645.           return Boolean(ALL_SVG_TAGS[tagName]);
  10646.         }
  10647.         if (element.namespaceURI === MATHML_NAMESPACE) {
  10648.           if (parent.namespaceURI === HTML_NAMESPACE) {
  10649.             return tagName === 'math';
  10650.           }
  10651.           if (parent.namespaceURI === SVG_NAMESPACE) {
  10652.             return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
  10653.           }
  10654.           return Boolean(ALL_MATHML_TAGS[tagName]);
  10655.         }
  10656.         if (element.namespaceURI === HTML_NAMESPACE) {
  10657.           if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
  10658.             return false;
  10659.           }
  10660.           if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
  10661.             return false;
  10662.           }
  10663.           return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
  10664.         }
  10665.         return false;
  10666.       };
  10667.       var _forceRemove = function _forceRemove(node) {
  10668.         arrayPush(DOMPurify.removed, { element: node });
  10669.         try {
  10670.           node.parentNode.removeChild(node);
  10671.         } catch (_) {
  10672.           try {
  10673.             node.outerHTML = emptyHTML;
  10674.           } catch (_) {
  10675.             node.remove();
  10676.           }
  10677.         }
  10678.       };
  10679.       var _removeAttribute = function _removeAttribute(name, node) {
  10680.         try {
  10681.           arrayPush(DOMPurify.removed, {
  10682.             attribute: node.getAttributeNode(name),
  10683.             from: node
  10684.           });
  10685.         } catch (_) {
  10686.           arrayPush(DOMPurify.removed, {
  10687.             attribute: null,
  10688.             from: node
  10689.           });
  10690.         }
  10691.         node.removeAttribute(name);
  10692.         if (name === 'is' && !ALLOWED_ATTR[name]) {
  10693.           if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
  10694.             try {
  10695.               _forceRemove(node);
  10696.             } catch (_) {
  10697.             }
  10698.           } else {
  10699.             try {
  10700.               node.setAttribute(name, '');
  10701.             } catch (_) {
  10702.             }
  10703.           }
  10704.         }
  10705.       };
  10706.       var _initDocument = function _initDocument(dirty) {
  10707.         var doc;
  10708.         var leadingWhitespace;
  10709.         if (FORCE_BODY) {
  10710.           dirty = '<remove></remove>' + dirty;
  10711.         } else {
  10712.           var matches = stringMatch(dirty, /^[\r\n\t ]+/);
  10713.           leadingWhitespace = matches && matches[0];
  10714.         }
  10715.         if (PARSER_MEDIA_TYPE === 'application/xhtml+xml') {
  10716.           dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
  10717.         }
  10718.         var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
  10719.         if (NAMESPACE === HTML_NAMESPACE) {
  10720.           try {
  10721.             doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
  10722.           } catch (_) {
  10723.           }
  10724.         }
  10725.         if (!doc || !doc.documentElement) {
  10726.           doc = implementation.createDocument(NAMESPACE, 'template', null);
  10727.           try {
  10728.             doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;
  10729.           } catch (_) {
  10730.           }
  10731.         }
  10732.         var body = doc.body || doc.documentElement;
  10733.         if (dirty && leadingWhitespace) {
  10734.           body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
  10735.         }
  10736.         if (NAMESPACE === HTML_NAMESPACE) {
  10737.           return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
  10738.         }
  10739.         return WHOLE_DOCUMENT ? doc.documentElement : body;
  10740.       };
  10741.       var _createIterator = function _createIterator(root) {
  10742.         return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  10743.       };
  10744.       var _isClobbered = function _isClobbered(elm) {
  10745.         return elm instanceof HTMLFormElement && (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function');
  10746.       };
  10747.       var _isNode = function _isNode(object) {
  10748.         return _typeof(Node) === 'object' ? object instanceof Node : object && _typeof(object) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';
  10749.       };
  10750.       var _executeHook = function _executeHook(entryPoint, currentNode, data) {
  10751.         if (!hooks[entryPoint]) {
  10752.           return;
  10753.         }
  10754.         arrayForEach(hooks[entryPoint], function (hook) {
  10755.           hook.call(DOMPurify, currentNode, data, CONFIG);
  10756.         });
  10757.       };
  10758.       var _sanitizeElements = function _sanitizeElements(currentNode) {
  10759.         var content;
  10760.         _executeHook('beforeSanitizeElements', currentNode, null);
  10761.         if (_isClobbered(currentNode)) {
  10762.           _forceRemove(currentNode);
  10763.           return true;
  10764.         }
  10765.         if (regExpTest(/[\u0080-\uFFFF]/, currentNode.nodeName)) {
  10766.           _forceRemove(currentNode);
  10767.           return true;
  10768.         }
  10769.         var tagName = transformCaseFunc(currentNode.nodeName);
  10770.         _executeHook('uponSanitizeElement', currentNode, {
  10771.           tagName: tagName,
  10772.           allowedTags: ALLOWED_TAGS
  10773.         });
  10774.         if (currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
  10775.           _forceRemove(currentNode);
  10776.           return true;
  10777.         }
  10778.         if (tagName === 'select' && regExpTest(/<template/i, currentNode.innerHTML)) {
  10779.           _forceRemove(currentNode);
  10780.           return true;
  10781.         }
  10782.         if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  10783.           if (!FORBID_TAGS[tagName] && _basicCustomElementTest(tagName)) {
  10784.             if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName))
  10785.               return false;
  10786.             if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName))
  10787.               return false;
  10788.           }
  10789.           if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
  10790.             var parentNode = getParentNode(currentNode) || currentNode.parentNode;
  10791.             var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
  10792.             if (childNodes && parentNode) {
  10793.               var childCount = childNodes.length;
  10794.               for (var i = childCount - 1; i >= 0; --i) {
  10795.                 parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
  10796.               }
  10797.             }
  10798.           }
  10799.           _forceRemove(currentNode);
  10800.           return true;
  10801.         }
  10802.         if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
  10803.           _forceRemove(currentNode);
  10804.           return true;
  10805.         }
  10806.         if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
  10807.           _forceRemove(currentNode);
  10808.           return true;
  10809.         }
  10810.         if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
  10811.           content = currentNode.textContent;
  10812.           content = stringReplace(content, MUSTACHE_EXPR$1, ' ');
  10813.           content = stringReplace(content, ERB_EXPR$1, ' ');
  10814.           if (currentNode.textContent !== content) {
  10815.             arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
  10816.             currentNode.textContent = content;
  10817.           }
  10818.         }
  10819.         _executeHook('afterSanitizeElements', currentNode, null);
  10820.         return false;
  10821.       };
  10822.       var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
  10823.         if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
  10824.           return false;
  10825.         }
  10826.         if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$1, lcName));
  10827.         else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName));
  10828.         else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
  10829.           if (_basicCustomElementTest(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName)) || lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)));
  10830.           else {
  10831.             return false;
  10832.           }
  10833.         } else if (URI_SAFE_ATTRIBUTES[lcName]);
  10834.         else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  10835.         else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]);
  10836.         else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, '')));
  10837.         else if (!value);
  10838.         else {
  10839.           return false;
  10840.         }
  10841.         return true;
  10842.       };
  10843.       var _basicCustomElementTest = function _basicCustomElementTest(tagName) {
  10844.         return tagName.indexOf('-') > 0;
  10845.       };
  10846.       var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
  10847.         var attr;
  10848.         var value;
  10849.         var lcName;
  10850.         var l;
  10851.         _executeHook('beforeSanitizeAttributes', currentNode, null);
  10852.         var attributes = currentNode.attributes;
  10853.         if (!attributes) {
  10854.           return;
  10855.         }
  10856.         var hookEvent = {
  10857.           attrName: '',
  10858.           attrValue: '',
  10859.           keepAttr: true,
  10860.           allowedAttributes: ALLOWED_ATTR
  10861.         };
  10862.         l = attributes.length;
  10863.         while (l--) {
  10864.           attr = attributes[l];
  10865.           var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
  10866.           value = name === 'value' ? attr.value : stringTrim(attr.value);
  10867.           lcName = transformCaseFunc(name);
  10868.           hookEvent.attrName = lcName;
  10869.           hookEvent.attrValue = value;
  10870.           hookEvent.keepAttr = true;
  10871.           hookEvent.forceKeepAttr = undefined;
  10872.           _executeHook('uponSanitizeAttribute', currentNode, hookEvent);
  10873.           value = hookEvent.attrValue;
  10874.           if (hookEvent.forceKeepAttr) {
  10875.             continue;
  10876.           }
  10877.           _removeAttribute(name, currentNode);
  10878.           if (!hookEvent.keepAttr) {
  10879.             continue;
  10880.           }
  10881.           if (regExpTest(/\/>/i, value)) {
  10882.             _removeAttribute(name, currentNode);
  10883.             continue;
  10884.           }
  10885.           if (SAFE_FOR_TEMPLATES) {
  10886.             value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
  10887.             value = stringReplace(value, ERB_EXPR$1, ' ');
  10888.           }
  10889.           var lcTag = transformCaseFunc(currentNode.nodeName);
  10890.           if (!_isValidAttribute(lcTag, lcName, value)) {
  10891.             continue;
  10892.           }
  10893.           try {
  10894.             if (namespaceURI) {
  10895.               currentNode.setAttributeNS(namespaceURI, name, value);
  10896.             } else {
  10897.               currentNode.setAttribute(name, value);
  10898.             }
  10899.             arrayPop(DOMPurify.removed);
  10900.           } catch (_) {
  10901.           }
  10902.         }
  10903.         _executeHook('afterSanitizeAttributes', currentNode, null);
  10904.       };
  10905.       var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
  10906.         var shadowNode;
  10907.         var shadowIterator = _createIterator(fragment);
  10908.         _executeHook('beforeSanitizeShadowDOM', fragment, null);
  10909.         while (shadowNode = shadowIterator.nextNode()) {
  10910.           _executeHook('uponSanitizeShadowNode', shadowNode, null);
  10911.           if (_sanitizeElements(shadowNode)) {
  10912.             continue;
  10913.           }
  10914.           if (shadowNode.content instanceof DocumentFragment) {
  10915.             _sanitizeShadowDOM(shadowNode.content);
  10916.           }
  10917.           _sanitizeAttributes(shadowNode);
  10918.         }
  10919.         _executeHook('afterSanitizeShadowDOM', fragment, null);
  10920.       };
  10921.       DOMPurify.sanitize = function (dirty, cfg) {
  10922.         var body;
  10923.         var importedNode;
  10924.         var currentNode;
  10925.         var oldNode;
  10926.         var returnNode;
  10927.         IS_EMPTY_INPUT = !dirty;
  10928.         if (IS_EMPTY_INPUT) {
  10929.           dirty = '<!-->';
  10930.         }
  10931.         if (typeof dirty !== 'string' && !_isNode(dirty)) {
  10932.           if (typeof dirty.toString !== 'function') {
  10933.             throw typeErrorCreate('toString is not a function');
  10934.           } else {
  10935.             dirty = dirty.toString();
  10936.             if (typeof dirty !== 'string') {
  10937.               throw typeErrorCreate('dirty is not a string, aborting');
  10938.             }
  10939.           }
  10940.         }
  10941.         if (!DOMPurify.isSupported) {
  10942.           if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {
  10943.             if (typeof dirty === 'string') {
  10944.               return window.toStaticHTML(dirty);
  10945.             }
  10946.             if (_isNode(dirty)) {
  10947.               return window.toStaticHTML(dirty.outerHTML);
  10948.             }
  10949.           }
  10950.           return dirty;
  10951.         }
  10952.         if (!SET_CONFIG) {
  10953.           _parseConfig(cfg);
  10954.         }
  10955.         DOMPurify.removed = [];
  10956.         if (typeof dirty === 'string') {
  10957.           IN_PLACE = false;
  10958.         }
  10959.         if (IN_PLACE) {
  10960.           if (dirty.nodeName) {
  10961.             var tagName = transformCaseFunc(dirty.nodeName);
  10962.             if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
  10963.               throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
  10964.             }
  10965.           }
  10966.         } else if (dirty instanceof Node) {
  10967.           body = _initDocument('<!---->');
  10968.           importedNode = body.ownerDocument.importNode(dirty, true);
  10969.           if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
  10970.             body = importedNode;
  10971.           } else if (importedNode.nodeName === 'HTML') {
  10972.             body = importedNode;
  10973.           } else {
  10974.             body.appendChild(importedNode);
  10975.           }
  10976.         } else {
  10977.           if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
  10978.             return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
  10979.           }
  10980.           body = _initDocument(dirty);
  10981.           if (!body) {
  10982.             return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
  10983.           }
  10984.         }
  10985.         if (body && FORCE_BODY) {
  10986.           _forceRemove(body.firstChild);
  10987.         }
  10988.         var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
  10989.         while (currentNode = nodeIterator.nextNode()) {
  10990.           if (currentNode.nodeType === 3 && currentNode === oldNode) {
  10991.             continue;
  10992.           }
  10993.           if (_sanitizeElements(currentNode)) {
  10994.             continue;
  10995.           }
  10996.           if (currentNode.content instanceof DocumentFragment) {
  10997.             _sanitizeShadowDOM(currentNode.content);
  10998.           }
  10999.           _sanitizeAttributes(currentNode);
  11000.           oldNode = currentNode;
  11001.         }
  11002.         oldNode = null;
  11003.         if (IN_PLACE) {
  11004.           return dirty;
  11005.         }
  11006.         if (RETURN_DOM) {
  11007.           if (RETURN_DOM_FRAGMENT) {
  11008.             returnNode = createDocumentFragment.call(body.ownerDocument);
  11009.             while (body.firstChild) {
  11010.               returnNode.appendChild(body.firstChild);
  11011.             }
  11012.           } else {
  11013.             returnNode = body;
  11014.           }
  11015.           if (ALLOWED_ATTR.shadowroot) {
  11016.             returnNode = importNode.call(originalDocument, returnNode, true);
  11017.           }
  11018.           return returnNode;
  11019.         }
  11020.         var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
  11021.         if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
  11022.           serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
  11023.         }
  11024.         if (SAFE_FOR_TEMPLATES) {
  11025.           serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$1, ' ');
  11026.           serializedHTML = stringReplace(serializedHTML, ERB_EXPR$1, ' ');
  11027.         }
  11028.         return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  11029.       };
  11030.       DOMPurify.setConfig = function (cfg) {
  11031.         _parseConfig(cfg);
  11032.         SET_CONFIG = true;
  11033.       };
  11034.       DOMPurify.clearConfig = function () {
  11035.         CONFIG = null;
  11036.         SET_CONFIG = false;
  11037.       };
  11038.       DOMPurify.isValidAttribute = function (tag, attr, value) {
  11039.         if (!CONFIG) {
  11040.           _parseConfig({});
  11041.         }
  11042.         var lcTag = transformCaseFunc(tag);
  11043.         var lcName = transformCaseFunc(attr);
  11044.         return _isValidAttribute(lcTag, lcName, value);
  11045.       };
  11046.       DOMPurify.addHook = function (entryPoint, hookFunction) {
  11047.         if (typeof hookFunction !== 'function') {
  11048.           return;
  11049.         }
  11050.         hooks[entryPoint] = hooks[entryPoint] || [];
  11051.         arrayPush(hooks[entryPoint], hookFunction);
  11052.       };
  11053.       DOMPurify.removeHook = function (entryPoint) {
  11054.         if (hooks[entryPoint]) {
  11055.           return arrayPop(hooks[entryPoint]);
  11056.         }
  11057.       };
  11058.       DOMPurify.removeHooks = function (entryPoint) {
  11059.         if (hooks[entryPoint]) {
  11060.           hooks[entryPoint] = [];
  11061.         }
  11062.       };
  11063.       DOMPurify.removeAllHooks = function () {
  11064.         hooks = {};
  11065.       };
  11066.       return DOMPurify;
  11067.     }
  11068.     var purify = createDOMPurify();
  11069.  
  11070.     var sanitizeHtmlString = function (html) {
  11071.       return purify().sanitize(html);
  11072.     };
  11073.  
  11074.     var global$e = tinymce.util.Tools.resolve('tinymce.util.I18n');
  11075.  
  11076.     var rtlTransform = {
  11077.       'indent': true,
  11078.       'outdent': true,
  11079.       'table-insert-column-after': true,
  11080.       'table-insert-column-before': true,
  11081.       'paste-column-after': true,
  11082.       'paste-column-before': true,
  11083.       'unordered-list': true,
  11084.       'list-bull-circle': true,
  11085.       'list-bull-default': true,
  11086.       'list-bull-square': true
  11087.     };
  11088.     var defaultIconName = 'temporary-placeholder';
  11089.     var defaultIcon = function (icons) {
  11090.       return function () {
  11091.         return get$e(icons, defaultIconName).getOr('!not found!');
  11092.       };
  11093.     };
  11094.     var getIconName = function (name, icons) {
  11095.       var lcName = name.toLowerCase();
  11096.       if (global$e.isRtl()) {
  11097.         var rtlName = ensureTrailing(lcName, '-rtl');
  11098.         return has$2(icons, rtlName) ? rtlName : lcName;
  11099.       } else {
  11100.         return lcName;
  11101.       }
  11102.     };
  11103.     var lookupIcon = function (name, icons) {
  11104.       return get$e(icons, getIconName(name, icons));
  11105.     };
  11106.     var get$1 = function (name, iconProvider) {
  11107.       var icons = iconProvider();
  11108.       return lookupIcon(name, icons).getOrThunk(defaultIcon(icons));
  11109.     };
  11110.     var getOr = function (name, iconProvider, fallbackIcon) {
  11111.       var icons = iconProvider();
  11112.       return lookupIcon(name, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  11113.     };
  11114.     var needsRtlTransform = function (iconName) {
  11115.       return global$e.isRtl() ? has$2(rtlTransform, iconName) : false;
  11116.     };
  11117.     var addFocusableBehaviour = function () {
  11118.       return config('add-focusable', [runOnAttached(function (comp) {
  11119.           child(comp.element, 'svg').each(function (svg) {
  11120.             return set$8(svg, 'focusable', 'false');
  11121.           });
  11122.         })]);
  11123.     };
  11124.     var renderIcon$2 = function (spec, iconName, icons, fallbackIcon) {
  11125.       var _a, _b;
  11126.       var rtlIconClasses = needsRtlTransform(iconName) ? ['tox-icon--flip'] : [];
  11127.       var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  11128.       return {
  11129.         dom: {
  11130.           tag: spec.tag,
  11131.           attributes: (_a = spec.attributes) !== null && _a !== void 0 ? _a : {},
  11132.           classes: spec.classes.concat(rtlIconClasses),
  11133.           innerHtml: iconHtml
  11134.         },
  11135.         behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : [], true), [addFocusableBehaviour()], false))
  11136.       };
  11137.     };
  11138.     var render$3 = function (iconName, spec, iconProvider, fallbackIcon) {
  11139.       if (fallbackIcon === void 0) {
  11140.         fallbackIcon = Optional.none();
  11141.       }
  11142.       return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
  11143.     };
  11144.     var renderFirst = function (iconNames, spec, iconProvider) {
  11145.       var icons = iconProvider();
  11146.       var iconName = find$5(iconNames, function (name) {
  11147.         return has$2(icons, getIconName(name, icons));
  11148.       });
  11149.       return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
  11150.     };
  11151.  
  11152.     var notificationIconMap = {
  11153.       success: 'checkmark',
  11154.       error: 'warning',
  11155.       err: 'error',
  11156.       warning: 'warning',
  11157.       warn: 'warning',
  11158.       info: 'info'
  11159.     };
  11160.     var factory$k = function (detail) {
  11161.       var memBannerText = record({
  11162.         dom: fromHtml('<p>' + sanitizeHtmlString(detail.translationProvider(detail.text)) + '</p>'),
  11163.         behaviours: derive$1([Replacing.config({})])
  11164.       });
  11165.       var renderPercentBar = function (percent) {
  11166.         return {
  11167.           dom: {
  11168.             tag: 'div',
  11169.             classes: ['tox-bar'],
  11170.             attributes: { style: 'width: ' + percent + '%' }
  11171.           }
  11172.         };
  11173.       };
  11174.       var renderPercentText = function (percent) {
  11175.         return {
  11176.           dom: {
  11177.             tag: 'div',
  11178.             classes: ['tox-text'],
  11179.             innerHtml: percent + '%'
  11180.           }
  11181.         };
  11182.       };
  11183.       var memBannerProgress = record({
  11184.         dom: {
  11185.           tag: 'div',
  11186.           classes: detail.progress ? [
  11187.             'tox-progress-bar',
  11188.             'tox-progress-indicator'
  11189.           ] : ['tox-progress-bar']
  11190.         },
  11191.         components: [
  11192.           {
  11193.             dom: {
  11194.               tag: 'div',
  11195.               classes: ['tox-bar-container']
  11196.             },
  11197.             components: [renderPercentBar(0)]
  11198.           },
  11199.           renderPercentText(0)
  11200.         ],
  11201.         behaviours: derive$1([Replacing.config({})])
  11202.       });
  11203.       var updateProgress = function (comp, percent) {
  11204.         if (comp.getSystem().isConnected()) {
  11205.           memBannerProgress.getOpt(comp).each(function (progress) {
  11206.             Replacing.set(progress, [
  11207.               {
  11208.                 dom: {
  11209.                   tag: 'div',
  11210.                   classes: ['tox-bar-container']
  11211.                 },
  11212.                 components: [renderPercentBar(percent)]
  11213.               },
  11214.               renderPercentText(percent)
  11215.             ]);
  11216.           });
  11217.         }
  11218.       };
  11219.       var updateText = function (comp, text) {
  11220.         if (comp.getSystem().isConnected()) {
  11221.           var banner = memBannerText.get(comp);
  11222.           Replacing.set(banner, [text$1(text)]);
  11223.         }
  11224.       };
  11225.       var apis = {
  11226.         updateProgress: updateProgress,
  11227.         updateText: updateText
  11228.       };
  11229.       var iconChoices = flatten([
  11230.         detail.icon.toArray(),
  11231.         detail.level.toArray(),
  11232.         detail.level.bind(function (level) {
  11233.           return Optional.from(notificationIconMap[level]);
  11234.         }).toArray()
  11235.       ]);
  11236.       var memButton = record(Button.sketch({
  11237.         dom: {
  11238.           tag: 'button',
  11239.           classes: [
  11240.             'tox-notification__dismiss',
  11241.             'tox-button',
  11242.             'tox-button--naked',
  11243.             'tox-button--icon'
  11244.           ]
  11245.         },
  11246.         components: [render$3('close', {
  11247.             tag: 'div',
  11248.             classes: ['tox-icon'],
  11249.             attributes: { 'aria-label': detail.translationProvider('Close') }
  11250.           }, detail.iconProvider)],
  11251.         action: function (comp) {
  11252.           detail.onAction(comp);
  11253.         }
  11254.       }));
  11255.       var notificationIconSpec = renderFirst(iconChoices, {
  11256.         tag: 'div',
  11257.         classes: ['tox-notification__icon']
  11258.       }, detail.iconProvider);
  11259.       var notificationBodySpec = {
  11260.         dom: {
  11261.           tag: 'div',
  11262.           classes: ['tox-notification__body']
  11263.         },
  11264.         components: [memBannerText.asSpec()],
  11265.         behaviours: derive$1([Replacing.config({})])
  11266.       };
  11267.       var components = [
  11268.         notificationIconSpec,
  11269.         notificationBodySpec
  11270.       ];
  11271.       return {
  11272.         uid: detail.uid,
  11273.         dom: {
  11274.           tag: 'div',
  11275.           attributes: { role: 'alert' },
  11276.           classes: detail.level.map(function (level) {
  11277.             return [
  11278.               'tox-notification',
  11279.               'tox-notification--in',
  11280.               'tox-notification--' + level
  11281.             ];
  11282.           }).getOr([
  11283.             'tox-notification',
  11284.             'tox-notification--in'
  11285.           ])
  11286.         },
  11287.         behaviours: derive$1([
  11288.           Focusing.config({}),
  11289.           config('notification-events', [run$1(focusin(), function (comp) {
  11290.               memButton.getOpt(comp).each(Focusing.focus);
  11291.             })])
  11292.         ]),
  11293.         components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
  11294.         apis: apis
  11295.       };
  11296.     };
  11297.     var Notification = single({
  11298.       name: 'Notification',
  11299.       factory: factory$k,
  11300.       configFields: [
  11301.         option('level'),
  11302.         required$1('progress'),
  11303.         required$1('icon'),
  11304.         required$1('onAction'),
  11305.         required$1('text'),
  11306.         required$1('iconProvider'),
  11307.         required$1('translationProvider'),
  11308.         defaultedBoolean('closeButton', true)
  11309.       ],
  11310.       apis: {
  11311.         updateProgress: function (apis, comp, percent) {
  11312.           apis.updateProgress(comp, percent);
  11313.         },
  11314.         updateText: function (apis, comp, text) {
  11315.           apis.updateText(comp, text);
  11316.         }
  11317.       }
  11318.     });
  11319.  
  11320.     function NotificationManagerImpl (editor, extras, uiMothership) {
  11321.       var sharedBackstage = extras.backstage.shared;
  11322.       var getLayoutDirection = function (rel) {
  11323.         switch (rel) {
  11324.         case 'bc-bc':
  11325.           return south;
  11326.         case 'tc-tc':
  11327.           return north;
  11328.         case 'tc-bc':
  11329.           return north$2;
  11330.         case 'bc-tc':
  11331.         default:
  11332.           return south$2;
  11333.         }
  11334.       };
  11335.       var reposition = function (notifications) {
  11336.         if (notifications.length > 0) {
  11337.           each$1(notifications, function (notification, index) {
  11338.             if (index === 0) {
  11339.               notification.moveRel(null, 'banner');
  11340.             } else {
  11341.               notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  11342.             }
  11343.           });
  11344.         }
  11345.       };
  11346.       var open = function (settings, closeCallback) {
  11347.         var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  11348.         var close = function () {
  11349.           closeCallback();
  11350.           InlineView.hide(notificationWrapper);
  11351.         };
  11352.         var notification = build$1(Notification.sketch({
  11353.           text: settings.text,
  11354.           level: contains$2([
  11355.             'success',
  11356.             'error',
  11357.             'warning',
  11358.             'warn',
  11359.             'info'
  11360.           ], settings.type) ? settings.type : undefined,
  11361.           progress: settings.progressBar === true,
  11362.           icon: Optional.from(settings.icon),
  11363.           closeButton: !hideCloseButton,
  11364.           onAction: close,
  11365.           iconProvider: sharedBackstage.providers.icons,
  11366.           translationProvider: sharedBackstage.providers.translate
  11367.         }));
  11368.         var notificationWrapper = build$1(InlineView.sketch(__assign({
  11369.           dom: {
  11370.             tag: 'div',
  11371.             classes: ['tox-notifications-container']
  11372.           },
  11373.           lazySink: sharedBackstage.getSink,
  11374.           fireDismissalEventInstead: {}
  11375.         }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
  11376.         uiMothership.add(notificationWrapper);
  11377.         if (settings.timeout > 0) {
  11378.           global$f.setTimeout(function () {
  11379.             close();
  11380.           }, settings.timeout);
  11381.         }
  11382.         var getBounds = function () {
  11383.           var contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  11384.           var win$1 = win();
  11385.           var x = clamp$1(win$1.x, contentArea.x, contentArea.right);
  11386.           var y = clamp$1(win$1.y, contentArea.y, contentArea.bottom);
  11387.           var right = Math.max(contentArea.right, win$1.right);
  11388.           var bottom = Math.max(contentArea.bottom, win$1.bottom);
  11389.           return Optional.some(bounds(x, y, right - x, bottom - y));
  11390.         };
  11391.         return {
  11392.           close: close,
  11393.           moveTo: function (x, y) {
  11394.             InlineView.showAt(notificationWrapper, premade(notification), {
  11395.               anchor: {
  11396.                 type: 'makeshift',
  11397.                 x: x,
  11398.                 y: y
  11399.               }
  11400.             });
  11401.           },
  11402.           moveRel: function (element, rel) {
  11403.             var notificationSpec = premade(notification);
  11404.             var anchorOverrides = { maxHeightFunction: expandable$1() };
  11405.             if (rel !== 'banner' && isNonNullable(element)) {
  11406.               var layoutDirection_1 = getLayoutDirection(rel);
  11407.               var nodeAnchor = {
  11408.                 type: 'node',
  11409.                 root: body(),
  11410.                 node: Optional.some(SugarElement.fromDom(element)),
  11411.                 overrides: anchorOverrides,
  11412.                 layouts: {
  11413.                   onRtl: function () {
  11414.                     return [layoutDirection_1];
  11415.                   },
  11416.                   onLtr: function () {
  11417.                     return [layoutDirection_1];
  11418.                   }
  11419.                 }
  11420.               };
  11421.               InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds);
  11422.             } else {
  11423.               var anchor = __assign(__assign({}, sharedBackstage.anchors.banner()), { overrides: anchorOverrides });
  11424.               InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: anchor }, getBounds);
  11425.             }
  11426.           },
  11427.           text: function (nuText) {
  11428.             Notification.updateText(notification, nuText);
  11429.           },
  11430.           settings: settings,
  11431.           getEl: function () {
  11432.             return notification.element.dom;
  11433.           },
  11434.           progressBar: {
  11435.             value: function (percent) {
  11436.               Notification.updateProgress(notification, percent);
  11437.             }
  11438.           }
  11439.         };
  11440.       };
  11441.       var close = function (notification) {
  11442.         notification.close();
  11443.       };
  11444.       var getArgs = function (notification) {
  11445.         return notification.settings;
  11446.       };
  11447.       return {
  11448.         open: open,
  11449.         close: close,
  11450.         reposition: reposition,
  11451.         getArgs: getArgs
  11452.       };
  11453.     }
  11454.  
  11455.     var first = function (fn, rate) {
  11456.       var timer = null;
  11457.       var cancel = function () {
  11458.         if (!isNull(timer)) {
  11459.           clearTimeout(timer);
  11460.           timer = null;
  11461.         }
  11462.       };
  11463.       var throttle = function () {
  11464.         var args = [];
  11465.         for (var _i = 0; _i < arguments.length; _i++) {
  11466.           args[_i] = arguments[_i];
  11467.         }
  11468.         if (isNull(timer)) {
  11469.           timer = setTimeout(function () {
  11470.             timer = null;
  11471.             fn.apply(null, args);
  11472.           }, rate);
  11473.         }
  11474.       };
  11475.       return {
  11476.         cancel: cancel,
  11477.         throttle: throttle
  11478.       };
  11479.     };
  11480.     var last = function (fn, rate) {
  11481.       var timer = null;
  11482.       var cancel = function () {
  11483.         if (!isNull(timer)) {
  11484.           clearTimeout(timer);
  11485.           timer = null;
  11486.         }
  11487.       };
  11488.       var throttle = function () {
  11489.         var args = [];
  11490.         for (var _i = 0; _i < arguments.length; _i++) {
  11491.           args[_i] = arguments[_i];
  11492.         }
  11493.         cancel();
  11494.         timer = setTimeout(function () {
  11495.           timer = null;
  11496.           fn.apply(null, args);
  11497.         }, rate);
  11498.       };
  11499.       return {
  11500.         cancel: cancel,
  11501.         throttle: throttle
  11502.       };
  11503.     };
  11504.  
  11505.     var global$d = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  11506.  
  11507.     var isBoundary = function (dom, node) {
  11508.       return dom.isBlock(node) || contains$2([
  11509.         'BR',
  11510.         'IMG',
  11511.         'HR',
  11512.         'INPUT'
  11513.       ], node.nodeName) || dom.getContentEditable(node) === 'false';
  11514.     };
  11515.     var repeatLeft = function (dom, node, offset, process, rootNode) {
  11516.       var search = global$d(dom, function (node) {
  11517.         return isBoundary(dom, node);
  11518.       });
  11519.       return Optional.from(search.backwards(node, offset, process, rootNode));
  11520.     };
  11521.  
  11522.     var autocompleteSelector = '[data-mce-autocompleter]';
  11523.     var create$4 = function (editor, range) {
  11524.       return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function () {
  11525.         var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  11526.         append$2(wrapper, SugarElement.fromDom(range.extractContents()));
  11527.         range.insertNode(wrapper.dom);
  11528.         parent(wrapper).each(function (elm) {
  11529.           return elm.dom.normalize();
  11530.         });
  11531.         last$1(wrapper).map(function (last) {
  11532.           editor.selection.setCursorLocation(last.dom, getEnd(last));
  11533.         });
  11534.         return wrapper;
  11535.       });
  11536.     };
  11537.     var detect = function (elm) {
  11538.       return closest$1(elm, autocompleteSelector);
  11539.     };
  11540.  
  11541.     var isValidTextRange = function (rng) {
  11542.       return rng.collapsed && rng.startContainer.nodeType === 3;
  11543.     };
  11544.     var getText = function (rng) {
  11545.       return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  11546.     };
  11547.     var isWhitespace = function (chr) {
  11548.       return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  11549.     };
  11550.  
  11551.     var stripTriggerChar = function (text, triggerCh) {
  11552.       return text.substring(triggerCh.length);
  11553.     };
  11554.     var findChar = function (text, index, ch) {
  11555.       var i;
  11556.       for (i = index - 1; i >= 0; i--) {
  11557.         var char = text.charAt(i);
  11558.         if (isWhitespace(char)) {
  11559.           return Optional.none();
  11560.         }
  11561.         if (char === ch) {
  11562.           break;
  11563.         }
  11564.       }
  11565.       return Optional.some(i);
  11566.     };
  11567.     var findStart = function (dom, initRange, ch, minChars) {
  11568.       if (minChars === void 0) {
  11569.         minChars = 0;
  11570.       }
  11571.       if (!isValidTextRange(initRange)) {
  11572.         return Optional.none();
  11573.       }
  11574.       var findTriggerChIndex = function (element, offset, text) {
  11575.         return findChar(text, offset, ch).getOr(offset);
  11576.       };
  11577.       var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  11578.       return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  11579.         var range = initRange.cloneRange();
  11580.         range.setStart(spot.container, spot.offset);
  11581.         range.setEnd(initRange.endContainer, initRange.endOffset);
  11582.         if (range.collapsed) {
  11583.           return Optional.none();
  11584.         }
  11585.         var text = getText(range);
  11586.         var triggerCharIndex = text.lastIndexOf(ch);
  11587.         if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  11588.           return Optional.none();
  11589.         } else {
  11590.           return Optional.some({
  11591.             text: stripTriggerChar(text, ch),
  11592.             range: range,
  11593.             triggerChar: ch
  11594.           });
  11595.         }
  11596.       });
  11597.     };
  11598.     var getContext = function (dom, initRange, ch, minChars) {
  11599.       if (minChars === void 0) {
  11600.         minChars = 0;
  11601.       }
  11602.       return detect(SugarElement.fromDom(initRange.startContainer)).fold(function () {
  11603.         return findStart(dom, initRange, ch, minChars);
  11604.       }, function (elm) {
  11605.         var range = dom.createRng();
  11606.         range.selectNode(elm.dom);
  11607.         var text = getText(range);
  11608.         return Optional.some({
  11609.           range: range,
  11610.           text: stripTriggerChar(text, ch),
  11611.           triggerChar: ch
  11612.         });
  11613.       });
  11614.     };
  11615.  
  11616.     var setup$e = function (api, editor) {
  11617.       editor.on('keypress compositionend', api.onKeypress.throttle);
  11618.       editor.on('remove', api.onKeypress.cancel);
  11619.       var redirectKeyToItem = function (item, e) {
  11620.         emitWith(item, keydown(), { raw: e });
  11621.       };
  11622.       editor.on('keydown', function (e) {
  11623.         var getItem = function () {
  11624.           return api.getView().bind(Highlighting.getHighlighted);
  11625.         };
  11626.         if (e.which === 8) {
  11627.           api.onKeypress.throttle(e);
  11628.         }
  11629.         if (api.isActive()) {
  11630.           if (e.which === 27) {
  11631.             api.cancelIfNecessary();
  11632.           }
  11633.           if (api.isMenuOpen()) {
  11634.             if (e.which === 13) {
  11635.               getItem().each(emitExecute);
  11636.               e.preventDefault();
  11637.             } else if (e.which === 40) {
  11638.               getItem().fold(function () {
  11639.                 api.getView().each(Highlighting.highlightFirst);
  11640.               }, function (item) {
  11641.                 redirectKeyToItem(item, e);
  11642.               });
  11643.               e.preventDefault();
  11644.               e.stopImmediatePropagation();
  11645.             } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  11646.               getItem().each(function (item) {
  11647.                 redirectKeyToItem(item, e);
  11648.                 e.preventDefault();
  11649.                 e.stopImmediatePropagation();
  11650.               });
  11651.             }
  11652.           } else {
  11653.             if (e.which === 13 || e.which === 38 || e.which === 40) {
  11654.               api.cancelIfNecessary();
  11655.             }
  11656.           }
  11657.         }
  11658.       });
  11659.       editor.on('NodeChange', function (e) {
  11660.         if (api.isActive() && !api.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) {
  11661.           api.cancelIfNecessary();
  11662.         }
  11663.       });
  11664.     };
  11665.     var AutocompleterEditorEvents = { setup: setup$e };
  11666.  
  11667.     var global$c = tinymce.util.Tools.resolve('tinymce.util.Promise');
  11668.  
  11669.     var point = function (container, offset) {
  11670.       return {
  11671.         container: container,
  11672.         offset: offset
  11673.       };
  11674.     };
  11675.  
  11676.     var isText = function (node) {
  11677.       return node.nodeType === TEXT;
  11678.     };
  11679.     var isElement$1 = function (node) {
  11680.       return node.nodeType === ELEMENT;
  11681.     };
  11682.     var toLast = function (node) {
  11683.       if (isText(node)) {
  11684.         return point(node, node.data.length);
  11685.       } else {
  11686.         var children = node.childNodes;
  11687.         return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  11688.       }
  11689.     };
  11690.     var toLeaf = function (node, offset) {
  11691.       var children = node.childNodes;
  11692.       if (children.length > 0 && offset < children.length) {
  11693.         return toLeaf(children[offset], 0);
  11694.       } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  11695.         return toLast(children[children.length - 1]);
  11696.       } else {
  11697.         return point(node, offset);
  11698.       }
  11699.     };
  11700.  
  11701.     var isPreviousCharContent = function (dom, leaf) {
  11702.       return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  11703.         return offset === 0 ? -1 : offset;
  11704.       }, dom.getRoot()).filter(function (spot) {
  11705.         var char = spot.container.data.charAt(spot.offset - 1);
  11706.         return !isWhitespace(char);
  11707.       }).isSome();
  11708.     };
  11709.     var isStartOfWord = function (dom) {
  11710.       return function (rng) {
  11711.         var leaf = toLeaf(rng.startContainer, rng.startOffset);
  11712.         return !isPreviousCharContent(dom, leaf);
  11713.       };
  11714.     };
  11715.     var getTriggerContext = function (dom, initRange, database) {
  11716.       return findMap(database.triggerChars, function (ch) {
  11717.         return getContext(dom, initRange, ch);
  11718.       });
  11719.     };
  11720.     var lookup$2 = function (editor, getDatabase) {
  11721.       var database = getDatabase();
  11722.       var rng = editor.selection.getRng();
  11723.       return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  11724.         return lookupWithContext(editor, getDatabase, context);
  11725.       });
  11726.     };
  11727.     var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  11728.       if (fetchOptions === void 0) {
  11729.         fetchOptions = {};
  11730.       }
  11731.       var database = getDatabase();
  11732.       var rng = editor.selection.getRng();
  11733.       var startText = rng.startContainer.nodeValue;
  11734.       var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function (autocompleter) {
  11735.         return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  11736.           return isStartOfWord(editor.dom);
  11737.         })(context.range, startText, context.text);
  11738.       });
  11739.       if (autocompleters.length === 0) {
  11740.         return Optional.none();
  11741.       }
  11742.       var lookupData = global$c.all(map$2(autocompleters, function (ac) {
  11743.         var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  11744.         return fetchResult.then(function (results) {
  11745.           return {
  11746.             matchText: context.text,
  11747.             items: results,
  11748.             columns: ac.columns,
  11749.             onAction: ac.onAction,
  11750.             highlightOn: ac.highlightOn
  11751.           };
  11752.         });
  11753.       }));
  11754.       return Optional.some({
  11755.         lookupData: lookupData,
  11756.         context: context
  11757.       });
  11758.     };
  11759.  
  11760.     var separatorMenuItemSchema = objOf([
  11761.       requiredString('type'),
  11762.       optionString('text')
  11763.     ]);
  11764.     var createSeparatorMenuItem = function (spec) {
  11765.       return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  11766.     };
  11767.  
  11768.     var autocompleterItemSchema = objOf([
  11769.       defaulted('type', 'autocompleteitem'),
  11770.       defaulted('active', false),
  11771.       defaulted('disabled', false),
  11772.       defaulted('meta', {}),
  11773.       requiredString('value'),
  11774.       optionString('text'),
  11775.       optionString('icon')
  11776.     ]);
  11777.     var autocompleterSchema = objOf([
  11778.       requiredString('type'),
  11779.       requiredString('ch'),
  11780.       defaultedNumber('minChars', 1),
  11781.       defaulted('columns', 1),
  11782.       defaultedNumber('maxResults', 10),
  11783.       optionFunction('matches'),
  11784.       requiredFunction('fetch'),
  11785.       requiredFunction('onAction'),
  11786.       defaultedArrayOf('highlightOn', [], string)
  11787.     ]);
  11788.     var createSeparatorItem = function (spec) {
  11789.       return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  11790.     };
  11791.     var createAutocompleterItem = function (spec) {
  11792.       return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  11793.     };
  11794.     var createAutocompleter = function (spec) {
  11795.       return asRaw('Autocompleter', autocompleterSchema, spec);
  11796.     };
  11797.  
  11798.     var baseToolbarButtonFields = [
  11799.       defaultedBoolean('disabled', false),
  11800.       optionString('tooltip'),
  11801.       optionString('icon'),
  11802.       optionString('text'),
  11803.       defaultedFunction('onSetup', function () {
  11804.         return noop;
  11805.       })
  11806.     ];
  11807.     var toolbarButtonSchema = objOf([
  11808.       requiredString('type'),
  11809.       requiredFunction('onAction')
  11810.     ].concat(baseToolbarButtonFields));
  11811.     var createToolbarButton = function (spec) {
  11812.       return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  11813.     };
  11814.  
  11815.     var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  11816.     var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  11817.       requiredString('type'),
  11818.       requiredFunction('onAction')
  11819.     ]));
  11820.     var createToggleButton = function (spec) {
  11821.       return asRaw('ToggleButton', toggleButtonSchema, spec);
  11822.     };
  11823.  
  11824.     var contextBarFields = [
  11825.       defaultedFunction('predicate', never),
  11826.       defaultedStringEnum('scope', 'node', [
  11827.         'node',
  11828.         'editor'
  11829.       ]),
  11830.       defaultedStringEnum('position', 'selection', [
  11831.         'node',
  11832.         'selection',
  11833.         'line'
  11834.       ])
  11835.     ];
  11836.  
  11837.     var contextButtonFields = baseToolbarButtonFields.concat([
  11838.       defaulted('type', 'contextformbutton'),
  11839.       defaulted('primary', false),
  11840.       requiredFunction('onAction'),
  11841.       customField('original', identity$1)
  11842.     ]);
  11843.     var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  11844.       defaulted('type', 'contextformbutton'),
  11845.       defaulted('primary', false),
  11846.       requiredFunction('onAction'),
  11847.       customField('original', identity$1)
  11848.     ]);
  11849.     var launchButtonFields = baseToolbarButtonFields.concat([defaulted('type', 'contextformbutton')]);
  11850.     var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted('type', 'contextformtogglebutton')]);
  11851.     var toggleOrNormal = choose$1('type', {
  11852.       contextformbutton: contextButtonFields,
  11853.       contextformtogglebutton: contextToggleButtonFields
  11854.     });
  11855.     var contextFormSchema = objOf([
  11856.       defaulted('type', 'contextform'),
  11857.       defaultedFunction('initValue', constant$1('')),
  11858.       optionString('label'),
  11859.       requiredArrayOf('commands', toggleOrNormal),
  11860.       optionOf('launch', choose$1('type', {
  11861.         contextformbutton: launchButtonFields,
  11862.         contextformtogglebutton: launchToggleButtonFields
  11863.       }))
  11864.     ].concat(contextBarFields));
  11865.     var createContextForm = function (spec) {
  11866.       return asRaw('ContextForm', contextFormSchema, spec);
  11867.     };
  11868.  
  11869.     var contextToolbarSchema = objOf([
  11870.       defaulted('type', 'contexttoolbar'),
  11871.       requiredString('items')
  11872.     ].concat(contextBarFields));
  11873.     var createContextToolbar = function (spec) {
  11874.       return asRaw('ContextToolbar', contextToolbarSchema, spec);
  11875.     };
  11876.  
  11877.     var stringArray = function (a) {
  11878.       var all = {};
  11879.       each$1(a, function (key) {
  11880.         all[key] = {};
  11881.       });
  11882.       return keys(all);
  11883.     };
  11884.  
  11885.     var register$b = function (editor) {
  11886.       var popups = editor.ui.registry.getAll().popups;
  11887.       var dataset = map$1(popups, function (popup) {
  11888.         return createAutocompleter(popup).fold(function (err) {
  11889.           throw new Error(formatError(err));
  11890.         }, identity$1);
  11891.       });
  11892.       var triggerChars = stringArray(mapToArray(dataset, function (v) {
  11893.         return v.ch;
  11894.       }));
  11895.       var datasetValues = values(dataset);
  11896.       var lookupByChar = function (ch) {
  11897.         return filter$2(datasetValues, function (dv) {
  11898.           return dv.ch === ch;
  11899.         });
  11900.       };
  11901.       return {
  11902.         dataset: dataset,
  11903.         triggerChars: triggerChars,
  11904.         lookupByChar: lookupByChar
  11905.       };
  11906.     };
  11907.  
  11908.     var ItemResponse;
  11909.     (function (ItemResponse) {
  11910.       ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  11911.       ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  11912.     }(ItemResponse || (ItemResponse = {})));
  11913.     var ItemResponse$1 = ItemResponse;
  11914.  
  11915.     var navClass = 'tox-menu-nav__js';
  11916.     var selectableClass = 'tox-collection__item';
  11917.     var colorClass = 'tox-swatch';
  11918.     var presetClasses = {
  11919.       normal: navClass,
  11920.       color: colorClass
  11921.     };
  11922.     var tickedClass = 'tox-collection__item--enabled';
  11923.     var groupHeadingClass = 'tox-collection__group-heading';
  11924.     var iconClass = 'tox-collection__item-icon';
  11925.     var textClass = 'tox-collection__item-label';
  11926.     var accessoryClass = 'tox-collection__item-accessory';
  11927.     var caretClass = 'tox-collection__item-caret';
  11928.     var checkmarkClass = 'tox-collection__item-checkmark';
  11929.     var activeClass = 'tox-collection__item--active';
  11930.     var containerClass = 'tox-collection__item-container';
  11931.     var containerColumnClass = 'tox-collection__item-container--column';
  11932.     var containerRowClass = 'tox-collection__item-container--row';
  11933.     var containerAlignRightClass = 'tox-collection__item-container--align-right';
  11934.     var containerAlignLeftClass = 'tox-collection__item-container--align-left';
  11935.     var containerValignTopClass = 'tox-collection__item-container--valign-top';
  11936.     var containerValignMiddleClass = 'tox-collection__item-container--valign-middle';
  11937.     var containerValignBottomClass = 'tox-collection__item-container--valign-bottom';
  11938.     var classForPreset = function (presets) {
  11939.       return get$e(presetClasses, presets).getOr(navClass);
  11940.     };
  11941.  
  11942.     var forMenu = function (presets) {
  11943.       if (presets === 'color') {
  11944.         return 'tox-swatches';
  11945.       } else {
  11946.         return 'tox-menu';
  11947.       }
  11948.     };
  11949.     var classes = function (presets) {
  11950.       return {
  11951.         backgroundMenu: 'tox-background-menu',
  11952.         selectedMenu: 'tox-selected-menu',
  11953.         selectedItem: 'tox-collection__item--active',
  11954.         hasIcons: 'tox-menu--has-icons',
  11955.         menu: forMenu(presets),
  11956.         tieredMenu: 'tox-tiered-menu'
  11957.       };
  11958.     };
  11959.  
  11960.     var markers = function (presets) {
  11961.       var menuClasses = classes(presets);
  11962.       return {
  11963.         backgroundMenu: menuClasses.backgroundMenu,
  11964.         selectedMenu: menuClasses.selectedMenu,
  11965.         menu: menuClasses.menu,
  11966.         selectedItem: menuClasses.selectedItem,
  11967.         item: classForPreset(presets)
  11968.       };
  11969.     };
  11970.     var dom$1 = function (hasIcons, columns, presets) {
  11971.       var menuClasses = classes(presets);
  11972.       return {
  11973.         tag: 'div',
  11974.         classes: flatten([
  11975.           [
  11976.             menuClasses.menu,
  11977.             'tox-menu-' + columns + '-column'
  11978.           ],
  11979.           hasIcons ? [menuClasses.hasIcons] : []
  11980.         ])
  11981.       };
  11982.     };
  11983.     var components = [Menu.parts.items({})];
  11984.     var part = function (hasIcons, columns, presets) {
  11985.       var menuClasses = classes(presets);
  11986.       var d = {
  11987.         tag: 'div',
  11988.         classes: flatten([[menuClasses.tieredMenu]])
  11989.       };
  11990.       return {
  11991.         dom: d,
  11992.         markers: markers(presets)
  11993.       };
  11994.     };
  11995.  
  11996.     var chunk = function (rowDom, numColumns) {
  11997.       return function (items) {
  11998.         var chunks = chunk$1(items, numColumns);
  11999.         return map$2(chunks, function (c) {
  12000.           return {
  12001.             dom: rowDom,
  12002.             components: c
  12003.           };
  12004.         });
  12005.       };
  12006.     };
  12007.     var forSwatch = function (columns) {
  12008.       return {
  12009.         dom: {
  12010.           tag: 'div',
  12011.           classes: [
  12012.             'tox-menu',
  12013.             'tox-swatches-menu'
  12014.           ]
  12015.         },
  12016.         components: [{
  12017.             dom: {
  12018.               tag: 'div',
  12019.               classes: ['tox-swatches']
  12020.             },
  12021.             components: [Menu.parts.items({
  12022.                 preprocess: columns !== 'auto' ? chunk({
  12023.                   tag: 'div',
  12024.                   classes: ['tox-swatches__row']
  12025.                 }, columns) : identity$1
  12026.               })]
  12027.           }]
  12028.       };
  12029.     };
  12030.     var forToolbar = function (columns) {
  12031.       return {
  12032.         dom: {
  12033.           tag: 'div',
  12034.           classes: [
  12035.             'tox-menu',
  12036.             'tox-collection',
  12037.             'tox-collection--toolbar',
  12038.             'tox-collection--toolbar-lg'
  12039.           ]
  12040.         },
  12041.         components: [Menu.parts.items({
  12042.             preprocess: chunk({
  12043.               tag: 'div',
  12044.               classes: ['tox-collection__group']
  12045.             }, columns)
  12046.           })]
  12047.       };
  12048.     };
  12049.     var preprocessCollection = function (items, isSeparator) {
  12050.       var allSplits = [];
  12051.       var currentSplit = [];
  12052.       each$1(items, function (item, i) {
  12053.         if (isSeparator(item, i)) {
  12054.           if (currentSplit.length > 0) {
  12055.             allSplits.push(currentSplit);
  12056.           }
  12057.           currentSplit = [];
  12058.           if (has$2(item.dom, 'innerHtml')) {
  12059.             currentSplit.push(item);
  12060.           }
  12061.         } else {
  12062.           currentSplit.push(item);
  12063.         }
  12064.       });
  12065.       if (currentSplit.length > 0) {
  12066.         allSplits.push(currentSplit);
  12067.       }
  12068.       return map$2(allSplits, function (s) {
  12069.         return {
  12070.           dom: {
  12071.             tag: 'div',
  12072.             classes: ['tox-collection__group']
  12073.           },
  12074.           components: s
  12075.         };
  12076.       });
  12077.     };
  12078.     var forCollection = function (columns, initItems, _hasIcons) {
  12079.       return {
  12080.         dom: {
  12081.           tag: 'div',
  12082.           classes: [
  12083.             'tox-menu',
  12084.             'tox-collection'
  12085.           ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  12086.         },
  12087.         components: [Menu.parts.items({
  12088.             preprocess: function (items) {
  12089.               if (columns !== 'auto' && columns > 1) {
  12090.                 return chunk({
  12091.                   tag: 'div',
  12092.                   classes: ['tox-collection__group']
  12093.                 }, columns)(items);
  12094.               } else {
  12095.                 return preprocessCollection(items, function (_item, i) {
  12096.                   return initItems[i].type === 'separator';
  12097.                 });
  12098.               }
  12099.             }
  12100.           })]
  12101.       };
  12102.     };
  12103.     var forHorizontalCollection = function (initItems, _hasIcons) {
  12104.       return {
  12105.         dom: {
  12106.           tag: 'div',
  12107.           classes: [
  12108.             'tox-collection',
  12109.             'tox-collection--horizontal'
  12110.           ]
  12111.         },
  12112.         components: [Menu.parts.items({
  12113.             preprocess: function (items) {
  12114.               return preprocessCollection(items, function (_item, i) {
  12115.                 return initItems[i].type === 'separator';
  12116.               });
  12117.             }
  12118.           })]
  12119.       };
  12120.     };
  12121.  
  12122.     var menuHasIcons = function (xs) {
  12123.       return exists(xs, function (item) {
  12124.         return 'icon' in item && item.icon !== undefined;
  12125.       });
  12126.     };
  12127.     var handleError = function (error) {
  12128.       console.error(formatError(error));
  12129.       console.log(error);
  12130.       return Optional.none();
  12131.     };
  12132.     var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  12133.       var structure = forHorizontalCollection(items);
  12134.       return {
  12135.         value: value,
  12136.         dom: structure.dom,
  12137.         components: structure.components,
  12138.         items: items
  12139.       };
  12140.     };
  12141.     var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  12142.       if (presets === 'color') {
  12143.         var structure = forSwatch(columns);
  12144.         return {
  12145.           value: value,
  12146.           dom: structure.dom,
  12147.           components: structure.components,
  12148.           items: items
  12149.         };
  12150.       }
  12151.       if (presets === 'normal' && columns === 'auto') {
  12152.         var structure = forCollection(columns, items);
  12153.         return {
  12154.           value: value,
  12155.           dom: structure.dom,
  12156.           components: structure.components,
  12157.           items: items
  12158.         };
  12159.       }
  12160.       if (presets === 'normal' && columns === 1) {
  12161.         var structure = forCollection(1, items);
  12162.         return {
  12163.           value: value,
  12164.           dom: structure.dom,
  12165.           components: structure.components,
  12166.           items: items
  12167.         };
  12168.       }
  12169.       if (presets === 'normal') {
  12170.         var structure = forCollection(columns, items);
  12171.         return {
  12172.           value: value,
  12173.           dom: structure.dom,
  12174.           components: structure.components,
  12175.           items: items
  12176.         };
  12177.       }
  12178.       if (presets === 'listpreview' && columns !== 'auto') {
  12179.         var structure = forToolbar(columns);
  12180.         return {
  12181.           value: value,
  12182.           dom: structure.dom,
  12183.           components: structure.components,
  12184.           items: items
  12185.         };
  12186.       }
  12187.       return {
  12188.         value: value,
  12189.         dom: dom$1(hasIcons, columns, presets),
  12190.         components: components,
  12191.         items: items
  12192.       };
  12193.     };
  12194.  
  12195.     var cardImageFields = [
  12196.       requiredString('type'),
  12197.       requiredString('src'),
  12198.       optionString('alt'),
  12199.       defaultedArrayOf('classes', [], string)
  12200.     ];
  12201.     var cardImageSchema = objOf(cardImageFields);
  12202.  
  12203.     var cardTextFields = [
  12204.       requiredString('type'),
  12205.       requiredString('text'),
  12206.       optionString('name'),
  12207.       defaultedArrayOf('classes', ['tox-collection__item-label'], string)
  12208.     ];
  12209.     var cardTextSchema = objOf(cardTextFields);
  12210.  
  12211.     var itemSchema$1 = valueThunk(function () {
  12212.       return choose$2('type', {
  12213.         cardimage: cardImageSchema,
  12214.         cardtext: cardTextSchema,
  12215.         cardcontainer: cardContainerSchema
  12216.       });
  12217.     });
  12218.     var cardContainerSchema = objOf([
  12219.       requiredString('type'),
  12220.       defaultedString('direction', 'horizontal'),
  12221.       defaultedString('align', 'left'),
  12222.       defaultedString('valign', 'middle'),
  12223.       requiredArrayOf('items', itemSchema$1)
  12224.     ]);
  12225.  
  12226.     var commonMenuItemFields = [
  12227.       defaultedBoolean('disabled', false),
  12228.       optionString('text'),
  12229.       optionString('shortcut'),
  12230.       field$1('value', 'value', defaultedThunk(function () {
  12231.         return generate$6('menuitem-value');
  12232.       }), anyValue()),
  12233.       defaulted('meta', {})
  12234.     ];
  12235.  
  12236.     var cardMenuItemSchema = objOf([
  12237.       requiredString('type'),
  12238.       optionString('label'),
  12239.       requiredArrayOf('items', itemSchema$1),
  12240.       defaultedFunction('onSetup', function () {
  12241.         return noop;
  12242.       }),
  12243.       defaultedFunction('onAction', noop)
  12244.     ].concat(commonMenuItemFields));
  12245.     var createCardMenuItem = function (spec) {
  12246.       return asRaw('cardmenuitem', cardMenuItemSchema, spec);
  12247.     };
  12248.  
  12249.     var choiceMenuItemSchema = objOf([
  12250.       requiredString('type'),
  12251.       defaultedBoolean('active', false),
  12252.       optionString('icon')
  12253.     ].concat(commonMenuItemFields));
  12254.     var createChoiceMenuItem = function (spec) {
  12255.       return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  12256.     };
  12257.  
  12258.     var baseFields = [
  12259.       requiredString('type'),
  12260.       requiredString('fancytype'),
  12261.       defaultedFunction('onAction', noop)
  12262.     ];
  12263.     var insertTableFields = [defaulted('initData', {})].concat(baseFields);
  12264.     var colorSwatchFields = [defaultedObjOf('initData', {}, [
  12265.         defaultedBoolean('allowCustomColors', true),
  12266.         optionArrayOf('colors', anyValue())
  12267.       ])].concat(baseFields);
  12268.     var fancyMenuItemSchema = choose$1('fancytype', {
  12269.       inserttable: insertTableFields,
  12270.       colorswatch: colorSwatchFields
  12271.     });
  12272.     var createFancyMenuItem = function (spec) {
  12273.       return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  12274.     };
  12275.  
  12276.     var menuItemSchema = objOf([
  12277.       requiredString('type'),
  12278.       defaultedFunction('onSetup', function () {
  12279.         return noop;
  12280.       }),
  12281.       defaultedFunction('onAction', noop),
  12282.       optionString('icon')
  12283.     ].concat(commonMenuItemFields));
  12284.     var createMenuItem = function (spec) {
  12285.       return asRaw('menuitem', menuItemSchema, spec);
  12286.     };
  12287.  
  12288.     var nestedMenuItemSchema = objOf([
  12289.       requiredString('type'),
  12290.       requiredFunction('getSubmenuItems'),
  12291.       defaultedFunction('onSetup', function () {
  12292.         return noop;
  12293.       }),
  12294.       optionString('icon')
  12295.     ].concat(commonMenuItemFields));
  12296.     var createNestedMenuItem = function (spec) {
  12297.       return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  12298.     };
  12299.  
  12300.     var toggleMenuItemSchema = objOf([
  12301.       requiredString('type'),
  12302.       optionString('icon'),
  12303.       defaultedBoolean('active', false),
  12304.       defaultedFunction('onSetup', function () {
  12305.         return noop;
  12306.       }),
  12307.       requiredFunction('onAction')
  12308.     ].concat(commonMenuItemFields));
  12309.     var createToggleMenuItem = function (spec) {
  12310.       return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  12311.     };
  12312.  
  12313.     var detectSize = function (comp, margin, selectorClass) {
  12314.       var descendants$1 = descendants(comp.element, '.' + selectorClass);
  12315.       if (descendants$1.length > 0) {
  12316.         var columnLength = findIndex$1(descendants$1, function (c) {
  12317.           var thisTop = c.dom.getBoundingClientRect().top;
  12318.           var cTop = descendants$1[0].dom.getBoundingClientRect().top;
  12319.           return Math.abs(thisTop - cTop) > margin;
  12320.         }).getOr(descendants$1.length);
  12321.         return Optional.some({
  12322.           numColumns: columnLength,
  12323.           numRows: Math.ceil(descendants$1.length / columnLength)
  12324.         });
  12325.       } else {
  12326.         return Optional.none();
  12327.       }
  12328.     };
  12329.  
  12330.     var namedEvents = function (name, handlers) {
  12331.       return derive$1([config(name, handlers)]);
  12332.     };
  12333.     var unnamedEvents = function (handlers) {
  12334.       return namedEvents(generate$6('unnamed-events'), handlers);
  12335.     };
  12336.     var SimpleBehaviours = {
  12337.       namedEvents: namedEvents,
  12338.       unnamedEvents: unnamedEvents
  12339.     };
  12340.  
  12341.     var ExclusivityChannel = generate$6('tooltip.exclusive');
  12342.     var ShowTooltipEvent = generate$6('tooltip.show');
  12343.     var HideTooltipEvent = generate$6('tooltip.hide');
  12344.  
  12345.     var hideAllExclusive = function (component, _tConfig, _tState) {
  12346.       component.getSystem().broadcastOn([ExclusivityChannel], {});
  12347.     };
  12348.     var setComponents = function (component, tConfig, tState, specs) {
  12349.       tState.getTooltip().each(function (tooltip) {
  12350.         if (tooltip.getSystem().isConnected()) {
  12351.           Replacing.set(tooltip, specs);
  12352.         }
  12353.       });
  12354.     };
  12355.  
  12356.     var TooltippingApis = /*#__PURE__*/Object.freeze({
  12357.         __proto__: null,
  12358.         hideAllExclusive: hideAllExclusive,
  12359.         setComponents: setComponents
  12360.     });
  12361.  
  12362.     var events$9 = function (tooltipConfig, state) {
  12363.       var hide = function (comp) {
  12364.         state.getTooltip().each(function (p) {
  12365.           detach(p);
  12366.           tooltipConfig.onHide(comp, p);
  12367.           state.clearTooltip();
  12368.         });
  12369.         state.clearTimer();
  12370.       };
  12371.       var show = function (comp) {
  12372.         if (!state.isShowing()) {
  12373.           hideAllExclusive(comp);
  12374.           var sink = tooltipConfig.lazySink(comp).getOrDie();
  12375.           var popup = comp.getSystem().build({
  12376.             dom: tooltipConfig.tooltipDom,
  12377.             components: tooltipConfig.tooltipComponents,
  12378.             events: derive$2(tooltipConfig.mode === 'normal' ? [
  12379.               run$1(mouseover(), function (_) {
  12380.                 emit(comp, ShowTooltipEvent);
  12381.               }),
  12382.               run$1(mouseout(), function (_) {
  12383.                 emit(comp, HideTooltipEvent);
  12384.               })
  12385.             ] : []),
  12386.             behaviours: derive$1([Replacing.config({})])
  12387.           });
  12388.           state.setTooltip(popup);
  12389.           attach(sink, popup);
  12390.           tooltipConfig.onShow(comp, popup);
  12391.           Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
  12392.         }
  12393.       };
  12394.       return derive$2(flatten([
  12395.         [
  12396.           run$1(ShowTooltipEvent, function (comp) {
  12397.             state.resetTimer(function () {
  12398.               show(comp);
  12399.             }, tooltipConfig.delay);
  12400.           }),
  12401.           run$1(HideTooltipEvent, function (comp) {
  12402.             state.resetTimer(function () {
  12403.               hide(comp);
  12404.             }, tooltipConfig.delay);
  12405.           }),
  12406.           run$1(receive(), function (comp, message) {
  12407.             var receivingData = message;
  12408.             if (!receivingData.universal) {
  12409.               if (contains$2(receivingData.channels, ExclusivityChannel)) {
  12410.                 hide(comp);
  12411.               }
  12412.             }
  12413.           }),
  12414.           runOnDetached(function (comp) {
  12415.             hide(comp);
  12416.           })
  12417.         ],
  12418.         tooltipConfig.mode === 'normal' ? [
  12419.           run$1(focusin(), function (comp) {
  12420.             emit(comp, ShowTooltipEvent);
  12421.           }),
  12422.           run$1(postBlur(), function (comp) {
  12423.             emit(comp, HideTooltipEvent);
  12424.           }),
  12425.           run$1(mouseover(), function (comp) {
  12426.             emit(comp, ShowTooltipEvent);
  12427.           }),
  12428.           run$1(mouseout(), function (comp) {
  12429.             emit(comp, HideTooltipEvent);
  12430.           })
  12431.         ] : [
  12432.           run$1(highlight$1(), function (comp, _se) {
  12433.             emit(comp, ShowTooltipEvent);
  12434.           }),
  12435.           run$1(dehighlight$1(), function (comp) {
  12436.             emit(comp, HideTooltipEvent);
  12437.           })
  12438.         ]
  12439.       ]));
  12440.     };
  12441.  
  12442.     var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  12443.         __proto__: null,
  12444.         events: events$9
  12445.     });
  12446.  
  12447.     var TooltippingSchema = [
  12448.       required$1('lazySink'),
  12449.       required$1('tooltipDom'),
  12450.       defaulted('exclusive', true),
  12451.       defaulted('tooltipComponents', []),
  12452.       defaulted('delay', 300),
  12453.       defaultedStringEnum('mode', 'normal', [
  12454.         'normal',
  12455.         'follow-highlight'
  12456.       ]),
  12457.       defaulted('anchor', function (comp) {
  12458.         return {
  12459.           type: 'hotspot',
  12460.           hotspot: comp,
  12461.           layouts: {
  12462.             onLtr: constant$1([
  12463.               south$2,
  12464.               north$2,
  12465.               southeast$2,
  12466.               northeast$2,
  12467.               southwest$2,
  12468.               northwest$2
  12469.             ]),
  12470.             onRtl: constant$1([
  12471.               south$2,
  12472.               north$2,
  12473.               southeast$2,
  12474.               northeast$2,
  12475.               southwest$2,
  12476.               northwest$2
  12477.             ])
  12478.           }
  12479.         };
  12480.       }),
  12481.       onHandler('onHide'),
  12482.       onHandler('onShow')
  12483.     ];
  12484.  
  12485.     var init$b = function () {
  12486.       var timer = value$1();
  12487.       var popup = value$1();
  12488.       var clearTimer = function () {
  12489.         timer.on(clearTimeout);
  12490.       };
  12491.       var resetTimer = function (f, delay) {
  12492.         clearTimer();
  12493.         timer.set(setTimeout(f, delay));
  12494.       };
  12495.       var readState = constant$1('not-implemented');
  12496.       return nu$8({
  12497.         getTooltip: popup.get,
  12498.         isShowing: popup.isSet,
  12499.         setTooltip: popup.set,
  12500.         clearTooltip: popup.clear,
  12501.         clearTimer: clearTimer,
  12502.         resetTimer: resetTimer,
  12503.         readState: readState
  12504.       });
  12505.     };
  12506.  
  12507.     var TooltippingState = /*#__PURE__*/Object.freeze({
  12508.         __proto__: null,
  12509.         init: init$b
  12510.     });
  12511.  
  12512.     var Tooltipping = create$8({
  12513.       fields: TooltippingSchema,
  12514.       name: 'tooltipping',
  12515.       active: ActiveTooltipping,
  12516.       state: TooltippingState,
  12517.       apis: TooltippingApis
  12518.     });
  12519.  
  12520.     var escape = function (text) {
  12521.       return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  12522.     };
  12523.  
  12524.     var global$b = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  12525.  
  12526.     var global$a = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12527.  
  12528.     var getSkinUrl = function (editor) {
  12529.       var skin = editor.getParam('skin');
  12530.       var skinUrl = editor.getParam('skin_url');
  12531.       if (skin !== false) {
  12532.         var skinName = skin ? skin : 'oxide';
  12533.         if (skinUrl) {
  12534.           skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  12535.         } else {
  12536.           skinUrl = global$a.baseURL + '/skins/ui/' + skinName;
  12537.         }
  12538.       }
  12539.       return skinUrl;
  12540.     };
  12541.     var isReadOnly = function (editor) {
  12542.       return editor.getParam('readonly', false, 'boolean');
  12543.     };
  12544.     var isSkinDisabled = function (editor) {
  12545.       return editor.getParam('skin') === false;
  12546.     };
  12547.     var getHeightSetting = function (editor) {
  12548.       return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  12549.     };
  12550.     var getWidthSetting = function (editor) {
  12551.       return editor.getParam('width', global$b.DOM.getStyle(editor.getElement(), 'width'));
  12552.     };
  12553.     var getMinWidthSetting = function (editor) {
  12554.       return Optional.from(editor.getParam('min_width')).filter(isNumber);
  12555.     };
  12556.     var getMinHeightSetting = function (editor) {
  12557.       return Optional.from(editor.getParam('min_height')).filter(isNumber);
  12558.     };
  12559.     var getMaxWidthSetting = function (editor) {
  12560.       return Optional.from(editor.getParam('max_width')).filter(isNumber);
  12561.     };
  12562.     var getMaxHeightSetting = function (editor) {
  12563.       return Optional.from(editor.getParam('max_height')).filter(isNumber);
  12564.     };
  12565.     var getUserStyleFormats = function (editor) {
  12566.       return Optional.from(editor.getParam('style_formats')).filter(isArray);
  12567.     };
  12568.     var isMergeStyleFormats = function (editor) {
  12569.       return editor.getParam('style_formats_merge', false, 'boolean');
  12570.     };
  12571.     var getLineHeightFormats = function (editor) {
  12572.       return editor.getParam('lineheight_formats', '1 1.1 1.2 1.3 1.4 1.5 2', 'string').split(' ');
  12573.     };
  12574.     var getContentLanguages = function (editor) {
  12575.       return editor.getParam('content_langs', undefined, 'array');
  12576.     };
  12577.     var getRemovedMenuItems = function (editor) {
  12578.       return editor.getParam('removed_menuitems', '');
  12579.     };
  12580.     var isMenubarEnabled = function (editor) {
  12581.       return editor.getParam('menubar', true, 'boolean') !== false;
  12582.     };
  12583.     var isToolbarEnabled = function (editor) {
  12584.       var toolbar = editor.getParam('toolbar', true);
  12585.       var isToolbarTrue = toolbar === true;
  12586.       var isToolbarString = isString(toolbar);
  12587.       var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  12588.       return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  12589.     };
  12590.     var getMultipleToolbarsSetting = function (editor) {
  12591.       var toolbars = range$2(9, function (num) {
  12592.         return editor.getParam('toolbar' + (num + 1), false, 'string');
  12593.       });
  12594.       var toolbarArray = filter$2(toolbars, function (toolbar) {
  12595.         return typeof toolbar === 'string';
  12596.       });
  12597.       return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
  12598.     };
  12599.     var isMultipleToolbars = function (editor) {
  12600.       return getMultipleToolbarsSetting(editor).fold(function () {
  12601.         var toolbar = editor.getParam('toolbar', [], 'string[]');
  12602.         return toolbar.length > 0;
  12603.       }, always);
  12604.     };
  12605.     var ToolbarMode;
  12606.     (function (ToolbarMode) {
  12607.       ToolbarMode['default'] = 'wrap';
  12608.       ToolbarMode['floating'] = 'floating';
  12609.       ToolbarMode['sliding'] = 'sliding';
  12610.       ToolbarMode['scrolling'] = 'scrolling';
  12611.     }(ToolbarMode || (ToolbarMode = {})));
  12612.     var getToolbarMode = function (editor) {
  12613.       return editor.getParam('toolbar_mode', '', 'string');
  12614.     };
  12615.     var ToolbarLocation;
  12616.     (function (ToolbarLocation) {
  12617.       ToolbarLocation['auto'] = 'auto';
  12618.       ToolbarLocation['top'] = 'top';
  12619.       ToolbarLocation['bottom'] = 'bottom';
  12620.     }(ToolbarLocation || (ToolbarLocation = {})));
  12621.     var getToolbarGroups = function (editor) {
  12622.       return editor.getParam('toolbar_groups', {}, 'object');
  12623.     };
  12624.     var getToolbarLocation = function (editor) {
  12625.       return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string');
  12626.     };
  12627.     var isToolbarLocationBottom = function (editor) {
  12628.       return getToolbarLocation(editor) === ToolbarLocation.bottom;
  12629.     };
  12630.     var fixedContainerSelector = function (editor) {
  12631.       return editor.getParam('fixed_toolbar_container', '', 'string');
  12632.     };
  12633.     var fixedToolbarContainerTarget = function (editor) {
  12634.       return editor.getParam('fixed_toolbar_container_target');
  12635.     };
  12636.     var isToolbarPersist = function (editor) {
  12637.       return editor.getParam('toolbar_persist', false, 'boolean');
  12638.     };
  12639.     var fixedContainerTarget = function (editor) {
  12640.       if (!editor.inline) {
  12641.         return Optional.none();
  12642.       }
  12643.       var selector = fixedContainerSelector(editor);
  12644.       if (selector.length > 0) {
  12645.         return descendant(body(), selector);
  12646.       }
  12647.       var element = fixedToolbarContainerTarget(editor);
  12648.       if (isNonNullable(element)) {
  12649.         return Optional.some(SugarElement.fromDom(element));
  12650.       }
  12651.       return Optional.none();
  12652.     };
  12653.     var useFixedContainer = function (editor) {
  12654.       return editor.inline && fixedContainerTarget(editor).isSome();
  12655.     };
  12656.     var getUiContainer = function (editor) {
  12657.       var fixedContainer = fixedContainerTarget(editor);
  12658.       return fixedContainer.getOrThunk(function () {
  12659.         return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
  12660.       });
  12661.     };
  12662.     var isDistractionFree = function (editor) {
  12663.       return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  12664.     };
  12665.     var isStickyToolbar = function (editor) {
  12666.       var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  12667.       return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  12668.     };
  12669.     var getStickyToolbarOffset = function (editor) {
  12670.       return editor.getParam('toolbar_sticky_offset', 0, 'number');
  12671.     };
  12672.     var isDraggableModal$1 = function (editor) {
  12673.       return editor.getParam('draggable_modal', false, 'boolean');
  12674.     };
  12675.     var getMenus = function (editor) {
  12676.       var menu = editor.getParam('menu');
  12677.       if (menu) {
  12678.         return map$1(menu, function (menu) {
  12679.           return __assign(__assign({}, menu), { items: menu.items });
  12680.         });
  12681.       } else {
  12682.         return {};
  12683.       }
  12684.     };
  12685.     var getMenubar = function (editor) {
  12686.       return editor.getParam('menubar');
  12687.     };
  12688.     var getToolbar = function (editor) {
  12689.       return editor.getParam('toolbar', true);
  12690.     };
  12691.     var getFilePickerCallback = function (editor) {
  12692.       return editor.getParam('file_picker_callback');
  12693.     };
  12694.     var getFilePickerTypes = function (editor) {
  12695.       return editor.getParam('file_picker_types');
  12696.     };
  12697.     var getFileBrowserCallbackTypes = function (editor) {
  12698.       return editor.getParam('file_browser_callback_types');
  12699.     };
  12700.     var noTypeaheadUrls = function (editor) {
  12701.       return editor.getParam('typeahead_urls') === false;
  12702.     };
  12703.     var getAnchorTop = function (editor) {
  12704.       return editor.getParam('anchor_top', '#top');
  12705.     };
  12706.     var getAnchorBottom = function (editor) {
  12707.       return editor.getParam('anchor_bottom', '#bottom');
  12708.     };
  12709.     var getFilePickerValidatorHandler = function (editor) {
  12710.       var handler = editor.getParam('file_picker_validator_handler', undefined, 'function');
  12711.       if (handler === undefined) {
  12712.         return editor.getParam('filepicker_validator_handler', undefined, 'function');
  12713.       } else {
  12714.         return handler;
  12715.       }
  12716.     };
  12717.  
  12718.     var ReadOnlyChannel = 'silver.readonly';
  12719.     var ReadOnlyDataSchema = objOf([requiredBoolean('readonly')]);
  12720.     var broadcastReadonly = function (uiComponents, readonly) {
  12721.       var outerContainer = uiComponents.outerContainer;
  12722.       var target = outerContainer.element;
  12723.       if (readonly) {
  12724.         uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  12725.         uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  12726.       }
  12727.       uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  12728.       uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  12729.     };
  12730.     var setupReadonlyModeSwitch = function (editor, uiComponents) {
  12731.       editor.on('init', function () {
  12732.         if (editor.mode.isReadOnly()) {
  12733.           broadcastReadonly(uiComponents, true);
  12734.         }
  12735.       });
  12736.       editor.on('SwitchMode', function () {
  12737.         return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
  12738.       });
  12739.       if (isReadOnly(editor)) {
  12740.         editor.setMode('readonly');
  12741.       }
  12742.     };
  12743.     var receivingConfig = function () {
  12744.       var _a;
  12745.       return Receiving.config({
  12746.         channels: (_a = {}, _a[ReadOnlyChannel] = {
  12747.           schema: ReadOnlyDataSchema,
  12748.           onReceive: function (comp, data) {
  12749.             Disabling.set(comp, data.readonly);
  12750.           }
  12751.         }, _a)
  12752.       });
  12753.     };
  12754.  
  12755.     var item = function (disabled) {
  12756.       return Disabling.config({
  12757.         disabled: disabled,
  12758.         disableClass: 'tox-collection__item--state-disabled'
  12759.       });
  12760.     };
  12761.     var button = function (disabled) {
  12762.       return Disabling.config({ disabled: disabled });
  12763.     };
  12764.     var splitButton = function (disabled) {
  12765.       return Disabling.config({
  12766.         disabled: disabled,
  12767.         disableClass: 'tox-tbtn--disabled'
  12768.       });
  12769.     };
  12770.     var toolbarButton = function (disabled) {
  12771.       return Disabling.config({
  12772.         disabled: disabled,
  12773.         disableClass: 'tox-tbtn--disabled',
  12774.         useNative: false
  12775.       });
  12776.     };
  12777.     var DisablingConfigs = {
  12778.       item: item,
  12779.       button: button,
  12780.       splitButton: splitButton,
  12781.       toolbarButton: toolbarButton
  12782.     };
  12783.  
  12784.     var runWithApi = function (info, comp) {
  12785.       var api = info.getApi(comp);
  12786.       return function (f) {
  12787.         f(api);
  12788.       };
  12789.     };
  12790.     var onControlAttached = function (info, editorOffCell) {
  12791.       return runOnAttached(function (comp) {
  12792.         var run = runWithApi(info, comp);
  12793.         run(function (api) {
  12794.           var onDestroy = info.onSetup(api);
  12795.           if (isFunction(onDestroy)) {
  12796.             editorOffCell.set(onDestroy);
  12797.           }
  12798.         });
  12799.       });
  12800.     };
  12801.     var onControlDetached = function (getApi, editorOffCell) {
  12802.       return runOnDetached(function (comp) {
  12803.         return runWithApi(getApi, comp)(editorOffCell.get());
  12804.       });
  12805.     };
  12806.  
  12807.     var _a$1;
  12808.     var onMenuItemExecute = function (info, itemResponse) {
  12809.       return runOnExecute$1(function (comp, simulatedEvent) {
  12810.         runWithApi(info, comp)(info.onAction);
  12811.         if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  12812.           emit(comp, sandboxClose());
  12813.           simulatedEvent.stop();
  12814.         }
  12815.       });
  12816.     };
  12817.     var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [
  12818.       'disabling',
  12819.       'alloy.base.behaviour',
  12820.       'toggling',
  12821.       'item-events'
  12822.     ], _a$1);
  12823.  
  12824.     var componentRenderPipeline = cat;
  12825.     var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) {
  12826.       var editorOffCell = Cell(noop);
  12827.       return {
  12828.         type: 'item',
  12829.         dom: structure.dom,
  12830.         components: componentRenderPipeline(structure.optComponents),
  12831.         data: spec.data,
  12832.         eventOrder: menuItemEventOrder,
  12833.         hasSubmenu: spec.triggersSubmenu,
  12834.         itemBehaviours: derive$1([
  12835.           config('item-events', [
  12836.             onMenuItemExecute(spec, itemResponse),
  12837.             onControlAttached(spec, editorOffCell),
  12838.             onControlDetached(spec, editorOffCell)
  12839.           ]),
  12840.           DisablingConfigs.item(function () {
  12841.             return spec.disabled || providersbackstage.isDisabled();
  12842.           }),
  12843.           receivingConfig(),
  12844.           Replacing.config({})
  12845.         ].concat(spec.itemBehaviours))
  12846.       };
  12847.     };
  12848.     var buildData = function (source) {
  12849.       return {
  12850.         value: source.value,
  12851.         meta: __assign({ text: source.text.getOr('') }, source.meta)
  12852.       };
  12853.     };
  12854.  
  12855.     var global$9 = tinymce.util.Tools.resolve('tinymce.Env');
  12856.  
  12857.     var convertText = function (source) {
  12858.       var mac = {
  12859.         alt: '&#x2325;',
  12860.         ctrl: '&#x2303;',
  12861.         shift: '&#x21E7;',
  12862.         meta: '&#x2318;',
  12863.         access: '&#x2303;&#x2325;'
  12864.       };
  12865.       var other = {
  12866.         meta: 'Ctrl',
  12867.         access: 'Shift+Alt'
  12868.       };
  12869.       var replace = global$9.mac ? mac : other;
  12870.       var shortcut = source.split('+');
  12871.       var updated = map$2(shortcut, function (segment) {
  12872.         var search = segment.toLowerCase().trim();
  12873.         return has$2(replace, search) ? replace[search] : segment;
  12874.       });
  12875.       return global$9.mac ? updated.join('') : updated.join('+');
  12876.     };
  12877.  
  12878.     var renderIcon$1 = function (name, icons, classes) {
  12879.       if (classes === void 0) {
  12880.         classes = [iconClass];
  12881.       }
  12882.       return render$3(name, {
  12883.         tag: 'div',
  12884.         classes: classes
  12885.       }, icons);
  12886.     };
  12887.     var renderText = function (text) {
  12888.       return {
  12889.         dom: {
  12890.           tag: 'div',
  12891.           classes: [textClass]
  12892.         },
  12893.         components: [text$1(global$e.translate(text))]
  12894.       };
  12895.     };
  12896.     var renderHtml = function (html, classes) {
  12897.       return {
  12898.         dom: {
  12899.           tag: 'div',
  12900.           classes: classes,
  12901.           innerHtml: html
  12902.         }
  12903.       };
  12904.     };
  12905.     var renderStyledText = function (style, text) {
  12906.       return {
  12907.         dom: {
  12908.           tag: 'div',
  12909.           classes: [textClass]
  12910.         },
  12911.         components: [{
  12912.             dom: {
  12913.               tag: style.tag,
  12914.               styles: style.styles
  12915.             },
  12916.             components: [text$1(global$e.translate(text))]
  12917.           }]
  12918.       };
  12919.     };
  12920.     var renderShortcut = function (shortcut) {
  12921.       return {
  12922.         dom: {
  12923.           tag: 'div',
  12924.           classes: [accessoryClass],
  12925.           innerHtml: convertText(shortcut)
  12926.         }
  12927.       };
  12928.     };
  12929.     var renderCheckmark = function (icons) {
  12930.       return renderIcon$1('checkmark', icons, [checkmarkClass]);
  12931.     };
  12932.     var renderSubmenuCaret = function (icons) {
  12933.       return renderIcon$1('chevron-right', icons, [caretClass]);
  12934.     };
  12935.     var renderDownwardsCaret = function (icons) {
  12936.       return renderIcon$1('chevron-down', icons, [caretClass]);
  12937.     };
  12938.     var renderContainer = function (container, components) {
  12939.       var directionClass = container.direction === 'vertical' ? containerColumnClass : containerRowClass;
  12940.       var alignClass = container.align === 'left' ? containerAlignLeftClass : containerAlignRightClass;
  12941.       var getValignClass = function () {
  12942.         switch (container.valign) {
  12943.         case 'top':
  12944.           return containerValignTopClass;
  12945.         case 'middle':
  12946.           return containerValignMiddleClass;
  12947.         case 'bottom':
  12948.           return containerValignBottomClass;
  12949.         }
  12950.       };
  12951.       return {
  12952.         dom: {
  12953.           tag: 'div',
  12954.           classes: [
  12955.             containerClass,
  12956.             directionClass,
  12957.             alignClass,
  12958.             getValignClass()
  12959.           ]
  12960.         },
  12961.         components: components
  12962.       };
  12963.     };
  12964.     var renderImage = function (src, classes, alt) {
  12965.       return {
  12966.         dom: {
  12967.           tag: 'img',
  12968.           classes: classes,
  12969.           attributes: {
  12970.             src: src,
  12971.             alt: alt.getOr('')
  12972.           }
  12973.         }
  12974.       };
  12975.     };
  12976.  
  12977.     var renderColorStructure = function (item, providerBackstage, fallbackIcon) {
  12978.       var colorPickerCommand = 'custom';
  12979.       var removeColorCommand = 'remove';
  12980.       var itemText = item.ariaLabel;
  12981.       var itemValue = item.value;
  12982.       var iconSvg = item.iconContent.map(function (name) {
  12983.         return getOr(name, providerBackstage.icons, fallbackIcon);
  12984.       });
  12985.       var getDom = function () {
  12986.         var common = colorClass;
  12987.         var icon = iconSvg.getOr('');
  12988.         var attributes = itemText.map(function (text) {
  12989.           return { title: providerBackstage.translate(text) };
  12990.         }).getOr({});
  12991.         var baseDom = {
  12992.           tag: 'div',
  12993.           attributes: attributes,
  12994.           classes: [common]
  12995.         };
  12996.         if (itemValue === colorPickerCommand) {
  12997.           return __assign(__assign({}, baseDom), {
  12998.             tag: 'button',
  12999.             classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatches__picker-btn'], false),
  13000.             innerHtml: icon
  13001.           });
  13002.         } else if (itemValue === removeColorCommand) {
  13003.           return __assign(__assign({}, baseDom), {
  13004.             classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatch--remove'], false),
  13005.             innerHtml: icon
  13006.           });
  13007.         } else {
  13008.           return __assign(__assign({}, baseDom), {
  13009.             attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  13010.             styles: { 'background-color': itemValue }
  13011.           });
  13012.         }
  13013.       };
  13014.       return {
  13015.         dom: getDom(),
  13016.         optComponents: []
  13017.       };
  13018.     };
  13019.     var renderItemDomStructure = function (ariaLabel) {
  13020.       var domTitle = ariaLabel.map(function (label) {
  13021.         return { attributes: { title: global$e.translate(label) } };
  13022.       }).getOr({});
  13023.       return __assign({
  13024.         tag: 'div',
  13025.         classes: [
  13026.           navClass,
  13027.           selectableClass
  13028.         ]
  13029.       }, domTitle);
  13030.     };
  13031.     var renderNormalItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  13032.       var iconSpec = {
  13033.         tag: 'div',
  13034.         classes: [iconClass]
  13035.       };
  13036.       var renderIcon = function (iconName) {
  13037.         return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
  13038.       };
  13039.       var renderEmptyIcon = function () {
  13040.         return Optional.some({ dom: iconSpec });
  13041.       };
  13042.       var leftIcon = renderIcons ? info.iconContent.map(renderIcon).orThunk(renderEmptyIcon) : Optional.none();
  13043.       var checkmark = info.checkMark;
  13044.       var textRender = Optional.from(info.meta).fold(function () {
  13045.         return renderText;
  13046.       }, function (meta) {
  13047.         return has$2(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  13048.       });
  13049.       var content = info.htmlContent.fold(function () {
  13050.         return info.textContent.map(textRender);
  13051.       }, function (html) {
  13052.         return Optional.some(renderHtml(html, [textClass]));
  13053.       });
  13054.       var menuItem = {
  13055.         dom: renderItemDomStructure(info.ariaLabel),
  13056.         optComponents: [
  13057.           leftIcon,
  13058.           content,
  13059.           info.shortcutContent.map(renderShortcut),
  13060.           checkmark,
  13061.           info.caret
  13062.         ]
  13063.       };
  13064.       return menuItem;
  13065.     };
  13066.     var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  13067.       if (fallbackIcon === void 0) {
  13068.         fallbackIcon = Optional.none();
  13069.       }
  13070.       if (info.presets === 'color') {
  13071.         return renderColorStructure(info, providersBackstage, fallbackIcon);
  13072.       } else {
  13073.         return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
  13074.       }
  13075.     };
  13076.  
  13077.     var tooltipBehaviour = function (meta, sharedBackstage) {
  13078.       return get$e(meta, 'tooltipWorker').map(function (tooltipWorker) {
  13079.         return [Tooltipping.config({
  13080.             lazySink: sharedBackstage.getSink,
  13081.             tooltipDom: {
  13082.               tag: 'div',
  13083.               classes: ['tox-tooltip-worker-container']
  13084.             },
  13085.             tooltipComponents: [],
  13086.             anchor: function (comp) {
  13087.               return {
  13088.                 type: 'submenu',
  13089.                 item: comp,
  13090.                 overrides: { maxHeightFunction: expandable$1 }
  13091.               };
  13092.             },
  13093.             mode: 'follow-highlight',
  13094.             onShow: function (component, _tooltip) {
  13095.               tooltipWorker(function (elm) {
  13096.                 Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]);
  13097.               });
  13098.             }
  13099.           })];
  13100.       }).getOr([]);
  13101.     };
  13102.     var encodeText = function (text) {
  13103.       return global$b.DOM.encode(text);
  13104.     };
  13105.     var replaceText = function (text, matchText) {
  13106.       var translated = global$e.translate(text);
  13107.       var encoded = encodeText(translated);
  13108.       if (matchText.length > 0) {
  13109.         var escapedMatchRegex = new RegExp(escape(matchText), 'gi');
  13110.         return encoded.replace(escapedMatchRegex, function (match) {
  13111.           return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  13112.         });
  13113.       } else {
  13114.         return encoded;
  13115.       }
  13116.     };
  13117.     var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  13118.       if (renderIcons === void 0) {
  13119.         renderIcons = true;
  13120.       }
  13121.       var structure = renderItemStructure({
  13122.         presets: presets,
  13123.         textContent: Optional.none(),
  13124.         htmlContent: useText ? spec.text.map(function (text) {
  13125.           return replaceText(text, matchText);
  13126.         }) : Optional.none(),
  13127.         ariaLabel: spec.text,
  13128.         iconContent: spec.icon,
  13129.         shortcutContent: Optional.none(),
  13130.         checkMark: Optional.none(),
  13131.         caret: Optional.none(),
  13132.         value: spec.value
  13133.       }, sharedBackstage.providers, renderIcons, spec.icon);
  13134.       return renderCommonItem({
  13135.         data: buildData(spec),
  13136.         disabled: spec.disabled,
  13137.         getApi: constant$1({}),
  13138.         onAction: function (_api) {
  13139.           return onItemValueHandler(spec.value, spec.meta);
  13140.         },
  13141.         onSetup: constant$1(noop),
  13142.         triggersSubmenu: false,
  13143.         itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  13144.       }, structure, itemResponse, sharedBackstage.providers);
  13145.     };
  13146.  
  13147.     var render$2 = function (items, extras) {
  13148.       return map$2(items, function (item) {
  13149.         switch (item.type) {
  13150.         case 'cardcontainer':
  13151.           return renderContainer(item, render$2(item.items, extras));
  13152.         case 'cardimage':
  13153.           return renderImage(item.src, item.classes, item.alt);
  13154.         case 'cardtext':
  13155.           var shouldHighlight = item.name.exists(function (name) {
  13156.             return contains$2(extras.cardText.highlightOn, name);
  13157.           });
  13158.           var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr('') : '';
  13159.           return renderHtml(replaceText(item.text, matchText), item.classes);
  13160.         }
  13161.       });
  13162.     };
  13163.     var renderCardMenuItem = function (spec, itemResponse, sharedBackstage, extras) {
  13164.       var getApi = function (component) {
  13165.         return {
  13166.           isDisabled: function () {
  13167.             return Disabling.isDisabled(component);
  13168.           },
  13169.           setDisabled: function (state) {
  13170.             Disabling.set(component, state);
  13171.             each$1(descendants(component.element, '*'), function (elm) {
  13172.               component.getSystem().getByDom(elm).each(function (comp) {
  13173.                 if (comp.hasConfigured(Disabling)) {
  13174.                   Disabling.set(comp, state);
  13175.                 }
  13176.               });
  13177.             });
  13178.           }
  13179.         };
  13180.       };
  13181.       var structure = {
  13182.         dom: renderItemDomStructure(spec.label),
  13183.         optComponents: [Optional.some({
  13184.             dom: {
  13185.               tag: 'div',
  13186.               classes: [
  13187.                 containerClass,
  13188.                 containerRowClass
  13189.               ]
  13190.             },
  13191.             components: render$2(spec.items, extras)
  13192.           })]
  13193.       };
  13194.       return renderCommonItem({
  13195.         data: buildData(__assign({ text: Optional.none() }, spec)),
  13196.         disabled: spec.disabled,
  13197.         getApi: getApi,
  13198.         onAction: spec.onAction,
  13199.         onSetup: spec.onSetup,
  13200.         triggersSubmenu: false,
  13201.         itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
  13202.       }, structure, itemResponse, sharedBackstage.providers);
  13203.     };
  13204.  
  13205.     var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
  13206.       if (renderIcons === void 0) {
  13207.         renderIcons = true;
  13208.       }
  13209.       var getApi = function (component) {
  13210.         return {
  13211.           setActive: function (state) {
  13212.             Toggling.set(component, state);
  13213.           },
  13214.           isActive: function () {
  13215.             return Toggling.isOn(component);
  13216.           },
  13217.           isDisabled: function () {
  13218.             return Disabling.isDisabled(component);
  13219.           },
  13220.           setDisabled: function (state) {
  13221.             return Disabling.set(component, state);
  13222.           }
  13223.         };
  13224.       };
  13225.       var structure = renderItemStructure({
  13226.         presets: presets,
  13227.         textContent: useText ? spec.text : Optional.none(),
  13228.         htmlContent: Optional.none(),
  13229.         ariaLabel: spec.text,
  13230.         iconContent: spec.icon,
  13231.         shortcutContent: useText ? spec.shortcut : Optional.none(),
  13232.         checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
  13233.         caret: Optional.none(),
  13234.         value: spec.value
  13235.       }, providersBackstage, renderIcons);
  13236.       return deepMerge(renderCommonItem({
  13237.         data: buildData(spec),
  13238.         disabled: spec.disabled,
  13239.         getApi: getApi,
  13240.         onAction: function (_api) {
  13241.           return onItemValueHandler(spec.value);
  13242.         },
  13243.         onSetup: function (api) {
  13244.           api.setActive(isSelected);
  13245.           return noop;
  13246.         },
  13247.         triggersSubmenu: false,
  13248.         itemBehaviours: []
  13249.       }, structure, itemResponse, providersBackstage), {
  13250.         toggling: {
  13251.           toggleClass: tickedClass,
  13252.           toggleOnExecute: false,
  13253.           selected: spec.active
  13254.         }
  13255.       });
  13256.     };
  13257.  
  13258.     var parts$f = generate$3(owner$2(), parts$h());
  13259.  
  13260.     var hexColour = function (value) {
  13261.       return { value: value };
  13262.     };
  13263.     var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  13264.     var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  13265.     var isHexString = function (hex) {
  13266.       return shorthandRegex.test(hex) || longformRegex.test(hex);
  13267.     };
  13268.     var normalizeHex = function (hex) {
  13269.       return removeLeading(hex, '#').toUpperCase();
  13270.     };
  13271.     var fromString$1 = function (hex) {
  13272.       return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  13273.     };
  13274.     var getLongForm = function (hex) {
  13275.       var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) {
  13276.         return r + r + g + g + b + b;
  13277.       });
  13278.       return { value: hexString };
  13279.     };
  13280.     var extractValues = function (hex) {
  13281.       var longForm = getLongForm(hex);
  13282.       var splitForm = longformRegex.exec(longForm.value);
  13283.       return splitForm === null ? [
  13284.         'FFFFFF',
  13285.         'FF',
  13286.         'FF',
  13287.         'FF'
  13288.       ] : splitForm;
  13289.     };
  13290.     var toHex = function (component) {
  13291.       var hex = component.toString(16);
  13292.       return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  13293.     };
  13294.     var fromRgba = function (rgbaColour) {
  13295.       var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  13296.       return hexColour(value);
  13297.     };
  13298.  
  13299.     var min = Math.min;
  13300.     var max = Math.max;
  13301.     var round$1 = Math.round;
  13302.     var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  13303.     var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  13304.     var rgbaColour = function (red, green, blue, alpha) {
  13305.       return {
  13306.         red: red,
  13307.         green: green,
  13308.         blue: blue,
  13309.         alpha: alpha
  13310.       };
  13311.     };
  13312.     var isRgbaComponent = function (value) {
  13313.       var num = parseInt(value, 10);
  13314.       return num.toString() === value && num >= 0 && num <= 255;
  13315.     };
  13316.     var fromHsv = function (hsv) {
  13317.       var r;
  13318.       var g;
  13319.       var b;
  13320.       var hue = (hsv.hue || 0) % 360;
  13321.       var saturation = hsv.saturation / 100;
  13322.       var brightness = hsv.value / 100;
  13323.       saturation = max(0, min(saturation, 1));
  13324.       brightness = max(0, min(brightness, 1));
  13325.       if (saturation === 0) {
  13326.         r = g = b = round$1(255 * brightness);
  13327.         return rgbaColour(r, g, b, 1);
  13328.       }
  13329.       var side = hue / 60;
  13330.       var chroma = brightness * saturation;
  13331.       var x = chroma * (1 - Math.abs(side % 2 - 1));
  13332.       var match = brightness - chroma;
  13333.       switch (Math.floor(side)) {
  13334.       case 0:
  13335.         r = chroma;
  13336.         g = x;
  13337.         b = 0;
  13338.         break;
  13339.       case 1:
  13340.         r = x;
  13341.         g = chroma;
  13342.         b = 0;
  13343.         break;
  13344.       case 2:
  13345.         r = 0;
  13346.         g = chroma;
  13347.         b = x;
  13348.         break;
  13349.       case 3:
  13350.         r = 0;
  13351.         g = x;
  13352.         b = chroma;
  13353.         break;
  13354.       case 4:
  13355.         r = x;
  13356.         g = 0;
  13357.         b = chroma;
  13358.         break;
  13359.       case 5:
  13360.         r = chroma;
  13361.         g = 0;
  13362.         b = x;
  13363.         break;
  13364.       default:
  13365.         r = g = b = 0;
  13366.       }
  13367.       r = round$1(255 * (r + match));
  13368.       g = round$1(255 * (g + match));
  13369.       b = round$1(255 * (b + match));
  13370.       return rgbaColour(r, g, b, 1);
  13371.     };
  13372.     var fromHex = function (hexColour) {
  13373.       var result = extractValues(hexColour);
  13374.       var red = parseInt(result[1], 16);
  13375.       var green = parseInt(result[2], 16);
  13376.       var blue = parseInt(result[3], 16);
  13377.       return rgbaColour(red, green, blue, 1);
  13378.     };
  13379.     var fromStringValues = function (red, green, blue, alpha) {
  13380.       var r = parseInt(red, 10);
  13381.       var g = parseInt(green, 10);
  13382.       var b = parseInt(blue, 10);
  13383.       var a = parseFloat(alpha);
  13384.       return rgbaColour(r, g, b, a);
  13385.     };
  13386.     var fromString = function (rgbaString) {
  13387.       if (rgbaString === 'transparent') {
  13388.         return Optional.some(rgbaColour(0, 0, 0, 0));
  13389.       }
  13390.       var rgbMatch = rgbRegex.exec(rgbaString);
  13391.       if (rgbMatch !== null) {
  13392.         return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  13393.       }
  13394.       var rgbaMatch = rgbaRegex.exec(rgbaString);
  13395.       if (rgbaMatch !== null) {
  13396.         return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  13397.       }
  13398.       return Optional.none();
  13399.     };
  13400.     var toString = function (rgba) {
  13401.       return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')';
  13402.     };
  13403.     var red = rgbaColour(255, 0, 0, 1);
  13404.  
  13405.     var fireSkinLoaded$1 = function (editor) {
  13406.       return editor.fire('SkinLoaded');
  13407.     };
  13408.     var fireSkinLoadError$1 = function (editor, error) {
  13409.       return editor.fire('SkinLoadError', error);
  13410.     };
  13411.     var fireResizeEditor = function (editor) {
  13412.       return editor.fire('ResizeEditor');
  13413.     };
  13414.     var fireResizeContent = function (editor, e) {
  13415.       return editor.fire('ResizeContent', e);
  13416.     };
  13417.     var fireScrollContent = function (editor, e) {
  13418.       return editor.fire('ScrollContent', e);
  13419.     };
  13420.     var fireTextColorChange = function (editor, data) {
  13421.       return editor.fire('TextColorChange', data);
  13422.     };
  13423.  
  13424.     var hsvColour = function (hue, saturation, value) {
  13425.       return {
  13426.         hue: hue,
  13427.         saturation: saturation,
  13428.         value: value
  13429.       };
  13430.     };
  13431.     var fromRgb = function (rgbaColour) {
  13432.       var h = 0;
  13433.       var s = 0;
  13434.       var v = 0;
  13435.       var r = rgbaColour.red / 255;
  13436.       var g = rgbaColour.green / 255;
  13437.       var b = rgbaColour.blue / 255;
  13438.       var minRGB = Math.min(r, Math.min(g, b));
  13439.       var maxRGB = Math.max(r, Math.max(g, b));
  13440.       if (minRGB === maxRGB) {
  13441.         v = minRGB;
  13442.         return hsvColour(0, 0, v * 100);
  13443.       }
  13444.       var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  13445.       h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  13446.       h = 60 * (h - d / (maxRGB - minRGB));
  13447.       s = (maxRGB - minRGB) / maxRGB;
  13448.       v = maxRGB;
  13449.       return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  13450.     };
  13451.  
  13452.     var hexToHsv = function (hex) {
  13453.       return fromRgb(fromHex(hex));
  13454.     };
  13455.     var hsvToHex = function (hsv) {
  13456.       return fromRgba(fromHsv(hsv));
  13457.     };
  13458.     var anyToHex = function (color) {
  13459.       return fromString$1(color).orThunk(function () {
  13460.         return fromString(color).map(fromRgba);
  13461.       }).getOrThunk(function () {
  13462.         var canvas = document.createElement('canvas');
  13463.         canvas.height = 1;
  13464.         canvas.width = 1;
  13465.         var canvasContext = canvas.getContext('2d');
  13466.         canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  13467.         canvasContext.fillStyle = '#FFFFFF';
  13468.         canvasContext.fillStyle = color;
  13469.         canvasContext.fillRect(0, 0, 1, 1);
  13470.         var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  13471.         var r = rgba[0];
  13472.         var g = rgba[1];
  13473.         var b = rgba[2];
  13474.         var a = rgba[3];
  13475.         return fromRgba(rgbaColour(r, g, b, a));
  13476.       });
  13477.     };
  13478.  
  13479.     var global$8 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  13480.  
  13481.     var storageName = 'tinymce-custom-colors';
  13482.     function ColorCache (max) {
  13483.       if (max === void 0) {
  13484.         max = 10;
  13485.       }
  13486.       var storageString = global$8.getItem(storageName);
  13487.       var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  13488.       var prune = function (list) {
  13489.         var diff = max - list.length;
  13490.         return diff < 0 ? list.slice(0, max) : list;
  13491.       };
  13492.       var cache = prune(localstorage);
  13493.       var add = function (key) {
  13494.         indexOf(cache, key).each(remove);
  13495.         cache.unshift(key);
  13496.         if (cache.length > max) {
  13497.           cache.pop();
  13498.         }
  13499.         global$8.setItem(storageName, JSON.stringify(cache));
  13500.       };
  13501.       var remove = function (idx) {
  13502.         cache.splice(idx, 1);
  13503.       };
  13504.       var state = function () {
  13505.         return cache.slice(0);
  13506.       };
  13507.       return {
  13508.         add: add,
  13509.         state: state
  13510.       };
  13511.     }
  13512.  
  13513.     var choiceItem = 'choiceitem';
  13514.     var defaultColors = [
  13515.       {
  13516.         type: choiceItem,
  13517.         text: 'Light Green',
  13518.         value: '#BFEDD2'
  13519.       },
  13520.       {
  13521.         type: choiceItem,
  13522.         text: 'Light Yellow',
  13523.         value: '#FBEEB8'
  13524.       },
  13525.       {
  13526.         type: choiceItem,
  13527.         text: 'Light Red',
  13528.         value: '#F8CAC6'
  13529.       },
  13530.       {
  13531.         type: choiceItem,
  13532.         text: 'Light Purple',
  13533.         value: '#ECCAFA'
  13534.       },
  13535.       {
  13536.         type: choiceItem,
  13537.         text: 'Light Blue',
  13538.         value: '#C2E0F4'
  13539.       },
  13540.       {
  13541.         type: choiceItem,
  13542.         text: 'Green',
  13543.         value: '#2DC26B'
  13544.       },
  13545.       {
  13546.         type: choiceItem,
  13547.         text: 'Yellow',
  13548.         value: '#F1C40F'
  13549.       },
  13550.       {
  13551.         type: choiceItem,
  13552.         text: 'Red',
  13553.         value: '#E03E2D'
  13554.       },
  13555.       {
  13556.         type: choiceItem,
  13557.         text: 'Purple',
  13558.         value: '#B96AD9'
  13559.       },
  13560.       {
  13561.         type: choiceItem,
  13562.         text: 'Blue',
  13563.         value: '#3598DB'
  13564.       },
  13565.       {
  13566.         type: choiceItem,
  13567.         text: 'Dark Turquoise',
  13568.         value: '#169179'
  13569.       },
  13570.       {
  13571.         type: choiceItem,
  13572.         text: 'Orange',
  13573.         value: '#E67E23'
  13574.       },
  13575.       {
  13576.         type: choiceItem,
  13577.         text: 'Dark Red',
  13578.         value: '#BA372A'
  13579.       },
  13580.       {
  13581.         type: choiceItem,
  13582.         text: 'Dark Purple',
  13583.         value: '#843FA1'
  13584.       },
  13585.       {
  13586.         type: choiceItem,
  13587.         text: 'Dark Blue',
  13588.         value: '#236FA1'
  13589.       },
  13590.       {
  13591.         type: choiceItem,
  13592.         text: 'Light Gray',
  13593.         value: '#ECF0F1'
  13594.       },
  13595.       {
  13596.         type: choiceItem,
  13597.         text: 'Medium Gray',
  13598.         value: '#CED4D9'
  13599.       },
  13600.       {
  13601.         type: choiceItem,
  13602.         text: 'Gray',
  13603.         value: '#95A5A6'
  13604.       },
  13605.       {
  13606.         type: choiceItem,
  13607.         text: 'Dark Gray',
  13608.         value: '#7E8C8D'
  13609.       },
  13610.       {
  13611.         type: choiceItem,
  13612.         text: 'Navy Blue',
  13613.         value: '#34495E'
  13614.       },
  13615.       {
  13616.         type: choiceItem,
  13617.         text: 'Black',
  13618.         value: '#000000'
  13619.       },
  13620.       {
  13621.         type: choiceItem,
  13622.         text: 'White',
  13623.         value: '#ffffff'
  13624.       }
  13625.     ];
  13626.     var colorCache = ColorCache(10);
  13627.     var mapColors = function (colorMap) {
  13628.       var colors = [];
  13629.       for (var i = 0; i < colorMap.length; i += 2) {
  13630.         colors.push({
  13631.           text: colorMap[i + 1],
  13632.           value: '#' + anyToHex(colorMap[i]).value,
  13633.           type: 'choiceitem'
  13634.         });
  13635.       }
  13636.       return colors;
  13637.     };
  13638.     var getColorCols$2 = function (editor, defaultCols) {
  13639.       return editor.getParam('color_cols', defaultCols, 'number');
  13640.     };
  13641.     var hasCustomColors$1 = function (editor) {
  13642.       return editor.getParam('custom_colors') !== false;
  13643.     };
  13644.     var getColorMap = function (editor) {
  13645.       return editor.getParam('color_map');
  13646.     };
  13647.     var getColors$2 = function (editor) {
  13648.       var unmapped = getColorMap(editor);
  13649.       return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  13650.     };
  13651.     var getCurrentColors = function () {
  13652.       return map$2(colorCache.state(), function (color) {
  13653.         return {
  13654.           type: choiceItem,
  13655.           text: color,
  13656.           value: color
  13657.         };
  13658.       });
  13659.     };
  13660.     var addColor = function (color) {
  13661.       colorCache.add(color);
  13662.     };
  13663.  
  13664.     var fallbackColor = '#000000';
  13665.     var getCurrentColor = function (editor, format) {
  13666.       var color;
  13667.       editor.dom.getParents(editor.selection.getStart(), function (elm) {
  13668.         var value;
  13669.         if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  13670.           color = color ? color : value;
  13671.         }
  13672.       });
  13673.       return Optional.from(color);
  13674.     };
  13675.     var applyFormat = function (editor, format, value) {
  13676.       editor.undoManager.transact(function () {
  13677.         editor.focus();
  13678.         editor.formatter.apply(format, { value: value });
  13679.         editor.nodeChanged();
  13680.       });
  13681.     };
  13682.     var removeFormat = function (editor, format) {
  13683.       editor.undoManager.transact(function () {
  13684.         editor.focus();
  13685.         editor.formatter.remove(format, { value: null }, null, true);
  13686.         editor.nodeChanged();
  13687.       });
  13688.     };
  13689.     var registerCommands = function (editor) {
  13690.       editor.addCommand('mceApplyTextcolor', function (format, value) {
  13691.         applyFormat(editor, format, value);
  13692.       });
  13693.       editor.addCommand('mceRemoveTextcolor', function (format) {
  13694.         removeFormat(editor, format);
  13695.       });
  13696.     };
  13697.     var calcCols = function (colors) {
  13698.       return Math.max(5, Math.ceil(Math.sqrt(colors)));
  13699.     };
  13700.     var getColorCols$1 = function (editor) {
  13701.       var colors = getColors$2(editor);
  13702.       var defaultCols = calcCols(colors.length);
  13703.       return getColorCols$2(editor, defaultCols);
  13704.     };
  13705.     var getAdditionalColors = function (hasCustom) {
  13706.       var type = 'choiceitem';
  13707.       var remove = {
  13708.         type: type,
  13709.         text: 'Remove color',
  13710.         icon: 'color-swatch-remove-color',
  13711.         value: 'remove'
  13712.       };
  13713.       var custom = {
  13714.         type: type,
  13715.         text: 'Custom color',
  13716.         icon: 'color-picker',
  13717.         value: 'custom'
  13718.       };
  13719.       return hasCustom ? [
  13720.         remove,
  13721.         custom
  13722.       ] : [remove];
  13723.     };
  13724.     var applyColor = function (editor, format, value, onChoice) {
  13725.       if (value === 'custom') {
  13726.         var dialog = colorPickerDialog(editor);
  13727.         dialog(function (colorOpt) {
  13728.           colorOpt.each(function (color) {
  13729.             addColor(color);
  13730.             editor.execCommand('mceApplyTextcolor', format, color);
  13731.             onChoice(color);
  13732.           });
  13733.         }, fallbackColor);
  13734.       } else if (value === 'remove') {
  13735.         onChoice('');
  13736.         editor.execCommand('mceRemoveTextcolor', format);
  13737.       } else {
  13738.         onChoice(value);
  13739.         editor.execCommand('mceApplyTextcolor', format, value);
  13740.       }
  13741.     };
  13742.     var getColors$1 = function (colors, hasCustom) {
  13743.       return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  13744.     };
  13745.     var getFetch$1 = function (colors, hasCustom) {
  13746.       return function (callback) {
  13747.         callback(getColors$1(colors, hasCustom));
  13748.       };
  13749.     };
  13750.     var setIconColor = function (splitButtonApi, name, newColor) {
  13751.       var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  13752.       splitButtonApi.setIconFill(id, newColor);
  13753.     };
  13754.     var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  13755.       editor.ui.registry.addSplitButton(name, {
  13756.         tooltip: tooltip,
  13757.         presets: 'color',
  13758.         icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  13759.         select: function (value) {
  13760.           var optCurrentRgb = getCurrentColor(editor, format);
  13761.           return optCurrentRgb.bind(function (currentRgb) {
  13762.             return fromString(currentRgb).map(function (rgba) {
  13763.               var currentHex = fromRgba(rgba).value;
  13764.               return contains$1(value.toLowerCase(), currentHex);
  13765.             });
  13766.           }).getOr(false);
  13767.         },
  13768.         columns: getColorCols$1(editor),
  13769.         fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
  13770.         onAction: function (_splitButtonApi) {
  13771.           applyColor(editor, format, lastColor.get(), noop);
  13772.         },
  13773.         onItemAction: function (_splitButtonApi, value) {
  13774.           applyColor(editor, format, value, function (newColor) {
  13775.             lastColor.set(newColor);
  13776.             fireTextColorChange(editor, {
  13777.               name: name,
  13778.               color: newColor
  13779.             });
  13780.           });
  13781.         },
  13782.         onSetup: function (splitButtonApi) {
  13783.           setIconColor(splitButtonApi, name, lastColor.get());
  13784.           var handler = function (e) {
  13785.             if (e.name === name) {
  13786.               setIconColor(splitButtonApi, e.name, e.color);
  13787.             }
  13788.           };
  13789.           editor.on('TextColorChange', handler);
  13790.           return function () {
  13791.             editor.off('TextColorChange', handler);
  13792.           };
  13793.         }
  13794.       });
  13795.     };
  13796.     var registerTextColorMenuItem = function (editor, name, format, text) {
  13797.       editor.ui.registry.addNestedMenuItem(name, {
  13798.         text: text,
  13799.         icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  13800.         getSubmenuItems: function () {
  13801.           return [{
  13802.               type: 'fancymenuitem',
  13803.               fancytype: 'colorswatch',
  13804.               onAction: function (data) {
  13805.                 applyColor(editor, format, data.value, noop);
  13806.               }
  13807.             }];
  13808.         }
  13809.       });
  13810.     };
  13811.     var colorPickerDialog = function (editor) {
  13812.       return function (callback, value) {
  13813.         var isValid = false;
  13814.         var onSubmit = function (api) {
  13815.           var data = api.getData();
  13816.           var hex = data.colorpicker;
  13817.           if (isValid) {
  13818.             callback(Optional.from(hex));
  13819.             api.close();
  13820.           } else {
  13821.             editor.windowManager.alert(editor.translate([
  13822.               'Invalid hex color code: {0}',
  13823.               hex
  13824.             ]));
  13825.           }
  13826.         };
  13827.         var onAction = function (_api, details) {
  13828.           if (details.name === 'hex-valid') {
  13829.             isValid = details.value;
  13830.           }
  13831.         };
  13832.         var initialData = { colorpicker: value };
  13833.         editor.windowManager.open({
  13834.           title: 'Color Picker',
  13835.           size: 'normal',
  13836.           body: {
  13837.             type: 'panel',
  13838.             items: [{
  13839.                 type: 'colorpicker',
  13840.                 name: 'colorpicker',
  13841.                 label: 'Color'
  13842.               }]
  13843.           },
  13844.           buttons: [
  13845.             {
  13846.               type: 'cancel',
  13847.               name: 'cancel',
  13848.               text: 'Cancel'
  13849.             },
  13850.             {
  13851.               type: 'submit',
  13852.               name: 'save',
  13853.               text: 'Save',
  13854.               primary: true
  13855.             }
  13856.           ],
  13857.           initialData: initialData,
  13858.           onAction: onAction,
  13859.           onSubmit: onSubmit,
  13860.           onClose: noop,
  13861.           onCancel: function () {
  13862.             callback(Optional.none());
  13863.           }
  13864.         });
  13865.       };
  13866.     };
  13867.     var register$a = function (editor) {
  13868.       registerCommands(editor);
  13869.       var lastForeColor = Cell(fallbackColor);
  13870.       var lastBackColor = Cell(fallbackColor);
  13871.       registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  13872.       registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  13873.       registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  13874.       registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  13875.     };
  13876.  
  13877.     var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  13878.       var hasIcons = menuHasIcons(items);
  13879.       var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  13880.       var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  13881.       return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  13882.     };
  13883.     var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  13884.       return cat(map$2(items, function (item) {
  13885.         if (item.type === 'choiceitem') {
  13886.           return createChoiceMenuItem(item).fold(handleError, function (d) {
  13887.             return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items)));
  13888.           });
  13889.         } else {
  13890.           return Optional.none();
  13891.         }
  13892.       }));
  13893.     };
  13894.  
  13895.     var deriveMenuMovement = function (columns, presets) {
  13896.       var menuMarkers = markers(presets);
  13897.       if (columns === 1) {
  13898.         return {
  13899.           mode: 'menu',
  13900.           moveOnTab: true
  13901.         };
  13902.       } else if (columns === 'auto') {
  13903.         return {
  13904.           mode: 'grid',
  13905.           selector: '.' + menuMarkers.item,
  13906.           initSize: {
  13907.             numColumns: 1,
  13908.             numRows: 1
  13909.           }
  13910.         };
  13911.       } else {
  13912.         var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  13913.         return {
  13914.           mode: 'matrix',
  13915.           rowSelector: '.' + rowClass
  13916.         };
  13917.       }
  13918.     };
  13919.     var deriveCollectionMovement = function (columns, presets) {
  13920.       if (columns === 1) {
  13921.         return {
  13922.           mode: 'menu',
  13923.           moveOnTab: false,
  13924.           selector: '.tox-collection__item'
  13925.         };
  13926.       } else if (columns === 'auto') {
  13927.         return {
  13928.           mode: 'flatgrid',
  13929.           selector: '.' + 'tox-collection__item',
  13930.           initSize: {
  13931.             numColumns: 1,
  13932.             numRows: 1
  13933.           }
  13934.         };
  13935.       } else {
  13936.         return {
  13937.           mode: 'matrix',
  13938.           selectors: {
  13939.             row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  13940.             cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  13941.           }
  13942.         };
  13943.       }
  13944.     };
  13945.  
  13946.     var renderColorSwatchItem = function (spec, backstage) {
  13947.       var items = getColorItems(spec, backstage);
  13948.       var columns = backstage.colorinput.getColorCols();
  13949.       var presets = 'color';
  13950.       var menuSpec = createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  13951.         spec.onAction({ value: value });
  13952.       }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
  13953.       var widgetSpec = __assign(__assign({}, menuSpec), {
  13954.         markers: markers(presets),
  13955.         movement: deriveMenuMovement(columns, presets)
  13956.       });
  13957.       return {
  13958.         type: 'widget',
  13959.         data: { value: generate$6('widget-id') },
  13960.         dom: {
  13961.           tag: 'div',
  13962.           classes: ['tox-fancymenuitem']
  13963.         },
  13964.         autofocus: true,
  13965.         components: [parts$f.widget(Menu.sketch(widgetSpec))]
  13966.       };
  13967.     };
  13968.     var getColorItems = function (spec, backstage) {
  13969.       var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
  13970.       return spec.initData.colors.fold(function () {
  13971.         return getColors$1(backstage.colorinput.getColors(), useCustomColors);
  13972.       }, function (colors) {
  13973.         return colors.concat(getAdditionalColors(useCustomColors));
  13974.       });
  13975.     };
  13976.  
  13977.     var cellOverEvent = generate$6('cell-over');
  13978.     var cellExecuteEvent = generate$6('cell-execute');
  13979.     var makeCell = function (row, col, labelId) {
  13980.       var _a;
  13981.       var emitCellOver = function (c) {
  13982.         return emitWith(c, cellOverEvent, {
  13983.           row: row,
  13984.           col: col
  13985.         });
  13986.       };
  13987.       var emitExecute = function (c) {
  13988.         return emitWith(c, cellExecuteEvent, {
  13989.           row: row,
  13990.           col: col
  13991.         });
  13992.       };
  13993.       var onClick = function (c, se) {
  13994.         se.stop();
  13995.         emitExecute(c);
  13996.       };
  13997.       return build$1({
  13998.         dom: {
  13999.           tag: 'div',
  14000.           attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  14001.         },
  14002.         behaviours: derive$1([
  14003.           config('insert-table-picker-cell', [
  14004.             run$1(mouseover(), Focusing.focus),
  14005.             run$1(execute$5(), emitExecute),
  14006.             run$1(click(), onClick),
  14007.             run$1(tap(), onClick)
  14008.           ]),
  14009.           Toggling.config({
  14010.             toggleClass: 'tox-insert-table-picker__selected',
  14011.             toggleOnExecute: false
  14012.           }),
  14013.           Focusing.config({ onFocus: emitCellOver })
  14014.         ])
  14015.       });
  14016.     };
  14017.     var makeCells = function (labelId, numRows, numCols) {
  14018.       var cells = [];
  14019.       for (var i = 0; i < numRows; i++) {
  14020.         var row = [];
  14021.         for (var j = 0; j < numCols; j++) {
  14022.           row.push(makeCell(i, j, labelId));
  14023.         }
  14024.         cells.push(row);
  14025.       }
  14026.       return cells;
  14027.     };
  14028.     var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  14029.       for (var i = 0; i < numRows; i++) {
  14030.         for (var j = 0; j < numColumns; j++) {
  14031.           Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  14032.         }
  14033.       }
  14034.     };
  14035.     var makeComponents = function (cells) {
  14036.       return bind$3(cells, function (cellRow) {
  14037.         return map$2(cellRow, premade);
  14038.       });
  14039.     };
  14040.     var makeLabelText = function (row, col) {
  14041.       return text$1(col + 'x' + row);
  14042.     };
  14043.     var renderInsertTableMenuItem = function (spec) {
  14044.       var numRows = 10;
  14045.       var numColumns = 10;
  14046.       var sizeLabelId = generate$6('size-label');
  14047.       var cells = makeCells(sizeLabelId, numRows, numColumns);
  14048.       var emptyLabelText = makeLabelText(0, 0);
  14049.       var memLabel = record({
  14050.         dom: {
  14051.           tag: 'span',
  14052.           classes: ['tox-insert-table-picker__label'],
  14053.           attributes: { id: sizeLabelId }
  14054.         },
  14055.         components: [emptyLabelText],
  14056.         behaviours: derive$1([Replacing.config({})])
  14057.       });
  14058.       return {
  14059.         type: 'widget',
  14060.         data: { value: generate$6('widget-id') },
  14061.         dom: {
  14062.           tag: 'div',
  14063.           classes: ['tox-fancymenuitem']
  14064.         },
  14065.         autofocus: true,
  14066.         components: [parts$f.widget({
  14067.             dom: {
  14068.               tag: 'div',
  14069.               classes: ['tox-insert-table-picker']
  14070.             },
  14071.             components: makeComponents(cells).concat(memLabel.asSpec()),
  14072.             behaviours: derive$1([
  14073.               config('insert-table-picker', [
  14074.                 runOnAttached(function (c) {
  14075.                   Replacing.set(memLabel.get(c), [emptyLabelText]);
  14076.                 }),
  14077.                 runWithTarget(cellOverEvent, function (c, t, e) {
  14078.                   var _a = e.event, row = _a.row, col = _a.col;
  14079.                   selectCells(cells, row, col, numRows, numColumns);
  14080.                   Replacing.set(memLabel.get(c), [makeLabelText(row + 1, col + 1)]);
  14081.                 }),
  14082.                 runWithTarget(cellExecuteEvent, function (c, _, e) {
  14083.                   var _a = e.event, row = _a.row, col = _a.col;
  14084.                   spec.onAction({
  14085.                     numRows: row + 1,
  14086.                     numColumns: col + 1
  14087.                   });
  14088.                   emit(c, sandboxClose());
  14089.                 })
  14090.               ]),
  14091.               Keying.config({
  14092.                 initSize: {
  14093.                   numRows: numRows,
  14094.                   numColumns: numColumns
  14095.                 },
  14096.                 mode: 'flatgrid',
  14097.                 selector: '[role="button"]'
  14098.               })
  14099.             ])
  14100.           })]
  14101.       };
  14102.     };
  14103.  
  14104.     var fancyMenuItems = {
  14105.       inserttable: renderInsertTableMenuItem,
  14106.       colorswatch: renderColorSwatchItem
  14107.     };
  14108.     var renderFancyMenuItem = function (spec, backstage) {
  14109.       return get$e(fancyMenuItems, spec.fancytype).map(function (render) {
  14110.         return render(spec, backstage);
  14111.       });
  14112.     };
  14113.  
  14114.     var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  14115.       if (renderIcons === void 0) {
  14116.         renderIcons = true;
  14117.       }
  14118.       if (downwardsCaret === void 0) {
  14119.         downwardsCaret = false;
  14120.       }
  14121.       var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  14122.       var getApi = function (component) {
  14123.         return {
  14124.           isDisabled: function () {
  14125.             return Disabling.isDisabled(component);
  14126.           },
  14127.           setDisabled: function (state) {
  14128.             return Disabling.set(component, state);
  14129.           }
  14130.         };
  14131.       };
  14132.       var structure = renderItemStructure({
  14133.         presets: 'normal',
  14134.         iconContent: spec.icon,
  14135.         textContent: spec.text,
  14136.         htmlContent: Optional.none(),
  14137.         ariaLabel: spec.text,
  14138.         caret: Optional.some(caret),
  14139.         checkMark: Optional.none(),
  14140.         shortcutContent: spec.shortcut
  14141.       }, providersBackstage, renderIcons);
  14142.       return renderCommonItem({
  14143.         data: buildData(spec),
  14144.         getApi: getApi,
  14145.         disabled: spec.disabled,
  14146.         onAction: noop,
  14147.         onSetup: spec.onSetup,
  14148.         triggersSubmenu: true,
  14149.         itemBehaviours: []
  14150.       }, structure, itemResponse, providersBackstage);
  14151.     };
  14152.  
  14153.     var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  14154.       if (renderIcons === void 0) {
  14155.         renderIcons = true;
  14156.       }
  14157.       var getApi = function (component) {
  14158.         return {
  14159.           isDisabled: function () {
  14160.             return Disabling.isDisabled(component);
  14161.           },
  14162.           setDisabled: function (state) {
  14163.             return Disabling.set(component, state);
  14164.           }
  14165.         };
  14166.       };
  14167.       var structure = renderItemStructure({
  14168.         presets: 'normal',
  14169.         iconContent: spec.icon,
  14170.         textContent: spec.text,
  14171.         htmlContent: Optional.none(),
  14172.         ariaLabel: spec.text,
  14173.         caret: Optional.none(),
  14174.         checkMark: Optional.none(),
  14175.         shortcutContent: spec.shortcut
  14176.       }, providersBackstage, renderIcons);
  14177.       return renderCommonItem({
  14178.         data: buildData(spec),
  14179.         getApi: getApi,
  14180.         disabled: spec.disabled,
  14181.         onAction: spec.onAction,
  14182.         onSetup: spec.onSetup,
  14183.         triggersSubmenu: false,
  14184.         itemBehaviours: []
  14185.       }, structure, itemResponse, providersBackstage);
  14186.     };
  14187.  
  14188.     var renderSeparatorItem = function (spec) {
  14189.       var innerHtml = spec.text.fold(function () {
  14190.         return {};
  14191.       }, function (text) {
  14192.         return { innerHtml: text };
  14193.       });
  14194.       return {
  14195.         type: 'separator',
  14196.         dom: __assign({
  14197.           tag: 'div',
  14198.           classes: [
  14199.             selectableClass,
  14200.             groupHeadingClass
  14201.           ]
  14202.         }, innerHtml),
  14203.         components: []
  14204.       };
  14205.     };
  14206.  
  14207.     var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  14208.       if (renderIcons === void 0) {
  14209.         renderIcons = true;
  14210.       }
  14211.       var getApi = function (component) {
  14212.         return {
  14213.           setActive: function (state) {
  14214.             Toggling.set(component, state);
  14215.           },
  14216.           isActive: function () {
  14217.             return Toggling.isOn(component);
  14218.           },
  14219.           isDisabled: function () {
  14220.             return Disabling.isDisabled(component);
  14221.           },
  14222.           setDisabled: function (state) {
  14223.             return Disabling.set(component, state);
  14224.           }
  14225.         };
  14226.       };
  14227.       var structure = renderItemStructure({
  14228.         iconContent: spec.icon,
  14229.         textContent: spec.text,
  14230.         htmlContent: Optional.none(),
  14231.         ariaLabel: spec.text,
  14232.         checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
  14233.         caret: Optional.none(),
  14234.         shortcutContent: spec.shortcut,
  14235.         presets: 'normal',
  14236.         meta: spec.meta
  14237.       }, providersBackstage, renderIcons);
  14238.       return deepMerge(renderCommonItem({
  14239.         data: buildData(spec),
  14240.         disabled: spec.disabled,
  14241.         getApi: getApi,
  14242.         onAction: spec.onAction,
  14243.         onSetup: spec.onSetup,
  14244.         triggersSubmenu: false,
  14245.         itemBehaviours: []
  14246.       }, structure, itemResponse, providersBackstage), {
  14247.         toggling: {
  14248.           toggleClass: tickedClass,
  14249.           toggleOnExecute: false,
  14250.           selected: spec.active
  14251.         }
  14252.       });
  14253.     };
  14254.  
  14255.     var autocomplete = renderAutocompleteItem;
  14256.     var separator$3 = renderSeparatorItem;
  14257.     var normal = renderNormalItem;
  14258.     var nested = renderNestedItem;
  14259.     var toggle$1 = renderToggleMenuItem;
  14260.     var fancy = renderFancyMenuItem;
  14261.     var card = renderCardMenuItem;
  14262.  
  14263.     var FocusMode;
  14264.     (function (FocusMode) {
  14265.       FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  14266.       FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  14267.     }(FocusMode || (FocusMode = {})));
  14268.     var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  14269.       var providersBackstage = backstage.shared.providers;
  14270.       var parseForHorizontalMenu = function (menuitem) {
  14271.         return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  14272.           shortcut: Optional.none(),
  14273.           icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
  14274.         });
  14275.       };
  14276.       switch (item.type) {
  14277.       case 'menuitem':
  14278.         return createMenuItem(item).fold(handleError, function (d) {
  14279.           return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  14280.         });
  14281.       case 'nestedmenuitem':
  14282.         return createNestedMenuItem(item).fold(handleError, function (d) {
  14283.           return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  14284.         });
  14285.       case 'togglemenuitem':
  14286.         return createToggleMenuItem(item).fold(handleError, function (d) {
  14287.           return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  14288.         });
  14289.       case 'separator':
  14290.         return createSeparatorMenuItem(item).fold(handleError, function (d) {
  14291.           return Optional.some(separator$3(d));
  14292.         });
  14293.       case 'fancymenuitem':
  14294.         return createFancyMenuItem(item).fold(handleError, function (d) {
  14295.           return fancy(parseForHorizontalMenu(d), backstage);
  14296.         });
  14297.       default: {
  14298.           console.error('Unknown item in general menu', item);
  14299.           return Optional.none();
  14300.         }
  14301.       }
  14302.     };
  14303.     var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) {
  14304.       var renderText = columns === 1;
  14305.       var renderIcons = !renderText || menuHasIcons(items);
  14306.       return cat(map$2(items, function (item) {
  14307.         switch (item.type) {
  14308.         case 'separator':
  14309.           return createSeparatorItem(item).fold(handleError, function (d) {
  14310.             return Optional.some(separator$3(d));
  14311.           });
  14312.         case 'cardmenuitem':
  14313.           return createCardMenuItem(item).fold(handleError, function (d) {
  14314.             return Optional.some(card(__assign(__assign({}, d), {
  14315.               onAction: function (api) {
  14316.                 d.onAction(api);
  14317.                 onItemValueHandler(d.value, d.meta);
  14318.               }
  14319.             }), itemResponse, sharedBackstage, {
  14320.               itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage),
  14321.               cardText: {
  14322.                 matchText: matchText,
  14323.                 highlightOn: highlightOn
  14324.               }
  14325.             }));
  14326.           });
  14327.         case 'autocompleteitem':
  14328.         default:
  14329.           return createAutocompleterItem(item).fold(handleError, function (d) {
  14330.             return Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  14331.           });
  14332.         }
  14333.       }));
  14334.     };
  14335.     var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  14336.       var hasIcons = menuHasIcons(items);
  14337.       var alloyItems = cat(map$2(items, function (item) {
  14338.         var itemHasIcon = function (i) {
  14339.           return isHorizontalMenu ? !has$2(i, 'text') : hasIcons;
  14340.         };
  14341.         var createItem = function (i) {
  14342.           return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  14343.         };
  14344.         if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  14345.           return createItem(__assign(__assign({}, item), { disabled: true }));
  14346.         } else {
  14347.           return createItem(item);
  14348.         }
  14349.       }));
  14350.       var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  14351.       return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  14352.     };
  14353.     var createTieredDataFrom = function (partialMenu) {
  14354.       return tieredMenu.singleData(partialMenu.value, partialMenu);
  14355.     };
  14356.     var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  14357.       var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
  14358.       var movement = deriveMenuMovement(columns, presets);
  14359.       var menuMarkers = markers(presets);
  14360.       return {
  14361.         dom: partialMenu.dom,
  14362.         components: partialMenu.components,
  14363.         items: partialMenu.items,
  14364.         value: partialMenu.value,
  14365.         markers: {
  14366.           selectedItem: menuMarkers.selectedItem,
  14367.           item: menuMarkers.item
  14368.         },
  14369.         movement: movement,
  14370.         fakeFocus: focusMode === FocusMode.ContentFocus,
  14371.         focusManager: focusManager,
  14372.         menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  14373.             detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  14374.               var numColumns = _a.numColumns, numRows = _a.numRows;
  14375.               Keying.setGridSize(comp, numRows, numColumns);
  14376.             });
  14377.           })])
  14378.       };
  14379.     };
  14380.  
  14381.     var register$9 = function (editor, sharedBackstage) {
  14382.       var activeAutocompleter = value$1();
  14383.       var processingAction = Cell(false);
  14384.       var autocompleter = build$1(InlineView.sketch({
  14385.         dom: {
  14386.           tag: 'div',
  14387.           classes: ['tox-autocompleter']
  14388.         },
  14389.         components: [],
  14390.         fireDismissalEventInstead: {},
  14391.         inlineBehaviours: derive$1([config('dismissAutocompleter', [run$1(dismissRequested(), function () {
  14392.               return cancelIfNecessary();
  14393.             })])]),
  14394.         lazySink: sharedBackstage.getSink
  14395.       }));
  14396.       var isMenuOpen = function () {
  14397.         return InlineView.isOpen(autocompleter);
  14398.       };
  14399.       var isActive = function () {
  14400.         return activeAutocompleter.get().isSome();
  14401.       };
  14402.       var hideIfNecessary = function () {
  14403.         if (isActive()) {
  14404.           InlineView.hide(autocompleter);
  14405.         }
  14406.       };
  14407.       var cancelIfNecessary = function () {
  14408.         if (isActive()) {
  14409.           var lastElement = activeAutocompleter.get().map(function (ac) {
  14410.             return ac.element;
  14411.           });
  14412.           detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
  14413.           hideIfNecessary();
  14414.           activeAutocompleter.clear();
  14415.           processingAction.set(false);
  14416.         }
  14417.       };
  14418.       var getAutocompleters = cached(function () {
  14419.         return register$b(editor);
  14420.       });
  14421.       var getCombinedItems = function (triggerChar, matches) {
  14422.         var columns = findMap(matches, function (m) {
  14423.           return Optional.from(m.columns);
  14424.         }).getOr(1);
  14425.         return bind$3(matches, function (match) {
  14426.           var choices = match.items;
  14427.           return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  14428.             var nr = editor.selection.getRng();
  14429.             getContext(editor.dom, nr, triggerChar).fold(function () {
  14430.               return console.error('Lost context. Cursor probably moved');
  14431.             }, function (_a) {
  14432.               var range = _a.range;
  14433.               var autocompleterApi = {
  14434.                 hide: function () {
  14435.                   cancelIfNecessary();
  14436.                 },
  14437.                 reload: function (fetchOptions) {
  14438.                   hideIfNecessary();
  14439.                   load(fetchOptions);
  14440.                 }
  14441.               };
  14442.               processingAction.set(true);
  14443.               match.onAction(autocompleterApi, range, itemValue, itemMeta);
  14444.               processingAction.set(false);
  14445.             });
  14446.           }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn);
  14447.         });
  14448.       };
  14449.       var commenceIfNecessary = function (context) {
  14450.         if (!isActive()) {
  14451.           var wrapper = create$4(editor, context.range);
  14452.           activeAutocompleter.set({
  14453.             triggerChar: context.triggerChar,
  14454.             element: wrapper,
  14455.             matchLength: context.text.length
  14456.           });
  14457.           processingAction.set(false);
  14458.         }
  14459.       };
  14460.       var display = function (ac, context, lookupData, items) {
  14461.         ac.matchLength = context.text.length;
  14462.         var columns = findMap(lookupData, function (ld) {
  14463.           return Optional.from(ld.columns);
  14464.         }).getOr(1);
  14465.         InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')), {
  14466.           anchor: {
  14467.             type: 'node',
  14468.             root: SugarElement.fromDom(editor.getBody()),
  14469.             node: Optional.from(ac.element)
  14470.           }
  14471.         });
  14472.         InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  14473.       };
  14474.       var doLookup = function (fetchOptions) {
  14475.         return activeAutocompleter.get().map(function (ac) {
  14476.           return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  14477.             return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  14478.           });
  14479.         }).getOrThunk(function () {
  14480.           return lookup$2(editor, getAutocompleters);
  14481.         });
  14482.       };
  14483.       var load = function (fetchOptions) {
  14484.         doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  14485.           commenceIfNecessary(lookupInfo.context);
  14486.           lookupInfo.lookupData.then(function (lookupData) {
  14487.             activeAutocompleter.get().map(function (ac) {
  14488.               var context = lookupInfo.context;
  14489.               if (ac.triggerChar === context.triggerChar) {
  14490.                 var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  14491.                 if (combinedItems.length > 0) {
  14492.                   display(ac, context, lookupData, combinedItems);
  14493.                 } else if (context.text.length - ac.matchLength >= 10) {
  14494.                   cancelIfNecessary();
  14495.                 } else {
  14496.                   hideIfNecessary();
  14497.                 }
  14498.               }
  14499.             });
  14500.           });
  14501.         });
  14502.       };
  14503.       var onKeypress = last(function (e) {
  14504.         if (e.which === 27) {
  14505.           return;
  14506.         }
  14507.         load();
  14508.       }, 50);
  14509.       var autocompleterUiApi = {
  14510.         onKeypress: onKeypress,
  14511.         cancelIfNecessary: cancelIfNecessary,
  14512.         isMenuOpen: isMenuOpen,
  14513.         isActive: isActive,
  14514.         isProcessingAction: processingAction.get,
  14515.         getView: function () {
  14516.           return InlineView.getContent(autocompleter);
  14517.         }
  14518.       };
  14519.       if (editor.hasPlugin('rtc') === false) {
  14520.         AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  14521.       }
  14522.     };
  14523.     var Autocompleter = { register: register$9 };
  14524.  
  14525.     var closest = function (scope, selector, isRoot) {
  14526.       return closest$1(scope, selector, isRoot).isSome();
  14527.     };
  14528.  
  14529.     var DelayedFunction = function (fun, delay) {
  14530.       var ref = null;
  14531.       var schedule = function () {
  14532.         var args = [];
  14533.         for (var _i = 0; _i < arguments.length; _i++) {
  14534.           args[_i] = arguments[_i];
  14535.         }
  14536.         ref = setTimeout(function () {
  14537.           fun.apply(null, args);
  14538.           ref = null;
  14539.         }, delay);
  14540.       };
  14541.       var cancel = function () {
  14542.         if (ref !== null) {
  14543.           clearTimeout(ref);
  14544.           ref = null;
  14545.         }
  14546.       };
  14547.       return {
  14548.         cancel: cancel,
  14549.         schedule: schedule
  14550.       };
  14551.     };
  14552.  
  14553.     var SIGNIFICANT_MOVE = 5;
  14554.     var LONGPRESS_DELAY = 400;
  14555.     var getTouch = function (event) {
  14556.       var raw = event.raw;
  14557.       if (raw.touches === undefined || raw.touches.length !== 1) {
  14558.         return Optional.none();
  14559.       }
  14560.       return Optional.some(raw.touches[0]);
  14561.     };
  14562.     var isFarEnough = function (touch, data) {
  14563.       var distX = Math.abs(touch.clientX - data.x);
  14564.       var distY = Math.abs(touch.clientY - data.y);
  14565.       return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  14566.     };
  14567.     var monitor = function (settings) {
  14568.       var startData = value$1();
  14569.       var longpressFired = Cell(false);
  14570.       var longpress$1 = DelayedFunction(function (event) {
  14571.         settings.triggerEvent(longpress(), event);
  14572.         longpressFired.set(true);
  14573.       }, LONGPRESS_DELAY);
  14574.       var handleTouchstart = function (event) {
  14575.         getTouch(event).each(function (touch) {
  14576.           longpress$1.cancel();
  14577.           var data = {
  14578.             x: touch.clientX,
  14579.             y: touch.clientY,
  14580.             target: event.target
  14581.           };
  14582.           longpress$1.schedule(event);
  14583.           longpressFired.set(false);
  14584.           startData.set(data);
  14585.         });
  14586.         return Optional.none();
  14587.       };
  14588.       var handleTouchmove = function (event) {
  14589.         longpress$1.cancel();
  14590.         getTouch(event).each(function (touch) {
  14591.           startData.on(function (data) {
  14592.             if (isFarEnough(touch, data)) {
  14593.               startData.clear();
  14594.             }
  14595.           });
  14596.         });
  14597.         return Optional.none();
  14598.       };
  14599.       var handleTouchend = function (event) {
  14600.         longpress$1.cancel();
  14601.         var isSame = function (data) {
  14602.           return eq(data.target, event.target);
  14603.         };
  14604.         return startData.get().filter(isSame).map(function (_data) {
  14605.           if (longpressFired.get()) {
  14606.             event.prevent();
  14607.             return false;
  14608.           } else {
  14609.             return settings.triggerEvent(tap(), event);
  14610.           }
  14611.         });
  14612.       };
  14613.       var handlers = wrapAll([
  14614.         {
  14615.           key: touchstart(),
  14616.           value: handleTouchstart
  14617.         },
  14618.         {
  14619.           key: touchmove(),
  14620.           value: handleTouchmove
  14621.         },
  14622.         {
  14623.           key: touchend(),
  14624.           value: handleTouchend
  14625.         }
  14626.       ]);
  14627.       var fireIfReady = function (event, type) {
  14628.         return get$e(handlers, type).bind(function (handler) {
  14629.           return handler(event);
  14630.         });
  14631.       };
  14632.       return { fireIfReady: fireIfReady };
  14633.     };
  14634.  
  14635.     var isDangerous = function (event) {
  14636.       var keyEv = event.raw;
  14637.       return keyEv.which === BACKSPACE[0] && !contains$2([
  14638.         'input',
  14639.         'textarea'
  14640.       ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]');
  14641.     };
  14642.     var isFirefox = function () {
  14643.       return detect$1().browser.isFirefox();
  14644.     };
  14645.     var bindFocus = function (container, handler) {
  14646.       if (isFirefox()) {
  14647.         return capture(container, 'focus', handler);
  14648.       } else {
  14649.         return bind(container, 'focusin', handler);
  14650.       }
  14651.     };
  14652.     var bindBlur = function (container, handler) {
  14653.       if (isFirefox()) {
  14654.         return capture(container, 'blur', handler);
  14655.       } else {
  14656.         return bind(container, 'focusout', handler);
  14657.       }
  14658.     };
  14659.     var setup$d = function (container, rawSettings) {
  14660.       var settings = __assign({ stopBackspace: true }, rawSettings);
  14661.       var pointerEvents = [
  14662.         'touchstart',
  14663.         'touchmove',
  14664.         'touchend',
  14665.         'touchcancel',
  14666.         'gesturestart',
  14667.         'mousedown',
  14668.         'mouseup',
  14669.         'mouseover',
  14670.         'mousemove',
  14671.         'mouseout',
  14672.         'click'
  14673.       ];
  14674.       var tapEvent = monitor(settings);
  14675.       var simpleEvents = map$2(pointerEvents.concat([
  14676.         'selectstart',
  14677.         'input',
  14678.         'contextmenu',
  14679.         'change',
  14680.         'transitionend',
  14681.         'transitioncancel',
  14682.         'drag',
  14683.         'dragstart',
  14684.         'dragend',
  14685.         'dragenter',
  14686.         'dragleave',
  14687.         'dragover',
  14688.         'drop',
  14689.         'keyup'
  14690.       ]), function (type) {
  14691.         return bind(container, type, function (event) {
  14692.           tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  14693.             if (tapStopped) {
  14694.               event.kill();
  14695.             }
  14696.           });
  14697.           var stopped = settings.triggerEvent(type, event);
  14698.           if (stopped) {
  14699.             event.kill();
  14700.           }
  14701.         });
  14702.       });
  14703.       var pasteTimeout = value$1();
  14704.       var onPaste = bind(container, 'paste', function (event) {
  14705.         tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  14706.           if (tapStopped) {
  14707.             event.kill();
  14708.           }
  14709.         });
  14710.         var stopped = settings.triggerEvent('paste', event);
  14711.         if (stopped) {
  14712.           event.kill();
  14713.         }
  14714.         pasteTimeout.set(setTimeout(function () {
  14715.           settings.triggerEvent(postPaste(), event);
  14716.         }, 0));
  14717.       });
  14718.       var onKeydown = bind(container, 'keydown', function (event) {
  14719.         var stopped = settings.triggerEvent('keydown', event);
  14720.         if (stopped) {
  14721.           event.kill();
  14722.         } else if (settings.stopBackspace && isDangerous(event)) {
  14723.           event.prevent();
  14724.         }
  14725.       });
  14726.       var onFocusIn = bindFocus(container, function (event) {
  14727.         var stopped = settings.triggerEvent('focusin', event);
  14728.         if (stopped) {
  14729.           event.kill();
  14730.         }
  14731.       });
  14732.       var focusoutTimeout = value$1();
  14733.       var onFocusOut = bindBlur(container, function (event) {
  14734.         var stopped = settings.triggerEvent('focusout', event);
  14735.         if (stopped) {
  14736.           event.kill();
  14737.         }
  14738.         focusoutTimeout.set(setTimeout(function () {
  14739.           settings.triggerEvent(postBlur(), event);
  14740.         }, 0));
  14741.       });
  14742.       var unbind = function () {
  14743.         each$1(simpleEvents, function (e) {
  14744.           e.unbind();
  14745.         });
  14746.         onKeydown.unbind();
  14747.         onFocusIn.unbind();
  14748.         onFocusOut.unbind();
  14749.         onPaste.unbind();
  14750.         pasteTimeout.on(clearTimeout);
  14751.         focusoutTimeout.on(clearTimeout);
  14752.       };
  14753.       return { unbind: unbind };
  14754.     };
  14755.  
  14756.     var derive = function (rawEvent, rawTarget) {
  14757.       var source = get$e(rawEvent, 'target').getOr(rawTarget);
  14758.       return Cell(source);
  14759.     };
  14760.  
  14761.     var fromSource = function (event, source) {
  14762.       var stopper = Cell(false);
  14763.       var cutter = Cell(false);
  14764.       var stop = function () {
  14765.         stopper.set(true);
  14766.       };
  14767.       var cut = function () {
  14768.         cutter.set(true);
  14769.       };
  14770.       return {
  14771.         stop: stop,
  14772.         cut: cut,
  14773.         isStopped: stopper.get,
  14774.         isCut: cutter.get,
  14775.         event: event,
  14776.         setSource: source.set,
  14777.         getSource: source.get
  14778.       };
  14779.     };
  14780.     var fromExternal = function (event) {
  14781.       var stopper = Cell(false);
  14782.       var stop = function () {
  14783.         stopper.set(true);
  14784.       };
  14785.       return {
  14786.         stop: stop,
  14787.         cut: noop,
  14788.         isStopped: stopper.get,
  14789.         isCut: never,
  14790.         event: event,
  14791.         setSource: die('Cannot set source of a broadcasted event'),
  14792.         getSource: die('Cannot get source of a broadcasted event')
  14793.       };
  14794.     };
  14795.  
  14796.     var adt$1 = Adt.generate([
  14797.       { stopped: [] },
  14798.       { resume: ['element'] },
  14799.       { complete: [] }
  14800.     ]);
  14801.     var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  14802.       var handler = lookup(eventType, target);
  14803.       var simulatedEvent = fromSource(rawEvent, source);
  14804.       return handler.fold(function () {
  14805.         logger.logEventNoHandlers(eventType, target);
  14806.         return adt$1.complete();
  14807.       }, function (handlerInfo) {
  14808.         var descHandler = handlerInfo.descHandler;
  14809.         var eventHandler = getCurried(descHandler);
  14810.         eventHandler(simulatedEvent);
  14811.         if (simulatedEvent.isStopped()) {
  14812.           logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  14813.           return adt$1.stopped();
  14814.         } else if (simulatedEvent.isCut()) {
  14815.           logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  14816.           return adt$1.complete();
  14817.         } else {
  14818.           return parent(handlerInfo.element).fold(function () {
  14819.             logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  14820.             return adt$1.complete();
  14821.           }, function (parent) {
  14822.             logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  14823.             return adt$1.resume(parent);
  14824.           });
  14825.         }
  14826.       });
  14827.     };
  14828.     var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  14829.       return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  14830.         return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  14831.       }, never);
  14832.     };
  14833.     var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  14834.       var source = derive(rawEvent, target);
  14835.       return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  14836.     };
  14837.     var broadcast = function (listeners, rawEvent, _logger) {
  14838.       var simulatedEvent = fromExternal(rawEvent);
  14839.       each$1(listeners, function (listener) {
  14840.         var descHandler = listener.descHandler;
  14841.         var handler = getCurried(descHandler);
  14842.         handler(simulatedEvent);
  14843.       });
  14844.       return simulatedEvent.isStopped();
  14845.     };
  14846.     var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  14847.       return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  14848.     };
  14849.     var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  14850.       var source = derive(rawEvent, rawTarget);
  14851.       return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  14852.     };
  14853.  
  14854.     var eventHandler = function (element, descHandler) {
  14855.       return {
  14856.         element: element,
  14857.         descHandler: descHandler
  14858.       };
  14859.     };
  14860.     var broadcastHandler = function (id, handler) {
  14861.       return {
  14862.         id: id,
  14863.         descHandler: handler
  14864.       };
  14865.     };
  14866.     var EventRegistry = function () {
  14867.       var registry = {};
  14868.       var registerId = function (extraArgs, id, events) {
  14869.         each(events, function (v, k) {
  14870.           var handlers = registry[k] !== undefined ? registry[k] : {};
  14871.           handlers[id] = curryArgs(v, extraArgs);
  14872.           registry[k] = handlers;
  14873.         });
  14874.       };
  14875.       var findHandler = function (handlers, elem) {
  14876.         return read$1(elem).bind(function (id) {
  14877.           return get$e(handlers, id);
  14878.         }).map(function (descHandler) {
  14879.           return eventHandler(elem, descHandler);
  14880.         });
  14881.       };
  14882.       var filterByType = function (type) {
  14883.         return get$e(registry, type).map(function (handlers) {
  14884.           return mapToArray(handlers, function (f, id) {
  14885.             return broadcastHandler(id, f);
  14886.           });
  14887.         }).getOr([]);
  14888.       };
  14889.       var find = function (isAboveRoot, type, target) {
  14890.         return get$e(registry, type).bind(function (handlers) {
  14891.           return closest$4(target, function (elem) {
  14892.             return findHandler(handlers, elem);
  14893.           }, isAboveRoot);
  14894.         });
  14895.       };
  14896.       var unregisterId = function (id) {
  14897.         each(registry, function (handlersById, _eventName) {
  14898.           if (has$2(handlersById, id)) {
  14899.             delete handlersById[id];
  14900.           }
  14901.         });
  14902.       };
  14903.       return {
  14904.         registerId: registerId,
  14905.         unregisterId: unregisterId,
  14906.         filterByType: filterByType,
  14907.         find: find
  14908.       };
  14909.     };
  14910.  
  14911.     var Registry = function () {
  14912.       var events = EventRegistry();
  14913.       var components = {};
  14914.       var readOrTag = function (component) {
  14915.         var elem = component.element;
  14916.         return read$1(elem).getOrThunk(function () {
  14917.           return write('uid-', component.element);
  14918.         });
  14919.       };
  14920.       var failOnDuplicate = function (component, tagId) {
  14921.         var conflict = components[tagId];
  14922.         if (conflict === component) {
  14923.           unregister(component);
  14924.         } else {
  14925.           throw new Error('The tagId "' + tagId + '" is already used by: ' + element(conflict.element) + '\nCannot use it for: ' + element(component.element) + '\n' + 'The conflicting element is' + (inBody(conflict.element) ? ' ' : ' not ') + 'already in the DOM');
  14926.         }
  14927.       };
  14928.       var register = function (component) {
  14929.         var tagId = readOrTag(component);
  14930.         if (hasNonNullableKey(components, tagId)) {
  14931.           failOnDuplicate(component, tagId);
  14932.         }
  14933.         var extraArgs = [component];
  14934.         events.registerId(extraArgs, tagId, component.events);
  14935.         components[tagId] = component;
  14936.       };
  14937.       var unregister = function (component) {
  14938.         read$1(component.element).each(function (tagId) {
  14939.           delete components[tagId];
  14940.           events.unregisterId(tagId);
  14941.         });
  14942.       };
  14943.       var filter = function (type) {
  14944.         return events.filterByType(type);
  14945.       };
  14946.       var find = function (isAboveRoot, type, target) {
  14947.         return events.find(isAboveRoot, type, target);
  14948.       };
  14949.       var getById = function (id) {
  14950.         return get$e(components, id);
  14951.       };
  14952.       return {
  14953.         find: find,
  14954.         filter: filter,
  14955.         register: register,
  14956.         unregister: unregister,
  14957.         getById: getById
  14958.       };
  14959.     };
  14960.  
  14961.     var factory$j = function (detail) {
  14962.       var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  14963.       return {
  14964.         uid: detail.uid,
  14965.         dom: __assign({
  14966.           tag: 'div',
  14967.           attributes: __assign({ role: 'presentation' }, attributes)
  14968.         }, domWithoutAttributes),
  14969.         components: detail.components,
  14970.         behaviours: get$2(detail.containerBehaviours),
  14971.         events: detail.events,
  14972.         domModification: detail.domModification,
  14973.         eventOrder: detail.eventOrder
  14974.       };
  14975.     };
  14976.     var Container = single({
  14977.       name: 'Container',
  14978.       factory: factory$j,
  14979.       configFields: [
  14980.         defaulted('components', []),
  14981.         field('containerBehaviours', []),
  14982.         defaulted('events', {}),
  14983.         defaulted('domModification', {}),
  14984.         defaulted('eventOrder', {})
  14985.       ]
  14986.     });
  14987.  
  14988.     var takeover = function (root) {
  14989.       var isAboveRoot = function (el) {
  14990.         return parent(root.element).fold(always, function (parent) {
  14991.           return eq(el, parent);
  14992.         });
  14993.       };
  14994.       var registry = Registry();
  14995.       var lookup = function (eventName, target) {
  14996.         return registry.find(isAboveRoot, eventName, target);
  14997.       };
  14998.       var domEvents = setup$d(root.element, {
  14999.         triggerEvent: function (eventName, event) {
  15000.           return monitorEvent(eventName, event.target, function (logger) {
  15001.             return triggerUntilStopped(lookup, eventName, event, logger);
  15002.           });
  15003.         }
  15004.       });
  15005.       var systemApi = {
  15006.         debugInfo: constant$1('real'),
  15007.         triggerEvent: function (eventName, target, data) {
  15008.           monitorEvent(eventName, target, function (logger) {
  15009.             return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  15010.           });
  15011.         },
  15012.         triggerFocus: function (target, originator) {
  15013.           read$1(target).fold(function () {
  15014.             focus$3(target);
  15015.           }, function (_alloyId) {
  15016.             monitorEvent(focus$4(), target, function (logger) {
  15017.               triggerHandler(lookup, focus$4(), {
  15018.                 originator: originator,
  15019.                 kill: noop,
  15020.                 prevent: noop,
  15021.                 target: target
  15022.               }, target, logger);
  15023.               return false;
  15024.             });
  15025.           });
  15026.         },
  15027.         triggerEscape: function (comp, simulatedEvent) {
  15028.           systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  15029.         },
  15030.         getByUid: function (uid) {
  15031.           return getByUid(uid);
  15032.         },
  15033.         getByDom: function (elem) {
  15034.           return getByDom(elem);
  15035.         },
  15036.         build: build$1,
  15037.         addToGui: function (c) {
  15038.           add(c);
  15039.         },
  15040.         removeFromGui: function (c) {
  15041.           remove(c);
  15042.         },
  15043.         addToWorld: function (c) {
  15044.           addToWorld(c);
  15045.         },
  15046.         removeFromWorld: function (c) {
  15047.           removeFromWorld(c);
  15048.         },
  15049.         broadcast: function (message) {
  15050.           broadcast$1(message);
  15051.         },
  15052.         broadcastOn: function (channels, message) {
  15053.           broadcastOn(channels, message);
  15054.         },
  15055.         broadcastEvent: function (eventName, event) {
  15056.           broadcastEvent(eventName, event);
  15057.         },
  15058.         isConnected: always
  15059.       };
  15060.       var addToWorld = function (component) {
  15061.         component.connect(systemApi);
  15062.         if (!isText$1(component.element)) {
  15063.           registry.register(component);
  15064.           each$1(component.components(), addToWorld);
  15065.           systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  15066.         }
  15067.       };
  15068.       var removeFromWorld = function (component) {
  15069.         if (!isText$1(component.element)) {
  15070.           each$1(component.components(), removeFromWorld);
  15071.           registry.unregister(component);
  15072.         }
  15073.         component.disconnect();
  15074.       };
  15075.       var add = function (component) {
  15076.         attach(root, component);
  15077.       };
  15078.       var remove = function (component) {
  15079.         detach(component);
  15080.       };
  15081.       var destroy = function () {
  15082.         domEvents.unbind();
  15083.         remove$5(root.element);
  15084.       };
  15085.       var broadcastData = function (data) {
  15086.         var receivers = registry.filter(receive());
  15087.         each$1(receivers, function (receiver) {
  15088.           var descHandler = receiver.descHandler;
  15089.           var handler = getCurried(descHandler);
  15090.           handler(data);
  15091.         });
  15092.       };
  15093.       var broadcast$1 = function (message) {
  15094.         broadcastData({
  15095.           universal: true,
  15096.           data: message
  15097.         });
  15098.       };
  15099.       var broadcastOn = function (channels, message) {
  15100.         broadcastData({
  15101.           universal: false,
  15102.           channels: channels,
  15103.           data: message
  15104.         });
  15105.       };
  15106.       var broadcastEvent = function (eventName, event) {
  15107.         var listeners = registry.filter(eventName);
  15108.         return broadcast(listeners, event);
  15109.       };
  15110.       var getByUid = function (uid) {
  15111.         return registry.getById(uid).fold(function () {
  15112.           return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  15113.         }, Result.value);
  15114.       };
  15115.       var getByDom = function (elem) {
  15116.         var uid = read$1(elem).getOr('not found');
  15117.         return getByUid(uid);
  15118.       };
  15119.       addToWorld(root);
  15120.       return {
  15121.         root: root,
  15122.         element: root.element,
  15123.         destroy: destroy,
  15124.         add: add,
  15125.         remove: remove,
  15126.         getByUid: getByUid,
  15127.         getByDom: getByDom,
  15128.         addToWorld: addToWorld,
  15129.         removeFromWorld: removeFromWorld,
  15130.         broadcast: broadcast$1,
  15131.         broadcastOn: broadcastOn,
  15132.         broadcastEvent: broadcastEvent
  15133.       };
  15134.     };
  15135.  
  15136.     var renderBar = function (spec, backstage) {
  15137.       return {
  15138.         dom: {
  15139.           tag: 'div',
  15140.           classes: [
  15141.             'tox-bar',
  15142.             'tox-form__controls-h-stack'
  15143.           ]
  15144.         },
  15145.         components: map$2(spec.items, backstage.interpreter)
  15146.       };
  15147.     };
  15148.  
  15149.     var schema$l = constant$1([
  15150.       defaulted('prefix', 'form-field'),
  15151.       field('fieldBehaviours', [
  15152.         Composing,
  15153.         Representing
  15154.       ])
  15155.     ]);
  15156.     var parts$e = constant$1([
  15157.       optional({
  15158.         schema: [required$1('dom')],
  15159.         name: 'label'
  15160.       }),
  15161.       optional({
  15162.         factory: {
  15163.           sketch: function (spec) {
  15164.             return {
  15165.               uid: spec.uid,
  15166.               dom: {
  15167.                 tag: 'span',
  15168.                 styles: { display: 'none' },
  15169.                 attributes: { 'aria-hidden': 'true' },
  15170.                 innerHtml: spec.text
  15171.               }
  15172.             };
  15173.           }
  15174.         },
  15175.         schema: [required$1('text')],
  15176.         name: 'aria-descriptor'
  15177.       }),
  15178.       required({
  15179.         factory: {
  15180.           sketch: function (spec) {
  15181.             var excludeFactory = exclude(spec, ['factory']);
  15182.             return spec.factory.sketch(excludeFactory);
  15183.           }
  15184.         },
  15185.         schema: [required$1('factory')],
  15186.         name: 'field'
  15187.       })
  15188.     ]);
  15189.  
  15190.     var factory$i = function (detail, components, _spec, _externals) {
  15191.       var behaviours = augment(detail.fieldBehaviours, [
  15192.         Composing.config({
  15193.           find: function (container) {
  15194.             return getPart(container, detail, 'field');
  15195.           }
  15196.         }),
  15197.         Representing.config({
  15198.           store: {
  15199.             mode: 'manual',
  15200.             getValue: function (field) {
  15201.               return Composing.getCurrent(field).bind(Representing.getValue);
  15202.             },
  15203.             setValue: function (field, value) {
  15204.               Composing.getCurrent(field).each(function (current) {
  15205.                 Representing.setValue(current, value);
  15206.               });
  15207.             }
  15208.           }
  15209.         })
  15210.       ]);
  15211.       var events = derive$2([runOnAttached(function (component, _simulatedEvent) {
  15212.           var ps = getParts(component, detail, [
  15213.             'label',
  15214.             'field',
  15215.             'aria-descriptor'
  15216.           ]);
  15217.           ps.field().each(function (field) {
  15218.             var id = generate$6(detail.prefix);
  15219.             ps.label().each(function (label) {
  15220.               set$8(label.element, 'for', id);
  15221.               set$8(field.element, 'id', id);
  15222.             });
  15223.             ps['aria-descriptor']().each(function (descriptor) {
  15224.               var descriptorId = generate$6(detail.prefix);
  15225.               set$8(descriptor.element, 'id', descriptorId);
  15226.               set$8(field.element, 'aria-describedby', descriptorId);
  15227.             });
  15228.           });
  15229.         })]);
  15230.       var apis = {
  15231.         getField: function (container) {
  15232.           return getPart(container, detail, 'field');
  15233.         },
  15234.         getLabel: function (container) {
  15235.           return getPart(container, detail, 'label');
  15236.         }
  15237.       };
  15238.       return {
  15239.         uid: detail.uid,
  15240.         dom: detail.dom,
  15241.         components: components,
  15242.         behaviours: behaviours,
  15243.         events: events,
  15244.         apis: apis
  15245.       };
  15246.     };
  15247.     var FormField = composite({
  15248.       name: 'FormField',
  15249.       configFields: schema$l(),
  15250.       partFields: parts$e(),
  15251.       factory: factory$i,
  15252.       apis: {
  15253.         getField: function (apis, comp) {
  15254.           return apis.getField(comp);
  15255.         },
  15256.         getLabel: function (apis, comp) {
  15257.           return apis.getLabel(comp);
  15258.         }
  15259.       }
  15260.     });
  15261.  
  15262.     var exhibit$2 = function (base, tabConfig) {
  15263.       return nu$7({
  15264.         attributes: wrapAll([{
  15265.             key: tabConfig.tabAttr,
  15266.             value: 'true'
  15267.           }])
  15268.       });
  15269.     };
  15270.  
  15271.     var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  15272.         __proto__: null,
  15273.         exhibit: exhibit$2
  15274.     });
  15275.  
  15276.     var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  15277.  
  15278.     var Tabstopping = create$8({
  15279.       fields: TabstopSchema,
  15280.       name: 'tabstopping',
  15281.       active: ActiveTabstopping
  15282.     });
  15283.  
  15284.     var global$7 = tinymce.util.Tools.resolve('tinymce.html.Entities');
  15285.  
  15286.     var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  15287.       var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  15288.       return FormField.sketch(spec);
  15289.     };
  15290.     var renderFormField = function (pLabel, pField) {
  15291.       return renderFormFieldWith(pLabel, pField, [], []);
  15292.     };
  15293.     var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  15294.       return {
  15295.         dom: renderFormFieldDomWith(extraClasses),
  15296.         components: pLabel.toArray().concat([pField]),
  15297.         fieldBehaviours: derive$1(extraBehaviours)
  15298.       };
  15299.     };
  15300.     var renderFormFieldDom = function () {
  15301.       return renderFormFieldDomWith([]);
  15302.     };
  15303.     var renderFormFieldDomWith = function (extraClasses) {
  15304.       return {
  15305.         tag: 'div',
  15306.         classes: ['tox-form__group'].concat(extraClasses)
  15307.       };
  15308.     };
  15309.     var renderLabel$2 = function (label, providersBackstage) {
  15310.       return FormField.parts.label({
  15311.         dom: {
  15312.           tag: 'label',
  15313.           classes: ['tox-label'],
  15314.           innerHtml: providersBackstage.translate(label)
  15315.         }
  15316.       });
  15317.     };
  15318.  
  15319.     var formChangeEvent = generate$6('form-component-change');
  15320.     var formCloseEvent = generate$6('form-close');
  15321.     var formCancelEvent = generate$6('form-cancel');
  15322.     var formActionEvent = generate$6('form-action');
  15323.     var formSubmitEvent = generate$6('form-submit');
  15324.     var formBlockEvent = generate$6('form-block');
  15325.     var formUnblockEvent = generate$6('form-unblock');
  15326.     var formTabChangeEvent = generate$6('form-tabchange');
  15327.     var formResizeEvent = generate$6('form-resize');
  15328.  
  15329.     var renderCollection = function (spec, providersBackstage) {
  15330.       var _a;
  15331.       var pLabel = spec.label.map(function (label) {
  15332.         return renderLabel$2(label, providersBackstage);
  15333.       });
  15334.       var runOnItem = function (f) {
  15335.         return function (comp, se) {
  15336.           closest$1(se.event.target, '[data-collection-item-value]').each(function (target) {
  15337.             f(comp, se, target, get$d(target, 'data-collection-item-value'));
  15338.           });
  15339.         };
  15340.       };
  15341.       var setContents = function (comp, items) {
  15342.         var htmlLines = map$2(items, function (item) {
  15343.           var itemText = global$e.translate(item.text);
  15344.           var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  15345.           var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  15346.           var mapItemName = {
  15347.             '_': ' ',
  15348.             ' - ': ' ',
  15349.             '-': ' '
  15350.           };
  15351.           var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  15352.             return mapItemName[match];
  15353.           });
  15354.           var disabledClass = providersBackstage.isDisabled() ? ' tox-collection__item--state-disabled' : '';
  15355.           return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$7.encodeAllRaw(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  15356.         });
  15357.         var chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
  15358.         var html = map$2(chunks, function (ch) {
  15359.           return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  15360.         });
  15361.         set$5(comp.element, html.join(''));
  15362.       };
  15363.       var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  15364.         se.stop();
  15365.         if (!providersBackstage.isDisabled()) {
  15366.           emitWith(comp, formActionEvent, {
  15367.             name: spec.name,
  15368.             value: itemValue
  15369.           });
  15370.         }
  15371.       });
  15372.       var collectionEvents = [
  15373.         run$1(mouseover(), runOnItem(function (comp, se, tgt) {
  15374.           focus$3(tgt);
  15375.         })),
  15376.         run$1(click(), onClick),
  15377.         run$1(tap(), onClick),
  15378.         run$1(focusin(), runOnItem(function (comp, se, tgt) {
  15379.           descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  15380.             remove$2(currentActive, activeClass);
  15381.           });
  15382.           add$2(tgt, activeClass);
  15383.         })),
  15384.         run$1(focusout(), runOnItem(function (comp) {
  15385.           descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  15386.             remove$2(currentActive, activeClass);
  15387.           });
  15388.         })),
  15389.         runOnExecute$1(runOnItem(function (comp, se, tgt, itemValue) {
  15390.           emitWith(comp, formActionEvent, {
  15391.             name: spec.name,
  15392.             value: itemValue
  15393.           });
  15394.         }))
  15395.       ];
  15396.       var iterCollectionItems = function (comp, applyAttributes) {
  15397.         return map$2(descendants(comp.element, '.tox-collection__item'), applyAttributes);
  15398.       };
  15399.       var pField = FormField.parts.field({
  15400.         dom: {
  15401.           tag: 'div',
  15402.           classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  15403.         },
  15404.         components: [],
  15405.         factory: { sketch: identity$1 },
  15406.         behaviours: derive$1([
  15407.           Disabling.config({
  15408.             disabled: providersBackstage.isDisabled,
  15409.             onDisabled: function (comp) {
  15410.               iterCollectionItems(comp, function (childElm) {
  15411.                 add$2(childElm, 'tox-collection__item--state-disabled');
  15412.                 set$8(childElm, 'aria-disabled', true);
  15413.               });
  15414.             },
  15415.             onEnabled: function (comp) {
  15416.               iterCollectionItems(comp, function (childElm) {
  15417.                 remove$2(childElm, 'tox-collection__item--state-disabled');
  15418.                 remove$7(childElm, 'aria-disabled');
  15419.               });
  15420.             }
  15421.           }),
  15422.           receivingConfig(),
  15423.           Replacing.config({}),
  15424.           Representing.config({
  15425.             store: {
  15426.               mode: 'memory',
  15427.               initialValue: []
  15428.             },
  15429.             onSetValue: function (comp, items) {
  15430.               setContents(comp, items);
  15431.               if (spec.columns === 'auto') {
  15432.                 detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  15433.                   var numRows = _a.numRows, numColumns = _a.numColumns;
  15434.                   Keying.setGridSize(comp, numRows, numColumns);
  15435.                 });
  15436.               }
  15437.               emit(comp, formResizeEvent);
  15438.             }
  15439.           }),
  15440.           Tabstopping.config({}),
  15441.           Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  15442.           config('collection-events', collectionEvents)
  15443.         ]),
  15444.         eventOrder: (_a = {}, _a[execute$5()] = [
  15445.           'disabling',
  15446.           'alloy.base.behaviour',
  15447.           'collection-events'
  15448.         ], _a)
  15449.       });
  15450.       var extraClasses = ['tox-form__group--collection'];
  15451.       return renderFormFieldWith(pLabel, pField, extraClasses, []);
  15452.     };
  15453.  
  15454.     var schema$k = constant$1([
  15455.       option('data'),
  15456.       defaulted('inputAttributes', {}),
  15457.       defaulted('inputStyles', {}),
  15458.       defaulted('tag', 'input'),
  15459.       defaulted('inputClasses', []),
  15460.       onHandler('onSetValue'),
  15461.       defaulted('styles', {}),
  15462.       defaulted('eventOrder', {}),
  15463.       field('inputBehaviours', [
  15464.         Representing,
  15465.         Focusing
  15466.       ]),
  15467.       defaulted('selectOnFocus', true)
  15468.     ]);
  15469.     var focusBehaviours = function (detail) {
  15470.       return derive$1([Focusing.config({
  15471.           onFocus: !detail.selectOnFocus ? noop : function (component) {
  15472.             var input = component.element;
  15473.             var value = get$5(input);
  15474.             input.dom.setSelectionRange(0, value.length);
  15475.           }
  15476.         })]);
  15477.     };
  15478.     var behaviours = function (detail) {
  15479.       return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  15480.           store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  15481.             return { initialValue: data };
  15482.           }).getOr({})), {
  15483.             getValue: function (input) {
  15484.               return get$5(input.element);
  15485.             },
  15486.             setValue: function (input, data) {
  15487.               var current = get$5(input.element);
  15488.               if (current !== data) {
  15489.                 set$4(input.element, data);
  15490.               }
  15491.             }
  15492.           }),
  15493.           onSetValue: detail.onSetValue
  15494.         })]));
  15495.     };
  15496.     var dom = function (detail) {
  15497.       return {
  15498.         tag: detail.tag,
  15499.         attributes: __assign({ type: 'text' }, detail.inputAttributes),
  15500.         styles: detail.inputStyles,
  15501.         classes: detail.inputClasses
  15502.       };
  15503.     };
  15504.  
  15505.     var factory$h = function (detail, _spec) {
  15506.       return {
  15507.         uid: detail.uid,
  15508.         dom: dom(detail),
  15509.         components: [],
  15510.         behaviours: behaviours(detail),
  15511.         eventOrder: detail.eventOrder
  15512.       };
  15513.     };
  15514.     var Input = single({
  15515.       name: 'Input',
  15516.       configFields: schema$k(),
  15517.       factory: factory$h
  15518.     });
  15519.  
  15520.     var exports$1 = {}, module = { exports: exports$1 };
  15521.     (function (define, exports, module, require) {
  15522.       (function (global, factory) {
  15523.         typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  15524.       }(this, function () {
  15525.         var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  15526.         var promise = { exports: {} };
  15527.         (function (module) {
  15528.           (function (root) {
  15529.             var setTimeoutFunc = setTimeout;
  15530.             function noop() {
  15531.             }
  15532.             function bind(fn, thisArg) {
  15533.               return function () {
  15534.                 fn.apply(thisArg, arguments);
  15535.               };
  15536.             }
  15537.             function Promise(fn) {
  15538.               if (typeof this !== 'object')
  15539.                 throw new TypeError('Promises must be constructed via new');
  15540.               if (typeof fn !== 'function')
  15541.                 throw new TypeError('not a function');
  15542.               this._state = 0;
  15543.               this._handled = false;
  15544.               this._value = undefined;
  15545.               this._deferreds = [];
  15546.               doResolve(fn, this);
  15547.             }
  15548.             function handle(self, deferred) {
  15549.               while (self._state === 3) {
  15550.                 self = self._value;
  15551.               }
  15552.               if (self._state === 0) {
  15553.                 self._deferreds.push(deferred);
  15554.                 return;
  15555.               }
  15556.               self._handled = true;
  15557.               Promise._immediateFn(function () {
  15558.                 var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  15559.                 if (cb === null) {
  15560.                   (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  15561.                   return;
  15562.                 }
  15563.                 var ret;
  15564.                 try {
  15565.                   ret = cb(self._value);
  15566.                 } catch (e) {
  15567.                   reject(deferred.promise, e);
  15568.                   return;
  15569.                 }
  15570.                 resolve(deferred.promise, ret);
  15571.               });
  15572.             }
  15573.             function resolve(self, newValue) {
  15574.               try {
  15575.                 if (newValue === self)
  15576.                   throw new TypeError('A promise cannot be resolved with itself.');
  15577.                 if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  15578.                   var then = newValue.then;
  15579.                   if (newValue instanceof Promise) {
  15580.                     self._state = 3;
  15581.                     self._value = newValue;
  15582.                     finale(self);
  15583.                     return;
  15584.                   } else if (typeof then === 'function') {
  15585.                     doResolve(bind(then, newValue), self);
  15586.                     return;
  15587.                   }
  15588.                 }
  15589.                 self._state = 1;
  15590.                 self._value = newValue;
  15591.                 finale(self);
  15592.               } catch (e) {
  15593.                 reject(self, e);
  15594.               }
  15595.             }
  15596.             function reject(self, newValue) {
  15597.               self._state = 2;
  15598.               self._value = newValue;
  15599.               finale(self);
  15600.             }
  15601.             function finale(self) {
  15602.               if (self._state === 2 && self._deferreds.length === 0) {
  15603.                 Promise._immediateFn(function () {
  15604.                   if (!self._handled) {
  15605.                     Promise._unhandledRejectionFn(self._value);
  15606.                   }
  15607.                 });
  15608.               }
  15609.               for (var i = 0, len = self._deferreds.length; i < len; i++) {
  15610.                 handle(self, self._deferreds[i]);
  15611.               }
  15612.               self._deferreds = null;
  15613.             }
  15614.             function Handler(onFulfilled, onRejected, promise) {
  15615.               this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  15616.               this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  15617.               this.promise = promise;
  15618.             }
  15619.             function doResolve(fn, self) {
  15620.               var done = false;
  15621.               try {
  15622.                 fn(function (value) {
  15623.                   if (done)
  15624.                     return;
  15625.                   done = true;
  15626.                   resolve(self, value);
  15627.                 }, function (reason) {
  15628.                   if (done)
  15629.                     return;
  15630.                   done = true;
  15631.                   reject(self, reason);
  15632.                 });
  15633.               } catch (ex) {
  15634.                 if (done)
  15635.                   return;
  15636.                 done = true;
  15637.                 reject(self, ex);
  15638.               }
  15639.             }
  15640.             Promise.prototype['catch'] = function (onRejected) {
  15641.               return this.then(null, onRejected);
  15642.             };
  15643.             Promise.prototype.then = function (onFulfilled, onRejected) {
  15644.               var prom = new this.constructor(noop);
  15645.               handle(this, new Handler(onFulfilled, onRejected, prom));
  15646.               return prom;
  15647.             };
  15648.             Promise.all = function (arr) {
  15649.               var args = Array.prototype.slice.call(arr);
  15650.               return new Promise(function (resolve, reject) {
  15651.                 if (args.length === 0)
  15652.                   return resolve([]);
  15653.                 var remaining = args.length;
  15654.                 function res(i, val) {
  15655.                   try {
  15656.                     if (val && (typeof val === 'object' || typeof val === 'function')) {
  15657.                       var then = val.then;
  15658.                       if (typeof then === 'function') {
  15659.                         then.call(val, function (val) {
  15660.                           res(i, val);
  15661.                         }, reject);
  15662.                         return;
  15663.                       }
  15664.                     }
  15665.                     args[i] = val;
  15666.                     if (--remaining === 0) {
  15667.                       resolve(args);
  15668.                     }
  15669.                   } catch (ex) {
  15670.                     reject(ex);
  15671.                   }
  15672.                 }
  15673.                 for (var i = 0; i < args.length; i++) {
  15674.                   res(i, args[i]);
  15675.                 }
  15676.               });
  15677.             };
  15678.             Promise.resolve = function (value) {
  15679.               if (value && typeof value === 'object' && value.constructor === Promise) {
  15680.                 return value;
  15681.               }
  15682.               return new Promise(function (resolve) {
  15683.                 resolve(value);
  15684.               });
  15685.             };
  15686.             Promise.reject = function (value) {
  15687.               return new Promise(function (resolve, reject) {
  15688.                 reject(value);
  15689.               });
  15690.             };
  15691.             Promise.race = function (values) {
  15692.               return new Promise(function (resolve, reject) {
  15693.                 for (var i = 0, len = values.length; i < len; i++) {
  15694.                   values[i].then(resolve, reject);
  15695.                 }
  15696.               });
  15697.             };
  15698.             Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  15699.               setImmediate(fn);
  15700.             } : function (fn) {
  15701.               setTimeoutFunc(fn, 0);
  15702.             };
  15703.             Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  15704.               if (typeof console !== 'undefined' && console) {
  15705.                 console.warn('Possible Unhandled Promise Rejection:', err);
  15706.               }
  15707.             };
  15708.             Promise._setImmediateFn = function _setImmediateFn(fn) {
  15709.               Promise._immediateFn = fn;
  15710.             };
  15711.             Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  15712.               Promise._unhandledRejectionFn = fn;
  15713.             };
  15714.             if (module.exports) {
  15715.               module.exports = Promise;
  15716.             } else if (!root.Promise) {
  15717.               root.Promise = Promise;
  15718.             }
  15719.           }(commonjsGlobal));
  15720.         }(promise));
  15721.         var promisePolyfill = promise.exports;
  15722.         var Global = function () {
  15723.           if (typeof window !== 'undefined') {
  15724.             return window;
  15725.           } else {
  15726.             return Function('return this;')();
  15727.           }
  15728.         }();
  15729.         var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  15730.         return promisePolyfill_1;
  15731.       }));
  15732.     }(undefined, exports$1, module));
  15733.     var Promise$1 = module.exports.boltExport;
  15734.  
  15735.     var nu$3 = function (baseFn) {
  15736.       var data = Optional.none();
  15737.       var callbacks = [];
  15738.       var map = function (f) {
  15739.         return nu$3(function (nCallback) {
  15740.           get(function (data) {
  15741.             nCallback(f(data));
  15742.           });
  15743.         });
  15744.       };
  15745.       var get = function (nCallback) {
  15746.         if (isReady()) {
  15747.           call(nCallback);
  15748.         } else {
  15749.           callbacks.push(nCallback);
  15750.         }
  15751.       };
  15752.       var set = function (x) {
  15753.         if (!isReady()) {
  15754.           data = Optional.some(x);
  15755.           run(callbacks);
  15756.           callbacks = [];
  15757.         }
  15758.       };
  15759.       var isReady = function () {
  15760.         return data.isSome();
  15761.       };
  15762.       var run = function (cbs) {
  15763.         each$1(cbs, call);
  15764.       };
  15765.       var call = function (cb) {
  15766.         data.each(function (x) {
  15767.           setTimeout(function () {
  15768.             cb(x);
  15769.           }, 0);
  15770.         });
  15771.       };
  15772.       baseFn(set);
  15773.       return {
  15774.         get: get,
  15775.         map: map,
  15776.         isReady: isReady
  15777.       };
  15778.     };
  15779.     var pure$1 = function (a) {
  15780.       return nu$3(function (callback) {
  15781.         callback(a);
  15782.       });
  15783.     };
  15784.     var LazyValue = {
  15785.       nu: nu$3,
  15786.       pure: pure$1
  15787.     };
  15788.  
  15789.     var errorReporter = function (err) {
  15790.       setTimeout(function () {
  15791.         throw err;
  15792.       }, 0);
  15793.     };
  15794.     var make$5 = function (run) {
  15795.       var get = function (callback) {
  15796.         run().then(callback, errorReporter);
  15797.       };
  15798.       var map = function (fab) {
  15799.         return make$5(function () {
  15800.           return run().then(fab);
  15801.         });
  15802.       };
  15803.       var bind = function (aFutureB) {
  15804.         return make$5(function () {
  15805.           return run().then(function (v) {
  15806.             return aFutureB(v).toPromise();
  15807.           });
  15808.         });
  15809.       };
  15810.       var anonBind = function (futureB) {
  15811.         return make$5(function () {
  15812.           return run().then(function () {
  15813.             return futureB.toPromise();
  15814.           });
  15815.         });
  15816.       };
  15817.       var toLazy = function () {
  15818.         return LazyValue.nu(get);
  15819.       };
  15820.       var toCached = function () {
  15821.         var cache = null;
  15822.         return make$5(function () {
  15823.           if (cache === null) {
  15824.             cache = run();
  15825.           }
  15826.           return cache;
  15827.         });
  15828.       };
  15829.       var toPromise = run;
  15830.       return {
  15831.         map: map,
  15832.         bind: bind,
  15833.         anonBind: anonBind,
  15834.         toLazy: toLazy,
  15835.         toCached: toCached,
  15836.         toPromise: toPromise,
  15837.         get: get
  15838.       };
  15839.     };
  15840.     var nu$2 = function (baseFn) {
  15841.       return make$5(function () {
  15842.         return new Promise$1(baseFn);
  15843.       });
  15844.     };
  15845.     var pure = function (a) {
  15846.       return make$5(function () {
  15847.         return Promise$1.resolve(a);
  15848.       });
  15849.     };
  15850.     var Future = {
  15851.       nu: nu$2,
  15852.       pure: pure
  15853.     };
  15854.  
  15855.     var ariaElements = [
  15856.       'input',
  15857.       'textarea'
  15858.     ];
  15859.     var isAriaElement = function (elem) {
  15860.       var name = name$2(elem);
  15861.       return contains$2(ariaElements, name);
  15862.     };
  15863.     var markValid = function (component, invalidConfig) {
  15864.       var elem = invalidConfig.getRoot(component).getOr(component.element);
  15865.       remove$2(elem, invalidConfig.invalidClass);
  15866.       invalidConfig.notify.each(function (notifyInfo) {
  15867.         if (isAriaElement(component.element)) {
  15868.           set$8(component.element, 'aria-invalid', false);
  15869.         }
  15870.         notifyInfo.getContainer(component).each(function (container) {
  15871.           set$5(container, notifyInfo.validHtml);
  15872.         });
  15873.         notifyInfo.onValid(component);
  15874.       });
  15875.     };
  15876.     var markInvalid = function (component, invalidConfig, invalidState, text) {
  15877.       var elem = invalidConfig.getRoot(component).getOr(component.element);
  15878.       add$2(elem, invalidConfig.invalidClass);
  15879.       invalidConfig.notify.each(function (notifyInfo) {
  15880.         if (isAriaElement(component.element)) {
  15881.           set$8(component.element, 'aria-invalid', true);
  15882.         }
  15883.         notifyInfo.getContainer(component).each(function (container) {
  15884.           set$5(container, text);
  15885.         });
  15886.         notifyInfo.onInvalid(component, text);
  15887.       });
  15888.     };
  15889.     var query = function (component, invalidConfig, _invalidState) {
  15890.       return invalidConfig.validator.fold(function () {
  15891.         return Future.pure(Result.value(true));
  15892.       }, function (validatorInfo) {
  15893.         return validatorInfo.validate(component);
  15894.       });
  15895.     };
  15896.     var run = function (component, invalidConfig, invalidState) {
  15897.       invalidConfig.notify.each(function (notifyInfo) {
  15898.         notifyInfo.onValidate(component);
  15899.       });
  15900.       return query(component, invalidConfig).map(function (valid) {
  15901.         if (component.getSystem().isConnected()) {
  15902.           return valid.fold(function (err) {
  15903.             markInvalid(component, invalidConfig, invalidState, err);
  15904.             return Result.error(err);
  15905.           }, function (v) {
  15906.             markValid(component, invalidConfig);
  15907.             return Result.value(v);
  15908.           });
  15909.         } else {
  15910.           return Result.error('No longer in system');
  15911.         }
  15912.       });
  15913.     };
  15914.     var isInvalid = function (component, invalidConfig) {
  15915.       var elem = invalidConfig.getRoot(component).getOr(component.element);
  15916.       return has(elem, invalidConfig.invalidClass);
  15917.     };
  15918.  
  15919.     var InvalidateApis = /*#__PURE__*/Object.freeze({
  15920.         __proto__: null,
  15921.         markValid: markValid,
  15922.         markInvalid: markInvalid,
  15923.         query: query,
  15924.         run: run,
  15925.         isInvalid: isInvalid
  15926.     });
  15927.  
  15928.     var events$8 = function (invalidConfig, invalidState) {
  15929.       return invalidConfig.validator.map(function (validatorInfo) {
  15930.         return derive$2([run$1(validatorInfo.onEvent, function (component) {
  15931.             run(component, invalidConfig, invalidState).get(identity$1);
  15932.           })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  15933.             run(component, invalidConfig, invalidState).get(noop);
  15934.           })] : []));
  15935.       }).getOr({});
  15936.     };
  15937.  
  15938.     var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  15939.         __proto__: null,
  15940.         events: events$8
  15941.     });
  15942.  
  15943.     var InvalidateSchema = [
  15944.       required$1('invalidClass'),
  15945.       defaulted('getRoot', Optional.none),
  15946.       optionObjOf('notify', [
  15947.         defaulted('aria', 'alert'),
  15948.         defaulted('getContainer', Optional.none),
  15949.         defaulted('validHtml', ''),
  15950.         onHandler('onValid'),
  15951.         onHandler('onInvalid'),
  15952.         onHandler('onValidate')
  15953.       ]),
  15954.       optionObjOf('validator', [
  15955.         required$1('validate'),
  15956.         defaulted('onEvent', 'input'),
  15957.         defaulted('validateOnLoad', true)
  15958.       ])
  15959.     ];
  15960.  
  15961.     var Invalidating = create$8({
  15962.       fields: InvalidateSchema,
  15963.       name: 'invalidating',
  15964.       active: ActiveInvalidate,
  15965.       apis: InvalidateApis,
  15966.       extra: {
  15967.         validation: function (validator) {
  15968.           return function (component) {
  15969.             var v = Representing.getValue(component);
  15970.             return Future.pure(validator(v));
  15971.           };
  15972.         }
  15973.       }
  15974.     });
  15975.  
  15976.     var getCoupled = function (component, coupleConfig, coupleState, name) {
  15977.       return coupleState.getOrCreate(component, coupleConfig, name);
  15978.     };
  15979.  
  15980.     var CouplingApis = /*#__PURE__*/Object.freeze({
  15981.         __proto__: null,
  15982.         getCoupled: getCoupled
  15983.     });
  15984.  
  15985.     var CouplingSchema = [requiredOf('others', setOf(Result.value, anyValue()))];
  15986.  
  15987.     var init$a = function () {
  15988.       var coupled = {};
  15989.       var getOrCreate = function (component, coupleConfig, name) {
  15990.         var available = keys(coupleConfig.others);
  15991.         if (!available) {
  15992.           throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  15993.         } else {
  15994.           return get$e(coupled, name).getOrThunk(function () {
  15995.             var builder = get$e(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  15996.             var spec = builder(component);
  15997.             var built = component.getSystem().build(spec);
  15998.             coupled[name] = built;
  15999.             return built;
  16000.           });
  16001.         }
  16002.       };
  16003.       var readState = constant$1({});
  16004.       return nu$8({
  16005.         readState: readState,
  16006.         getOrCreate: getOrCreate
  16007.       });
  16008.     };
  16009.  
  16010.     var CouplingState = /*#__PURE__*/Object.freeze({
  16011.         __proto__: null,
  16012.         init: init$a
  16013.     });
  16014.  
  16015.     var Coupling = create$8({
  16016.       fields: CouplingSchema,
  16017.       name: 'coupling',
  16018.       apis: CouplingApis,
  16019.       state: CouplingState
  16020.     });
  16021.  
  16022.     var suffix = constant$1('sink');
  16023.     var partType$1 = constant$1(optional({
  16024.       name: suffix(),
  16025.       overrides: constant$1({
  16026.         dom: { tag: 'div' },
  16027.         behaviours: derive$1([Positioning.config({ useFixed: always })]),
  16028.         events: derive$2([
  16029.           cutter(keydown()),
  16030.           cutter(mousedown()),
  16031.           cutter(click())
  16032.         ])
  16033.       })
  16034.     }));
  16035.  
  16036.     var HighlightOnOpen;
  16037.     (function (HighlightOnOpen) {
  16038.       HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  16039.       HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  16040.     }(HighlightOnOpen || (HighlightOnOpen = {})));
  16041.     var getAnchor = function (detail, component) {
  16042.       var hotspot = detail.getHotspot(component).getOr(component);
  16043.       var type = 'hotspot';
  16044.       var overrides = detail.getAnchorOverrides();
  16045.       return detail.layouts.fold(function () {
  16046.         return {
  16047.           type: type,
  16048.           hotspot: hotspot,
  16049.           overrides: overrides
  16050.         };
  16051.       }, function (layouts) {
  16052.         return {
  16053.           type: type,
  16054.           hotspot: hotspot,
  16055.           overrides: overrides,
  16056.           layouts: layouts
  16057.         };
  16058.       });
  16059.     };
  16060.     var fetch = function (detail, mapFetch, component) {
  16061.       var fetcher = detail.fetch;
  16062.       return fetcher(component).map(mapFetch);
  16063.     };
  16064.     var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  16065.       var futureData = fetch(detail, mapFetch, component);
  16066.       var getLazySink = getSink(component, detail);
  16067.       return futureData.map(function (tdata) {
  16068.         return tdata.bind(function (data) {
  16069.           return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  16070.             uid: generate$5(''),
  16071.             data: data,
  16072.             highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  16073.             onOpenMenu: function (tmenu, menu) {
  16074.               var sink = getLazySink().getOrDie();
  16075.               Positioning.position(sink, menu, { anchor: anchor });
  16076.               Sandboxing.decloak(sandbox);
  16077.             },
  16078.             onOpenSubmenu: function (tmenu, item, submenu) {
  16079.               var sink = getLazySink().getOrDie();
  16080.               Positioning.position(sink, submenu, {
  16081.                 anchor: {
  16082.                   type: 'submenu',
  16083.                   item: item
  16084.                 }
  16085.               });
  16086.               Sandboxing.decloak(sandbox);
  16087.             },
  16088.             onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  16089.               var sink = getLazySink().getOrDie();
  16090.               Positioning.position(sink, primaryMenu, { anchor: anchor });
  16091.               each$1(submenuTriggers, function (st) {
  16092.                 Positioning.position(sink, st.triggeredMenu, {
  16093.                   anchor: {
  16094.                     type: 'submenu',
  16095.                     item: st.triggeringItem
  16096.                   }
  16097.                 });
  16098.               });
  16099.             },
  16100.             onEscape: function () {
  16101.               Focusing.focus(component);
  16102.               Sandboxing.close(sandbox);
  16103.               return Optional.some(true);
  16104.             }
  16105.           })));
  16106.         });
  16107.       });
  16108.     };
  16109.     var open = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  16110.       var anchor = getAnchor(detail, hotspot);
  16111.       var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  16112.       return processed.map(function (tdata) {
  16113.         tdata.fold(function () {
  16114.           if (Sandboxing.isOpen(sandbox)) {
  16115.             Sandboxing.close(sandbox);
  16116.           }
  16117.         }, function (data) {
  16118.           Sandboxing.cloak(sandbox);
  16119.           Sandboxing.open(sandbox, data);
  16120.           onOpenSync(sandbox);
  16121.         });
  16122.         return sandbox;
  16123.       });
  16124.     };
  16125.     var close = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  16126.       Sandboxing.close(sandbox);
  16127.       return Future.pure(sandbox);
  16128.     };
  16129.     var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  16130.       var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  16131.       var showing = Sandboxing.isOpen(sandbox);
  16132.       var action = showing ? close : open;
  16133.       return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  16134.     };
  16135.     var matchWidth = function (hotspot, container, useMinWidth) {
  16136.       var menu = Composing.getCurrent(container).getOr(container);
  16137.       var buttonWidth = get$a(hotspot.element);
  16138.       if (useMinWidth) {
  16139.         set$7(menu.element, 'min-width', buttonWidth + 'px');
  16140.       } else {
  16141.         set$6(menu.element, buttonWidth);
  16142.       }
  16143.     };
  16144.     var getSink = function (anyInSystem, sinkDetail) {
  16145.       return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  16146.         return function () {
  16147.           return Result.value(internalSink);
  16148.         };
  16149.       }).getOrThunk(function () {
  16150.         return sinkDetail.lazySink.fold(function () {
  16151.           return function () {
  16152.             return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  16153.           };
  16154.         }, function (lazySinkFn) {
  16155.           return function () {
  16156.             return lazySinkFn(anyInSystem);
  16157.           };
  16158.         });
  16159.       });
  16160.     };
  16161.     var doRepositionMenus = function (sandbox) {
  16162.       Sandboxing.getState(sandbox).each(function (tmenu) {
  16163.         tieredMenu.repositionMenus(tmenu);
  16164.       });
  16165.     };
  16166.     var makeSandbox$1 = function (detail, hotspot, extras) {
  16167.       var ariaOwner = manager();
  16168.       var onOpen = function (component, menu) {
  16169.         var anchor = getAnchor(detail, hotspot);
  16170.         ariaOwner.link(hotspot.element);
  16171.         if (detail.matchWidth) {
  16172.           matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  16173.         }
  16174.         detail.onOpen(anchor, component, menu);
  16175.         if (extras !== undefined && extras.onOpen !== undefined) {
  16176.           extras.onOpen(component, menu);
  16177.         }
  16178.       };
  16179.       var onClose = function (component, menu) {
  16180.         ariaOwner.unlink(hotspot.element);
  16181.         if (extras !== undefined && extras.onClose !== undefined) {
  16182.           extras.onClose(component, menu);
  16183.         }
  16184.       };
  16185.       var lazySink = getSink(hotspot, detail);
  16186.       return {
  16187.         dom: {
  16188.           tag: 'div',
  16189.           classes: detail.sandboxClasses,
  16190.           attributes: {
  16191.             id: ariaOwner.id,
  16192.             role: 'listbox'
  16193.           }
  16194.         },
  16195.         behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  16196.           Representing.config({
  16197.             store: {
  16198.               mode: 'memory',
  16199.               initialValue: hotspot
  16200.             }
  16201.           }),
  16202.           Sandboxing.config({
  16203.             onOpen: onOpen,
  16204.             onClose: onClose,
  16205.             isPartOf: function (container, data, queryElem) {
  16206.               return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
  16207.             },
  16208.             getAttachPoint: function () {
  16209.               return lazySink().getOrDie();
  16210.             }
  16211.           }),
  16212.           Composing.config({
  16213.             find: function (sandbox) {
  16214.               return Sandboxing.getState(sandbox).bind(function (menu) {
  16215.                 return Composing.getCurrent(menu);
  16216.               });
  16217.             }
  16218.           }),
  16219.           Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) })
  16220.         ])
  16221.       };
  16222.     };
  16223.     var repositionMenus = function (comp) {
  16224.       var sandbox = Coupling.getCoupled(comp, 'sandbox');
  16225.       doRepositionMenus(sandbox);
  16226.     };
  16227.  
  16228.     var sandboxFields = function () {
  16229.       return [
  16230.         defaulted('sandboxClasses', []),
  16231.         SketchBehaviours.field('sandboxBehaviours', [
  16232.           Composing,
  16233.           Receiving,
  16234.           Sandboxing,
  16235.           Representing
  16236.         ])
  16237.       ];
  16238.     };
  16239.  
  16240.     var schema$j = constant$1([
  16241.       required$1('dom'),
  16242.       required$1('fetch'),
  16243.       onHandler('onOpen'),
  16244.       onKeyboardHandler('onExecute'),
  16245.       defaulted('getHotspot', Optional.some),
  16246.       defaulted('getAnchorOverrides', constant$1({})),
  16247.       schema$y(),
  16248.       field('dropdownBehaviours', [
  16249.         Toggling,
  16250.         Coupling,
  16251.         Keying,
  16252.         Focusing
  16253.       ]),
  16254.       required$1('toggleClass'),
  16255.       defaulted('eventOrder', {}),
  16256.       option('lazySink'),
  16257.       defaulted('matchWidth', false),
  16258.       defaulted('useMinWidth', false),
  16259.       option('role')
  16260.     ].concat(sandboxFields()));
  16261.     var parts$d = constant$1([
  16262.       external$1({
  16263.         schema: [tieredMenuMarkers()],
  16264.         name: 'menu',
  16265.         defaults: function (detail) {
  16266.           return { onExecute: detail.onExecute };
  16267.         }
  16268.       }),
  16269.       partType$1()
  16270.     ]);
  16271.  
  16272.     var factory$g = function (detail, components, _spec, externals) {
  16273.       var _a;
  16274.       var lookupAttr = function (attr) {
  16275.         return get$e(detail.dom, 'attributes').bind(function (attrs) {
  16276.           return get$e(attrs, attr);
  16277.         });
  16278.       };
  16279.       var switchToMenu = function (sandbox) {
  16280.         Sandboxing.getState(sandbox).each(function (tmenu) {
  16281.           tieredMenu.highlightPrimary(tmenu);
  16282.         });
  16283.       };
  16284.       var action = function (component) {
  16285.         var onOpenSync = switchToMenu;
  16286.         togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  16287.       };
  16288.       var apis = {
  16289.         expand: function (comp) {
  16290.           if (!Toggling.isOn(comp)) {
  16291.             togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  16292.           }
  16293.         },
  16294.         open: function (comp) {
  16295.           if (!Toggling.isOn(comp)) {
  16296.             togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  16297.           }
  16298.         },
  16299.         isOpen: Toggling.isOn,
  16300.         close: function (comp) {
  16301.           if (Toggling.isOn(comp)) {
  16302.             togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  16303.           }
  16304.         },
  16305.         repositionMenus: function (comp) {
  16306.           if (Toggling.isOn(comp)) {
  16307.             repositionMenus(comp);
  16308.           }
  16309.         }
  16310.       };
  16311.       var triggerExecute = function (comp, _se) {
  16312.         emitExecute(comp);
  16313.         return Optional.some(true);
  16314.       };
  16315.       return {
  16316.         uid: detail.uid,
  16317.         dom: detail.dom,
  16318.         components: components,
  16319.         behaviours: augment(detail.dropdownBehaviours, [
  16320.           Toggling.config({
  16321.             toggleClass: detail.toggleClass,
  16322.             aria: { mode: 'expanded' }
  16323.           }),
  16324.           Coupling.config({
  16325.             others: {
  16326.               sandbox: function (hotspot) {
  16327.                 return makeSandbox$1(detail, hotspot, {
  16328.                   onOpen: function () {
  16329.                     return Toggling.on(hotspot);
  16330.                   },
  16331.                   onClose: function () {
  16332.                     return Toggling.off(hotspot);
  16333.                   }
  16334.                 });
  16335.               }
  16336.             }
  16337.           }),
  16338.           Keying.config({
  16339.             mode: 'special',
  16340.             onSpace: triggerExecute,
  16341.             onEnter: triggerExecute,
  16342.             onDown: function (comp, _se) {
  16343.               if (Dropdown.isOpen(comp)) {
  16344.                 var sandbox = Coupling.getCoupled(comp, 'sandbox');
  16345.                 switchToMenu(sandbox);
  16346.               } else {
  16347.                 Dropdown.open(comp);
  16348.               }
  16349.               return Optional.some(true);
  16350.             },
  16351.             onEscape: function (comp, _se) {
  16352.               if (Dropdown.isOpen(comp)) {
  16353.                 Dropdown.close(comp);
  16354.                 return Optional.some(true);
  16355.               } else {
  16356.                 return Optional.none();
  16357.               }
  16358.             }
  16359.           }),
  16360.           Focusing.config({})
  16361.         ]),
  16362.         events: events$a(Optional.some(action)),
  16363.         eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  16364.           'disabling',
  16365.           'toggling',
  16366.           'alloy.base.behaviour'
  16367.         ], _a)),
  16368.         apis: apis,
  16369.         domModification: {
  16370.           attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  16371.             return {};
  16372.           }, function (role) {
  16373.             return { role: role };
  16374.           })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  16375.         }
  16376.       };
  16377.     };
  16378.     var Dropdown = composite({
  16379.       name: 'Dropdown',
  16380.       configFields: schema$j(),
  16381.       partFields: parts$d(),
  16382.       factory: factory$g,
  16383.       apis: {
  16384.         open: function (apis, comp) {
  16385.           return apis.open(comp);
  16386.         },
  16387.         expand: function (apis, comp) {
  16388.           return apis.expand(comp);
  16389.         },
  16390.         close: function (apis, comp) {
  16391.           return apis.close(comp);
  16392.         },
  16393.         isOpen: function (apis, comp) {
  16394.           return apis.isOpen(comp);
  16395.         },
  16396.         repositionMenus: function (apis, comp) {
  16397.           return apis.repositionMenus(comp);
  16398.         }
  16399.       }
  16400.     });
  16401.  
  16402.     var exhibit$1 = function () {
  16403.       return nu$7({
  16404.         styles: {
  16405.           '-webkit-user-select': 'none',
  16406.           'user-select': 'none',
  16407.           '-ms-user-select': 'none',
  16408.           '-moz-user-select': '-moz-none'
  16409.         },
  16410.         attributes: { unselectable: 'on' }
  16411.       });
  16412.     };
  16413.     var events$7 = function () {
  16414.       return derive$2([abort(selectstart(), always)]);
  16415.     };
  16416.  
  16417.     var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  16418.         __proto__: null,
  16419.         events: events$7,
  16420.         exhibit: exhibit$1
  16421.     });
  16422.  
  16423.     var Unselecting = create$8({
  16424.       fields: [],
  16425.       name: 'unselecting',
  16426.       active: ActiveUnselecting
  16427.     });
  16428.  
  16429.     var renderPanelButton = function (spec, sharedBackstage) {
  16430.       return Dropdown.sketch({
  16431.         dom: spec.dom,
  16432.         components: spec.components,
  16433.         toggleClass: 'mce-active',
  16434.         dropdownBehaviours: derive$1([
  16435.           DisablingConfigs.button(sharedBackstage.providers.isDisabled),
  16436.           receivingConfig(),
  16437.           Unselecting.config({}),
  16438.           Tabstopping.config({})
  16439.         ]),
  16440.         layouts: spec.layouts,
  16441.         sandboxClasses: ['tox-dialog__popups'],
  16442.         lazySink: sharedBackstage.getSink,
  16443.         fetch: function (comp) {
  16444.           return Future.nu(function (callback) {
  16445.             return spec.fetch(callback);
  16446.           }).map(function (items) {
  16447.             return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  16448.               spec.onItemAction(comp, value);
  16449.             }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  16450.           });
  16451.         },
  16452.         parts: { menu: part(false, 1, spec.presets) }
  16453.       });
  16454.     };
  16455.  
  16456.     var colorInputChangeEvent = generate$6('color-input-change');
  16457.     var colorSwatchChangeEvent = generate$6('color-swatch-change');
  16458.     var colorPickerCancelEvent = generate$6('color-picker-cancel');
  16459.     var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  16460.       var pField = FormField.parts.field({
  16461.         factory: Input,
  16462.         inputClasses: ['tox-textfield'],
  16463.         onSetValue: function (c) {
  16464.           return Invalidating.run(c).get(noop);
  16465.         },
  16466.         inputBehaviours: derive$1([
  16467.           Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
  16468.           receivingConfig(),
  16469.           Tabstopping.config({}),
  16470.           Invalidating.config({
  16471.             invalidClass: 'tox-textbox-field-invalid',
  16472.             getRoot: function (comp) {
  16473.               return parent(comp.element);
  16474.             },
  16475.             notify: {
  16476.               onValid: function (comp) {
  16477.                 var val = Representing.getValue(comp);
  16478.                 emitWith(comp, colorInputChangeEvent, { color: val });
  16479.               }
  16480.             },
  16481.             validator: {
  16482.               validateOnLoad: false,
  16483.               validate: function (input) {
  16484.                 var inputValue = Representing.getValue(input);
  16485.                 if (inputValue.length === 0) {
  16486.                   return Future.pure(Result.value(true));
  16487.                 } else {
  16488.                   var span = SugarElement.fromTag('span');
  16489.                   set$7(span, 'background-color', inputValue);
  16490.                   var res = getRaw(span, 'background-color').fold(function () {
  16491.                     return Result.error('blah');
  16492.                   }, function (_) {
  16493.                     return Result.value(inputValue);
  16494.                   });
  16495.                   return Future.pure(res);
  16496.                 }
  16497.               }
  16498.             }
  16499.           })
  16500.         ]),
  16501.         selectOnFocus: false
  16502.       });
  16503.       var pLabel = spec.label.map(function (label) {
  16504.         return renderLabel$2(label, sharedBackstage.providers);
  16505.       });
  16506.       var emitSwatchChange = function (colorBit, value) {
  16507.         emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  16508.       };
  16509.       var onItemAction = function (comp, value) {
  16510.         memColorButton.getOpt(comp).each(function (colorBit) {
  16511.           if (value === 'custom') {
  16512.             colorInputBackstage.colorPicker(function (valueOpt) {
  16513.               valueOpt.fold(function () {
  16514.                 return emit(colorBit, colorPickerCancelEvent);
  16515.               }, function (value) {
  16516.                 emitSwatchChange(colorBit, value);
  16517.                 addColor(value);
  16518.               });
  16519.             }, '#ffffff');
  16520.           } else if (value === 'remove') {
  16521.             emitSwatchChange(colorBit, '');
  16522.           } else {
  16523.             emitSwatchChange(colorBit, value);
  16524.           }
  16525.         });
  16526.       };
  16527.       var memColorButton = record(renderPanelButton({
  16528.         dom: {
  16529.           tag: 'span',
  16530.           attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  16531.         },
  16532.         layouts: {
  16533.           onRtl: function () {
  16534.             return [
  16535.               southwest$2,
  16536.               southeast$2,
  16537.               south$2
  16538.             ];
  16539.           },
  16540.           onLtr: function () {
  16541.             return [
  16542.               southeast$2,
  16543.               southwest$2,
  16544.               south$2
  16545.             ];
  16546.           }
  16547.         },
  16548.         components: [],
  16549.         fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  16550.         columns: colorInputBackstage.getColorCols(),
  16551.         presets: 'color',
  16552.         onItemAction: onItemAction
  16553.       }, sharedBackstage));
  16554.       return FormField.sketch({
  16555.         dom: {
  16556.           tag: 'div',
  16557.           classes: ['tox-form__group']
  16558.         },
  16559.         components: pLabel.toArray().concat([{
  16560.             dom: {
  16561.               tag: 'div',
  16562.               classes: ['tox-color-input']
  16563.             },
  16564.             components: [
  16565.               pField,
  16566.               memColorButton.asSpec()
  16567.             ]
  16568.           }]),
  16569.         fieldBehaviours: derive$1([config('form-field-events', [
  16570.             run$1(colorInputChangeEvent, function (comp, se) {
  16571.               memColorButton.getOpt(comp).each(function (colorButton) {
  16572.                 set$7(colorButton.element, 'background-color', se.event.color);
  16573.               });
  16574.               emitWith(comp, formChangeEvent, { name: spec.name });
  16575.             }),
  16576.             run$1(colorSwatchChangeEvent, function (comp, se) {
  16577.               FormField.getField(comp).each(function (field) {
  16578.                 Representing.setValue(field, se.event.value);
  16579.                 Composing.getCurrent(comp).each(Focusing.focus);
  16580.               });
  16581.             }),
  16582.             run$1(colorPickerCancelEvent, function (comp, _se) {
  16583.               FormField.getField(comp).each(function (_field) {
  16584.                 Composing.getCurrent(comp).each(Focusing.focus);
  16585.               });
  16586.             })
  16587.           ])])
  16588.       });
  16589.     };
  16590.  
  16591.     var labelPart = optional({
  16592.       schema: [required$1('dom')],
  16593.       name: 'label'
  16594.     });
  16595.     var edgePart = function (name) {
  16596.       return optional({
  16597.         name: '' + name + '-edge',
  16598.         overrides: function (detail) {
  16599.           var action = detail.model.manager.edgeActions[name];
  16600.           return action.fold(function () {
  16601.             return {};
  16602.           }, function (a) {
  16603.             return {
  16604.               events: derive$2([
  16605.                 runActionExtra(touchstart(), function (comp, se, d) {
  16606.                   return a(comp, d);
  16607.                 }, [detail]),
  16608.                 runActionExtra(mousedown(), function (comp, se, d) {
  16609.                   return a(comp, d);
  16610.                 }, [detail]),
  16611.                 runActionExtra(mousemove(), function (comp, se, det) {
  16612.                   if (det.mouseIsDown.get()) {
  16613.                     a(comp, det);
  16614.                   }
  16615.                 }, [detail])
  16616.               ])
  16617.             };
  16618.           });
  16619.         }
  16620.       });
  16621.     };
  16622.     var tlEdgePart = edgePart('top-left');
  16623.     var tedgePart = edgePart('top');
  16624.     var trEdgePart = edgePart('top-right');
  16625.     var redgePart = edgePart('right');
  16626.     var brEdgePart = edgePart('bottom-right');
  16627.     var bedgePart = edgePart('bottom');
  16628.     var blEdgePart = edgePart('bottom-left');
  16629.     var ledgePart = edgePart('left');
  16630.     var thumbPart = required({
  16631.       name: 'thumb',
  16632.       defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  16633.       overrides: function (detail) {
  16634.         return {
  16635.           events: derive$2([
  16636.             redirectToPart(touchstart(), detail, 'spectrum'),
  16637.             redirectToPart(touchmove(), detail, 'spectrum'),
  16638.             redirectToPart(touchend(), detail, 'spectrum'),
  16639.             redirectToPart(mousedown(), detail, 'spectrum'),
  16640.             redirectToPart(mousemove(), detail, 'spectrum'),
  16641.             redirectToPart(mouseup(), detail, 'spectrum')
  16642.           ])
  16643.         };
  16644.       }
  16645.     });
  16646.     var spectrumPart = required({
  16647.       schema: [customField('mouseIsDown', function () {
  16648.           return Cell(false);
  16649.         })],
  16650.       name: 'spectrum',
  16651.       overrides: function (detail) {
  16652.         var modelDetail = detail.model;
  16653.         var model = modelDetail.manager;
  16654.         var setValueFrom = function (component, simulatedEvent) {
  16655.           return model.getValueFromEvent(simulatedEvent).map(function (value) {
  16656.             return model.setValueFrom(component, detail, value);
  16657.           });
  16658.         };
  16659.         return {
  16660.           behaviours: derive$1([
  16661.             Keying.config({
  16662.               mode: 'special',
  16663.               onLeft: function (spectrum) {
  16664.                 return model.onLeft(spectrum, detail);
  16665.               },
  16666.               onRight: function (spectrum) {
  16667.                 return model.onRight(spectrum, detail);
  16668.               },
  16669.               onUp: function (spectrum) {
  16670.                 return model.onUp(spectrum, detail);
  16671.               },
  16672.               onDown: function (spectrum) {
  16673.                 return model.onDown(spectrum, detail);
  16674.               }
  16675.             }),
  16676.             Focusing.config({})
  16677.           ]),
  16678.           events: derive$2([
  16679.             run$1(touchstart(), setValueFrom),
  16680.             run$1(touchmove(), setValueFrom),
  16681.             run$1(mousedown(), setValueFrom),
  16682.             run$1(mousemove(), function (spectrum, se) {
  16683.               if (detail.mouseIsDown.get()) {
  16684.                 setValueFrom(spectrum, se);
  16685.               }
  16686.             })
  16687.           ])
  16688.         };
  16689.       }
  16690.     });
  16691.     var SliderParts = [
  16692.       labelPart,
  16693.       ledgePart,
  16694.       redgePart,
  16695.       tedgePart,
  16696.       bedgePart,
  16697.       tlEdgePart,
  16698.       trEdgePart,
  16699.       blEdgePart,
  16700.       brEdgePart,
  16701.       thumbPart,
  16702.       spectrumPart
  16703.     ];
  16704.  
  16705.     var _sliderChangeEvent = 'slider.change.value';
  16706.     var sliderChangeEvent = constant$1(_sliderChangeEvent);
  16707.     var isTouchEvent$2 = function (evt) {
  16708.       return evt.type.indexOf('touch') !== -1;
  16709.     };
  16710.     var getEventSource = function (simulatedEvent) {
  16711.       var evt = simulatedEvent.event.raw;
  16712.       if (isTouchEvent$2(evt)) {
  16713.         var touchEvent = evt;
  16714.         return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  16715.           return SugarPosition(t.clientX, t.clientY);
  16716.         }) : Optional.none();
  16717.       } else {
  16718.         var mouseEvent = evt;
  16719.         return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  16720.           return SugarPosition(me.clientX, me.clientY);
  16721.         }) : Optional.none();
  16722.       }
  16723.     };
  16724.  
  16725.     var t = 'top', r = 'right', b = 'bottom', l = 'left';
  16726.     var minX = function (detail) {
  16727.       return detail.model.minX;
  16728.     };
  16729.     var minY = function (detail) {
  16730.       return detail.model.minY;
  16731.     };
  16732.     var min1X = function (detail) {
  16733.       return detail.model.minX - 1;
  16734.     };
  16735.     var min1Y = function (detail) {
  16736.       return detail.model.minY - 1;
  16737.     };
  16738.     var maxX = function (detail) {
  16739.       return detail.model.maxX;
  16740.     };
  16741.     var maxY = function (detail) {
  16742.       return detail.model.maxY;
  16743.     };
  16744.     var max1X = function (detail) {
  16745.       return detail.model.maxX + 1;
  16746.     };
  16747.     var max1Y = function (detail) {
  16748.       return detail.model.maxY + 1;
  16749.     };
  16750.     var range = function (detail, max, min) {
  16751.       return max(detail) - min(detail);
  16752.     };
  16753.     var xRange = function (detail) {
  16754.       return range(detail, maxX, minX);
  16755.     };
  16756.     var yRange = function (detail) {
  16757.       return range(detail, maxY, minY);
  16758.     };
  16759.     var halfX = function (detail) {
  16760.       return xRange(detail) / 2;
  16761.     };
  16762.     var halfY = function (detail) {
  16763.       return yRange(detail) / 2;
  16764.     };
  16765.     var step = function (detail) {
  16766.       return detail.stepSize;
  16767.     };
  16768.     var snap = function (detail) {
  16769.       return detail.snapToGrid;
  16770.     };
  16771.     var snapStart = function (detail) {
  16772.       return detail.snapStart;
  16773.     };
  16774.     var rounded = function (detail) {
  16775.       return detail.rounded;
  16776.     };
  16777.     var hasEdge = function (detail, edgeName) {
  16778.       return detail[edgeName + '-edge'] !== undefined;
  16779.     };
  16780.     var hasLEdge = function (detail) {
  16781.       return hasEdge(detail, l);
  16782.     };
  16783.     var hasREdge = function (detail) {
  16784.       return hasEdge(detail, r);
  16785.     };
  16786.     var hasTEdge = function (detail) {
  16787.       return hasEdge(detail, t);
  16788.     };
  16789.     var hasBEdge = function (detail) {
  16790.       return hasEdge(detail, b);
  16791.     };
  16792.     var currentValue = function (detail) {
  16793.       return detail.model.value.get();
  16794.     };
  16795.  
  16796.     var xValue = function (x) {
  16797.       return { x: x };
  16798.     };
  16799.     var yValue = function (y) {
  16800.       return { y: y };
  16801.     };
  16802.     var xyValue = function (x, y) {
  16803.       return {
  16804.         x: x,
  16805.         y: y
  16806.       };
  16807.     };
  16808.     var fireSliderChange$3 = function (component, value) {
  16809.       emitWith(component, sliderChangeEvent(), { value: value });
  16810.     };
  16811.     var setToTLEdgeXY = function (edge, detail) {
  16812.       fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  16813.     };
  16814.     var setToTEdge = function (edge, detail) {
  16815.       fireSliderChange$3(edge, yValue(min1Y(detail)));
  16816.     };
  16817.     var setToTEdgeXY = function (edge, detail) {
  16818.       fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  16819.     };
  16820.     var setToTREdgeXY = function (edge, detail) {
  16821.       fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  16822.     };
  16823.     var setToREdge = function (edge, detail) {
  16824.       fireSliderChange$3(edge, xValue(max1X(detail)));
  16825.     };
  16826.     var setToREdgeXY = function (edge, detail) {
  16827.       fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  16828.     };
  16829.     var setToBREdgeXY = function (edge, detail) {
  16830.       fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  16831.     };
  16832.     var setToBEdge = function (edge, detail) {
  16833.       fireSliderChange$3(edge, yValue(max1Y(detail)));
  16834.     };
  16835.     var setToBEdgeXY = function (edge, detail) {
  16836.       fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  16837.     };
  16838.     var setToBLEdgeXY = function (edge, detail) {
  16839.       fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  16840.     };
  16841.     var setToLEdge = function (edge, detail) {
  16842.       fireSliderChange$3(edge, xValue(min1X(detail)));
  16843.     };
  16844.     var setToLEdgeXY = function (edge, detail) {
  16845.       fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  16846.     };
  16847.  
  16848.     var reduceBy = function (value, min, max, step) {
  16849.       if (value < min) {
  16850.         return value;
  16851.       } else if (value > max) {
  16852.         return max;
  16853.       } else if (value === min) {
  16854.         return min - 1;
  16855.       } else {
  16856.         return Math.max(min, value - step);
  16857.       }
  16858.     };
  16859.     var increaseBy = function (value, min, max, step) {
  16860.       if (value > max) {
  16861.         return value;
  16862.       } else if (value < min) {
  16863.         return min;
  16864.       } else if (value === max) {
  16865.         return max + 1;
  16866.       } else {
  16867.         return Math.min(max, value + step);
  16868.       }
  16869.     };
  16870.     var capValue = function (value, min, max) {
  16871.       return Math.max(min, Math.min(max, value));
  16872.     };
  16873.     var snapValueOf = function (value, min, max, step, snapStart) {
  16874.       return snapStart.fold(function () {
  16875.         var initValue = value - min;
  16876.         var extraValue = Math.round(initValue / step) * step;
  16877.         return capValue(min + extraValue, min - 1, max + 1);
  16878.       }, function (start) {
  16879.         var remainder = (value - start) % step;
  16880.         var adjustment = Math.round(remainder / step);
  16881.         var rawSteps = Math.floor((value - start) / step);
  16882.         var maxSteps = Math.floor((max - start) / step);
  16883.         var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  16884.         var r = start + numSteps * step;
  16885.         return Math.max(start, r);
  16886.       });
  16887.     };
  16888.     var findOffsetOf = function (value, min, max) {
  16889.       return Math.min(max, Math.max(value, min)) - min;
  16890.     };
  16891.     var findValueOf = function (args) {
  16892.       var min = args.min, max = args.max, range = args.range, value = args.value, step = args.step, snap = args.snap, snapStart = args.snapStart, rounded = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
  16893.       var capMin = hasMinEdge ? min - 1 : min;
  16894.       var capMax = hasMaxEdge ? max + 1 : max;
  16895.       if (value < minBound) {
  16896.         return capMin;
  16897.       } else if (value > maxBound) {
  16898.         return capMax;
  16899.       } else {
  16900.         var offset = findOffsetOf(value, minBound, maxBound);
  16901.         var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  16902.         if (snap && newValue >= min && newValue <= max) {
  16903.           return snapValueOf(newValue, min, max, step, snapStart);
  16904.         } else if (rounded) {
  16905.           return Math.round(newValue);
  16906.         } else {
  16907.           return newValue;
  16908.         }
  16909.       }
  16910.     };
  16911.     var findOffsetOfValue$2 = function (args) {
  16912.       var min = args.min, max = args.max, range = args.range, value = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
  16913.       if (value < min) {
  16914.         return hasMinEdge ? 0 : centerMinEdge;
  16915.       } else if (value > max) {
  16916.         return hasMaxEdge ? maxBound : centerMaxEdge;
  16917.       } else {
  16918.         return (value - min) / range * maxOffset;
  16919.       }
  16920.     };
  16921.  
  16922.     var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  16923.     var getBounds = function (component) {
  16924.       return component.element.dom.getBoundingClientRect();
  16925.     };
  16926.     var getBoundsProperty = function (bounds, property) {
  16927.       return bounds[property];
  16928.     };
  16929.     var getMinXBounds = function (component) {
  16930.       var bounds = getBounds(component);
  16931.       return getBoundsProperty(bounds, left);
  16932.     };
  16933.     var getMaxXBounds = function (component) {
  16934.       var bounds = getBounds(component);
  16935.       return getBoundsProperty(bounds, right);
  16936.     };
  16937.     var getMinYBounds = function (component) {
  16938.       var bounds = getBounds(component);
  16939.       return getBoundsProperty(bounds, top);
  16940.     };
  16941.     var getMaxYBounds = function (component) {
  16942.       var bounds = getBounds(component);
  16943.       return getBoundsProperty(bounds, bottom);
  16944.     };
  16945.     var getXScreenRange = function (component) {
  16946.       var bounds = getBounds(component);
  16947.       return getBoundsProperty(bounds, width);
  16948.     };
  16949.     var getYScreenRange = function (component) {
  16950.       var bounds = getBounds(component);
  16951.       return getBoundsProperty(bounds, height);
  16952.     };
  16953.     var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  16954.       return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  16955.     };
  16956.     var getXCenterOffSetOf = function (component, spectrum) {
  16957.       var componentBounds = getBounds(component);
  16958.       var spectrumBounds = getBounds(spectrum);
  16959.       var componentMinEdge = getBoundsProperty(componentBounds, left);
  16960.       var componentMaxEdge = getBoundsProperty(componentBounds, right);
  16961.       var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  16962.       return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  16963.     };
  16964.     var getYCenterOffSetOf = function (component, spectrum) {
  16965.       var componentBounds = getBounds(component);
  16966.       var spectrumBounds = getBounds(spectrum);
  16967.       var componentMinEdge = getBoundsProperty(componentBounds, top);
  16968.       var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  16969.       var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  16970.       return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  16971.     };
  16972.  
  16973.     var fireSliderChange$2 = function (spectrum, value) {
  16974.       emitWith(spectrum, sliderChangeEvent(), { value: value });
  16975.     };
  16976.     var sliderValue$2 = function (x) {
  16977.       return { x: x };
  16978.     };
  16979.     var findValueOfOffset$1 = function (spectrum, detail, left) {
  16980.       var args = {
  16981.         min: minX(detail),
  16982.         max: maxX(detail),
  16983.         range: xRange(detail),
  16984.         value: left,
  16985.         step: step(detail),
  16986.         snap: snap(detail),
  16987.         snapStart: snapStart(detail),
  16988.         rounded: rounded(detail),
  16989.         hasMinEdge: hasLEdge(detail),
  16990.         hasMaxEdge: hasREdge(detail),
  16991.         minBound: getMinXBounds(spectrum),
  16992.         maxBound: getMaxXBounds(spectrum),
  16993.         screenRange: getXScreenRange(spectrum)
  16994.       };
  16995.       return findValueOf(args);
  16996.     };
  16997.     var setValueFrom$2 = function (spectrum, detail, value) {
  16998.       var xValue = findValueOfOffset$1(spectrum, detail, value);
  16999.       var sliderVal = sliderValue$2(xValue);
  17000.       fireSliderChange$2(spectrum, sliderVal);
  17001.       return xValue;
  17002.     };
  17003.     var setToMin$2 = function (spectrum, detail) {
  17004.       var min = minX(detail);
  17005.       fireSliderChange$2(spectrum, sliderValue$2(min));
  17006.     };
  17007.     var setToMax$2 = function (spectrum, detail) {
  17008.       var max = maxX(detail);
  17009.       fireSliderChange$2(spectrum, sliderValue$2(max));
  17010.     };
  17011.     var moveBy$2 = function (direction, spectrum, detail) {
  17012.       var f = direction > 0 ? increaseBy : reduceBy;
  17013.       var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  17014.       fireSliderChange$2(spectrum, sliderValue$2(xValue));
  17015.       return Optional.some(xValue);
  17016.     };
  17017.     var handleMovement$2 = function (direction) {
  17018.       return function (spectrum, detail) {
  17019.         return moveBy$2(direction, spectrum, detail).map(always);
  17020.       };
  17021.     };
  17022.     var getValueFromEvent$2 = function (simulatedEvent) {
  17023.       var pos = getEventSource(simulatedEvent);
  17024.       return pos.map(function (p) {
  17025.         return p.left;
  17026.       });
  17027.     };
  17028.     var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  17029.       var minOffset = 0;
  17030.       var maxOffset = getXScreenRange(spectrum);
  17031.       var centerMinEdge = minEdge.bind(function (edge) {
  17032.         return Optional.some(getXCenterOffSetOf(edge, spectrum));
  17033.       }).getOr(minOffset);
  17034.       var centerMaxEdge = maxEdge.bind(function (edge) {
  17035.         return Optional.some(getXCenterOffSetOf(edge, spectrum));
  17036.       }).getOr(maxOffset);
  17037.       var args = {
  17038.         min: minX(detail),
  17039.         max: maxX(detail),
  17040.         range: xRange(detail),
  17041.         value: value,
  17042.         hasMinEdge: hasLEdge(detail),
  17043.         hasMaxEdge: hasREdge(detail),
  17044.         minBound: getMinXBounds(spectrum),
  17045.         minOffset: minOffset,
  17046.         maxBound: getMaxXBounds(spectrum),
  17047.         maxOffset: maxOffset,
  17048.         centerMinEdge: centerMinEdge,
  17049.         centerMaxEdge: centerMaxEdge
  17050.       };
  17051.       return findOffsetOfValue$2(args);
  17052.     };
  17053.     var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  17054.       var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  17055.       return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  17056.     };
  17057.     var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  17058.       var value = currentValue(detail);
  17059.       var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  17060.       var thumbRadius = get$a(thumb.element) / 2;
  17061.       set$7(thumb.element, 'left', pos - thumbRadius + 'px');
  17062.     };
  17063.     var onLeft$2 = handleMovement$2(-1);
  17064.     var onRight$2 = handleMovement$2(1);
  17065.     var onUp$2 = Optional.none;
  17066.     var onDown$2 = Optional.none;
  17067.     var edgeActions$2 = {
  17068.       'top-left': Optional.none(),
  17069.       'top': Optional.none(),
  17070.       'top-right': Optional.none(),
  17071.       'right': Optional.some(setToREdge),
  17072.       'bottom-right': Optional.none(),
  17073.       'bottom': Optional.none(),
  17074.       'bottom-left': Optional.none(),
  17075.       'left': Optional.some(setToLEdge)
  17076.     };
  17077.  
  17078.     var HorizontalModel = /*#__PURE__*/Object.freeze({
  17079.         __proto__: null,
  17080.         setValueFrom: setValueFrom$2,
  17081.         setToMin: setToMin$2,
  17082.         setToMax: setToMax$2,
  17083.         findValueOfOffset: findValueOfOffset$1,
  17084.         getValueFromEvent: getValueFromEvent$2,
  17085.         findPositionOfValue: findPositionOfValue$1,
  17086.         setPositionFromValue: setPositionFromValue$2,
  17087.         onLeft: onLeft$2,
  17088.         onRight: onRight$2,
  17089.         onUp: onUp$2,
  17090.         onDown: onDown$2,
  17091.         edgeActions: edgeActions$2
  17092.     });
  17093.  
  17094.     var fireSliderChange$1 = function (spectrum, value) {
  17095.       emitWith(spectrum, sliderChangeEvent(), { value: value });
  17096.     };
  17097.     var sliderValue$1 = function (y) {
  17098.       return { y: y };
  17099.     };
  17100.     var findValueOfOffset = function (spectrum, detail, top) {
  17101.       var args = {
  17102.         min: minY(detail),
  17103.         max: maxY(detail),
  17104.         range: yRange(detail),
  17105.         value: top,
  17106.         step: step(detail),
  17107.         snap: snap(detail),
  17108.         snapStart: snapStart(detail),
  17109.         rounded: rounded(detail),
  17110.         hasMinEdge: hasTEdge(detail),
  17111.         hasMaxEdge: hasBEdge(detail),
  17112.         minBound: getMinYBounds(spectrum),
  17113.         maxBound: getMaxYBounds(spectrum),
  17114.         screenRange: getYScreenRange(spectrum)
  17115.       };
  17116.       return findValueOf(args);
  17117.     };
  17118.     var setValueFrom$1 = function (spectrum, detail, value) {
  17119.       var yValue = findValueOfOffset(spectrum, detail, value);
  17120.       var sliderVal = sliderValue$1(yValue);
  17121.       fireSliderChange$1(spectrum, sliderVal);
  17122.       return yValue;
  17123.     };
  17124.     var setToMin$1 = function (spectrum, detail) {
  17125.       var min = minY(detail);
  17126.       fireSliderChange$1(spectrum, sliderValue$1(min));
  17127.     };
  17128.     var setToMax$1 = function (spectrum, detail) {
  17129.       var max = maxY(detail);
  17130.       fireSliderChange$1(spectrum, sliderValue$1(max));
  17131.     };
  17132.     var moveBy$1 = function (direction, spectrum, detail) {
  17133.       var f = direction > 0 ? increaseBy : reduceBy;
  17134.       var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  17135.       fireSliderChange$1(spectrum, sliderValue$1(yValue));
  17136.       return Optional.some(yValue);
  17137.     };
  17138.     var handleMovement$1 = function (direction) {
  17139.       return function (spectrum, detail) {
  17140.         return moveBy$1(direction, spectrum, detail).map(always);
  17141.       };
  17142.     };
  17143.     var getValueFromEvent$1 = function (simulatedEvent) {
  17144.       var pos = getEventSource(simulatedEvent);
  17145.       return pos.map(function (p) {
  17146.         return p.top;
  17147.       });
  17148.     };
  17149.     var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  17150.       var minOffset = 0;
  17151.       var maxOffset = getYScreenRange(spectrum);
  17152.       var centerMinEdge = minEdge.bind(function (edge) {
  17153.         return Optional.some(getYCenterOffSetOf(edge, spectrum));
  17154.       }).getOr(minOffset);
  17155.       var centerMaxEdge = maxEdge.bind(function (edge) {
  17156.         return Optional.some(getYCenterOffSetOf(edge, spectrum));
  17157.       }).getOr(maxOffset);
  17158.       var args = {
  17159.         min: minY(detail),
  17160.         max: maxY(detail),
  17161.         range: yRange(detail),
  17162.         value: value,
  17163.         hasMinEdge: hasTEdge(detail),
  17164.         hasMaxEdge: hasBEdge(detail),
  17165.         minBound: getMinYBounds(spectrum),
  17166.         minOffset: minOffset,
  17167.         maxBound: getMaxYBounds(spectrum),
  17168.         maxOffset: maxOffset,
  17169.         centerMinEdge: centerMinEdge,
  17170.         centerMaxEdge: centerMaxEdge
  17171.       };
  17172.       return findOffsetOfValue$2(args);
  17173.     };
  17174.     var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  17175.       var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  17176.       return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  17177.     };
  17178.     var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  17179.       var value = currentValue(detail);
  17180.       var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  17181.       var thumbRadius = get$b(thumb.element) / 2;
  17182.       set$7(thumb.element, 'top', pos - thumbRadius + 'px');
  17183.     };
  17184.     var onLeft$1 = Optional.none;
  17185.     var onRight$1 = Optional.none;
  17186.     var onUp$1 = handleMovement$1(-1);
  17187.     var onDown$1 = handleMovement$1(1);
  17188.     var edgeActions$1 = {
  17189.       'top-left': Optional.none(),
  17190.       'top': Optional.some(setToTEdge),
  17191.       'top-right': Optional.none(),
  17192.       'right': Optional.none(),
  17193.       'bottom-right': Optional.none(),
  17194.       'bottom': Optional.some(setToBEdge),
  17195.       'bottom-left': Optional.none(),
  17196.       'left': Optional.none()
  17197.     };
  17198.  
  17199.     var VerticalModel = /*#__PURE__*/Object.freeze({
  17200.         __proto__: null,
  17201.         setValueFrom: setValueFrom$1,
  17202.         setToMin: setToMin$1,
  17203.         setToMax: setToMax$1,
  17204.         findValueOfOffset: findValueOfOffset,
  17205.         getValueFromEvent: getValueFromEvent$1,
  17206.         findPositionOfValue: findPositionOfValue,
  17207.         setPositionFromValue: setPositionFromValue$1,
  17208.         onLeft: onLeft$1,
  17209.         onRight: onRight$1,
  17210.         onUp: onUp$1,
  17211.         onDown: onDown$1,
  17212.         edgeActions: edgeActions$1
  17213.     });
  17214.  
  17215.     var fireSliderChange = function (spectrum, value) {
  17216.       emitWith(spectrum, sliderChangeEvent(), { value: value });
  17217.     };
  17218.     var sliderValue = function (x, y) {
  17219.       return {
  17220.         x: x,
  17221.         y: y
  17222.       };
  17223.     };
  17224.     var setValueFrom = function (spectrum, detail, value) {
  17225.       var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  17226.       var yValue = findValueOfOffset(spectrum, detail, value.top);
  17227.       var val = sliderValue(xValue, yValue);
  17228.       fireSliderChange(spectrum, val);
  17229.       return val;
  17230.     };
  17231.     var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  17232.       var f = direction > 0 ? increaseBy : reduceBy;
  17233.       var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  17234.       var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  17235.       fireSliderChange(spectrum, sliderValue(xValue, yValue));
  17236.       return Optional.some(xValue);
  17237.     };
  17238.     var handleMovement = function (direction, isVerticalMovement) {
  17239.       return function (spectrum, detail) {
  17240.         return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  17241.       };
  17242.     };
  17243.     var setToMin = function (spectrum, detail) {
  17244.       var mX = minX(detail);
  17245.       var mY = minY(detail);
  17246.       fireSliderChange(spectrum, sliderValue(mX, mY));
  17247.     };
  17248.     var setToMax = function (spectrum, detail) {
  17249.       var mX = maxX(detail);
  17250.       var mY = maxY(detail);
  17251.       fireSliderChange(spectrum, sliderValue(mX, mY));
  17252.     };
  17253.     var getValueFromEvent = function (simulatedEvent) {
  17254.       return getEventSource(simulatedEvent);
  17255.     };
  17256.     var setPositionFromValue = function (slider, thumb, detail, edges) {
  17257.       var value = currentValue(detail);
  17258.       var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  17259.       var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  17260.       var thumbXRadius = get$a(thumb.element) / 2;
  17261.       var thumbYRadius = get$b(thumb.element) / 2;
  17262.       set$7(thumb.element, 'left', xPos - thumbXRadius + 'px');
  17263.       set$7(thumb.element, 'top', yPos - thumbYRadius + 'px');
  17264.     };
  17265.     var onLeft = handleMovement(-1, false);
  17266.     var onRight = handleMovement(1, false);
  17267.     var onUp = handleMovement(-1, true);
  17268.     var onDown = handleMovement(1, true);
  17269.     var edgeActions = {
  17270.       'top-left': Optional.some(setToTLEdgeXY),
  17271.       'top': Optional.some(setToTEdgeXY),
  17272.       'top-right': Optional.some(setToTREdgeXY),
  17273.       'right': Optional.some(setToREdgeXY),
  17274.       'bottom-right': Optional.some(setToBREdgeXY),
  17275.       'bottom': Optional.some(setToBEdgeXY),
  17276.       'bottom-left': Optional.some(setToBLEdgeXY),
  17277.       'left': Optional.some(setToLEdgeXY)
  17278.     };
  17279.  
  17280.     var TwoDModel = /*#__PURE__*/Object.freeze({
  17281.         __proto__: null,
  17282.         setValueFrom: setValueFrom,
  17283.         setToMin: setToMin,
  17284.         setToMax: setToMax,
  17285.         getValueFromEvent: getValueFromEvent,
  17286.         setPositionFromValue: setPositionFromValue,
  17287.         onLeft: onLeft,
  17288.         onRight: onRight,
  17289.         onUp: onUp,
  17290.         onDown: onDown,
  17291.         edgeActions: edgeActions
  17292.     });
  17293.  
  17294.     var SliderSchema = [
  17295.       defaulted('stepSize', 1),
  17296.       defaulted('onChange', noop),
  17297.       defaulted('onChoose', noop),
  17298.       defaulted('onInit', noop),
  17299.       defaulted('onDragStart', noop),
  17300.       defaulted('onDragEnd', noop),
  17301.       defaulted('snapToGrid', false),
  17302.       defaulted('rounded', true),
  17303.       option('snapStart'),
  17304.       requiredOf('model', choose$1('mode', {
  17305.         x: [
  17306.           defaulted('minX', 0),
  17307.           defaulted('maxX', 100),
  17308.           customField('value', function (spec) {
  17309.             return Cell(spec.mode.minX);
  17310.           }),
  17311.           required$1('getInitialValue'),
  17312.           output$1('manager', HorizontalModel)
  17313.         ],
  17314.         y: [
  17315.           defaulted('minY', 0),
  17316.           defaulted('maxY', 100),
  17317.           customField('value', function (spec) {
  17318.             return Cell(spec.mode.minY);
  17319.           }),
  17320.           required$1('getInitialValue'),
  17321.           output$1('manager', VerticalModel)
  17322.         ],
  17323.         xy: [
  17324.           defaulted('minX', 0),
  17325.           defaulted('maxX', 100),
  17326.           defaulted('minY', 0),
  17327.           defaulted('maxY', 100),
  17328.           customField('value', function (spec) {
  17329.             return Cell({
  17330.               x: spec.mode.minX,
  17331.               y: spec.mode.minY
  17332.             });
  17333.           }),
  17334.           required$1('getInitialValue'),
  17335.           output$1('manager', TwoDModel)
  17336.         ]
  17337.       })),
  17338.       field('sliderBehaviours', [
  17339.         Keying,
  17340.         Representing
  17341.       ]),
  17342.       customField('mouseIsDown', function () {
  17343.         return Cell(false);
  17344.       })
  17345.     ];
  17346.  
  17347.     var sketch$2 = function (detail, components, _spec, _externals) {
  17348.       var _a;
  17349.       var getThumb = function (component) {
  17350.         return getPartOrDie(component, detail, 'thumb');
  17351.       };
  17352.       var getSpectrum = function (component) {
  17353.         return getPartOrDie(component, detail, 'spectrum');
  17354.       };
  17355.       var getLeftEdge = function (component) {
  17356.         return getPart(component, detail, 'left-edge');
  17357.       };
  17358.       var getRightEdge = function (component) {
  17359.         return getPart(component, detail, 'right-edge');
  17360.       };
  17361.       var getTopEdge = function (component) {
  17362.         return getPart(component, detail, 'top-edge');
  17363.       };
  17364.       var getBottomEdge = function (component) {
  17365.         return getPart(component, detail, 'bottom-edge');
  17366.       };
  17367.       var modelDetail = detail.model;
  17368.       var model = modelDetail.manager;
  17369.       var refresh = function (slider, thumb) {
  17370.         model.setPositionFromValue(slider, thumb, detail, {
  17371.           getLeftEdge: getLeftEdge,
  17372.           getRightEdge: getRightEdge,
  17373.           getTopEdge: getTopEdge,
  17374.           getBottomEdge: getBottomEdge,
  17375.           getSpectrum: getSpectrum
  17376.         });
  17377.       };
  17378.       var setValue = function (slider, newValue) {
  17379.         modelDetail.value.set(newValue);
  17380.         var thumb = getThumb(slider);
  17381.         refresh(slider, thumb);
  17382.       };
  17383.       var changeValue = function (slider, newValue) {
  17384.         setValue(slider, newValue);
  17385.         var thumb = getThumb(slider);
  17386.         detail.onChange(slider, thumb, newValue);
  17387.         return Optional.some(true);
  17388.       };
  17389.       var resetToMin = function (slider) {
  17390.         model.setToMin(slider, detail);
  17391.       };
  17392.       var resetToMax = function (slider) {
  17393.         model.setToMax(slider, detail);
  17394.       };
  17395.       var choose = function (slider) {
  17396.         var fireOnChoose = function () {
  17397.           getPart(slider, detail, 'thumb').each(function (thumb) {
  17398.             var value = modelDetail.value.get();
  17399.             detail.onChoose(slider, thumb, value);
  17400.           });
  17401.         };
  17402.         var wasDown = detail.mouseIsDown.get();
  17403.         detail.mouseIsDown.set(false);
  17404.         if (wasDown) {
  17405.           fireOnChoose();
  17406.         }
  17407.       };
  17408.       var onDragStart = function (slider, simulatedEvent) {
  17409.         simulatedEvent.stop();
  17410.         detail.mouseIsDown.set(true);
  17411.         detail.onDragStart(slider, getThumb(slider));
  17412.       };
  17413.       var onDragEnd = function (slider, simulatedEvent) {
  17414.         simulatedEvent.stop();
  17415.         detail.onDragEnd(slider, getThumb(slider));
  17416.         choose(slider);
  17417.       };
  17418.       return {
  17419.         uid: detail.uid,
  17420.         dom: detail.dom,
  17421.         components: components,
  17422.         behaviours: augment(detail.sliderBehaviours, [
  17423.           Keying.config({
  17424.             mode: 'special',
  17425.             focusIn: function (slider) {
  17426.               return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  17427.             }
  17428.           }),
  17429.           Representing.config({
  17430.             store: {
  17431.               mode: 'manual',
  17432.               getValue: function (_) {
  17433.                 return modelDetail.value.get();
  17434.               }
  17435.             }
  17436.           }),
  17437.           Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  17438.         ]),
  17439.         events: derive$2([
  17440.           run$1(sliderChangeEvent(), function (slider, simulatedEvent) {
  17441.             changeValue(slider, simulatedEvent.event.value);
  17442.           }),
  17443.           runOnAttached(function (slider, _simulatedEvent) {
  17444.             var getInitial = modelDetail.getInitialValue();
  17445.             modelDetail.value.set(getInitial);
  17446.             var thumb = getThumb(slider);
  17447.             refresh(slider, thumb);
  17448.             var spectrum = getSpectrum(slider);
  17449.             detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  17450.           }),
  17451.           run$1(touchstart(), onDragStart),
  17452.           run$1(touchend(), onDragEnd),
  17453.           run$1(mousedown(), onDragStart),
  17454.           run$1(mouseup(), onDragEnd)
  17455.         ]),
  17456.         apis: {
  17457.           resetToMin: resetToMin,
  17458.           resetToMax: resetToMax,
  17459.           setValue: setValue,
  17460.           refresh: refresh
  17461.         },
  17462.         domModification: { styles: { position: 'relative' } }
  17463.       };
  17464.     };
  17465.  
  17466.     var Slider = composite({
  17467.       name: 'Slider',
  17468.       configFields: SliderSchema,
  17469.       partFields: SliderParts,
  17470.       factory: sketch$2,
  17471.       apis: {
  17472.         setValue: function (apis, slider, value) {
  17473.           apis.setValue(slider, value);
  17474.         },
  17475.         resetToMin: function (apis, slider) {
  17476.           apis.resetToMin(slider);
  17477.         },
  17478.         resetToMax: function (apis, slider) {
  17479.           apis.resetToMax(slider);
  17480.         },
  17481.         refresh: function (apis, slider) {
  17482.           apis.refresh(slider);
  17483.         }
  17484.       }
  17485.     });
  17486.  
  17487.     var fieldsUpdate = generate$6('rgb-hex-update');
  17488.     var sliderUpdate = generate$6('slider-update');
  17489.     var paletteUpdate = generate$6('palette-update');
  17490.  
  17491.     var sliderFactory = function (translate, getClass) {
  17492.       var spectrum = Slider.parts.spectrum({
  17493.         dom: {
  17494.           tag: 'div',
  17495.           classes: [getClass('hue-slider-spectrum')],
  17496.           attributes: { role: 'presentation' }
  17497.         }
  17498.       });
  17499.       var thumb = Slider.parts.thumb({
  17500.         dom: {
  17501.           tag: 'div',
  17502.           classes: [getClass('hue-slider-thumb')],
  17503.           attributes: { role: 'presentation' }
  17504.         }
  17505.       });
  17506.       return Slider.sketch({
  17507.         dom: {
  17508.           tag: 'div',
  17509.           classes: [getClass('hue-slider')],
  17510.           attributes: { role: 'presentation' }
  17511.         },
  17512.         rounded: false,
  17513.         model: {
  17514.           mode: 'y',
  17515.           getInitialValue: constant$1({ y: 0 })
  17516.         },
  17517.         components: [
  17518.           spectrum,
  17519.           thumb
  17520.         ],
  17521.         sliderBehaviours: derive$1([Focusing.config({})]),
  17522.         onChange: function (slider, _thumb, value) {
  17523.           emitWith(slider, sliderUpdate, { value: value });
  17524.         }
  17525.       });
  17526.     };
  17527.  
  17528.     var owner$1 = 'form';
  17529.     var schema$i = [field('formBehaviours', [Representing])];
  17530.     var getPartName$1 = function (name) {
  17531.       return '<alloy.field.' + name + '>';
  17532.     };
  17533.     var sketch$1 = function (fSpec) {
  17534.       var parts = function () {
  17535.         var record = [];
  17536.         var field = function (name, config) {
  17537.           record.push(name);
  17538.           return generateOne$1(owner$1, getPartName$1(name), config);
  17539.         };
  17540.         return {
  17541.           field: field,
  17542.           record: constant$1(record)
  17543.         };
  17544.       }();
  17545.       var spec = fSpec(parts);
  17546.       var partNames = parts.record();
  17547.       var fieldParts = map$2(partNames, function (n) {
  17548.         return required({
  17549.           name: n,
  17550.           pname: getPartName$1(n)
  17551.         });
  17552.       });
  17553.       return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
  17554.     };
  17555.     var toResult = function (o, e) {
  17556.       return o.fold(function () {
  17557.         return Result.error(e);
  17558.       }, Result.value);
  17559.     };
  17560.     var make$4 = function (detail, components) {
  17561.       return {
  17562.         uid: detail.uid,
  17563.         dom: detail.dom,
  17564.         components: components,
  17565.         behaviours: augment(detail.formBehaviours, [Representing.config({
  17566.             store: {
  17567.               mode: 'manual',
  17568.               getValue: function (form) {
  17569.                 var resPs = getAllParts(form, detail);
  17570.                 return map$1(resPs, function (resPThunk, pName) {
  17571.                   return resPThunk().bind(function (v) {
  17572.                     var opt = Composing.getCurrent(v);
  17573.                     return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  17574.                   }).map(Representing.getValue);
  17575.                 });
  17576.               },
  17577.               setValue: function (form, values) {
  17578.                 each(values, function (newValue, key) {
  17579.                   getPart(form, detail, key).each(function (wrapper) {
  17580.                     Composing.getCurrent(wrapper).each(function (field) {
  17581.                       Representing.setValue(field, newValue);
  17582.                     });
  17583.                   });
  17584.                 });
  17585.               }
  17586.             }
  17587.           })]),
  17588.         apis: {
  17589.           getField: function (form, key) {
  17590.             return getPart(form, detail, key).bind(Composing.getCurrent);
  17591.           }
  17592.         }
  17593.       };
  17594.     };
  17595.     var Form = {
  17596.       getField: makeApi(function (apis, component, key) {
  17597.         return apis.getField(component, key);
  17598.       }),
  17599.       sketch: sketch$1
  17600.     };
  17601.  
  17602.     var validInput = generate$6('valid-input');
  17603.     var invalidInput = generate$6('invalid-input');
  17604.     var validatingInput = generate$6('validating-input');
  17605.     var translatePrefix = 'colorcustom.rgb.';
  17606.     var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  17607.       var invalidation = function (label, isValid) {
  17608.         return Invalidating.config({
  17609.           invalidClass: getClass('invalid'),
  17610.           notify: {
  17611.             onValidate: function (comp) {
  17612.               emitWith(comp, validatingInput, { type: label });
  17613.             },
  17614.             onValid: function (comp) {
  17615.               emitWith(comp, validInput, {
  17616.                 type: label,
  17617.                 value: Representing.getValue(comp)
  17618.               });
  17619.             },
  17620.             onInvalid: function (comp) {
  17621.               emitWith(comp, invalidInput, {
  17622.                 type: label,
  17623.                 value: Representing.getValue(comp)
  17624.               });
  17625.             }
  17626.           },
  17627.           validator: {
  17628.             validate: function (comp) {
  17629.               var value = Representing.getValue(comp);
  17630.               var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  17631.               return Future.pure(res);
  17632.             },
  17633.             validateOnLoad: false
  17634.           }
  17635.         });
  17636.       };
  17637.       var renderTextField = function (isValid, name, label, description, data) {
  17638.         var helptext = translate(translatePrefix + 'range');
  17639.         var pLabel = FormField.parts.label({
  17640.           dom: {
  17641.             tag: 'label',
  17642.             innerHtml: label,
  17643.             attributes: { 'aria-label': description }
  17644.           }
  17645.         });
  17646.         var pField = FormField.parts.field({
  17647.           data: data,
  17648.           factory: Input,
  17649.           inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  17650.           inputClasses: [getClass('textfield')],
  17651.           inputBehaviours: derive$1([
  17652.             invalidation(name, isValid),
  17653.             Tabstopping.config({})
  17654.           ]),
  17655.           onSetValue: function (input) {
  17656.             if (Invalidating.isInvalid(input)) {
  17657.               var run = Invalidating.run(input);
  17658.               run.get(noop);
  17659.             }
  17660.           }
  17661.         });
  17662.         var comps = [
  17663.           pLabel,
  17664.           pField
  17665.         ];
  17666.         var concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : [];
  17667.         var components = comps.concat(concats);
  17668.         return {
  17669.           dom: {
  17670.             tag: 'div',
  17671.             attributes: { role: 'presentation' }
  17672.           },
  17673.           components: components
  17674.         };
  17675.       };
  17676.       var copyRgbToHex = function (form, rgba) {
  17677.         var hex = fromRgba(rgba);
  17678.         Form.getField(form, 'hex').each(function (hexField) {
  17679.           if (!Focusing.isFocused(hexField)) {
  17680.             Representing.setValue(form, { hex: hex.value });
  17681.           }
  17682.         });
  17683.         return hex;
  17684.       };
  17685.       var copyRgbToForm = function (form, rgb) {
  17686.         var red = rgb.red;
  17687.         var green = rgb.green;
  17688.         var blue = rgb.blue;
  17689.         Representing.setValue(form, {
  17690.           red: red,
  17691.           green: green,
  17692.           blue: blue
  17693.         });
  17694.       };
  17695.       var memPreview = record({
  17696.         dom: {
  17697.           tag: 'div',
  17698.           classes: [getClass('rgba-preview')],
  17699.           styles: { 'background-color': 'white' },
  17700.           attributes: { role: 'presentation' }
  17701.         }
  17702.       });
  17703.       var updatePreview = function (anyInSystem, hex) {
  17704.         memPreview.getOpt(anyInSystem).each(function (preview) {
  17705.           set$7(preview.element, 'background-color', '#' + hex.value);
  17706.         });
  17707.       };
  17708.       var factory = function () {
  17709.         var state = {
  17710.           red: Cell(Optional.some(255)),
  17711.           green: Cell(Optional.some(255)),
  17712.           blue: Cell(Optional.some(255)),
  17713.           hex: Cell(Optional.some('ffffff'))
  17714.         };
  17715.         var copyHexToRgb = function (form, hex) {
  17716.           var rgb = fromHex(hex);
  17717.           copyRgbToForm(form, rgb);
  17718.           setValueRgb(rgb);
  17719.         };
  17720.         var get = function (prop) {
  17721.           return state[prop].get();
  17722.         };
  17723.         var set = function (prop, value) {
  17724.           state[prop].set(value);
  17725.         };
  17726.         var getValueRgb = function () {
  17727.           return get('red').bind(function (red) {
  17728.             return get('green').bind(function (green) {
  17729.               return get('blue').map(function (blue) {
  17730.                 return rgbaColour(red, green, blue, 1);
  17731.               });
  17732.             });
  17733.           });
  17734.         };
  17735.         var setValueRgb = function (rgb) {
  17736.           var red = rgb.red;
  17737.           var green = rgb.green;
  17738.           var blue = rgb.blue;
  17739.           set('red', Optional.some(red));
  17740.           set('green', Optional.some(green));
  17741.           set('blue', Optional.some(blue));
  17742.         };
  17743.         var onInvalidInput = function (form, simulatedEvent) {
  17744.           var data = simulatedEvent.event;
  17745.           if (data.type !== 'hex') {
  17746.             set(data.type, Optional.none());
  17747.           } else {
  17748.             onInvalidHexx(form);
  17749.           }
  17750.         };
  17751.         var onValidHex = function (form, value) {
  17752.           onValidHexx(form);
  17753.           var hex = hexColour(value);
  17754.           set('hex', Optional.some(value));
  17755.           var rgb = fromHex(hex);
  17756.           copyRgbToForm(form, rgb);
  17757.           setValueRgb(rgb);
  17758.           emitWith(form, fieldsUpdate, { hex: hex });
  17759.           updatePreview(form, hex);
  17760.         };
  17761.         var onValidRgb = function (form, prop, value) {
  17762.           var val = parseInt(value, 10);
  17763.           set(prop, Optional.some(val));
  17764.           getValueRgb().each(function (rgb) {
  17765.             var hex = copyRgbToHex(form, rgb);
  17766.             emitWith(form, fieldsUpdate, { hex: hex });
  17767.             updatePreview(form, hex);
  17768.           });
  17769.         };
  17770.         var isHexInputEvent = function (data) {
  17771.           return data.type === 'hex';
  17772.         };
  17773.         var onValidInput = function (form, simulatedEvent) {
  17774.           var data = simulatedEvent.event;
  17775.           if (isHexInputEvent(data)) {
  17776.             onValidHex(form, data.value);
  17777.           } else {
  17778.             onValidRgb(form, data.type, data.value);
  17779.           }
  17780.         };
  17781.         var formPartStrings = function (key) {
  17782.           return {
  17783.             label: translate(translatePrefix + key + '.label'),
  17784.             description: translate(translatePrefix + key + '.description')
  17785.           };
  17786.         };
  17787.         var redStrings = formPartStrings('red');
  17788.         var greenStrings = formPartStrings('green');
  17789.         var blueStrings = formPartStrings('blue');
  17790.         var hexStrings = formPartStrings('hex');
  17791.         return deepMerge(Form.sketch(function (parts) {
  17792.           return {
  17793.             dom: {
  17794.               tag: 'form',
  17795.               classes: [getClass('rgb-form')],
  17796.               attributes: { 'aria-label': translate('aria.color.picker') }
  17797.             },
  17798.             components: [
  17799.               parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  17800.               parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  17801.               parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  17802.               parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  17803.               memPreview.asSpec()
  17804.             ],
  17805.             formBehaviours: derive$1([
  17806.               Invalidating.config({ invalidClass: getClass('form-invalid') }),
  17807.               config('rgb-form-events', [
  17808.                 run$1(validInput, onValidInput),
  17809.                 run$1(invalidInput, onInvalidInput),
  17810.                 run$1(validatingInput, onInvalidInput)
  17811.               ])
  17812.             ])
  17813.           };
  17814.         }), {
  17815.           apis: {
  17816.             updateHex: function (form, hex) {
  17817.               Representing.setValue(form, { hex: hex.value });
  17818.               copyHexToRgb(form, hex);
  17819.               updatePreview(form, hex);
  17820.             }
  17821.           }
  17822.         });
  17823.       };
  17824.       var rgbFormSketcher = single({
  17825.         factory: factory,
  17826.         name: 'RgbForm',
  17827.         configFields: [],
  17828.         apis: {
  17829.           updateHex: function (apis, form, hex) {
  17830.             apis.updateHex(form, hex);
  17831.           }
  17832.         },
  17833.         extraApis: {}
  17834.       });
  17835.       return rgbFormSketcher;
  17836.     };
  17837.  
  17838.     var paletteFactory = function (_translate, getClass) {
  17839.       var spectrumPart = Slider.parts.spectrum({
  17840.         dom: {
  17841.           tag: 'canvas',
  17842.           attributes: { role: 'presentation' },
  17843.           classes: [getClass('sv-palette-spectrum')]
  17844.         }
  17845.       });
  17846.       var thumbPart = Slider.parts.thumb({
  17847.         dom: {
  17848.           tag: 'div',
  17849.           attributes: { role: 'presentation' },
  17850.           classes: [getClass('sv-palette-thumb')],
  17851.           innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  17852.         }
  17853.       });
  17854.       var setColour = function (canvas, rgba) {
  17855.         var width = canvas.width, height = canvas.height;
  17856.         var ctx = canvas.getContext('2d');
  17857.         if (ctx === null) {
  17858.           return;
  17859.         }
  17860.         ctx.fillStyle = rgba;
  17861.         ctx.fillRect(0, 0, width, height);
  17862.         var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  17863.         grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  17864.         grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  17865.         ctx.fillStyle = grdWhite;
  17866.         ctx.fillRect(0, 0, width, height);
  17867.         var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  17868.         grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  17869.         grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  17870.         ctx.fillStyle = grdBlack;
  17871.         ctx.fillRect(0, 0, width, height);
  17872.       };
  17873.       var setPaletteHue = function (slider, hue) {
  17874.         var canvas = slider.components()[0].element.dom;
  17875.         var hsv = hsvColour(hue, 100, 100);
  17876.         var rgba = fromHsv(hsv);
  17877.         setColour(canvas, toString(rgba));
  17878.       };
  17879.       var setPaletteThumb = function (slider, hex) {
  17880.         var hsv = fromRgb(fromHex(hex));
  17881.         Slider.setValue(slider, {
  17882.           x: hsv.saturation,
  17883.           y: 100 - hsv.value
  17884.         });
  17885.       };
  17886.       var factory = function (_detail) {
  17887.         var getInitialValue = constant$1({
  17888.           x: 0,
  17889.           y: 0
  17890.         });
  17891.         var onChange = function (slider, _thumb, value) {
  17892.           emitWith(slider, paletteUpdate, { value: value });
  17893.         };
  17894.         var onInit = function (_slider, _thumb, spectrum, _value) {
  17895.           setColour(spectrum.element.dom, toString(red));
  17896.         };
  17897.         var sliderBehaviours = derive$1([
  17898.           Composing.config({ find: Optional.some }),
  17899.           Focusing.config({})
  17900.         ]);
  17901.         return Slider.sketch({
  17902.           dom: {
  17903.             tag: 'div',
  17904.             attributes: { role: 'presentation' },
  17905.             classes: [getClass('sv-palette')]
  17906.           },
  17907.           model: {
  17908.             mode: 'xy',
  17909.             getInitialValue: getInitialValue
  17910.           },
  17911.           rounded: false,
  17912.           components: [
  17913.             spectrumPart,
  17914.             thumbPart
  17915.           ],
  17916.           onChange: onChange,
  17917.           onInit: onInit,
  17918.           sliderBehaviours: sliderBehaviours
  17919.         });
  17920.       };
  17921.       var saturationBrightnessPaletteSketcher = single({
  17922.         factory: factory,
  17923.         name: 'SaturationBrightnessPalette',
  17924.         configFields: [],
  17925.         apis: {
  17926.           setHue: function (_apis, slider, hue) {
  17927.             setPaletteHue(slider, hue);
  17928.           },
  17929.           setThumb: function (_apis, slider, hex) {
  17930.             setPaletteThumb(slider, hex);
  17931.           }
  17932.         },
  17933.         extraApis: {}
  17934.       });
  17935.       return saturationBrightnessPaletteSketcher;
  17936.     };
  17937.  
  17938.     var makeFactory = function (translate, getClass) {
  17939.       var factory = function (detail) {
  17940.         var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  17941.         var sbPalette = paletteFactory(translate, getClass);
  17942.         var hueSliderToDegrees = function (hue) {
  17943.           return (100 - hue) / 100 * 360;
  17944.         };
  17945.         var hueDegreesToSlider = function (hue) {
  17946.           return 100 - hue / 360 * 100;
  17947.         };
  17948.         var state = {
  17949.           paletteRgba: Cell(red),
  17950.           paletteHue: Cell(0)
  17951.         };
  17952.         var memSlider = record(sliderFactory(translate, getClass));
  17953.         var memPalette = record(sbPalette.sketch({}));
  17954.         var memRgb = record(rgbForm.sketch({}));
  17955.         var updatePalette = function (anyInSystem, _hex, hue) {
  17956.           memPalette.getOpt(anyInSystem).each(function (palette) {
  17957.             sbPalette.setHue(palette, hue);
  17958.           });
  17959.         };
  17960.         var updateFields = function (anyInSystem, hex) {
  17961.           memRgb.getOpt(anyInSystem).each(function (form) {
  17962.             rgbForm.updateHex(form, hex);
  17963.           });
  17964.         };
  17965.         var updateSlider = function (anyInSystem, _hex, hue) {
  17966.           memSlider.getOpt(anyInSystem).each(function (slider) {
  17967.             Slider.setValue(slider, { y: hueDegreesToSlider(hue) });
  17968.           });
  17969.         };
  17970.         var updatePaletteThumb = function (anyInSystem, hex) {
  17971.           memPalette.getOpt(anyInSystem).each(function (palette) {
  17972.             sbPalette.setThumb(palette, hex);
  17973.           });
  17974.         };
  17975.         var updateState = function (hex, hue) {
  17976.           var rgba = fromHex(hex);
  17977.           state.paletteRgba.set(rgba);
  17978.           state.paletteHue.set(hue);
  17979.         };
  17980.         var runUpdates = function (anyInSystem, hex, hue, updates) {
  17981.           updateState(hex, hue);
  17982.           each$1(updates, function (update) {
  17983.             update(anyInSystem, hex, hue);
  17984.           });
  17985.         };
  17986.         var onPaletteUpdate = function () {
  17987.           var updates = [updateFields];
  17988.           return function (form, simulatedEvent) {
  17989.             var value = simulatedEvent.event.value;
  17990.             var oldHue = state.paletteHue.get();
  17991.             var newHsv = hsvColour(oldHue, value.x, 100 - value.y);
  17992.             var newHex = hsvToHex(newHsv);
  17993.             runUpdates(form, newHex, oldHue, updates);
  17994.           };
  17995.         };
  17996.         var onSliderUpdate = function () {
  17997.           var updates = [
  17998.             updatePalette,
  17999.             updateFields
  18000.           ];
  18001.           return function (form, simulatedEvent) {
  18002.             var hue = hueSliderToDegrees(simulatedEvent.event.value.y);
  18003.             var oldRgb = state.paletteRgba.get();
  18004.             var oldHsv = fromRgb(oldRgb);
  18005.             var newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value);
  18006.             var newHex = hsvToHex(newHsv);
  18007.             runUpdates(form, newHex, hue, updates);
  18008.           };
  18009.         };
  18010.         var onFieldsUpdate = function () {
  18011.           var updates = [
  18012.             updatePalette,
  18013.             updateSlider,
  18014.             updatePaletteThumb
  18015.           ];
  18016.           return function (form, simulatedEvent) {
  18017.             var hex = simulatedEvent.event.hex;
  18018.             var hsv = hexToHsv(hex);
  18019.             runUpdates(form, hex, hsv.hue, updates);
  18020.           };
  18021.         };
  18022.         return {
  18023.           uid: detail.uid,
  18024.           dom: detail.dom,
  18025.           components: [
  18026.             memPalette.asSpec(),
  18027.             memSlider.asSpec(),
  18028.             memRgb.asSpec()
  18029.           ],
  18030.           behaviours: derive$1([
  18031.             config('colour-picker-events', [
  18032.               run$1(fieldsUpdate, onFieldsUpdate()),
  18033.               run$1(paletteUpdate, onPaletteUpdate()),
  18034.               run$1(sliderUpdate, onSliderUpdate())
  18035.             ]),
  18036.             Composing.config({
  18037.               find: function (comp) {
  18038.                 return memRgb.getOpt(comp);
  18039.               }
  18040.             }),
  18041.             Keying.config({ mode: 'acyclic' })
  18042.           ])
  18043.         };
  18044.       };
  18045.       var colourPickerSketcher = single({
  18046.         name: 'ColourPicker',
  18047.         configFields: [
  18048.           required$1('dom'),
  18049.           defaulted('onValidHex', noop),
  18050.           defaulted('onInvalidHex', noop)
  18051.         ],
  18052.         factory: factory
  18053.       });
  18054.       return colourPickerSketcher;
  18055.     };
  18056.  
  18057.     var self$1 = function () {
  18058.       return Composing.config({ find: Optional.some });
  18059.     };
  18060.     var memento$1 = function (mem) {
  18061.       return Composing.config({ find: mem.getOpt });
  18062.     };
  18063.     var childAt = function (index) {
  18064.       return Composing.config({
  18065.         find: function (comp) {
  18066.           return child$2(comp.element, index).bind(function (element) {
  18067.             return comp.getSystem().getByDom(element).toOptional();
  18068.           });
  18069.         }
  18070.       });
  18071.     };
  18072.     var ComposingConfigs = {
  18073.       self: self$1,
  18074.       memento: memento$1,
  18075.       childAt: childAt
  18076.     };
  18077.  
  18078.     var english = {
  18079.       'colorcustom.rgb.red.label': 'R',
  18080.       'colorcustom.rgb.red.description': 'Red component',
  18081.       'colorcustom.rgb.green.label': 'G',
  18082.       'colorcustom.rgb.green.description': 'Green component',
  18083.       'colorcustom.rgb.blue.label': 'B',
  18084.       'colorcustom.rgb.blue.description': 'Blue component',
  18085.       'colorcustom.rgb.hex.label': '#',
  18086.       'colorcustom.rgb.hex.description': 'Hex color code',
  18087.       'colorcustom.rgb.range': 'Range 0 to 255',
  18088.       'colorcustom.sb.saturation': 'Saturation',
  18089.       'colorcustom.sb.brightness': 'Brightness',
  18090.       'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  18091.       'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  18092.       'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  18093.       'colorcustom.hue.hue': 'Hue',
  18094.       'colorcustom.hue.slider': 'Hue Slider',
  18095.       'colorcustom.hue.palette': 'Hue Palette',
  18096.       'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  18097.       'aria.color.picker': 'Color Picker',
  18098.       'aria.input.invalid': 'Invalid input'
  18099.     };
  18100.     var getEnglishText = function (key) {
  18101.       return english[key];
  18102.     };
  18103.     var translate$1 = function (key) {
  18104.       return getEnglishText(key);
  18105.     };
  18106.     var renderColorPicker = function (_spec) {
  18107.       var getClass = function (key) {
  18108.         return 'tox-' + key;
  18109.       };
  18110.       var colourPickerFactory = makeFactory(translate$1, getClass);
  18111.       var onValidHex = function (form) {
  18112.         emitWith(form, formActionEvent, {
  18113.           name: 'hex-valid',
  18114.           value: true
  18115.         });
  18116.       };
  18117.       var onInvalidHex = function (form) {
  18118.         emitWith(form, formActionEvent, {
  18119.           name: 'hex-valid',
  18120.           value: false
  18121.         });
  18122.       };
  18123.       var memPicker = record(colourPickerFactory.sketch({
  18124.         dom: {
  18125.           tag: 'div',
  18126.           classes: [getClass('color-picker-container')],
  18127.           attributes: { role: 'presentation' }
  18128.         },
  18129.         onValidHex: onValidHex,
  18130.         onInvalidHex: onInvalidHex
  18131.       }));
  18132.       return {
  18133.         dom: { tag: 'div' },
  18134.         components: [memPicker.asSpec()],
  18135.         behaviours: derive$1([
  18136.           Representing.config({
  18137.             store: {
  18138.               mode: 'manual',
  18139.               getValue: function (comp) {
  18140.                 var picker = memPicker.get(comp);
  18141.                 var optRgbForm = Composing.getCurrent(picker);
  18142.                 var optHex = optRgbForm.bind(function (rgbForm) {
  18143.                   var formValues = Representing.getValue(rgbForm);
  18144.                   return formValues.hex;
  18145.                 });
  18146.                 return optHex.map(function (hex) {
  18147.                   return '#' + hex;
  18148.                 }).getOr('');
  18149.               },
  18150.               setValue: function (comp, newValue) {
  18151.                 var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  18152.                 var m = pattern.exec(newValue);
  18153.                 var picker = memPicker.get(comp);
  18154.                 var optRgbForm = Composing.getCurrent(picker);
  18155.                 optRgbForm.fold(function () {
  18156.                   console.log('Can not find form');
  18157.                 }, function (rgbForm) {
  18158.                   Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') });
  18159.                   Form.getField(rgbForm, 'hex').each(function (hexField) {
  18160.                     emit(hexField, input());
  18161.                   });
  18162.                 });
  18163.               }
  18164.             }
  18165.           }),
  18166.           ComposingConfigs.self()
  18167.         ])
  18168.       };
  18169.     };
  18170.  
  18171.     var global$6 = tinymce.util.Tools.resolve('tinymce.Resource');
  18172.  
  18173.     var isOldCustomEditor = function (spec) {
  18174.       return has$2(spec, 'init');
  18175.     };
  18176.     var renderCustomEditor = function (spec) {
  18177.       var editorApi = value$1();
  18178.       var memReplaced = record({ dom: { tag: spec.tag } });
  18179.       var initialValue = value$1();
  18180.       return {
  18181.         dom: {
  18182.           tag: 'div',
  18183.           classes: ['tox-custom-editor']
  18184.         },
  18185.         behaviours: derive$1([
  18186.           config('custom-editor-events', [runOnAttached(function (component) {
  18187.               memReplaced.getOpt(component).each(function (ta) {
  18188.                 (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$6.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  18189.                   return init(ta.element.dom, spec.settings);
  18190.                 })).then(function (ea) {
  18191.                   initialValue.on(function (cvalue) {
  18192.                     ea.setValue(cvalue);
  18193.                   });
  18194.                   initialValue.clear();
  18195.                   editorApi.set(ea);
  18196.                 });
  18197.               });
  18198.             })]),
  18199.           Representing.config({
  18200.             store: {
  18201.               mode: 'manual',
  18202.               getValue: function () {
  18203.                 return editorApi.get().fold(function () {
  18204.                   return initialValue.get().getOr('');
  18205.                 }, function (ed) {
  18206.                   return ed.getValue();
  18207.                 });
  18208.               },
  18209.               setValue: function (component, value) {
  18210.                 editorApi.get().fold(function () {
  18211.                   initialValue.set(value);
  18212.                 }, function (ed) {
  18213.                   return ed.setValue(value);
  18214.                 });
  18215.               }
  18216.             }
  18217.           }),
  18218.           ComposingConfigs.self()
  18219.         ]),
  18220.         components: [memReplaced.asSpec()]
  18221.       };
  18222.     };
  18223.  
  18224.     var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  18225.  
  18226.     var processors = objOf([
  18227.       defaulted('preprocess', identity$1),
  18228.       defaulted('postprocess', identity$1)
  18229.     ]);
  18230.     var memento = function (mem, rawProcessors) {
  18231.       var ps = asRawOrDie$1('RepresentingConfigs.memento processors', processors, rawProcessors);
  18232.       return Representing.config({
  18233.         store: {
  18234.           mode: 'manual',
  18235.           getValue: function (comp) {
  18236.             var other = mem.get(comp);
  18237.             var rawValue = Representing.getValue(other);
  18238.             return ps.postprocess(rawValue);
  18239.           },
  18240.           setValue: function (comp, rawValue) {
  18241.             var newValue = ps.preprocess(rawValue);
  18242.             var other = mem.get(comp);
  18243.             Representing.setValue(other, newValue);
  18244.           }
  18245.         }
  18246.       });
  18247.     };
  18248.     var withComp = function (optInitialValue, getter, setter) {
  18249.       return Representing.config(deepMerge({
  18250.         store: {
  18251.           mode: 'manual',
  18252.           getValue: getter,
  18253.           setValue: setter
  18254.         }
  18255.       }, optInitialValue.map(function (initialValue) {
  18256.         return { store: { initialValue: initialValue } };
  18257.       }).getOr({})));
  18258.     };
  18259.     var withElement = function (initialValue, getter, setter) {
  18260.       return withComp(initialValue, function (c) {
  18261.         return getter(c.element);
  18262.       }, function (c, v) {
  18263.         return setter(c.element, v);
  18264.       });
  18265.     };
  18266.     var domValue = function (optInitialValue) {
  18267.       return withElement(optInitialValue, get$5, set$4);
  18268.     };
  18269.     var domHtml = function (optInitialValue) {
  18270.       return withElement(optInitialValue, get$7, set$5);
  18271.     };
  18272.     var memory = function (initialValue) {
  18273.       return Representing.config({
  18274.         store: {
  18275.           mode: 'memory',
  18276.           initialValue: initialValue
  18277.         }
  18278.       });
  18279.     };
  18280.     var RepresentingConfigs = {
  18281.       memento: memento,
  18282.       withElement: withElement,
  18283.       withComp: withComp,
  18284.       domValue: domValue,
  18285.       domHtml: domHtml,
  18286.       memory: memory
  18287.     };
  18288.  
  18289.     var defaultImageFileTypes = 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp';
  18290.     var filterByExtension = function (files, providersBackstage) {
  18291.       var allowedImageFileTypes = global$5.explode(providersBackstage.getSetting('images_file_types', defaultImageFileTypes, 'string'));
  18292.       var isFileInAllowedTypes = function (file) {
  18293.         return exists(allowedImageFileTypes, function (type) {
  18294.           return endsWith(file.name.toLowerCase(), '.' + type.toLowerCase());
  18295.         });
  18296.       };
  18297.       return filter$2(from(files), isFileInAllowedTypes);
  18298.     };
  18299.     var renderDropZone = function (spec, providersBackstage) {
  18300.       var stopper = function (_, se) {
  18301.         se.stop();
  18302.       };
  18303.       var sequence = function (actions) {
  18304.         return function (comp, se) {
  18305.           each$1(actions, function (a) {
  18306.             a(comp, se);
  18307.           });
  18308.         };
  18309.       };
  18310.       var onDrop = function (comp, se) {
  18311.         if (!Disabling.isDisabled(comp)) {
  18312.           var transferEvent = se.event.raw;
  18313.           handleFiles(comp, transferEvent.dataTransfer.files);
  18314.         }
  18315.       };
  18316.       var onSelect = function (component, simulatedEvent) {
  18317.         var input = simulatedEvent.event.raw.target;
  18318.         handleFiles(component, input.files);
  18319.       };
  18320.       var handleFiles = function (component, files) {
  18321.         Representing.setValue(component, filterByExtension(files, providersBackstage));
  18322.         emitWith(component, formChangeEvent, { name: spec.name });
  18323.       };
  18324.       var memInput = record({
  18325.         dom: {
  18326.           tag: 'input',
  18327.           attributes: {
  18328.             type: 'file',
  18329.             accept: 'image/*'
  18330.           },
  18331.           styles: { display: 'none' }
  18332.         },
  18333.         behaviours: derive$1([config('input-file-events', [
  18334.             cutter(click()),
  18335.             cutter(tap())
  18336.           ])])
  18337.       });
  18338.       var renderField = function (s) {
  18339.         return {
  18340.           uid: s.uid,
  18341.           dom: {
  18342.             tag: 'div',
  18343.             classes: ['tox-dropzone-container']
  18344.           },
  18345.           behaviours: derive$1([
  18346.             RepresentingConfigs.memory([]),
  18347.             ComposingConfigs.self(),
  18348.             Disabling.config({}),
  18349.             Toggling.config({
  18350.               toggleClass: 'dragenter',
  18351.               toggleOnExecute: false
  18352.             }),
  18353.             config('dropzone-events', [
  18354.               run$1('dragenter', sequence([
  18355.                 stopper,
  18356.                 Toggling.toggle
  18357.               ])),
  18358.               run$1('dragleave', sequence([
  18359.                 stopper,
  18360.                 Toggling.toggle
  18361.               ])),
  18362.               run$1('dragover', stopper),
  18363.               run$1('drop', sequence([
  18364.                 stopper,
  18365.                 onDrop
  18366.               ])),
  18367.               run$1(change(), onSelect)
  18368.             ])
  18369.           ]),
  18370.           components: [{
  18371.               dom: {
  18372.                 tag: 'div',
  18373.                 classes: ['tox-dropzone'],
  18374.                 styles: {}
  18375.               },
  18376.               components: [
  18377.                 {
  18378.                   dom: {
  18379.                     tag: 'p',
  18380.                     innerHtml: providersBackstage.translate('Drop an image here')
  18381.                   }
  18382.                 },
  18383.                 Button.sketch({
  18384.                   dom: {
  18385.                     tag: 'button',
  18386.                     innerHtml: providersBackstage.translate('Browse for an image'),
  18387.                     styles: { position: 'relative' },
  18388.                     classes: [
  18389.                       'tox-button',
  18390.                       'tox-button--secondary'
  18391.                     ]
  18392.                   },
  18393.                   components: [memInput.asSpec()],
  18394.                   action: function (comp) {
  18395.                     var inputComp = memInput.get(comp);
  18396.                     inputComp.element.dom.click();
  18397.                   },
  18398.                   buttonBehaviours: derive$1([
  18399.                     Tabstopping.config({}),
  18400.                     DisablingConfigs.button(providersBackstage.isDisabled),
  18401.                     receivingConfig()
  18402.                   ])
  18403.                 })
  18404.               ]
  18405.             }]
  18406.         };
  18407.       };
  18408.       var pLabel = spec.label.map(function (label) {
  18409.         return renderLabel$2(label, providersBackstage);
  18410.       });
  18411.       var pField = FormField.parts.field({ factory: { sketch: renderField } });
  18412.       return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  18413.     };
  18414.  
  18415.     var renderGrid = function (spec, backstage) {
  18416.       return {
  18417.         dom: {
  18418.           tag: 'div',
  18419.           classes: [
  18420.             'tox-form__grid',
  18421.             'tox-form__grid--' + spec.columns + 'col'
  18422.           ]
  18423.         },
  18424.         components: map$2(spec.items, backstage.interpreter)
  18425.       };
  18426.     };
  18427.  
  18428.     var beforeObject = generate$6('alloy-fake-before-tabstop');
  18429.     var afterObject = generate$6('alloy-fake-after-tabstop');
  18430.     var craftWithClasses = function (classes) {
  18431.       return {
  18432.         dom: {
  18433.           tag: 'div',
  18434.           styles: {
  18435.             width: '1px',
  18436.             height: '1px',
  18437.             outline: 'none'
  18438.           },
  18439.           attributes: { tabindex: '0' },
  18440.           classes: classes
  18441.         },
  18442.         behaviours: derive$1([
  18443.           Focusing.config({ ignore: true }),
  18444.           Tabstopping.config({})
  18445.         ])
  18446.       };
  18447.     };
  18448.     var craft = function (spec) {
  18449.       return {
  18450.         dom: {
  18451.           tag: 'div',
  18452.           classes: ['tox-navobj']
  18453.         },
  18454.         components: [
  18455.           craftWithClasses([beforeObject]),
  18456.           spec,
  18457.           craftWithClasses([afterObject])
  18458.         ],
  18459.         behaviours: derive$1([ComposingConfigs.childAt(1)])
  18460.       };
  18461.     };
  18462.     var triggerTab = function (placeholder, shiftKey) {
  18463.       emitWith(placeholder, keydown(), {
  18464.         raw: {
  18465.           which: 9,
  18466.           shiftKey: shiftKey
  18467.         }
  18468.       });
  18469.     };
  18470.     var onFocus = function (container, targetComp) {
  18471.       var target = targetComp.element;
  18472.       if (has(target, beforeObject)) {
  18473.         triggerTab(container, true);
  18474.       } else if (has(target, afterObject)) {
  18475.         triggerTab(container, false);
  18476.       }
  18477.     };
  18478.     var isPseudoStop = function (element) {
  18479.       return closest(element, [
  18480.         '.' + beforeObject,
  18481.         '.' + afterObject
  18482.       ].join(','), never);
  18483.     };
  18484.  
  18485.     var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge());
  18486.     var getDynamicSource = function (isSandbox) {
  18487.       var cachedValue = Cell('');
  18488.       return {
  18489.         getValue: function (_frameComponent) {
  18490.           return cachedValue.get();
  18491.         },
  18492.         setValue: function (frameComponent, html) {
  18493.           if (!isSandbox) {
  18494.             set$8(frameComponent.element, 'src', 'javascript:\'\'');
  18495.             var doc = frameComponent.element.dom.contentWindow.document;
  18496.             doc.open();
  18497.             doc.write(html);
  18498.             doc.close();
  18499.           } else {
  18500.             set$8(frameComponent.element, 'srcdoc', html);
  18501.           }
  18502.           cachedValue.set(html);
  18503.         }
  18504.       };
  18505.     };
  18506.     var renderIFrame = function (spec, providersBackstage) {
  18507.       var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  18508.       var attributes = __assign(__assign({}, spec.label.map(function (title) {
  18509.         return { title: title };
  18510.       }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  18511.       var sourcing = getDynamicSource(isSandbox);
  18512.       var pLabel = spec.label.map(function (label) {
  18513.         return renderLabel$2(label, providersBackstage);
  18514.       });
  18515.       var factory = function (newSpec) {
  18516.         return craft({
  18517.           uid: newSpec.uid,
  18518.           dom: {
  18519.             tag: 'iframe',
  18520.             attributes: attributes
  18521.           },
  18522.           behaviours: derive$1([
  18523.             Tabstopping.config({}),
  18524.             Focusing.config({}),
  18525.             RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
  18526.           ])
  18527.         });
  18528.       };
  18529.       var pField = FormField.parts.field({ factory: { sketch: factory } });
  18530.       return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  18531.     };
  18532.  
  18533.     var create$3 = function (width, height) {
  18534.       return resize$3(document.createElement('canvas'), width, height);
  18535.     };
  18536.     var clone = function (canvas) {
  18537.       var tCanvas = create$3(canvas.width, canvas.height);
  18538.       var ctx = get2dContext(tCanvas);
  18539.       ctx.drawImage(canvas, 0, 0);
  18540.       return tCanvas;
  18541.     };
  18542.     var get2dContext = function (canvas) {
  18543.       return canvas.getContext('2d');
  18544.     };
  18545.     var resize$3 = function (canvas, width, height) {
  18546.       canvas.width = width;
  18547.       canvas.height = height;
  18548.       return canvas;
  18549.     };
  18550.  
  18551.     var getWidth$1 = function (image) {
  18552.       return image.naturalWidth || image.width;
  18553.     };
  18554.     var getHeight$1 = function (image) {
  18555.       return image.naturalHeight || image.height;
  18556.     };
  18557.  
  18558.     var blobToImage = function (blob) {
  18559.       return new Promise$1(function (resolve, reject) {
  18560.         var blobUrl = URL.createObjectURL(blob);
  18561.         var image = new Image();
  18562.         var removeListeners = function () {
  18563.           image.removeEventListener('load', loaded);
  18564.           image.removeEventListener('error', error);
  18565.         };
  18566.         var loaded = function () {
  18567.           removeListeners();
  18568.           resolve(image);
  18569.         };
  18570.         var error = function () {
  18571.           removeListeners();
  18572.           reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  18573.         };
  18574.         image.addEventListener('load', loaded);
  18575.         image.addEventListener('error', error);
  18576.         image.src = blobUrl;
  18577.         if (image.complete) {
  18578.           setTimeout(loaded, 0);
  18579.         }
  18580.       });
  18581.     };
  18582.     var dataUriToBlobSync = function (uri) {
  18583.       var data = uri.split(',');
  18584.       var matches = /data:([^;]+)/.exec(data[0]);
  18585.       if (!matches) {
  18586.         return Optional.none();
  18587.       }
  18588.       var mimetype = matches[1];
  18589.       var base64 = data[1];
  18590.       var sliceSize = 1024;
  18591.       var byteCharacters = atob(base64);
  18592.       var bytesLength = byteCharacters.length;
  18593.       var slicesCount = Math.ceil(bytesLength / sliceSize);
  18594.       var byteArrays = new Array(slicesCount);
  18595.       for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  18596.         var begin = sliceIndex * sliceSize;
  18597.         var end = Math.min(begin + sliceSize, bytesLength);
  18598.         var bytes = new Array(end - begin);
  18599.         for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  18600.           bytes[i] = byteCharacters[offset].charCodeAt(0);
  18601.         }
  18602.         byteArrays[sliceIndex] = new Uint8Array(bytes);
  18603.       }
  18604.       return Optional.some(new Blob(byteArrays, { type: mimetype }));
  18605.     };
  18606.     var dataUriToBlob = function (uri) {
  18607.       return new Promise$1(function (resolve, reject) {
  18608.         dataUriToBlobSync(uri).fold(function () {
  18609.           reject('uri is not base64: ' + uri);
  18610.         }, resolve);
  18611.       });
  18612.     };
  18613.     var canvasToBlob = function (canvas, type, quality) {
  18614.       type = type || 'image/png';
  18615.       if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
  18616.         return new Promise$1(function (resolve, reject) {
  18617.           canvas.toBlob(function (blob) {
  18618.             if (blob) {
  18619.               resolve(blob);
  18620.             } else {
  18621.               reject();
  18622.             }
  18623.           }, type, quality);
  18624.         });
  18625.       } else {
  18626.         return dataUriToBlob(canvas.toDataURL(type, quality));
  18627.       }
  18628.     };
  18629.     var canvasToDataURL = function (canvas, type, quality) {
  18630.       type = type || 'image/png';
  18631.       return canvas.toDataURL(type, quality);
  18632.     };
  18633.     var blobToCanvas = function (blob) {
  18634.       return blobToImage(blob).then(function (image) {
  18635.         revokeImageUrl(image);
  18636.         var canvas = create$3(getWidth$1(image), getHeight$1(image));
  18637.         var context = get2dContext(canvas);
  18638.         context.drawImage(image, 0, 0);
  18639.         return canvas;
  18640.       });
  18641.     };
  18642.     var blobToDataUri = function (blob) {
  18643.       return new Promise$1(function (resolve) {
  18644.         var reader = new FileReader();
  18645.         reader.onloadend = function () {
  18646.           resolve(reader.result);
  18647.         };
  18648.         reader.readAsDataURL(blob);
  18649.       });
  18650.     };
  18651.     var revokeImageUrl = function (image) {
  18652.       URL.revokeObjectURL(image.src);
  18653.     };
  18654.  
  18655.     var create$2 = function (getCanvas, blob, uri) {
  18656.       var initialType = blob.type;
  18657.       var getType = constant$1(initialType);
  18658.       var toBlob = function () {
  18659.         return Promise$1.resolve(blob);
  18660.       };
  18661.       var toDataURL = constant$1(uri);
  18662.       var toBase64 = function () {
  18663.         return uri.split(',')[1];
  18664.       };
  18665.       var toAdjustedBlob = function (type, quality) {
  18666.         return getCanvas.then(function (canvas) {
  18667.           return canvasToBlob(canvas, type, quality);
  18668.         });
  18669.       };
  18670.       var toAdjustedDataURL = function (type, quality) {
  18671.         return getCanvas.then(function (canvas) {
  18672.           return canvasToDataURL(canvas, type, quality);
  18673.         });
  18674.       };
  18675.       var toAdjustedBase64 = function (type, quality) {
  18676.         return toAdjustedDataURL(type, quality).then(function (dataurl) {
  18677.           return dataurl.split(',')[1];
  18678.         });
  18679.       };
  18680.       var toCanvas = function () {
  18681.         return getCanvas.then(clone);
  18682.       };
  18683.       return {
  18684.         getType: getType,
  18685.         toBlob: toBlob,
  18686.         toDataURL: toDataURL,
  18687.         toBase64: toBase64,
  18688.         toAdjustedBlob: toAdjustedBlob,
  18689.         toAdjustedDataURL: toAdjustedDataURL,
  18690.         toAdjustedBase64: toAdjustedBase64,
  18691.         toCanvas: toCanvas
  18692.       };
  18693.     };
  18694.     var fromBlob = function (blob) {
  18695.       return blobToDataUri(blob).then(function (uri) {
  18696.         return create$2(blobToCanvas(blob), blob, uri);
  18697.       });
  18698.     };
  18699.     var fromCanvas = function (canvas, type) {
  18700.       return canvasToBlob(canvas, type).then(function (blob) {
  18701.         return create$2(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  18702.       });
  18703.     };
  18704.  
  18705.     var blobToImageResult = function (blob) {
  18706.       return fromBlob(blob);
  18707.     };
  18708.  
  18709.     var clamp = function (value, min, max) {
  18710.       var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  18711.       if (parsedValue > max) {
  18712.         parsedValue = max;
  18713.       } else if (parsedValue < min) {
  18714.         parsedValue = min;
  18715.       }
  18716.       return parsedValue;
  18717.     };
  18718.     var identity = function () {
  18719.       return [
  18720.         1,
  18721.         0,
  18722.         0,
  18723.         0,
  18724.         0,
  18725.         0,
  18726.         1,
  18727.         0,
  18728.         0,
  18729.         0,
  18730.         0,
  18731.         0,
  18732.         1,
  18733.         0,
  18734.         0,
  18735.         0,
  18736.         0,
  18737.         0,
  18738.         1,
  18739.         0,
  18740.         0,
  18741.         0,
  18742.         0,
  18743.         0,
  18744.         1
  18745.       ];
  18746.     };
  18747.     var DELTA_INDEX = [
  18748.       0,
  18749.       0.01,
  18750.       0.02,
  18751.       0.04,
  18752.       0.05,
  18753.       0.06,
  18754.       0.07,
  18755.       0.08,
  18756.       0.1,
  18757.       0.11,
  18758.       0.12,
  18759.       0.14,
  18760.       0.15,
  18761.       0.16,
  18762.       0.17,
  18763.       0.18,
  18764.       0.2,
  18765.       0.21,
  18766.       0.22,
  18767.       0.24,
  18768.       0.25,
  18769.       0.27,
  18770.       0.28,
  18771.       0.3,
  18772.       0.32,
  18773.       0.34,
  18774.       0.36,
  18775.       0.38,
  18776.       0.4,
  18777.       0.42,
  18778.       0.44,
  18779.       0.46,
  18780.       0.48,
  18781.       0.5,
  18782.       0.53,
  18783.       0.56,
  18784.       0.59,
  18785.       0.62,
  18786.       0.65,
  18787.       0.68,
  18788.       0.71,
  18789.       0.74,
  18790.       0.77,
  18791.       0.8,
  18792.       0.83,
  18793.       0.86,
  18794.       0.89,
  18795.       0.92,
  18796.       0.95,
  18797.       0.98,
  18798.       1,
  18799.       1.06,
  18800.       1.12,
  18801.       1.18,
  18802.       1.24,
  18803.       1.3,
  18804.       1.36,
  18805.       1.42,
  18806.       1.48,
  18807.       1.54,
  18808.       1.6,
  18809.       1.66,
  18810.       1.72,
  18811.       1.78,
  18812.       1.84,
  18813.       1.9,
  18814.       1.96,
  18815.       2,
  18816.       2.12,
  18817.       2.25,
  18818.       2.37,
  18819.       2.5,
  18820.       2.62,
  18821.       2.75,
  18822.       2.87,
  18823.       3,
  18824.       3.2,
  18825.       3.4,
  18826.       3.6,
  18827.       3.8,
  18828.       4,
  18829.       4.3,
  18830.       4.7,
  18831.       4.9,
  18832.       5,
  18833.       5.5,
  18834.       6,
  18835.       6.5,
  18836.       6.8,
  18837.       7,
  18838.       7.3,
  18839.       7.5,
  18840.       7.8,
  18841.       8,
  18842.       8.4,
  18843.       8.7,
  18844.       9,
  18845.       9.4,
  18846.       9.6,
  18847.       9.8,
  18848.       10
  18849.     ];
  18850.     var multiply = function (matrix1, matrix2) {
  18851.       var col = [];
  18852.       var out = new Array(25);
  18853.       var val;
  18854.       for (var i = 0; i < 5; i++) {
  18855.         for (var j = 0; j < 5; j++) {
  18856.           col[j] = matrix2[j + i * 5];
  18857.         }
  18858.         for (var j = 0; j < 5; j++) {
  18859.           val = 0;
  18860.           for (var k = 0; k < 5; k++) {
  18861.             val += matrix1[j + k * 5] * col[k];
  18862.           }
  18863.           out[j + i * 5] = val;
  18864.         }
  18865.       }
  18866.       return out;
  18867.     };
  18868.     var adjustContrast = function (matrix, value) {
  18869.       var x;
  18870.       value = clamp(value, -1, 1);
  18871.       value *= 100;
  18872.       if (value < 0) {
  18873.         x = 127 + value / 100 * 127;
  18874.       } else {
  18875.         x = value % 1;
  18876.         if (x === 0) {
  18877.           x = DELTA_INDEX[value];
  18878.         } else {
  18879.           x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  18880.         }
  18881.         x = x * 127 + 127;
  18882.       }
  18883.       return multiply(matrix, [
  18884.         x / 127,
  18885.         0,
  18886.         0,
  18887.         0,
  18888.         0.5 * (127 - x),
  18889.         0,
  18890.         x / 127,
  18891.         0,
  18892.         0,
  18893.         0.5 * (127 - x),
  18894.         0,
  18895.         0,
  18896.         x / 127,
  18897.         0,
  18898.         0.5 * (127 - x),
  18899.         0,
  18900.         0,
  18901.         0,
  18902.         1,
  18903.         0,
  18904.         0,
  18905.         0,
  18906.         0,
  18907.         0,
  18908.         1
  18909.       ]);
  18910.     };
  18911.     var adjustBrightness = function (matrix, value) {
  18912.       value = clamp(255 * value, -255, 255);
  18913.       return multiply(matrix, [
  18914.         1,
  18915.         0,
  18916.         0,
  18917.         0,
  18918.         value,
  18919.         0,
  18920.         1,
  18921.         0,
  18922.         0,
  18923.         value,
  18924.         0,
  18925.         0,
  18926.         1,
  18927.         0,
  18928.         value,
  18929.         0,
  18930.         0,
  18931.         0,
  18932.         1,
  18933.         0,
  18934.         0,
  18935.         0,
  18936.         0,
  18937.         0,
  18938.         1
  18939.       ]);
  18940.     };
  18941.     var adjustColors = function (matrix, adjustR, adjustG, adjustB) {
  18942.       adjustR = clamp(adjustR, 0, 2);
  18943.       adjustG = clamp(adjustG, 0, 2);
  18944.       adjustB = clamp(adjustB, 0, 2);
  18945.       return multiply(matrix, [
  18946.         adjustR,
  18947.         0,
  18948.         0,
  18949.         0,
  18950.         0,
  18951.         0,
  18952.         adjustG,
  18953.         0,
  18954.         0,
  18955.         0,
  18956.         0,
  18957.         0,
  18958.         adjustB,
  18959.         0,
  18960.         0,
  18961.         0,
  18962.         0,
  18963.         0,
  18964.         1,
  18965.         0,
  18966.         0,
  18967.         0,
  18968.         0,
  18969.         0,
  18970.         1
  18971.       ]);
  18972.     };
  18973.  
  18974.     var colorFilter = function (ir, matrix) {
  18975.       return ir.toCanvas().then(function (canvas) {
  18976.         return applyColorFilter(canvas, ir.getType(), matrix);
  18977.       });
  18978.     };
  18979.     var applyColorFilter = function (canvas, type, matrix) {
  18980.       var context = get2dContext(canvas);
  18981.       var applyMatrix = function (pixelsData, m) {
  18982.         var r, g, b, a;
  18983.         var data = pixelsData.data, m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8], m9 = m[9], m10 = m[10], m11 = m[11], m12 = m[12], m13 = m[13], m14 = m[14], m15 = m[15], m16 = m[16], m17 = m[17], m18 = m[18], m19 = m[19];
  18984.         for (var i = 0; i < data.length; i += 4) {
  18985.           r = data[i];
  18986.           g = data[i + 1];
  18987.           b = data[i + 2];
  18988.           a = data[i + 3];
  18989.           data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  18990.           data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  18991.           data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  18992.           data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  18993.         }
  18994.         return pixelsData;
  18995.       };
  18996.       var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  18997.       context.putImageData(pixels, 0, 0);
  18998.       return fromCanvas(canvas, type);
  18999.     };
  19000.     var convoluteFilter = function (ir, matrix) {
  19001.       return ir.toCanvas().then(function (canvas) {
  19002.         return applyConvoluteFilter(canvas, ir.getType(), matrix);
  19003.       });
  19004.     };
  19005.     var applyConvoluteFilter = function (canvas, type, matrix) {
  19006.       var context = get2dContext(canvas);
  19007.       var applyMatrix = function (pIn, pOut, aMatrix) {
  19008.         var clamp = function (value, min, max) {
  19009.           if (value > max) {
  19010.             value = max;
  19011.           } else if (value < min) {
  19012.             value = min;
  19013.           }
  19014.           return value;
  19015.         };
  19016.         var side = Math.round(Math.sqrt(aMatrix.length));
  19017.         var halfSide = Math.floor(side / 2);
  19018.         var rgba = pIn.data;
  19019.         var drgba = pOut.data;
  19020.         var w = pIn.width;
  19021.         var h = pIn.height;
  19022.         for (var y = 0; y < h; y++) {
  19023.           for (var x = 0; x < w; x++) {
  19024.             var r = 0;
  19025.             var g = 0;
  19026.             var b = 0;
  19027.             for (var cy = 0; cy < side; cy++) {
  19028.               for (var cx = 0; cx < side; cx++) {
  19029.                 var scx = clamp(x + cx - halfSide, 0, w - 1);
  19030.                 var scy = clamp(y + cy - halfSide, 0, h - 1);
  19031.                 var innerOffset = (scy * w + scx) * 4;
  19032.                 var wt = aMatrix[cy * side + cx];
  19033.                 r += rgba[innerOffset] * wt;
  19034.                 g += rgba[innerOffset + 1] * wt;
  19035.                 b += rgba[innerOffset + 2] * wt;
  19036.               }
  19037.             }
  19038.             var offset = (y * w + x) * 4;
  19039.             drgba[offset] = clamp(r, 0, 255);
  19040.             drgba[offset + 1] = clamp(g, 0, 255);
  19041.             drgba[offset + 2] = clamp(b, 0, 255);
  19042.           }
  19043.         }
  19044.         return pOut;
  19045.       };
  19046.       var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  19047.       var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  19048.       pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  19049.       context.putImageData(pixelsOut, 0, 0);
  19050.       return fromCanvas(canvas, type);
  19051.     };
  19052.     var functionColorFilter = function (colorFn) {
  19053.       var filterImpl = function (canvas, type, value) {
  19054.         var context = get2dContext(canvas);
  19055.         var lookup = new Array(256);
  19056.         var applyLookup = function (pixelsData, lookupData) {
  19057.           var data = pixelsData.data;
  19058.           for (var i = 0; i < data.length; i += 4) {
  19059.             data[i] = lookupData[data[i]];
  19060.             data[i + 1] = lookupData[data[i + 1]];
  19061.             data[i + 2] = lookupData[data[i + 2]];
  19062.           }
  19063.           return pixelsData;
  19064.         };
  19065.         for (var i = 0; i < lookup.length; i++) {
  19066.           lookup[i] = colorFn(i, value);
  19067.         }
  19068.         var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  19069.         context.putImageData(pixels, 0, 0);
  19070.         return fromCanvas(canvas, type);
  19071.       };
  19072.       return function (ir, value) {
  19073.         return ir.toCanvas().then(function (canvas) {
  19074.           return filterImpl(canvas, ir.getType(), value);
  19075.         });
  19076.       };
  19077.     };
  19078.     var complexAdjustableColorFilter = function (matrixAdjustFn) {
  19079.       return function (ir, adjust) {
  19080.         return colorFilter(ir, matrixAdjustFn(identity(), adjust));
  19081.       };
  19082.     };
  19083.     var basicColorFilter = function (matrix) {
  19084.       return function (ir) {
  19085.         return colorFilter(ir, matrix);
  19086.       };
  19087.     };
  19088.     var basicConvolutionFilter = function (kernel) {
  19089.       return function (ir) {
  19090.         return convoluteFilter(ir, kernel);
  19091.       };
  19092.     };
  19093.     var invert$1 = basicColorFilter([
  19094.       -1,
  19095.       0,
  19096.       0,
  19097.       0,
  19098.       255,
  19099.       0,
  19100.       -1,
  19101.       0,
  19102.       0,
  19103.       255,
  19104.       0,
  19105.       0,
  19106.       -1,
  19107.       0,
  19108.       255,
  19109.       0,
  19110.       0,
  19111.       0,
  19112.       1,
  19113.       0,
  19114.       0,
  19115.       0,
  19116.       0,
  19117.       0,
  19118.       1
  19119.     ]);
  19120.     var brightness$1 = complexAdjustableColorFilter(adjustBrightness);
  19121.     var contrast$1 = complexAdjustableColorFilter(adjustContrast);
  19122.     var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  19123.       return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB));
  19124.     };
  19125.     var sharpen$1 = basicConvolutionFilter([
  19126.       0,
  19127.       -1,
  19128.       0,
  19129.       -1,
  19130.       5,
  19131.       -1,
  19132.       0,
  19133.       -1,
  19134.       0
  19135.     ]);
  19136.     var gamma$1 = functionColorFilter(function (color, value) {
  19137.       return Math.pow(color / 255, 1 - value) * 255;
  19138.     });
  19139.  
  19140.     var scale = function (image, dW, dH) {
  19141.       var sW = getWidth$1(image);
  19142.       var sH = getHeight$1(image);
  19143.       var wRatio = dW / sW;
  19144.       var hRatio = dH / sH;
  19145.       var scaleCapped = false;
  19146.       if (wRatio < 0.5 || wRatio > 2) {
  19147.         wRatio = wRatio < 0.5 ? 0.5 : 2;
  19148.         scaleCapped = true;
  19149.       }
  19150.       if (hRatio < 0.5 || hRatio > 2) {
  19151.         hRatio = hRatio < 0.5 ? 0.5 : 2;
  19152.         scaleCapped = true;
  19153.       }
  19154.       var scaled = _scale(image, wRatio, hRatio);
  19155.       return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  19156.         return scale(tCanvas, dW, dH);
  19157.       });
  19158.     };
  19159.     var _scale = function (image, wRatio, hRatio) {
  19160.       return new Promise$1(function (resolve) {
  19161.         var sW = getWidth$1(image);
  19162.         var sH = getHeight$1(image);
  19163.         var dW = Math.floor(sW * wRatio);
  19164.         var dH = Math.floor(sH * hRatio);
  19165.         var canvas = create$3(dW, dH);
  19166.         var context = get2dContext(canvas);
  19167.         context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  19168.         resolve(canvas);
  19169.       });
  19170.     };
  19171.  
  19172.     var ceilWithPrecision = function (num, precision) {
  19173.       if (precision === void 0) {
  19174.         precision = 2;
  19175.       }
  19176.       var mul = Math.pow(10, precision);
  19177.       var upper = Math.round(num * mul);
  19178.       return Math.ceil(upper / mul);
  19179.     };
  19180.     var rotate$1 = function (ir, angle) {
  19181.       return ir.toCanvas().then(function (canvas) {
  19182.         return applyRotate(canvas, ir.getType(), angle);
  19183.       });
  19184.     };
  19185.     var applyRotate = function (image, type, angle) {
  19186.       var degrees = angle < 0 ? 360 + angle : angle;
  19187.       var rad = degrees * Math.PI / 180;
  19188.       var width = image.width;
  19189.       var height = image.height;
  19190.       var sin = Math.sin(rad);
  19191.       var cos = Math.cos(rad);
  19192.       var newWidth = ceilWithPrecision(Math.abs(width * cos) + Math.abs(height * sin));
  19193.       var newHeight = ceilWithPrecision(Math.abs(width * sin) + Math.abs(height * cos));
  19194.       var canvas = create$3(newWidth, newHeight);
  19195.       var context = get2dContext(canvas);
  19196.       context.translate(newWidth / 2, newHeight / 2);
  19197.       context.rotate(rad);
  19198.       context.drawImage(image, -width / 2, -height / 2);
  19199.       return fromCanvas(canvas, type);
  19200.     };
  19201.     var flip$1 = function (ir, axis) {
  19202.       return ir.toCanvas().then(function (canvas) {
  19203.         return applyFlip(canvas, ir.getType(), axis);
  19204.       });
  19205.     };
  19206.     var applyFlip = function (image, type, axis) {
  19207.       var canvas = create$3(image.width, image.height);
  19208.       var context = get2dContext(canvas);
  19209.       if (axis === 'v') {
  19210.         context.scale(1, -1);
  19211.         context.drawImage(image, 0, -canvas.height);
  19212.       } else {
  19213.         context.scale(-1, 1);
  19214.         context.drawImage(image, -canvas.width, 0);
  19215.       }
  19216.       return fromCanvas(canvas, type);
  19217.     };
  19218.     var crop$1 = function (ir, x, y, w, h) {
  19219.       return ir.toCanvas().then(function (canvas) {
  19220.         return applyCrop(canvas, ir.getType(), x, y, w, h);
  19221.       });
  19222.     };
  19223.     var applyCrop = function (image, type, x, y, w, h) {
  19224.       var canvas = create$3(w, h);
  19225.       var context = get2dContext(canvas);
  19226.       context.drawImage(image, -x, -y);
  19227.       return fromCanvas(canvas, type);
  19228.     };
  19229.     var resize$2 = function (ir, w, h) {
  19230.       return ir.toCanvas().then(function (canvas) {
  19231.         return scale(canvas, w, h).then(function (newCanvas) {
  19232.           return fromCanvas(newCanvas, ir.getType());
  19233.         });
  19234.       });
  19235.     };
  19236.  
  19237.     var invert = function (ir) {
  19238.       return invert$1(ir);
  19239.     };
  19240.     var sharpen = function (ir) {
  19241.       return sharpen$1(ir);
  19242.     };
  19243.     var gamma = function (ir, value) {
  19244.       return gamma$1(ir, value);
  19245.     };
  19246.     var colorize = function (ir, adjustR, adjustG, adjustB) {
  19247.       return colorize$1(ir, adjustR, adjustG, adjustB);
  19248.     };
  19249.     var brightness = function (ir, adjust) {
  19250.       return brightness$1(ir, adjust);
  19251.     };
  19252.     var contrast = function (ir, adjust) {
  19253.       return contrast$1(ir, adjust);
  19254.     };
  19255.     var flip = function (ir, axis) {
  19256.       return flip$1(ir, axis);
  19257.     };
  19258.     var crop = function (ir, x, y, w, h) {
  19259.       return crop$1(ir, x, y, w, h);
  19260.     };
  19261.     var resize$1 = function (ir, w, h) {
  19262.       return resize$2(ir, w, h);
  19263.     };
  19264.     var rotate = function (ir, angle) {
  19265.       return rotate$1(ir, angle);
  19266.     };
  19267.  
  19268.     var renderIcon = function (iconName, iconsProvider, behaviours) {
  19269.       return render$3(iconName, {
  19270.         tag: 'span',
  19271.         classes: [
  19272.           'tox-icon',
  19273.           'tox-tbtn__icon-wrap'
  19274.         ],
  19275.         behaviours: behaviours
  19276.       }, iconsProvider);
  19277.     };
  19278.     var renderIconFromPack = function (iconName, iconsProvider) {
  19279.       return renderIcon(iconName, iconsProvider, []);
  19280.     };
  19281.     var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  19282.       return renderIcon(iconName, iconsProvider, [Replacing.config({})]);
  19283.     };
  19284.     var renderLabel$1 = function (text, prefix, providersBackstage) {
  19285.       return {
  19286.         dom: {
  19287.           tag: 'span',
  19288.           innerHtml: providersBackstage.translate(text),
  19289.           classes: [prefix + '__select-label']
  19290.         },
  19291.         behaviours: derive$1([Replacing.config({})])
  19292.       };
  19293.     };
  19294.  
  19295.     var _a;
  19296.     var internalToolbarButtonExecute = generate$6('toolbar.button.execute');
  19297.     var onToolbarButtonExecute = function (info) {
  19298.       return runOnExecute$1(function (comp, _simulatedEvent) {
  19299.         runWithApi(info, comp)(function (itemApi) {
  19300.           emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  19301.           info.onAction(itemApi);
  19302.         });
  19303.       });
  19304.     };
  19305.     var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [
  19306.       'disabling',
  19307.       'alloy.base.behaviour',
  19308.       'toggling',
  19309.       'toolbar-button-events'
  19310.     ], _a);
  19311.  
  19312.     var updateMenuText = generate$6('update-menu-text');
  19313.     var updateMenuIcon = generate$6('update-menu-icon');
  19314.     var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  19315.       var editorOffCell = Cell(noop);
  19316.       var optMemDisplayText = spec.text.map(function (text) {
  19317.         return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  19318.       });
  19319.       var optMemDisplayIcon = spec.icon.map(function (iconName) {
  19320.         return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  19321.       });
  19322.       var onLeftOrRightInMenu = function (comp, se) {
  19323.         var dropdown = Representing.getValue(comp);
  19324.         Focusing.focus(dropdown);
  19325.         emitWith(dropdown, 'keydown', { raw: se.event.raw });
  19326.         Dropdown.close(dropdown);
  19327.         return Optional.some(true);
  19328.       };
  19329.       var role = spec.role.fold(function () {
  19330.         return {};
  19331.       }, function (role) {
  19332.         return { role: role };
  19333.       });
  19334.       var tooltipAttributes = spec.tooltip.fold(function () {
  19335.         return {};
  19336.       }, function (tooltip) {
  19337.         var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  19338.         return {
  19339.           'title': translatedTooltip,
  19340.           'aria-label': translatedTooltip
  19341.         };
  19342.       });
  19343.       var iconSpec = render$3('chevron-down', {
  19344.         tag: 'div',
  19345.         classes: [prefix + '__select-chevron']
  19346.       }, sharedBackstage.providers.icons);
  19347.       var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
  19348.         dom: {
  19349.           tag: 'button',
  19350.           classes: [
  19351.             prefix,
  19352.             prefix + '--select'
  19353.           ].concat(map$2(spec.classes, function (c) {
  19354.             return prefix + '--' + c;
  19355.           })),
  19356.           attributes: __assign({}, tooltipAttributes)
  19357.         },
  19358.         components: componentRenderPipeline([
  19359.           optMemDisplayIcon.map(function (mem) {
  19360.             return mem.asSpec();
  19361.           }),
  19362.           optMemDisplayText.map(function (mem) {
  19363.             return mem.asSpec();
  19364.           }),
  19365.           Optional.some(iconSpec)
  19366.         ]),
  19367.         matchWidth: true,
  19368.         useMinWidth: true,
  19369.         dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours, true), [
  19370.           DisablingConfigs.button(function () {
  19371.             return spec.disabled || sharedBackstage.providers.isDisabled();
  19372.           }),
  19373.           receivingConfig(),
  19374.           Unselecting.config({}),
  19375.           Replacing.config({}),
  19376.           config('dropdown-events', [
  19377.             onControlAttached(spec, editorOffCell),
  19378.             onControlDetached(spec, editorOffCell)
  19379.           ]),
  19380.           config('menubutton-update-display-text', [
  19381.             run$1(updateMenuText, function (comp, se) {
  19382.               optMemDisplayText.bind(function (mem) {
  19383.                 return mem.getOpt(comp);
  19384.               }).each(function (displayText) {
  19385.                 Replacing.set(displayText, [text$1(sharedBackstage.providers.translate(se.event.text))]);
  19386.               });
  19387.             }),
  19388.             run$1(updateMenuIcon, function (comp, se) {
  19389.               optMemDisplayIcon.bind(function (mem) {
  19390.                 return mem.getOpt(comp);
  19391.               }).each(function (displayIcon) {
  19392.                 Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
  19393.               });
  19394.             })
  19395.           ])
  19396.         ], false)),
  19397.         eventOrder: deepMerge(toolbarButtonEventOrder, {
  19398.           mousedown: [
  19399.             'focusing',
  19400.             'alloy.base.behaviour',
  19401.             'item-type-events',
  19402.             'normal-dropdown-events'
  19403.           ]
  19404.         }),
  19405.         sandboxBehaviours: derive$1([Keying.config({
  19406.             mode: 'special',
  19407.             onLeft: onLeftOrRightInMenu,
  19408.             onRight: onLeftOrRightInMenu
  19409.           })]),
  19410.         lazySink: sharedBackstage.getSink,
  19411.         toggleClass: prefix + '--active',
  19412.         parts: { menu: part(false, spec.columns, spec.presets) },
  19413.         fetch: function (comp) {
  19414.           return Future.nu(curry(spec.fetch, comp));
  19415.         }
  19416.       })));
  19417.       return memDropdown.asSpec();
  19418.     };
  19419.  
  19420.     var isMenuItemReference = function (item) {
  19421.       return isString(item);
  19422.     };
  19423.     var isSeparator$1 = function (item) {
  19424.       return item.type === 'separator';
  19425.     };
  19426.     var isExpandingMenuItem = function (item) {
  19427.       return has$2(item, 'getSubmenuItems');
  19428.     };
  19429.     var separator$2 = { type: 'separator' };
  19430.     var unwrapReferences = function (items, menuItems) {
  19431.       var realItems = foldl(items, function (acc, item) {
  19432.         if (isMenuItemReference(item)) {
  19433.           if (item === '') {
  19434.             return acc;
  19435.           } else if (item === '|') {
  19436.             return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
  19437.           } else if (has$2(menuItems, item.toLowerCase())) {
  19438.             return acc.concat([menuItems[item.toLowerCase()]]);
  19439.           } else {
  19440.             return acc;
  19441.           }
  19442.         } else {
  19443.           return acc.concat([item]);
  19444.         }
  19445.       }, []);
  19446.       if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
  19447.         realItems.pop();
  19448.       }
  19449.       return realItems;
  19450.     };
  19451.     var getFromExpandingItem = function (item, menuItems) {
  19452.       var submenuItems = item.getSubmenuItems();
  19453.       var rest = expand(submenuItems, menuItems);
  19454.       var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  19455.       var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  19456.       return {
  19457.         item: item,
  19458.         menus: newMenus,
  19459.         expansions: newExpansions
  19460.       };
  19461.     };
  19462.     var getFromItem = function (item, menuItems) {
  19463.       return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  19464.         item: item,
  19465.         menus: {},
  19466.         expansions: {}
  19467.       };
  19468.     };
  19469.     var generateValueIfRequired = function (item) {
  19470.       if (isSeparator$1(item)) {
  19471.         return item;
  19472.       } else {
  19473.         var itemValue = get$e(item, 'value').getOrThunk(function () {
  19474.           return generate$6('generated-menu-item');
  19475.         });
  19476.         return deepMerge({ value: itemValue }, item);
  19477.       }
  19478.     };
  19479.     var expand = function (items, menuItems) {
  19480.       var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  19481.       return foldr(realItems, function (acc, item) {
  19482.         var itemWithValue = generateValueIfRequired(item);
  19483.         var newData = getFromItem(itemWithValue, menuItems);
  19484.         return {
  19485.           menus: deepMerge(acc.menus, newData.menus),
  19486.           items: [newData.item].concat(acc.items),
  19487.           expansions: deepMerge(acc.expansions, newData.expansions)
  19488.         };
  19489.       }, {
  19490.         menus: {},
  19491.         expansions: {},
  19492.         items: []
  19493.       });
  19494.     };
  19495.  
  19496.     var build = function (items, itemResponse, backstage, isHorizontalMenu) {
  19497.       var primary = generate$6('primary-menu');
  19498.       var data = expand(items, backstage.shared.providers.menuItems());
  19499.       if (data.items.length === 0) {
  19500.         return Optional.none();
  19501.       }
  19502.       var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  19503.       var submenus = map$1(data.menus, function (menuItems, menuName) {
  19504.         return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  19505.       });
  19506.       var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  19507.       return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
  19508.     };
  19509.  
  19510.     var getMenuButtonApi = function (component) {
  19511.       return {
  19512.         isDisabled: function () {
  19513.           return Disabling.isDisabled(component);
  19514.         },
  19515.         setDisabled: function (state) {
  19516.           return Disabling.set(component, state);
  19517.         },
  19518.         setActive: function (state) {
  19519.           var elm = component.element;
  19520.           if (state) {
  19521.             add$2(elm, 'tox-tbtn--enabled');
  19522.             set$8(elm, 'aria-pressed', true);
  19523.           } else {
  19524.             remove$2(elm, 'tox-tbtn--enabled');
  19525.             remove$7(elm, 'aria-pressed');
  19526.           }
  19527.         },
  19528.         isActive: function () {
  19529.           return has(component.element, 'tox-tbtn--enabled');
  19530.         }
  19531.       };
  19532.     };
  19533.     var renderMenuButton = function (spec, prefix, backstage, role) {
  19534.       return renderCommonDropdown({
  19535.         text: spec.text,
  19536.         icon: spec.icon,
  19537.         tooltip: spec.tooltip,
  19538.         role: role,
  19539.         fetch: function (_comp, callback) {
  19540.           spec.fetch(function (items) {
  19541.             callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  19542.           });
  19543.         },
  19544.         onSetup: spec.onSetup,
  19545.         getApi: getMenuButtonApi,
  19546.         columns: 1,
  19547.         presets: 'normal',
  19548.         classes: [],
  19549.         dropdownBehaviours: [Tabstopping.config({})]
  19550.       }, prefix, backstage.shared);
  19551.     };
  19552.     var getFetch = function (items, getButton, backstage) {
  19553.       var getMenuItemAction = function (item) {
  19554.         return function (api) {
  19555.           var newValue = !api.isActive();
  19556.           api.setActive(newValue);
  19557.           item.storage.set(newValue);
  19558.           backstage.shared.getSink().each(function (sink) {
  19559.             getButton().getOpt(sink).each(function (orig) {
  19560.               focus$3(orig.element);
  19561.               emitWith(orig, formActionEvent, {
  19562.                 name: item.name,
  19563.                 value: item.storage.get()
  19564.               });
  19565.             });
  19566.           });
  19567.         };
  19568.       };
  19569.       var getMenuItemSetup = function (item) {
  19570.         return function (api) {
  19571.           api.setActive(item.storage.get());
  19572.         };
  19573.       };
  19574.       return function (success) {
  19575.         success(map$2(items, function (item) {
  19576.           var text = item.text.fold(function () {
  19577.             return {};
  19578.           }, function (text) {
  19579.             return { text: text };
  19580.           });
  19581.           return __assign(__assign({
  19582.             type: item.type,
  19583.             active: false
  19584.           }, text), {
  19585.             onAction: getMenuItemAction(item),
  19586.             onSetup: getMenuItemSetup(item)
  19587.           });
  19588.         }));
  19589.       };
  19590.     };
  19591.  
  19592.     var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) {
  19593.       if (extraBehaviours === void 0) {
  19594.         extraBehaviours = [];
  19595.       }
  19596.       var action = actionOpt.fold(function () {
  19597.         return {};
  19598.       }, function (action) {
  19599.         return { action: action };
  19600.       });
  19601.       var common = __assign({
  19602.         buttonBehaviours: derive$1([
  19603.           DisablingConfigs.button(function () {
  19604.             return spec.disabled || providersBackstage.isDisabled();
  19605.           }),
  19606.           receivingConfig(),
  19607.           Tabstopping.config({}),
  19608.           config('button press', [
  19609.             preventDefault('click'),
  19610.             preventDefault('mousedown')
  19611.           ])
  19612.         ].concat(extraBehaviours)),
  19613.         eventOrder: {
  19614.           click: [
  19615.             'button press',
  19616.             'alloy.base.behaviour'
  19617.           ],
  19618.           mousedown: [
  19619.             'button press',
  19620.             'alloy.base.behaviour'
  19621.           ]
  19622.         }
  19623.       }, action);
  19624.       var domFinal = deepMerge(common, { dom: dom });
  19625.       return deepMerge(domFinal, { components: components });
  19626.     };
  19627.     var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  19628.       if (extraBehaviours === void 0) {
  19629.         extraBehaviours = [];
  19630.       }
  19631.       var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  19632.         return {
  19633.           'aria-label': providersBackstage.translate(tooltip),
  19634.           'title': providersBackstage.translate(tooltip)
  19635.         };
  19636.       }).getOr({});
  19637.       var dom = {
  19638.         tag: 'button',
  19639.         classes: ['tox-tbtn'],
  19640.         attributes: tooltipAttributes
  19641.       };
  19642.       var icon = spec.icon.map(function (iconName) {
  19643.         return renderIconFromPack(iconName, providersBackstage.icons);
  19644.       });
  19645.       var components = componentRenderPipeline([icon]);
  19646.       return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  19647.     };
  19648.     var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  19649.       if (extraBehaviours === void 0) {
  19650.         extraBehaviours = [];
  19651.       }
  19652.       var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
  19653.       return Button.sketch(iconButtonSpec);
  19654.     };
  19655.     var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  19656.       if (extraBehaviours === void 0) {
  19657.         extraBehaviours = [];
  19658.       }
  19659.       if (extraClasses === void 0) {
  19660.         extraClasses = [];
  19661.       }
  19662.       var translatedText = providersBackstage.translate(spec.text);
  19663.       var icon = spec.icon ? spec.icon.map(function (iconName) {
  19664.         return renderIconFromPack(iconName, providersBackstage.icons);
  19665.       }) : Optional.none();
  19666.       var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  19667.       var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  19668.       var classes = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [
  19669.         'tox-button',
  19670.         'tox-button--secondary'
  19671.       ] : ['tox-button'], true), icon.isSome() ? ['tox-button--icon'] : [], true), spec.borderless ? ['tox-button--naked'] : [], true), extraClasses, true);
  19672.       var dom = __assign(__assign({
  19673.         tag: 'button',
  19674.         classes: classes
  19675.       }, innerHtml), { attributes: { title: translatedText } });
  19676.       return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  19677.     };
  19678.     var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  19679.       if (extraBehaviours === void 0) {
  19680.         extraBehaviours = [];
  19681.       }
  19682.       if (extraClasses === void 0) {
  19683.         extraClasses = [];
  19684.       }
  19685.       var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
  19686.       return Button.sketch(buttonSpec);
  19687.     };
  19688.     var getAction = function (name, buttonType) {
  19689.       return function (comp) {
  19690.         if (buttonType === 'custom') {
  19691.           emitWith(comp, formActionEvent, {
  19692.             name: name,
  19693.             value: {}
  19694.           });
  19695.         } else if (buttonType === 'submit') {
  19696.           emit(comp, formSubmitEvent);
  19697.         } else if (buttonType === 'cancel') {
  19698.           emit(comp, formCancelEvent);
  19699.         } else {
  19700.           console.error('Unknown button type: ', buttonType);
  19701.         }
  19702.       };
  19703.     };
  19704.     var isMenuFooterButtonSpec = function (spec, buttonType) {
  19705.       return buttonType === 'menu';
  19706.     };
  19707.     var isNormalFooterButtonSpec = function (spec, buttonType) {
  19708.       return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  19709.     };
  19710.     var renderFooterButton = function (spec, buttonType, backstage) {
  19711.       if (isMenuFooterButtonSpec(spec, buttonType)) {
  19712.         var getButton = function () {
  19713.           return memButton_1;
  19714.         };
  19715.         var menuButtonSpec = spec;
  19716.         var fixedSpec = __assign(__assign({}, spec), {
  19717.           onSetup: function (api) {
  19718.             api.setDisabled(spec.disabled);
  19719.             return noop;
  19720.           },
  19721.           fetch: getFetch(menuButtonSpec.items, getButton, backstage)
  19722.         });
  19723.         var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none()));
  19724.         return memButton_1.asSpec();
  19725.       } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  19726.         var action = getAction(spec.name, buttonType);
  19727.         var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  19728.         return renderButton(buttonSpec, action, backstage.shared.providers, []);
  19729.       } else {
  19730.         console.error('Unknown footer button type: ', buttonType);
  19731.       }
  19732.     };
  19733.     var renderDialogButton = function (spec, providersBackstage) {
  19734.       var action = getAction(spec.name, 'custom');
  19735.       return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
  19736.         RepresentingConfigs.memory(''),
  19737.         ComposingConfigs.self()
  19738.       ]))));
  19739.     };
  19740.  
  19741.     var schema$h = constant$1([
  19742.       defaulted('field1Name', 'field1'),
  19743.       defaulted('field2Name', 'field2'),
  19744.       onStrictHandler('onLockedChange'),
  19745.       markers$1(['lockClass']),
  19746.       defaulted('locked', false),
  19747.       SketchBehaviours.field('coupledFieldBehaviours', [
  19748.         Composing,
  19749.         Representing
  19750.       ])
  19751.     ]);
  19752.     var getField = function (comp, detail, partName) {
  19753.       return getPart(comp, detail, partName).bind(Composing.getCurrent);
  19754.     };
  19755.     var coupledPart = function (selfName, otherName) {
  19756.       return required({
  19757.         factory: FormField,
  19758.         name: selfName,
  19759.         overrides: function (detail) {
  19760.           return {
  19761.             fieldBehaviours: derive$1([config('coupled-input-behaviour', [run$1(input(), function (me) {
  19762.                   getField(me, detail, otherName).each(function (other) {
  19763.                     getPart(me, detail, 'lock').each(function (lock) {
  19764.                       if (Toggling.isOn(lock)) {
  19765.                         detail.onLockedChange(me, other, lock);
  19766.                       }
  19767.                     });
  19768.                   });
  19769.                 })])])
  19770.           };
  19771.         }
  19772.       });
  19773.     };
  19774.     var parts$c = constant$1([
  19775.       coupledPart('field1', 'field2'),
  19776.       coupledPart('field2', 'field1'),
  19777.       required({
  19778.         factory: Button,
  19779.         schema: [required$1('dom')],
  19780.         name: 'lock',
  19781.         overrides: function (detail) {
  19782.           return {
  19783.             buttonBehaviours: derive$1([Toggling.config({
  19784.                 selected: detail.locked,
  19785.                 toggleClass: detail.markers.lockClass,
  19786.                 aria: { mode: 'pressed' }
  19787.               })])
  19788.           };
  19789.         }
  19790.       })
  19791.     ]);
  19792.  
  19793.     var factory$f = function (detail, components, _spec, _externals) {
  19794.       return {
  19795.         uid: detail.uid,
  19796.         dom: detail.dom,
  19797.         components: components,
  19798.         behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  19799.           Composing.config({ find: Optional.some }),
  19800.           Representing.config({
  19801.             store: {
  19802.               mode: 'manual',
  19803.               getValue: function (comp) {
  19804.                 var _a;
  19805.                 var parts = getPartsOrDie(comp, detail, [
  19806.                   'field1',
  19807.                   'field2'
  19808.                 ]);
  19809.                 return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  19810.               },
  19811.               setValue: function (comp, value) {
  19812.                 var parts = getPartsOrDie(comp, detail, [
  19813.                   'field1',
  19814.                   'field2'
  19815.                 ]);
  19816.                 if (hasNonNullableKey(value, detail.field1Name)) {
  19817.                   Representing.setValue(parts.field1(), value[detail.field1Name]);
  19818.                 }
  19819.                 if (hasNonNullableKey(value, detail.field2Name)) {
  19820.                   Representing.setValue(parts.field2(), value[detail.field2Name]);
  19821.                 }
  19822.               }
  19823.             }
  19824.           })
  19825.         ]),
  19826.         apis: {
  19827.           getField1: function (component) {
  19828.             return getPart(component, detail, 'field1');
  19829.           },
  19830.           getField2: function (component) {
  19831.             return getPart(component, detail, 'field2');
  19832.           },
  19833.           getLock: function (component) {
  19834.             return getPart(component, detail, 'lock');
  19835.           }
  19836.         }
  19837.       };
  19838.     };
  19839.     var FormCoupledInputs = composite({
  19840.       name: 'FormCoupledInputs',
  19841.       configFields: schema$h(),
  19842.       partFields: parts$c(),
  19843.       factory: factory$f,
  19844.       apis: {
  19845.         getField1: function (apis, component) {
  19846.           return apis.getField1(component);
  19847.         },
  19848.         getField2: function (apis, component) {
  19849.           return apis.getField2(component);
  19850.         },
  19851.         getLock: function (apis, component) {
  19852.           return apis.getLock(component);
  19853.         }
  19854.       }
  19855.     });
  19856.  
  19857.     var formatSize = function (size) {
  19858.       var unitDec = {
  19859.         '': 0,
  19860.         'px': 0,
  19861.         'pt': 1,
  19862.         'mm': 1,
  19863.         'pc': 2,
  19864.         'ex': 2,
  19865.         'em': 2,
  19866.         'ch': 2,
  19867.         'rem': 2,
  19868.         'cm': 3,
  19869.         'in': 4,
  19870.         '%': 4
  19871.       };
  19872.       var maxDecimal = function (unit) {
  19873.         return unit in unitDec ? unitDec[unit] : 1;
  19874.       };
  19875.       var numText = size.value.toFixed(maxDecimal(size.unit));
  19876.       if (numText.indexOf('.') !== -1) {
  19877.         numText = numText.replace(/\.?0*$/, '');
  19878.       }
  19879.       return numText + size.unit;
  19880.     };
  19881.     var parseSize = function (sizeText) {
  19882.       var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  19883.       var match = numPattern.exec(sizeText);
  19884.       if (match !== null) {
  19885.         var value = parseFloat(match[1]);
  19886.         var unit = match[2];
  19887.         return Result.value({
  19888.           value: value,
  19889.           unit: unit
  19890.         });
  19891.       } else {
  19892.         return Result.error(sizeText);
  19893.       }
  19894.     };
  19895.     var convertUnit = function (size, unit) {
  19896.       var inInch = {
  19897.         '': 96,
  19898.         'px': 96,
  19899.         'pt': 72,
  19900.         'cm': 2.54,
  19901.         'pc': 12,
  19902.         'mm': 25.4,
  19903.         'in': 1
  19904.       };
  19905.       var supported = function (u) {
  19906.         return has$2(inInch, u);
  19907.       };
  19908.       if (size.unit === unit) {
  19909.         return Optional.some(size.value);
  19910.       } else if (supported(size.unit) && supported(unit)) {
  19911.         if (inInch[size.unit] === inInch[unit]) {
  19912.           return Optional.some(size.value);
  19913.         } else {
  19914.           return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
  19915.         }
  19916.       } else {
  19917.         return Optional.none();
  19918.       }
  19919.     };
  19920.     var noSizeConversion = function (_input) {
  19921.       return Optional.none();
  19922.     };
  19923.     var ratioSizeConversion = function (scale, unit) {
  19924.       return function (size) {
  19925.         return convertUnit(size, unit).map(function (value) {
  19926.           return {
  19927.             value: value * scale,
  19928.             unit: unit
  19929.           };
  19930.         });
  19931.       };
  19932.     };
  19933.     var makeRatioConverter = function (currentFieldText, otherFieldText) {
  19934.       var cValue = parseSize(currentFieldText).toOptional();
  19935.       var oValue = parseSize(otherFieldText).toOptional();
  19936.       return lift2(cValue, oValue, function (cSize, oSize) {
  19937.         return convertUnit(cSize, oSize.unit).map(function (val) {
  19938.           return oSize.value / val;
  19939.         }).map(function (r) {
  19940.           return ratioSizeConversion(r, oSize.unit);
  19941.         }).getOr(noSizeConversion);
  19942.       }).getOr(noSizeConversion);
  19943.     };
  19944.  
  19945.     var renderSizeInput = function (spec, providersBackstage) {
  19946.       var converter = noSizeConversion;
  19947.       var ratioEvent = generate$6('ratio-event');
  19948.       var makeIcon = function (iconName) {
  19949.         return render$3(iconName, {
  19950.           tag: 'span',
  19951.           classes: [
  19952.             'tox-icon',
  19953.             'tox-lock-icon__' + iconName
  19954.           ]
  19955.         }, providersBackstage.icons);
  19956.       };
  19957.       var pLock = FormCoupledInputs.parts.lock({
  19958.         dom: {
  19959.           tag: 'button',
  19960.           classes: [
  19961.             'tox-lock',
  19962.             'tox-button',
  19963.             'tox-button--naked',
  19964.             'tox-button--icon'
  19965.           ],
  19966.           attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  19967.         },
  19968.         components: [
  19969.           makeIcon('lock'),
  19970.           makeIcon('unlock')
  19971.         ],
  19972.         buttonBehaviours: derive$1([
  19973.           Disabling.config({
  19974.             disabled: function () {
  19975.               return spec.disabled || providersBackstage.isDisabled();
  19976.             }
  19977.           }),
  19978.           receivingConfig(),
  19979.           Tabstopping.config({})
  19980.         ])
  19981.       });
  19982.       var formGroup = function (components) {
  19983.         return {
  19984.           dom: {
  19985.             tag: 'div',
  19986.             classes: ['tox-form__group']
  19987.           },
  19988.           components: components
  19989.         };
  19990.       };
  19991.       var getFieldPart = function (isField1) {
  19992.         return FormField.parts.field({
  19993.           factory: Input,
  19994.           inputClasses: ['tox-textfield'],
  19995.           inputBehaviours: derive$1([
  19996.             Disabling.config({
  19997.               disabled: function () {
  19998.                 return spec.disabled || providersBackstage.isDisabled();
  19999.               }
  20000.             }),
  20001.             receivingConfig(),
  20002.             Tabstopping.config({}),
  20003.             config('size-input-events', [
  20004.               run$1(focusin(), function (component, _simulatedEvent) {
  20005.                 emitWith(component, ratioEvent, { isField1: isField1 });
  20006.               }),
  20007.               run$1(change(), function (component, _simulatedEvent) {
  20008.                 emitWith(component, formChangeEvent, { name: spec.name });
  20009.               })
  20010.             ])
  20011.           ]),
  20012.           selectOnFocus: false
  20013.         });
  20014.       };
  20015.       var getLabel = function (label) {
  20016.         return {
  20017.           dom: {
  20018.             tag: 'label',
  20019.             classes: ['tox-label'],
  20020.             innerHtml: providersBackstage.translate(label)
  20021.           }
  20022.         };
  20023.       };
  20024.       var widthField = FormCoupledInputs.parts.field1(formGroup([
  20025.         FormField.parts.label(getLabel('Width')),
  20026.         getFieldPart(true)
  20027.       ]));
  20028.       var heightField = FormCoupledInputs.parts.field2(formGroup([
  20029.         FormField.parts.label(getLabel('Height')),
  20030.         getFieldPart(false)
  20031.       ]));
  20032.       return FormCoupledInputs.sketch({
  20033.         dom: {
  20034.           tag: 'div',
  20035.           classes: ['tox-form__group']
  20036.         },
  20037.         components: [{
  20038.             dom: {
  20039.               tag: 'div',
  20040.               classes: ['tox-form__controls-h-stack']
  20041.             },
  20042.             components: [
  20043.               widthField,
  20044.               heightField,
  20045.               formGroup([
  20046.                 getLabel('&nbsp;'),
  20047.                 pLock
  20048.               ])
  20049.             ]
  20050.           }],
  20051.         field1Name: 'width',
  20052.         field2Name: 'height',
  20053.         locked: true,
  20054.         markers: { lockClass: 'tox-locked' },
  20055.         onLockedChange: function (current, other, _lock) {
  20056.           parseSize(Representing.getValue(current)).each(function (size) {
  20057.             converter(size).each(function (newSize) {
  20058.               Representing.setValue(other, formatSize(newSize));
  20059.             });
  20060.           });
  20061.         },
  20062.         coupledFieldBehaviours: derive$1([
  20063.           Disabling.config({
  20064.             disabled: function () {
  20065.               return spec.disabled || providersBackstage.isDisabled();
  20066.             },
  20067.             onDisabled: function (comp) {
  20068.               FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  20069.               FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  20070.               FormCoupledInputs.getLock(comp).each(Disabling.disable);
  20071.             },
  20072.             onEnabled: function (comp) {
  20073.               FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  20074.               FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  20075.               FormCoupledInputs.getLock(comp).each(Disabling.enable);
  20076.             }
  20077.           }),
  20078.           receivingConfig(),
  20079.           config('size-input-events2', [run$1(ratioEvent, function (component, simulatedEvent) {
  20080.               var isField1 = simulatedEvent.event.isField1;
  20081.               var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  20082.               var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  20083.               var value1 = optCurrent.map(Representing.getValue).getOr('');
  20084.               var value2 = optOther.map(Representing.getValue).getOr('');
  20085.               converter = makeRatioConverter(value1, value2);
  20086.             })])
  20087.         ])
  20088.       });
  20089.     };
  20090.  
  20091.     var undo = constant$1(generate$6('undo'));
  20092.     var redo = constant$1(generate$6('redo'));
  20093.     var zoom = constant$1(generate$6('zoom'));
  20094.     var back = constant$1(generate$6('back'));
  20095.     var apply = constant$1(generate$6('apply'));
  20096.     var swap = constant$1(generate$6('swap'));
  20097.     var transform$1 = constant$1(generate$6('transform'));
  20098.     var tempTransform = constant$1(generate$6('temp-transform'));
  20099.     var transformApply = constant$1(generate$6('transform-apply'));
  20100.     var internal = {
  20101.       undo: undo,
  20102.       redo: redo,
  20103.       zoom: zoom,
  20104.       back: back,
  20105.       apply: apply,
  20106.       swap: swap,
  20107.       transform: transform$1,
  20108.       tempTransform: tempTransform,
  20109.       transformApply: transformApply
  20110.     };
  20111.     var saveState = constant$1('save-state');
  20112.     var disable = constant$1('disable');
  20113.     var enable = constant$1('enable');
  20114.     var external = {
  20115.       formActionEvent: formActionEvent,
  20116.       saveState: saveState,
  20117.       disable: disable,
  20118.       enable: enable
  20119.     };
  20120.  
  20121.     var renderEditPanel = function (imagePanel, providersBackstage) {
  20122.       var createButton = function (text, action, disabled, primary) {
  20123.         return record(renderButton({
  20124.           name: text,
  20125.           text: text,
  20126.           disabled: disabled,
  20127.           primary: primary,
  20128.           icon: Optional.none(),
  20129.           borderless: false
  20130.         }, action, providersBackstage));
  20131.       };
  20132.       var createIconButton = function (icon, tooltip, action, disabled) {
  20133.         return record(renderIconButton({
  20134.           name: icon,
  20135.           icon: Optional.some(icon),
  20136.           tooltip: Optional.some(tooltip),
  20137.           disabled: disabled,
  20138.           primary: false,
  20139.           borderless: false
  20140.         }, action, providersBackstage));
  20141.       };
  20142.       var disableAllComponents = function (comps, eventcomp) {
  20143.         comps.map(function (mem) {
  20144.           var component = mem.get(eventcomp);
  20145.           if (component.hasConfigured(Disabling)) {
  20146.             Disabling.disable(component);
  20147.           }
  20148.         });
  20149.       };
  20150.       var enableAllComponents = function (comps, eventcomp) {
  20151.         comps.map(function (mem) {
  20152.           var component = mem.get(eventcomp);
  20153.           if (component.hasConfigured(Disabling)) {
  20154.             Disabling.enable(component);
  20155.           }
  20156.         });
  20157.       };
  20158.       var panelDom = {
  20159.         tag: 'div',
  20160.         classes: [
  20161.           'tox-image-tools__toolbar',
  20162.           'tox-image-tools-edit-panel'
  20163.         ]
  20164.       };
  20165.       var noop$1 = noop;
  20166.       var emit$1 = function (comp, event, data) {
  20167.         emitWith(comp, event, data);
  20168.       };
  20169.       var emitDisable = function (component) {
  20170.         return emit(component, external.disable());
  20171.       };
  20172.       var emitEnable = function (component) {
  20173.         return emit(component, external.enable());
  20174.       };
  20175.       var emitTransform = function (comp, transform) {
  20176.         emitDisable(comp);
  20177.         emit$1(comp, internal.transform(), { transform: transform });
  20178.         emitEnable(comp);
  20179.       };
  20180.       var emitTempTransform = function (comp, transform) {
  20181.         emitDisable(comp);
  20182.         emit$1(comp, internal.tempTransform(), { transform: transform });
  20183.         emitEnable(comp);
  20184.       };
  20185.       var getBackSwap = function (anyInSystem) {
  20186.         return function () {
  20187.           memContainer.getOpt(anyInSystem).each(function (container) {
  20188.             Replacing.set(container, [ButtonPanel]);
  20189.           });
  20190.         };
  20191.       };
  20192.       var emitTransformApply = function (comp, transform) {
  20193.         emitDisable(comp);
  20194.         emit$1(comp, internal.transformApply(), {
  20195.           transform: transform,
  20196.           swap: getBackSwap(comp)
  20197.         });
  20198.         emitEnable(comp);
  20199.       };
  20200.       var createBackButton = function () {
  20201.         return createButton('Back', function (button) {
  20202.           return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  20203.         }, false, false);
  20204.       };
  20205.       var createSpacer = function () {
  20206.         return record({
  20207.           dom: {
  20208.             tag: 'div',
  20209.             classes: ['tox-spacer']
  20210.           },
  20211.           behaviours: derive$1([Disabling.config({})])
  20212.         });
  20213.       };
  20214.       var createApplyButton = function () {
  20215.         return createButton('Apply', function (button) {
  20216.           return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  20217.         }, true, true);
  20218.       };
  20219.       var makeCropTransform = function () {
  20220.         return function (ir) {
  20221.           var rect = imagePanel.getRect();
  20222.           return crop(ir, rect.x, rect.y, rect.w, rect.h);
  20223.         };
  20224.       };
  20225.       var cropPanelComponents = [
  20226.         createBackButton(),
  20227.         createSpacer(),
  20228.         createButton('Apply', function (button) {
  20229.           var transform = makeCropTransform();
  20230.           emitTransformApply(button, transform);
  20231.           imagePanel.hideCrop();
  20232.         }, false, true)
  20233.       ];
  20234.       var CropPanel = Container.sketch({
  20235.         dom: panelDom,
  20236.         components: cropPanelComponents.map(function (mem) {
  20237.           return mem.asSpec();
  20238.         }),
  20239.         containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  20240.             run$1(external.disable(), function (comp, _se) {
  20241.               disableAllComponents(cropPanelComponents, comp);
  20242.             }),
  20243.             run$1(external.enable(), function (comp, _se) {
  20244.               enableAllComponents(cropPanelComponents, comp);
  20245.             })
  20246.           ])])
  20247.       });
  20248.       var memSize = record(renderSizeInput({
  20249.         name: 'size',
  20250.         label: Optional.none(),
  20251.         constrain: true,
  20252.         disabled: false
  20253.       }, providersBackstage));
  20254.       var makeResizeTransform = function (width, height) {
  20255.         return function (ir) {
  20256.           return resize$1(ir, width, height);
  20257.         };
  20258.       };
  20259.       var resizePanelComponents = [
  20260.         createBackButton(),
  20261.         createSpacer(),
  20262.         memSize,
  20263.         createSpacer(),
  20264.         createButton('Apply', function (button) {
  20265.           memSize.getOpt(button).each(function (sizeInput) {
  20266.             var value = Representing.getValue(sizeInput);
  20267.             var width = parseInt(value.width, 10);
  20268.             var height = parseInt(value.height, 10);
  20269.             var transform = makeResizeTransform(width, height);
  20270.             emitTransformApply(button, transform);
  20271.           });
  20272.         }, false, true)
  20273.       ];
  20274.       var ResizePanel = Container.sketch({
  20275.         dom: panelDom,
  20276.         components: resizePanelComponents.map(function (mem) {
  20277.           return mem.asSpec();
  20278.         }),
  20279.         containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  20280.             run$1(external.disable(), function (comp, _se) {
  20281.               disableAllComponents(resizePanelComponents, comp);
  20282.             }),
  20283.             run$1(external.enable(), function (comp, _se) {
  20284.               enableAllComponents(resizePanelComponents, comp);
  20285.             })
  20286.           ])])
  20287.       });
  20288.       var makeValueTransform = function (transform, value) {
  20289.         return function (ir) {
  20290.           return transform(ir, value);
  20291.         };
  20292.       };
  20293.       var horizontalFlip = makeValueTransform(flip, 'h');
  20294.       var verticalFlip = makeValueTransform(flip, 'v');
  20295.       var counterclockwiseRotate = makeValueTransform(rotate, -90);
  20296.       var clockwiseRotate = makeValueTransform(rotate, 90);
  20297.       var flipRotateOnAction = function (comp, operation) {
  20298.         emitTempTransform(comp, operation);
  20299.       };
  20300.       var flipRotateComponents = [
  20301.         createBackButton(),
  20302.         createSpacer(),
  20303.         createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  20304.           flipRotateOnAction(button, horizontalFlip);
  20305.         }, false),
  20306.         createIconButton('flip-vertically', 'Flip vertically', function (button) {
  20307.           flipRotateOnAction(button, verticalFlip);
  20308.         }, false),
  20309.         createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  20310.           flipRotateOnAction(button, counterclockwiseRotate);
  20311.         }, false),
  20312.         createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  20313.           flipRotateOnAction(button, clockwiseRotate);
  20314.         }, false),
  20315.         createSpacer(),
  20316.         createApplyButton()
  20317.       ];
  20318.       var FlipRotatePanel = Container.sketch({
  20319.         dom: panelDom,
  20320.         components: flipRotateComponents.map(function (mem) {
  20321.           return mem.asSpec();
  20322.         }),
  20323.         containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  20324.             run$1(external.disable(), function (comp, _se) {
  20325.               disableAllComponents(flipRotateComponents, comp);
  20326.             }),
  20327.             run$1(external.enable(), function (comp, _se) {
  20328.               enableAllComponents(flipRotateComponents, comp);
  20329.             })
  20330.           ])])
  20331.       });
  20332.       var makeSlider = function (label, onChoose, min, value, max) {
  20333.         var labelPart = Slider.parts.label({
  20334.           dom: {
  20335.             tag: 'label',
  20336.             classes: ['tox-label'],
  20337.             innerHtml: providersBackstage.translate(label)
  20338.           }
  20339.         });
  20340.         var spectrum = Slider.parts.spectrum({
  20341.           dom: {
  20342.             tag: 'div',
  20343.             classes: ['tox-slider__rail'],
  20344.             attributes: { role: 'presentation' }
  20345.           }
  20346.         });
  20347.         var thumb = Slider.parts.thumb({
  20348.           dom: {
  20349.             tag: 'div',
  20350.             classes: ['tox-slider__handle'],
  20351.             attributes: { role: 'presentation' }
  20352.           }
  20353.         });
  20354.         return record(Slider.sketch({
  20355.           dom: {
  20356.             tag: 'div',
  20357.             classes: ['tox-slider'],
  20358.             attributes: { role: 'presentation' }
  20359.           },
  20360.           model: {
  20361.             mode: 'x',
  20362.             minX: min,
  20363.             maxX: max,
  20364.             getInitialValue: constant$1({ x: value })
  20365.           },
  20366.           components: [
  20367.             labelPart,
  20368.             spectrum,
  20369.             thumb
  20370.           ],
  20371.           sliderBehaviours: derive$1([Focusing.config({})]),
  20372.           onChoose: onChoose
  20373.         }));
  20374.       };
  20375.       var makeVariableSlider = function (label, transform, min, value, max) {
  20376.         var onChoose = function (slider, _thumb, value) {
  20377.           var valTransform = makeValueTransform(transform, value.x / 100);
  20378.           emitTransform(slider, valTransform);
  20379.         };
  20380.         return makeSlider(label, onChoose, min, value, max);
  20381.       };
  20382.       var variableFilterPanelComponents = function (label, transform, min, value, max) {
  20383.         return [
  20384.           createBackButton(),
  20385.           makeVariableSlider(label, transform, min, value, max),
  20386.           createApplyButton()
  20387.         ];
  20388.       };
  20389.       var createVariableFilterPanel = function (label, transform, min, value, max) {
  20390.         var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  20391.         return Container.sketch({
  20392.           dom: panelDom,
  20393.           components: filterPanelComponents.map(function (mem) {
  20394.             return mem.asSpec();
  20395.           }),
  20396.           containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  20397.               run$1(external.disable(), function (comp, _se) {
  20398.                 disableAllComponents(filterPanelComponents, comp);
  20399.               }),
  20400.               run$1(external.enable(), function (comp, _se) {
  20401.                 enableAllComponents(filterPanelComponents, comp);
  20402.               })
  20403.             ])])
  20404.         });
  20405.       };
  20406.       var filterPanelComponents = [
  20407.         createBackButton(),
  20408.         createSpacer(),
  20409.         createApplyButton()
  20410.       ];
  20411.       var FilterPanel = Container.sketch({
  20412.         dom: panelDom,
  20413.         components: filterPanelComponents.map(function (mem) {
  20414.           return mem.asSpec();
  20415.         })
  20416.       });
  20417.       var BrightnessPanel = createVariableFilterPanel('Brightness', brightness, -100, 0, 100);
  20418.       var ContrastPanel = createVariableFilterPanel('Contrast', contrast, -100, 0, 100);
  20419.       var GammaPanel = createVariableFilterPanel('Gamma', gamma, -100, 0, 100);
  20420.       var makeColorTransform = function (red, green, blue) {
  20421.         return function (ir) {
  20422.           return colorize(ir, red, green, blue);
  20423.         };
  20424.       };
  20425.       var makeColorSlider = function (label) {
  20426.         var onChoose = function (slider, _thumb, _value) {
  20427.           var redOpt = memRed.getOpt(slider);
  20428.           var blueOpt = memBlue.getOpt(slider);
  20429.           var greenOpt = memGreen.getOpt(slider);
  20430.           redOpt.each(function (red) {
  20431.             blueOpt.each(function (blue) {
  20432.               greenOpt.each(function (green) {
  20433.                 var r = Representing.getValue(red).x / 100;
  20434.                 var g = Representing.getValue(green).x / 100;
  20435.                 var b = Representing.getValue(blue).x / 100;
  20436.                 var transform = makeColorTransform(r, g, b);
  20437.                 emitTransform(slider, transform);
  20438.               });
  20439.             });
  20440.           });
  20441.         };
  20442.         return makeSlider(label, onChoose, 0, 100, 200);
  20443.       };
  20444.       var memRed = makeColorSlider('R');
  20445.       var memGreen = makeColorSlider('G');
  20446.       var memBlue = makeColorSlider('B');
  20447.       var colorizePanelComponents = [
  20448.         createBackButton(),
  20449.         memRed,
  20450.         memGreen,
  20451.         memBlue,
  20452.         createApplyButton()
  20453.       ];
  20454.       var ColorizePanel = Container.sketch({
  20455.         dom: panelDom,
  20456.         components: colorizePanelComponents.map(function (mem) {
  20457.           return mem.asSpec();
  20458.         })
  20459.       });
  20460.       var getTransformPanelEvent = function (panel, transform, update) {
  20461.         return function (button) {
  20462.           var swap = function () {
  20463.             memContainer.getOpt(button).each(function (container) {
  20464.               Replacing.set(container, [panel]);
  20465.               update(container);
  20466.             });
  20467.           };
  20468.           emit$1(button, internal.swap(), {
  20469.             transform: transform,
  20470.             swap: swap
  20471.           });
  20472.         };
  20473.       };
  20474.       var cropPanelUpdate = function (_anyInSystem) {
  20475.         imagePanel.showCrop();
  20476.       };
  20477.       var resizePanelUpdate = function (anyInSystem) {
  20478.         memSize.getOpt(anyInSystem).each(function (sizeInput) {
  20479.           var measurements = imagePanel.getMeasurements();
  20480.           var width = measurements.width;
  20481.           var height = measurements.height;
  20482.           Representing.setValue(sizeInput, {
  20483.             width: width,
  20484.             height: height
  20485.           });
  20486.         });
  20487.       };
  20488.       var sharpenTransform = Optional.some(sharpen);
  20489.       var invertTransform = Optional.some(invert);
  20490.       var buttonPanelComponents = [
  20491.         createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
  20492.         createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
  20493.         createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
  20494.         createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
  20495.         createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  20496.         createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
  20497.         createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
  20498.         createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
  20499.         createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  20500.       ];
  20501.       var ButtonPanel = Container.sketch({
  20502.         dom: panelDom,
  20503.         components: buttonPanelComponents.map(function (mem) {
  20504.           return mem.asSpec();
  20505.         })
  20506.       });
  20507.       var container = Container.sketch({
  20508.         dom: { tag: 'div' },
  20509.         components: [ButtonPanel],
  20510.         containerBehaviours: derive$1([Replacing.config({})])
  20511.       });
  20512.       var memContainer = record(container);
  20513.       var getApplyButton = function (anyInSystem) {
  20514.         return memContainer.getOpt(anyInSystem).map(function (container) {
  20515.           var panel = container.components()[0];
  20516.           return panel.components()[panel.components().length - 1];
  20517.         });
  20518.       };
  20519.       return {
  20520.         memContainer: memContainer,
  20521.         getApplyButton: getApplyButton
  20522.       };
  20523.     };
  20524.  
  20525.     var global$4 = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  20526.  
  20527.     var global$3 = tinymce.util.Tools.resolve('tinymce.util.Observable');
  20528.  
  20529.     var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK');
  20530.  
  20531.     var getDocumentSize = function (doc) {
  20532.       var max = Math.max;
  20533.       var documentElement = doc.documentElement;
  20534.       var body = doc.body;
  20535.       var scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  20536.       var clientWidth = max(documentElement.clientWidth, body.clientWidth);
  20537.       var offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  20538.       var scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  20539.       var clientHeight = max(documentElement.clientHeight, body.clientHeight);
  20540.       var offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  20541.       return {
  20542.         width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  20543.         height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  20544.       };
  20545.     };
  20546.     var isTouchEvent$1 = function (e) {
  20547.       return isNonNullable(e.changedTouches);
  20548.     };
  20549.     var updateWithTouchData = function (e) {
  20550.       if (isTouchEvent$1(e)) {
  20551.         var keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  20552.         for (var i = 0; i < keys.length; i++) {
  20553.           e[keys[i]] = e.changedTouches[0][keys[i]];
  20554.         }
  20555.       }
  20556.     };
  20557.     function DragHelper (id, settings) {
  20558.       var _a, _b, _c;
  20559.       var eventOverlay;
  20560.       var handleEvents = [];
  20561.       var overlayEvents = [];
  20562.       var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  20563.       var root = (_b = settings.root) !== null && _b !== void 0 ? _b : doc;
  20564.       var sugarDoc = SugarElement.fromDom(doc);
  20565.       var downButton;
  20566.       var startX;
  20567.       var startY;
  20568.       var handleElement = SugarElement.fromDom(root.getElementById((_c = settings.handle) !== null && _c !== void 0 ? _c : id));
  20569.       var start = function (e) {
  20570.         var rawEvent = e.raw;
  20571.         var docSize = getDocumentSize(doc);
  20572.         updateWithTouchData(rawEvent);
  20573.         e.prevent();
  20574.         downButton = rawEvent.button;
  20575.         startX = rawEvent.screenX;
  20576.         startY = rawEvent.screenY;
  20577.         var cursor = get$c(handleElement, 'cursor');
  20578.         eventOverlay = SugarElement.fromTag('div', doc);
  20579.         setAll(eventOverlay, {
  20580.           'position': 'absolute',
  20581.           'top': '0',
  20582.           'left': '0',
  20583.           'width': docSize.width + 'px',
  20584.           'height': docSize.height + 'px',
  20585.           'z-index': 2147483647 + '',
  20586.           'opacity': '0.0001',
  20587.           cursor: cursor
  20588.         });
  20589.         append$2(getBody(sugarDoc), eventOverlay);
  20590.         overlayEvents.push(bind(sugarDoc, 'mousemove', drag), bind(sugarDoc, 'touchmove', drag), bind(sugarDoc, 'mouseup', stop), bind(sugarDoc, 'touchend', stop));
  20591.         settings.start(rawEvent);
  20592.       };
  20593.       var drag = function (e) {
  20594.         var rawEvent = e.raw;
  20595.         updateWithTouchData(rawEvent);
  20596.         if (rawEvent.button !== downButton) {
  20597.           return stop(e);
  20598.         }
  20599.         rawEvent.deltaX = rawEvent.screenX - startX;
  20600.         rawEvent.deltaY = rawEvent.screenY - startY;
  20601.         e.prevent();
  20602.         settings.drag(rawEvent);
  20603.       };
  20604.       var stop = function (e) {
  20605.         updateWithTouchData(e.raw);
  20606.         each$1(overlayEvents, function (e) {
  20607.           return e.unbind();
  20608.         });
  20609.         overlayEvents = [];
  20610.         remove$5(eventOverlay);
  20611.         if (settings.stop) {
  20612.           settings.stop(e.raw);
  20613.         }
  20614.       };
  20615.       var destroy = function () {
  20616.         each$1(overlayEvents.concat(handleEvents), function (e) {
  20617.           return e.unbind();
  20618.         });
  20619.         overlayEvents = [];
  20620.         handleEvents = [];
  20621.         if (isNonNullable(eventOverlay)) {
  20622.           remove$5(eventOverlay);
  20623.         }
  20624.       };
  20625.       handleEvents.push(bind(handleElement, 'mousedown', start), bind(handleElement, 'touchstart', start));
  20626.       return { destroy: destroy };
  20627.     }
  20628.  
  20629.     var count = 0;
  20630.     var create$1 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  20631.       var dragHelpers;
  20632.       var events = [];
  20633.       var prefix = 'tox-';
  20634.       var id = prefix + 'crid-' + count++;
  20635.       var container = SugarElement.fromDom(containerElm);
  20636.       var handles = [
  20637.         {
  20638.           name: 'move',
  20639.           xMul: 0,
  20640.           yMul: 0,
  20641.           deltaX: 1,
  20642.           deltaY: 1,
  20643.           deltaW: 0,
  20644.           deltaH: 0,
  20645.           label: 'Crop Mask'
  20646.         },
  20647.         {
  20648.           name: 'nw',
  20649.           xMul: 0,
  20650.           yMul: 0,
  20651.           deltaX: 1,
  20652.           deltaY: 1,
  20653.           deltaW: -1,
  20654.           deltaH: -1,
  20655.           label: 'Top Left Crop Handle'
  20656.         },
  20657.         {
  20658.           name: 'ne',
  20659.           xMul: 1,
  20660.           yMul: 0,
  20661.           deltaX: 0,
  20662.           deltaY: 1,
  20663.           deltaW: 1,
  20664.           deltaH: -1,
  20665.           label: 'Top Right Crop Handle'
  20666.         },
  20667.         {
  20668.           name: 'sw',
  20669.           xMul: 0,
  20670.           yMul: 1,
  20671.           deltaX: 1,
  20672.           deltaY: 0,
  20673.           deltaW: -1,
  20674.           deltaH: 1,
  20675.           label: 'Bottom Left Crop Handle'
  20676.         },
  20677.         {
  20678.           name: 'se',
  20679.           xMul: 1,
  20680.           yMul: 1,
  20681.           deltaX: 0,
  20682.           deltaY: 0,
  20683.           deltaW: 1,
  20684.           deltaH: 1,
  20685.           label: 'Bottom Right Crop Handle'
  20686.         }
  20687.       ];
  20688.       var blockers = [
  20689.         'top',
  20690.         'right',
  20691.         'bottom',
  20692.         'left'
  20693.       ];
  20694.       var getAbsoluteRect = function (outerRect, relativeRect) {
  20695.         return {
  20696.           x: relativeRect.x + outerRect.x,
  20697.           y: relativeRect.y + outerRect.y,
  20698.           w: relativeRect.w,
  20699.           h: relativeRect.h
  20700.         };
  20701.       };
  20702.       var getRelativeRect = function (outerRect, innerRect) {
  20703.         return {
  20704.           x: innerRect.x - outerRect.x,
  20705.           y: innerRect.y - outerRect.y,
  20706.           w: innerRect.w,
  20707.           h: innerRect.h
  20708.         };
  20709.       };
  20710.       var getInnerRect = function () {
  20711.         return getRelativeRect(clampRect, currentRect);
  20712.       };
  20713.       var moveRect = function (handle, startRect, deltaX, deltaY) {
  20714.         var x = startRect.x + deltaX * handle.deltaX;
  20715.         var y = startRect.y + deltaY * handle.deltaY;
  20716.         var w = Math.max(20, startRect.w + deltaX * handle.deltaW);
  20717.         var h = Math.max(20, startRect.h + deltaY * handle.deltaH);
  20718.         var rect = currentRect = global$4.clamp({
  20719.           x: x,
  20720.           y: y,
  20721.           w: w,
  20722.           h: h
  20723.         }, clampRect, handle.name === 'move');
  20724.         rect = getRelativeRect(clampRect, rect);
  20725.         instance.fire('updateRect', { rect: rect });
  20726.         setInnerRect(rect);
  20727.       };
  20728.       var render = function () {
  20729.         var createDragHelper = function (handle) {
  20730.           var startRect;
  20731.           return DragHelper(id, {
  20732.             document: containerElm.ownerDocument,
  20733.             root: getRootNode(container).dom,
  20734.             handle: id + '-' + handle.name,
  20735.             start: function () {
  20736.               startRect = currentRect;
  20737.             },
  20738.             drag: function (e) {
  20739.               moveRect(handle, startRect, e.deltaX, e.deltaY);
  20740.             }
  20741.           });
  20742.         };
  20743.         var cropContainer = SugarElement.fromTag('div');
  20744.         setAll$1(cropContainer, {
  20745.           id: id,
  20746.           'class': prefix + 'croprect-container',
  20747.           'role': 'grid',
  20748.           'aria-dropeffect': 'execute'
  20749.         });
  20750.         append$2(container, cropContainer);
  20751.         each$1(blockers, function (blocker) {
  20752.           descendant(container, '#' + id).each(function (blockerElm) {
  20753.             var cropBlocker = SugarElement.fromTag('div');
  20754.             setAll$1(cropBlocker, {
  20755.               'id': id + '-' + blocker,
  20756.               'class': prefix + 'croprect-block',
  20757.               'data-mce-bogus': 'all'
  20758.             });
  20759.             set$7(cropBlocker, 'display', 'none');
  20760.             append$2(blockerElm, cropBlocker);
  20761.           });
  20762.         });
  20763.         each$1(handles, function (handle) {
  20764.           descendant(container, '#' + id).each(function (handleElm) {
  20765.             var cropHandle = SugarElement.fromTag('div');
  20766.             setAll$1(cropHandle, {
  20767.               'id': id + '-' + handle.name,
  20768.               'aria-label': handle.label,
  20769.               'aria-grabbed': 'false',
  20770.               'data-mce-bogus': 'all',
  20771.               'role': 'gridcell',
  20772.               'tabindex': '-1',
  20773.               'title': handle.label
  20774.             });
  20775.             add$1(cropHandle, [
  20776.               prefix + 'croprect-handle',
  20777.               prefix + 'croprect-handle-' + handle.name
  20778.             ]);
  20779.             set$7(cropHandle, 'display', 'none');
  20780.             append$2(handleElm, cropHandle);
  20781.           });
  20782.         });
  20783.         dragHelpers = map$2(handles, createDragHelper);
  20784.         repaint(currentRect);
  20785.         var handleFocus = function (e) {
  20786.           set$8(e.target, 'aria-grabbed', e.raw.type === 'focus' ? 'true' : 'false');
  20787.         };
  20788.         var handleKeydown = function (e) {
  20789.           var activeHandle;
  20790.           each$1(handles, function (handle) {
  20791.             if (get$d(e.target, 'id') === id + '-' + handle.name) {
  20792.               activeHandle = handle;
  20793.               return false;
  20794.             }
  20795.           });
  20796.           var moveAndBlock = function (evt, handle, startRect, deltaX, deltaY) {
  20797.             evt.stopPropagation();
  20798.             evt.preventDefault();
  20799.             moveRect(activeHandle, startRect, deltaX, deltaY);
  20800.           };
  20801.           switch (e.raw.keyCode) {
  20802.           case global$2.LEFT:
  20803.             moveAndBlock(e, activeHandle, currentRect, -10, 0);
  20804.             break;
  20805.           case global$2.RIGHT:
  20806.             moveAndBlock(e, activeHandle, currentRect, 10, 0);
  20807.             break;
  20808.           case global$2.UP:
  20809.             moveAndBlock(e, activeHandle, currentRect, 0, -10);
  20810.             break;
  20811.           case global$2.DOWN:
  20812.             moveAndBlock(e, activeHandle, currentRect, 0, 10);
  20813.             break;
  20814.           case global$2.ENTER:
  20815.           case global$2.SPACEBAR:
  20816.             e.prevent();
  20817.             action();
  20818.             break;
  20819.           }
  20820.         };
  20821.         events.push(bind(container, 'focusin', handleFocus), bind(container, 'focusout', handleFocus), bind(container, 'keydown', handleKeydown));
  20822.       };
  20823.       var toggleVisibility = function (state) {
  20824.         var selectors = __spreadArray(__spreadArray([], map$2(handles, function (handle) {
  20825.           return '#' + id + '-' + handle.name;
  20826.         }), true), map$2(blockers, function (blocker) {
  20827.           return '#' + id + '-' + blocker;
  20828.         }), true).join(',');
  20829.         var elems = descendants(container, selectors);
  20830.         if (state) {
  20831.           each$1(elems, function (elm) {
  20832.             return remove$6(elm, 'display');
  20833.           });
  20834.         } else {
  20835.           each$1(elems, function (elm) {
  20836.             return set$7(elm, 'display', 'none');
  20837.           });
  20838.         }
  20839.       };
  20840.       var repaint = function (rect) {
  20841.         var updateElementRect = function (name, newRect) {
  20842.           descendant(container, '#' + id + '-' + name).each(function (elm) {
  20843.             setAll(elm, {
  20844.               left: newRect.x + 'px',
  20845.               top: newRect.y + 'px',
  20846.               width: Math.max(0, newRect.w) + 'px',
  20847.               height: Math.max(0, newRect.h) + 'px'
  20848.             });
  20849.           });
  20850.         };
  20851.         each$1(handles, function (handle) {
  20852.           descendant(container, '#' + id + '-' + handle.name).each(function (elm) {
  20853.             setAll(elm, {
  20854.               left: rect.w * handle.xMul + rect.x + 'px',
  20855.               top: rect.h * handle.yMul + rect.y + 'px'
  20856.             });
  20857.           });
  20858.         });
  20859.         updateElementRect('top', {
  20860.           x: viewPortRect.x,
  20861.           y: viewPortRect.y,
  20862.           w: viewPortRect.w,
  20863.           h: rect.y - viewPortRect.y
  20864.         });
  20865.         updateElementRect('right', {
  20866.           x: rect.x + rect.w,
  20867.           y: rect.y,
  20868.           w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  20869.           h: rect.h
  20870.         });
  20871.         updateElementRect('bottom', {
  20872.           x: viewPortRect.x,
  20873.           y: rect.y + rect.h,
  20874.           w: viewPortRect.w,
  20875.           h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  20876.         });
  20877.         updateElementRect('left', {
  20878.           x: viewPortRect.x,
  20879.           y: rect.y,
  20880.           w: rect.x - viewPortRect.x,
  20881.           h: rect.h
  20882.         });
  20883.         updateElementRect('move', rect);
  20884.       };
  20885.       var setRect = function (rect) {
  20886.         currentRect = rect;
  20887.         repaint(currentRect);
  20888.       };
  20889.       var setViewPortRect = function (rect) {
  20890.         viewPortRect = rect;
  20891.         repaint(currentRect);
  20892.       };
  20893.       var setInnerRect = function (rect) {
  20894.         setRect(getAbsoluteRect(clampRect, rect));
  20895.       };
  20896.       var setClampRect = function (rect) {
  20897.         clampRect = rect;
  20898.         repaint(currentRect);
  20899.       };
  20900.       var destroy = function () {
  20901.         each$1(dragHelpers, function (helper) {
  20902.           return helper.destroy();
  20903.         });
  20904.         dragHelpers = [];
  20905.         each$1(events, function (e) {
  20906.           return e.unbind();
  20907.         });
  20908.         events = [];
  20909.       };
  20910.       render();
  20911.       var instance = __assign(__assign({}, global$3), {
  20912.         toggleVisibility: toggleVisibility,
  20913.         setClampRect: setClampRect,
  20914.         setRect: setRect,
  20915.         getInnerRect: getInnerRect,
  20916.         setInnerRect: setInnerRect,
  20917.         setViewPortRect: setViewPortRect,
  20918.         destroy: destroy
  20919.       });
  20920.       return instance;
  20921.     };
  20922.     var CropRect = { create: create$1 };
  20923.  
  20924.     var loadImage = function (image) {
  20925.       return new global$c(function (resolve) {
  20926.         var loaded = function () {
  20927.           image.removeEventListener('load', loaded);
  20928.           resolve(image);
  20929.         };
  20930.         if (image.complete) {
  20931.           resolve(image);
  20932.         } else {
  20933.           image.addEventListener('load', loaded);
  20934.         }
  20935.       });
  20936.     };
  20937.     var renderImagePanel = function (initialUrl) {
  20938.       var memBg = record({
  20939.         dom: {
  20940.           tag: 'div',
  20941.           classes: ['tox-image-tools__image-bg'],
  20942.           attributes: { role: 'presentation' }
  20943.         }
  20944.       });
  20945.       var zoomState = Cell(1);
  20946.       var cropRect = api$1();
  20947.       var rectState = Cell({
  20948.         x: 0,
  20949.         y: 0,
  20950.         w: 1,
  20951.         h: 1
  20952.       });
  20953.       var viewRectState = Cell({
  20954.         x: 0,
  20955.         y: 0,
  20956.         w: 1,
  20957.         h: 1
  20958.       });
  20959.       var repaintImg = function (anyInSystem, img) {
  20960.         memContainer.getOpt(anyInSystem).each(function (panel) {
  20961.           var zoom = zoomState.get();
  20962.           var panelW = get$a(panel.element);
  20963.           var panelH = get$b(panel.element);
  20964.           var width = img.dom.naturalWidth * zoom;
  20965.           var height = img.dom.naturalHeight * zoom;
  20966.           var left = Math.max(0, panelW / 2 - width / 2);
  20967.           var top = Math.max(0, panelH / 2 - height / 2);
  20968.           var css = {
  20969.             left: left.toString() + 'px',
  20970.             top: top.toString() + 'px',
  20971.             width: width.toString() + 'px',
  20972.             height: height.toString() + 'px',
  20973.             position: 'absolute'
  20974.           };
  20975.           setAll(img, css);
  20976.           memBg.getOpt(panel).each(function (bg) {
  20977.             setAll(bg.element, css);
  20978.           });
  20979.           cropRect.run(function (cRect) {
  20980.             var rect = rectState.get();
  20981.             cRect.setRect({
  20982.               x: rect.x * zoom + left,
  20983.               y: rect.y * zoom + top,
  20984.               w: rect.w * zoom,
  20985.               h: rect.h * zoom
  20986.             });
  20987.             cRect.setClampRect({
  20988.               x: left,
  20989.               y: top,
  20990.               w: width,
  20991.               h: height
  20992.             });
  20993.             cRect.setViewPortRect({
  20994.               x: 0,
  20995.               y: 0,
  20996.               w: panelW,
  20997.               h: panelH
  20998.             });
  20999.           });
  21000.         });
  21001.       };
  21002.       var zoomFit = function (anyInSystem, img) {
  21003.         memContainer.getOpt(anyInSystem).each(function (panel) {
  21004.           var panelW = get$a(panel.element);
  21005.           var panelH = get$b(panel.element);
  21006.           var width = img.dom.naturalWidth;
  21007.           var height = img.dom.naturalHeight;
  21008.           var zoom = Math.min(panelW / width, panelH / height);
  21009.           if (zoom >= 1) {
  21010.             zoomState.set(1);
  21011.           } else {
  21012.             zoomState.set(zoom);
  21013.           }
  21014.         });
  21015.       };
  21016.       var updateSrc = function (anyInSystem, url) {
  21017.         var img = SugarElement.fromTag('img');
  21018.         set$8(img, 'src', url);
  21019.         return loadImage(img.dom).then(function () {
  21020.           if (anyInSystem.getSystem().isConnected()) {
  21021.             memContainer.getOpt(anyInSystem).map(function (panel) {
  21022.               var aImg = external$2({ element: img });
  21023.               Replacing.replaceAt(panel, 1, Optional.some(aImg));
  21024.               var lastViewRect = viewRectState.get();
  21025.               var viewRect = {
  21026.                 x: 0,
  21027.                 y: 0,
  21028.                 w: img.dom.naturalWidth,
  21029.                 h: img.dom.naturalHeight
  21030.               };
  21031.               viewRectState.set(viewRect);
  21032.               var rect = global$4.inflate(viewRect, -20, -20);
  21033.               rectState.set(rect);
  21034.               if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  21035.                 zoomFit(panel, img);
  21036.               }
  21037.               repaintImg(panel, img);
  21038.             });
  21039.           }
  21040.         });
  21041.       };
  21042.       var zoom = function (anyInSystem, direction) {
  21043.         var currentZoom = zoomState.get();
  21044.         var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  21045.         zoomState.set(newZoom);
  21046.         memContainer.getOpt(anyInSystem).each(function (panel) {
  21047.           var img = panel.components()[1].element;
  21048.           repaintImg(panel, img);
  21049.         });
  21050.       };
  21051.       var showCrop = function () {
  21052.         cropRect.run(function (cRect) {
  21053.           cRect.toggleVisibility(true);
  21054.         });
  21055.       };
  21056.       var hideCrop = function () {
  21057.         cropRect.run(function (cRect) {
  21058.           cRect.toggleVisibility(false);
  21059.         });
  21060.       };
  21061.       var getRect = function () {
  21062.         return rectState.get();
  21063.       };
  21064.       var container = Container.sketch({
  21065.         dom: {
  21066.           tag: 'div',
  21067.           classes: ['tox-image-tools__image']
  21068.         },
  21069.         components: [
  21070.           memBg.asSpec(),
  21071.           {
  21072.             dom: {
  21073.               tag: 'img',
  21074.               attributes: { src: initialUrl }
  21075.             }
  21076.           },
  21077.           {
  21078.             dom: { tag: 'div' },
  21079.             behaviours: derive$1([config('image-panel-crop-events', [
  21080.                 runOnAttached(function (comp) {
  21081.                   memContainer.getOpt(comp).each(function (container) {
  21082.                     var el = container.element.dom;
  21083.                     var cRect = CropRect.create({
  21084.                       x: 10,
  21085.                       y: 10,
  21086.                       w: 100,
  21087.                       h: 100
  21088.                     }, {
  21089.                       x: 0,
  21090.                       y: 0,
  21091.                       w: 200,
  21092.                       h: 200
  21093.                     }, {
  21094.                       x: 0,
  21095.                       y: 0,
  21096.                       w: 200,
  21097.                       h: 200
  21098.                     }, el, noop);
  21099.                     cRect.toggleVisibility(false);
  21100.                     cRect.on('updateRect', function (e) {
  21101.                       var rect = e.rect;
  21102.                       var zoom = zoomState.get();
  21103.                       var newRect = {
  21104.                         x: Math.round(rect.x / zoom),
  21105.                         y: Math.round(rect.y / zoom),
  21106.                         w: Math.round(rect.w / zoom),
  21107.                         h: Math.round(rect.h / zoom)
  21108.                       };
  21109.                       rectState.set(newRect);
  21110.                     });
  21111.                     cropRect.set(cRect);
  21112.                   });
  21113.                 }),
  21114.                 runOnDetached(function () {
  21115.                   cropRect.clear();
  21116.                 })
  21117.               ])])
  21118.           }
  21119.         ],
  21120.         containerBehaviours: derive$1([
  21121.           Replacing.config({}),
  21122.           config('image-panel-events', [runOnAttached(function (comp) {
  21123.               updateSrc(comp, initialUrl);
  21124.             })])
  21125.         ])
  21126.       });
  21127.       var memContainer = record(container);
  21128.       var getMeasurements = function () {
  21129.         var viewRect = viewRectState.get();
  21130.         return {
  21131.           width: viewRect.w,
  21132.           height: viewRect.h
  21133.         };
  21134.       };
  21135.       return {
  21136.         memContainer: memContainer,
  21137.         updateSrc: updateSrc,
  21138.         zoom: zoom,
  21139.         showCrop: showCrop,
  21140.         hideCrop: hideCrop,
  21141.         getRect: getRect,
  21142.         getMeasurements: getMeasurements
  21143.       };
  21144.     };
  21145.  
  21146.     var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  21147.       return renderIconButton({
  21148.         name: innerHtml,
  21149.         icon: Optional.some(icon),
  21150.         disabled: disabled,
  21151.         tooltip: Optional.some(innerHtml),
  21152.         primary: false,
  21153.         borderless: false
  21154.       }, action, providersBackstage);
  21155.     };
  21156.     var setButtonEnabled = function (button, enabled) {
  21157.       if (enabled) {
  21158.         Disabling.enable(button);
  21159.       } else {
  21160.         Disabling.disable(button);
  21161.       }
  21162.     };
  21163.     var renderSideBar = function (providersBackstage) {
  21164.       var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  21165.         memUndo.getOpt(anyInSystem).each(function (undo) {
  21166.           setButtonEnabled(undo, undoEnabled);
  21167.         });
  21168.         memRedo.getOpt(anyInSystem).each(function (redo) {
  21169.           setButtonEnabled(redo, redoEnabled);
  21170.         });
  21171.       };
  21172.       var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  21173.         emitWith(button, internal.undo(), { direction: 1 });
  21174.       }, providersBackstage));
  21175.       var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  21176.         emitWith(button, internal.redo(), { direction: 1 });
  21177.       }, providersBackstage));
  21178.       var container = Container.sketch({
  21179.         dom: {
  21180.           tag: 'div',
  21181.           classes: [
  21182.             'tox-image-tools__toolbar',
  21183.             'tox-image-tools__sidebar'
  21184.           ]
  21185.         },
  21186.         components: [
  21187.           memUndo.asSpec(),
  21188.           memRedo.asSpec(),
  21189.           createButton('Zoom in', 'zoom-in', false, function (button) {
  21190.             emitWith(button, internal.zoom(), { direction: 1 });
  21191.           }, providersBackstage),
  21192.           createButton('Zoom out', 'zoom-out', false, function (button) {
  21193.             emitWith(button, internal.zoom(), { direction: -1 });
  21194.           }, providersBackstage)
  21195.         ]
  21196.       });
  21197.       return {
  21198.         container: container,
  21199.         updateButtonUndoStates: updateButtonUndoStates
  21200.       };
  21201.     };
  21202.  
  21203.     function UndoStack () {
  21204.       var data = [];
  21205.       var index = -1;
  21206.       var add = function (state) {
  21207.         var removed = data.splice(++index);
  21208.         data.push(state);
  21209.         return {
  21210.           state: state,
  21211.           removed: removed
  21212.         };
  21213.       };
  21214.       var undo = function () {
  21215.         if (canUndo()) {
  21216.           return data[--index];
  21217.         }
  21218.       };
  21219.       var redo = function () {
  21220.         if (canRedo()) {
  21221.           return data[++index];
  21222.         }
  21223.       };
  21224.       var canUndo = function () {
  21225.         return index > 0;
  21226.       };
  21227.       var canRedo = function () {
  21228.         return index !== -1 && index < data.length - 1;
  21229.       };
  21230.       return {
  21231.         data: data,
  21232.         add: add,
  21233.         undo: undo,
  21234.         redo: redo,
  21235.         canUndo: canUndo,
  21236.         canRedo: canRedo
  21237.       };
  21238.     }
  21239.  
  21240.     var makeState = function (initialState) {
  21241.       var blobState = Cell(initialState);
  21242.       var tempState = value$1();
  21243.       var undoStack = UndoStack();
  21244.       undoStack.add(initialState);
  21245.       var getBlobState = function () {
  21246.         return blobState.get();
  21247.       };
  21248.       var setBlobState = function (state) {
  21249.         blobState.set(state);
  21250.       };
  21251.       var getTempState = function () {
  21252.         return tempState.get().getOrThunk(blobState.get);
  21253.       };
  21254.       var updateTempState = function (blob) {
  21255.         var newTempState = createState(blob);
  21256.         destroyTempState();
  21257.         tempState.set(newTempState);
  21258.         return newTempState.url;
  21259.       };
  21260.       var createState = function (blob) {
  21261.         return {
  21262.           blob: blob,
  21263.           url: URL.createObjectURL(blob)
  21264.         };
  21265.       };
  21266.       var destroyState = function (state) {
  21267.         URL.revokeObjectURL(state.url);
  21268.       };
  21269.       var destroyStates = function (states) {
  21270.         global$5.each(states, destroyState);
  21271.       };
  21272.       var destroyTempState = function () {
  21273.         tempState.on(destroyState);
  21274.         tempState.clear();
  21275.       };
  21276.       var addBlobState = function (blob) {
  21277.         var newState = createState(blob);
  21278.         setBlobState(newState);
  21279.         var removed = undoStack.add(newState).removed;
  21280.         destroyStates(removed);
  21281.         return newState.url;
  21282.       };
  21283.       var addTempState = function (blob) {
  21284.         var newState = createState(blob);
  21285.         tempState.set(newState);
  21286.         return newState.url;
  21287.       };
  21288.       var applyTempState = function (postApply) {
  21289.         return tempState.get().fold(noop, function (temp) {
  21290.           addBlobState(temp.blob);
  21291.           postApply();
  21292.         });
  21293.       };
  21294.       var undo = function () {
  21295.         var currentState = undoStack.undo();
  21296.         setBlobState(currentState);
  21297.         return currentState.url;
  21298.       };
  21299.       var redo = function () {
  21300.         var currentState = undoStack.redo();
  21301.         setBlobState(currentState);
  21302.         return currentState.url;
  21303.       };
  21304.       var getHistoryStates = function () {
  21305.         var undoEnabled = undoStack.canUndo();
  21306.         var redoEnabled = undoStack.canRedo();
  21307.         return {
  21308.           undoEnabled: undoEnabled,
  21309.           redoEnabled: redoEnabled
  21310.         };
  21311.       };
  21312.       return {
  21313.         getBlobState: getBlobState,
  21314.         setBlobState: setBlobState,
  21315.         addBlobState: addBlobState,
  21316.         getTempState: getTempState,
  21317.         updateTempState: updateTempState,
  21318.         addTempState: addTempState,
  21319.         applyTempState: applyTempState,
  21320.         destroyTempState: destroyTempState,
  21321.         undo: undo,
  21322.         redo: redo,
  21323.         getHistoryStates: getHistoryStates
  21324.       };
  21325.     };
  21326.  
  21327.     var renderImageTools = function (detail, providersBackstage) {
  21328.       var state = makeState(detail.currentState);
  21329.       var zoom = function (anyInSystem, simulatedEvent) {
  21330.         var direction = simulatedEvent.event.direction;
  21331.         imagePanel.zoom(anyInSystem, direction);
  21332.       };
  21333.       var updateButtonUndoStates = function (anyInSystem) {
  21334.         var historyStates = state.getHistoryStates();
  21335.         sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  21336.         emitWith(anyInSystem, external.formActionEvent, {
  21337.           name: external.saveState(),
  21338.           value: historyStates.undoEnabled
  21339.         });
  21340.       };
  21341.       var disableUndoRedo = function (anyInSystem) {
  21342.         sideBar.updateButtonUndoStates(anyInSystem, false, false);
  21343.       };
  21344.       var undo = function (anyInSystem, _simulatedEvent) {
  21345.         var url = state.undo();
  21346.         updateSrc(anyInSystem, url).then(function (_oImg) {
  21347.           unblock(anyInSystem);
  21348.           updateButtonUndoStates(anyInSystem);
  21349.         });
  21350.       };
  21351.       var redo = function (anyInSystem, _simulatedEvent) {
  21352.         var url = state.redo();
  21353.         updateSrc(anyInSystem, url).then(function (_oImg) {
  21354.           unblock(anyInSystem);
  21355.           updateButtonUndoStates(anyInSystem);
  21356.         });
  21357.       };
  21358.       var imageResultToBlob = function (ir) {
  21359.         return ir.toBlob();
  21360.       };
  21361.       var block = function (anyInSystem) {
  21362.         emitWith(anyInSystem, external.formActionEvent, {
  21363.           name: external.disable(),
  21364.           value: {}
  21365.         });
  21366.       };
  21367.       var unblock = function (anyInSystem) {
  21368.         editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  21369.           Disabling.enable(applyButton);
  21370.         });
  21371.         emitWith(anyInSystem, external.formActionEvent, {
  21372.           name: external.enable(),
  21373.           value: {}
  21374.         });
  21375.       };
  21376.       var updateSrc = function (anyInSystem, src) {
  21377.         block(anyInSystem);
  21378.         return imagePanel.updateSrc(anyInSystem, src);
  21379.       };
  21380.       var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  21381.         block(anyInSystem);
  21382.         blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  21383.           return updateSrc(anyInSystem, url);
  21384.         }).then(function () {
  21385.           updateButtonUndoStates(anyInSystem);
  21386.           swap();
  21387.           unblock(anyInSystem);
  21388.         }).catch(function (err) {
  21389.           console.log(err);
  21390.           if (anyInSystem.getSystem().isConnected()) {
  21391.             unblock(anyInSystem);
  21392.           }
  21393.         });
  21394.       };
  21395.       var manipulate = function (anyInSystem, filter, swap) {
  21396.         var blob = state.getBlobState().blob;
  21397.         var action = function (blob) {
  21398.           return state.updateTempState(blob);
  21399.         };
  21400.         blobManipulate(anyInSystem, blob, filter, action, swap);
  21401.       };
  21402.       var tempManipulate = function (anyInSystem, filter) {
  21403.         var blob = state.getTempState().blob;
  21404.         var action = function (blob) {
  21405.           return state.addTempState(blob);
  21406.         };
  21407.         blobManipulate(anyInSystem, blob, filter, action, noop);
  21408.       };
  21409.       var manipulateApply = function (anyInSystem, filter, swap) {
  21410.         var blob = state.getBlobState().blob;
  21411.         var action = function (blob) {
  21412.           var url = state.addBlobState(blob);
  21413.           destroyTempState(anyInSystem);
  21414.           return url;
  21415.         };
  21416.         blobManipulate(anyInSystem, blob, filter, action, swap);
  21417.       };
  21418.       var apply = function (anyInSystem, simulatedEvent) {
  21419.         var postApply = function () {
  21420.           destroyTempState(anyInSystem);
  21421.           var swap = simulatedEvent.event.swap;
  21422.           swap();
  21423.         };
  21424.         state.applyTempState(postApply);
  21425.       };
  21426.       var destroyTempState = function (anyInSystem) {
  21427.         var currentUrl = state.getBlobState().url;
  21428.         state.destroyTempState();
  21429.         updateButtonUndoStates(anyInSystem);
  21430.         return currentUrl;
  21431.       };
  21432.       var cancel = function (anyInSystem) {
  21433.         var currentUrl = destroyTempState(anyInSystem);
  21434.         updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
  21435.           unblock(anyInSystem);
  21436.         });
  21437.       };
  21438.       var back = function (anyInSystem, simulatedEvent) {
  21439.         cancel(anyInSystem);
  21440.         var swap = simulatedEvent.event.swap;
  21441.         swap();
  21442.         imagePanel.hideCrop();
  21443.       };
  21444.       var transform = function (anyInSystem, simulatedEvent) {
  21445.         return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
  21446.       };
  21447.       var tempTransform = function (anyInSystem, simulatedEvent) {
  21448.         return tempManipulate(anyInSystem, simulatedEvent.event.transform);
  21449.       };
  21450.       var transformApply = function (anyInSystem, simulatedEvent) {
  21451.         return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
  21452.       };
  21453.       var imagePanel = renderImagePanel(detail.currentState.url);
  21454.       var sideBar = renderSideBar(providersBackstage);
  21455.       var editPanel = renderEditPanel(imagePanel, providersBackstage);
  21456.       var swap = function (anyInSystem, simulatedEvent) {
  21457.         disableUndoRedo(anyInSystem);
  21458.         var transform = simulatedEvent.event.transform;
  21459.         var swap = simulatedEvent.event.swap;
  21460.         transform.fold(function () {
  21461.           swap();
  21462.         }, function (transform) {
  21463.           manipulate(anyInSystem, transform, swap);
  21464.         });
  21465.       };
  21466.       return {
  21467.         dom: {
  21468.           tag: 'div',
  21469.           attributes: { role: 'presentation' }
  21470.         },
  21471.         components: [
  21472.           editPanel.memContainer.asSpec(),
  21473.           imagePanel.memContainer.asSpec(),
  21474.           sideBar.container
  21475.         ],
  21476.         behaviours: derive$1([
  21477.           Representing.config({
  21478.             store: {
  21479.               mode: 'manual',
  21480.               getValue: function () {
  21481.                 return state.getBlobState();
  21482.               }
  21483.             }
  21484.           }),
  21485.           config('image-tools-events', [
  21486.             run$1(internal.undo(), undo),
  21487.             run$1(internal.redo(), redo),
  21488.             run$1(internal.zoom(), zoom),
  21489.             run$1(internal.back(), back),
  21490.             run$1(internal.apply(), apply),
  21491.             run$1(internal.transform(), transform),
  21492.             run$1(internal.tempTransform(), tempTransform),
  21493.             run$1(internal.transformApply(), transformApply),
  21494.             run$1(internal.swap(), swap)
  21495.           ]),
  21496.           ComposingConfigs.self()
  21497.         ])
  21498.       };
  21499.     };
  21500.  
  21501.     var renderLabel = function (spec, backstageShared) {
  21502.       var label = {
  21503.         dom: {
  21504.           tag: 'label',
  21505.           innerHtml: backstageShared.providers.translate(spec.label),
  21506.           classes: ['tox-label']
  21507.         }
  21508.       };
  21509.       var comps = map$2(spec.items, backstageShared.interpreter);
  21510.       return {
  21511.         dom: {
  21512.           tag: 'div',
  21513.           classes: ['tox-form__group']
  21514.         },
  21515.         components: [label].concat(comps),
  21516.         behaviours: derive$1([
  21517.           ComposingConfigs.self(),
  21518.           Replacing.config({}),
  21519.           RepresentingConfigs.domHtml(Optional.none()),
  21520.           Keying.config({ mode: 'acyclic' })
  21521.         ])
  21522.       };
  21523.     };
  21524.  
  21525.     var isSingleListItem = function (item) {
  21526.       return !has$2(item, 'items');
  21527.     };
  21528.     var dataAttribute = 'data-value';
  21529.     var fetchItems = function (dropdownComp, name, items, selectedValue) {
  21530.       return map$2(items, function (item) {
  21531.         if (!isSingleListItem(item)) {
  21532.           return {
  21533.             type: 'nestedmenuitem',
  21534.             text: item.text,
  21535.             getSubmenuItems: function () {
  21536.               return fetchItems(dropdownComp, name, item.items, selectedValue);
  21537.             }
  21538.           };
  21539.         } else {
  21540.           return {
  21541.             type: 'togglemenuitem',
  21542.             text: item.text,
  21543.             value: item.value,
  21544.             active: item.value === selectedValue,
  21545.             onAction: function () {
  21546.               Representing.setValue(dropdownComp, item.value);
  21547.               emitWith(dropdownComp, formChangeEvent, { name: name });
  21548.               Focusing.focus(dropdownComp);
  21549.             }
  21550.           };
  21551.         }
  21552.       });
  21553.     };
  21554.     var findItemByValue = function (items, value) {
  21555.       return findMap(items, function (item) {
  21556.         if (!isSingleListItem(item)) {
  21557.           return findItemByValue(item.items, value);
  21558.         } else {
  21559.           return someIf(item.value === value, item);
  21560.         }
  21561.       });
  21562.     };
  21563.     var renderListBox = function (spec, backstage) {
  21564.       var providersBackstage = backstage.shared.providers;
  21565.       var initialItem = head(spec.items).filter(isSingleListItem);
  21566.       var pLabel = spec.label.map(function (label) {
  21567.         return renderLabel$2(label, providersBackstage);
  21568.       });
  21569.       var pField = FormField.parts.field({
  21570.         dom: {},
  21571.         factory: {
  21572.           sketch: function (sketchSpec) {
  21573.             return renderCommonDropdown({
  21574.               uid: sketchSpec.uid,
  21575.               text: initialItem.map(function (item) {
  21576.                 return item.text;
  21577.               }),
  21578.               icon: Optional.none(),
  21579.               tooltip: spec.label,
  21580.               role: Optional.none(),
  21581.               fetch: function (comp, callback) {
  21582.                 var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
  21583.                 callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  21584.               },
  21585.               onSetup: constant$1(noop),
  21586.               getApi: constant$1({}),
  21587.               columns: 1,
  21588.               presets: 'normal',
  21589.               classes: [],
  21590.               dropdownBehaviours: [
  21591.                 Tabstopping.config({}),
  21592.                 Representing.config({
  21593.                   store: {
  21594.                     mode: 'manual',
  21595.                     initialValue: initialItem.map(function (item) {
  21596.                       return item.value;
  21597.                     }).getOr(''),
  21598.                     getValue: function (comp) {
  21599.                       return get$d(comp.element, dataAttribute);
  21600.                     },
  21601.                     setValue: function (comp, data) {
  21602.                       findItemByValue(spec.items, data).each(function (item) {
  21603.                         set$8(comp.element, dataAttribute, item.value);
  21604.                         emitWith(comp, updateMenuText, { text: item.text });
  21605.                       });
  21606.                     }
  21607.                   }
  21608.                 })
  21609.               ]
  21610.             }, 'tox-listbox', backstage.shared);
  21611.           }
  21612.         }
  21613.       });
  21614.       var listBoxWrap = {
  21615.         dom: {
  21616.           tag: 'div',
  21617.           classes: ['tox-listboxfield']
  21618.         },
  21619.         components: [pField]
  21620.       };
  21621.       return FormField.sketch({
  21622.         dom: {
  21623.           tag: 'div',
  21624.           classes: ['tox-form__group']
  21625.         },
  21626.         components: flatten([
  21627.           pLabel.toArray(),
  21628.           [listBoxWrap]
  21629.         ]),
  21630.         fieldBehaviours: derive$1([Disabling.config({
  21631.             disabled: constant$1(spec.disabled),
  21632.             onDisabled: function (comp) {
  21633.               FormField.getField(comp).each(Disabling.disable);
  21634.             },
  21635.             onEnabled: function (comp) {
  21636.               FormField.getField(comp).each(Disabling.enable);
  21637.             }
  21638.           })])
  21639.       });
  21640.     };
  21641.  
  21642.     var renderPanel = function (spec, backstage) {
  21643.       return {
  21644.         dom: {
  21645.           tag: 'div',
  21646.           classes: spec.classes
  21647.         },
  21648.         components: map$2(spec.items, backstage.shared.interpreter)
  21649.       };
  21650.     };
  21651.  
  21652.     var factory$e = function (detail, _spec) {
  21653.       var options = map$2(detail.options, function (option) {
  21654.         return {
  21655.           dom: {
  21656.             tag: 'option',
  21657.             value: option.value,
  21658.             innerHtml: option.text
  21659.           }
  21660.         };
  21661.       });
  21662.       var initialValues = detail.data.map(function (v) {
  21663.         return wrap$1('initialValue', v);
  21664.       }).getOr({});
  21665.       return {
  21666.         uid: detail.uid,
  21667.         dom: {
  21668.           tag: 'select',
  21669.           classes: detail.selectClasses,
  21670.           attributes: detail.selectAttributes
  21671.         },
  21672.         components: options,
  21673.         behaviours: augment(detail.selectBehaviours, [
  21674.           Focusing.config({}),
  21675.           Representing.config({
  21676.             store: __assign({
  21677.               mode: 'manual',
  21678.               getValue: function (select) {
  21679.                 return get$5(select.element);
  21680.               },
  21681.               setValue: function (select, newValue) {
  21682.                 var found = find$5(detail.options, function (opt) {
  21683.                   return opt.value === newValue;
  21684.                 });
  21685.                 if (found.isSome()) {
  21686.                   set$4(select.element, newValue);
  21687.                 }
  21688.               }
  21689.             }, initialValues)
  21690.           })
  21691.         ])
  21692.       };
  21693.     };
  21694.     var HtmlSelect = single({
  21695.       name: 'HtmlSelect',
  21696.       configFields: [
  21697.         required$1('options'),
  21698.         field('selectBehaviours', [
  21699.           Focusing,
  21700.           Representing
  21701.         ]),
  21702.         defaulted('selectClasses', []),
  21703.         defaulted('selectAttributes', {}),
  21704.         option('data')
  21705.       ],
  21706.       factory: factory$e
  21707.     });
  21708.  
  21709.     var renderSelectBox = function (spec, providersBackstage) {
  21710.       var translatedOptions = map$2(spec.items, function (item) {
  21711.         return {
  21712.           text: providersBackstage.translate(item.text),
  21713.           value: item.value
  21714.         };
  21715.       });
  21716.       var pLabel = spec.label.map(function (label) {
  21717.         return renderLabel$2(label, providersBackstage);
  21718.       });
  21719.       var pField = FormField.parts.field({
  21720.         dom: {},
  21721.         selectAttributes: { size: spec.size },
  21722.         options: translatedOptions,
  21723.         factory: HtmlSelect,
  21724.         selectBehaviours: derive$1([
  21725.           Disabling.config({
  21726.             disabled: function () {
  21727.               return spec.disabled || providersBackstage.isDisabled();
  21728.             }
  21729.           }),
  21730.           Tabstopping.config({}),
  21731.           config('selectbox-change', [run$1(change(), function (component, _) {
  21732.               emitWith(component, formChangeEvent, { name: spec.name });
  21733.             })])
  21734.         ])
  21735.       });
  21736.       var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3('chevron-down', {
  21737.         tag: 'div',
  21738.         classes: ['tox-selectfield__icon-js']
  21739.       }, providersBackstage.icons));
  21740.       var selectWrap = {
  21741.         dom: {
  21742.           tag: 'div',
  21743.           classes: ['tox-selectfield']
  21744.         },
  21745.         components: flatten([
  21746.           [pField],
  21747.           chevron.toArray()
  21748.         ])
  21749.       };
  21750.       return FormField.sketch({
  21751.         dom: {
  21752.           tag: 'div',
  21753.           classes: ['tox-form__group']
  21754.         },
  21755.         components: flatten([
  21756.           pLabel.toArray(),
  21757.           [selectWrap]
  21758.         ]),
  21759.         fieldBehaviours: derive$1([
  21760.           Disabling.config({
  21761.             disabled: function () {
  21762.               return spec.disabled || providersBackstage.isDisabled();
  21763.             },
  21764.             onDisabled: function (comp) {
  21765.               FormField.getField(comp).each(Disabling.disable);
  21766.             },
  21767.             onEnabled: function (comp) {
  21768.               FormField.getField(comp).each(Disabling.enable);
  21769.             }
  21770.           }),
  21771.           receivingConfig()
  21772.         ])
  21773.       });
  21774.     };
  21775.  
  21776.     var renderTable = function (spec, providersBackstage) {
  21777.       var renderTh = function (text) {
  21778.         return {
  21779.           dom: {
  21780.             tag: 'th',
  21781.             innerHtml: providersBackstage.translate(text)
  21782.           }
  21783.         };
  21784.       };
  21785.       var renderHeader = function (header) {
  21786.         return {
  21787.           dom: { tag: 'thead' },
  21788.           components: [{
  21789.               dom: { tag: 'tr' },
  21790.               components: map$2(header, renderTh)
  21791.             }]
  21792.         };
  21793.       };
  21794.       var renderTd = function (text) {
  21795.         return {
  21796.           dom: {
  21797.             tag: 'td',
  21798.             innerHtml: providersBackstage.translate(text)
  21799.           }
  21800.         };
  21801.       };
  21802.       var renderTr = function (row) {
  21803.         return {
  21804.           dom: { tag: 'tr' },
  21805.           components: map$2(row, renderTd)
  21806.         };
  21807.       };
  21808.       var renderRows = function (rows) {
  21809.         return {
  21810.           dom: { tag: 'tbody' },
  21811.           components: map$2(rows, renderTr)
  21812.         };
  21813.       };
  21814.       return {
  21815.         dom: {
  21816.           tag: 'table',
  21817.           classes: ['tox-dialog__table']
  21818.         },
  21819.         components: [
  21820.           renderHeader(spec.header),
  21821.           renderRows(spec.cells)
  21822.         ],
  21823.         behaviours: derive$1([
  21824.           Tabstopping.config({}),
  21825.           Focusing.config({})
  21826.         ])
  21827.       };
  21828.     };
  21829.  
  21830.     var renderTextField = function (spec, providersBackstage) {
  21831.       var pLabel = spec.label.map(function (label) {
  21832.         return renderLabel$2(label, providersBackstage);
  21833.       });
  21834.       var baseInputBehaviours = [
  21835.         Disabling.config({
  21836.           disabled: function () {
  21837.             return spec.disabled || providersBackstage.isDisabled();
  21838.           }
  21839.         }),
  21840.         receivingConfig(),
  21841.         Keying.config({
  21842.           mode: 'execution',
  21843.           useEnter: spec.multiline !== true,
  21844.           useControlEnter: spec.multiline === true,
  21845.           execute: function (comp) {
  21846.             emit(comp, formSubmitEvent);
  21847.             return Optional.some(true);
  21848.           }
  21849.         }),
  21850.         config('textfield-change', [
  21851.           run$1(input(), function (component, _) {
  21852.             emitWith(component, formChangeEvent, { name: spec.name });
  21853.           }),
  21854.           run$1(postPaste(), function (component, _) {
  21855.             emitWith(component, formChangeEvent, { name: spec.name });
  21856.           })
  21857.         ]),
  21858.         Tabstopping.config({})
  21859.       ];
  21860.       var validatingBehaviours = spec.validation.map(function (vl) {
  21861.         return Invalidating.config({
  21862.           getRoot: function (input) {
  21863.             return parent(input.element);
  21864.           },
  21865.           invalidClass: 'tox-invalid',
  21866.           validator: {
  21867.             validate: function (input) {
  21868.               var v = Representing.getValue(input);
  21869.               var result = vl.validator(v);
  21870.               return Future.pure(result === true ? Result.value(v) : Result.error(result));
  21871.             },
  21872.             validateOnLoad: vl.validateOnLoad
  21873.           }
  21874.         });
  21875.       }).toArray();
  21876.       var placeholder = spec.placeholder.fold(constant$1({}), function (p) {
  21877.         return { placeholder: providersBackstage.translate(p) };
  21878.       });
  21879.       var inputMode = spec.inputMode.fold(constant$1({}), function (mode) {
  21880.         return { inputmode: mode };
  21881.       });
  21882.       var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  21883.       var pField = FormField.parts.field({
  21884.         tag: spec.multiline === true ? 'textarea' : 'input',
  21885.         inputAttributes: inputAttributes,
  21886.         inputClasses: [spec.classname],
  21887.         inputBehaviours: derive$1(flatten([
  21888.           baseInputBehaviours,
  21889.           validatingBehaviours
  21890.         ])),
  21891.         selectOnFocus: false,
  21892.         factory: Input
  21893.       });
  21894.       var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  21895.       var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  21896.       var extraBehaviours = [
  21897.         Disabling.config({
  21898.           disabled: function () {
  21899.             return spec.disabled || providersBackstage.isDisabled();
  21900.           },
  21901.           onDisabled: function (comp) {
  21902.             FormField.getField(comp).each(Disabling.disable);
  21903.           },
  21904.           onEnabled: function (comp) {
  21905.             FormField.getField(comp).each(Disabling.enable);
  21906.           }
  21907.         }),
  21908.         receivingConfig()
  21909.       ];
  21910.       return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  21911.     };
  21912.     var renderInput = function (spec, providersBackstage) {
  21913.       return renderTextField({
  21914.         name: spec.name,
  21915.         multiline: false,
  21916.         label: spec.label,
  21917.         inputMode: spec.inputMode,
  21918.         placeholder: spec.placeholder,
  21919.         flex: false,
  21920.         disabled: spec.disabled,
  21921.         classname: 'tox-textfield',
  21922.         validation: Optional.none(),
  21923.         maximized: spec.maximized
  21924.       }, providersBackstage);
  21925.     };
  21926.     var renderTextarea = function (spec, providersBackstage) {
  21927.       return renderTextField({
  21928.         name: spec.name,
  21929.         multiline: true,
  21930.         label: spec.label,
  21931.         inputMode: Optional.none(),
  21932.         placeholder: spec.placeholder,
  21933.         flex: true,
  21934.         disabled: spec.disabled,
  21935.         classname: 'tox-textarea',
  21936.         validation: Optional.none(),
  21937.         maximized: spec.maximized
  21938.       }, providersBackstage);
  21939.     };
  21940.  
  21941.     var events$6 = function (streamConfig, streamState) {
  21942.       var streams = streamConfig.stream.streams;
  21943.       var processor = streams.setup(streamConfig, streamState);
  21944.       return derive$2([
  21945.         run$1(streamConfig.event, processor),
  21946.         runOnDetached(function () {
  21947.           return streamState.cancel();
  21948.         })
  21949.       ].concat(streamConfig.cancelEvent.map(function (e) {
  21950.         return [run$1(e, function () {
  21951.             return streamState.cancel();
  21952.           })];
  21953.       }).getOr([])));
  21954.     };
  21955.  
  21956.     var ActiveStreaming = /*#__PURE__*/Object.freeze({
  21957.         __proto__: null,
  21958.         events: events$6
  21959.     });
  21960.  
  21961.     var throttle = function (_config) {
  21962.       var state = Cell(null);
  21963.       var readState = function () {
  21964.         return { timer: state.get() !== null ? 'set' : 'unset' };
  21965.       };
  21966.       var setTimer = function (t) {
  21967.         state.set(t);
  21968.       };
  21969.       var cancel = function () {
  21970.         var t = state.get();
  21971.         if (t !== null) {
  21972.           t.cancel();
  21973.         }
  21974.       };
  21975.       return nu$8({
  21976.         readState: readState,
  21977.         setTimer: setTimer,
  21978.         cancel: cancel
  21979.       });
  21980.     };
  21981.     var init$9 = function (spec) {
  21982.       return spec.stream.streams.state(spec);
  21983.     };
  21984.  
  21985.     var StreamingState = /*#__PURE__*/Object.freeze({
  21986.         __proto__: null,
  21987.         throttle: throttle,
  21988.         init: init$9
  21989.     });
  21990.  
  21991.     var setup$c = function (streamInfo, streamState) {
  21992.       var sInfo = streamInfo.stream;
  21993.       var throttler = last(streamInfo.onStream, sInfo.delay);
  21994.       streamState.setTimer(throttler);
  21995.       return function (component, simulatedEvent) {
  21996.         throttler.throttle(component, simulatedEvent);
  21997.         if (sInfo.stopEvent) {
  21998.           simulatedEvent.stop();
  21999.         }
  22000.       };
  22001.     };
  22002.     var StreamingSchema = [
  22003.       requiredOf('stream', choose$1('mode', {
  22004.         throttle: [
  22005.           required$1('delay'),
  22006.           defaulted('stopEvent', true),
  22007.           output$1('streams', {
  22008.             setup: setup$c,
  22009.             state: throttle
  22010.           })
  22011.         ]
  22012.       })),
  22013.       defaulted('event', 'input'),
  22014.       option('cancelEvent'),
  22015.       onStrictHandler('onStream')
  22016.     ];
  22017.  
  22018.     var Streaming = create$8({
  22019.       fields: StreamingSchema,
  22020.       name: 'streaming',
  22021.       active: ActiveStreaming,
  22022.       state: StreamingState
  22023.     });
  22024.  
  22025.     var setValueFromItem = function (model, input, item) {
  22026.       var itemData = Representing.getValue(item);
  22027.       Representing.setValue(input, itemData);
  22028.       setCursorAtEnd(input);
  22029.     };
  22030.     var setSelectionOn = function (input, f) {
  22031.       var el = input.element;
  22032.       var value = get$5(el);
  22033.       var node = el.dom;
  22034.       if (get$d(el, 'type') !== 'number') {
  22035.         f(node, value);
  22036.       }
  22037.     };
  22038.     var setCursorAtEnd = function (input) {
  22039.       setSelectionOn(input, function (node, value) {
  22040.         return node.setSelectionRange(value.length, value.length);
  22041.       });
  22042.     };
  22043.     var setSelectionToEnd = function (input, startOffset) {
  22044.       setSelectionOn(input, function (node, value) {
  22045.         return node.setSelectionRange(startOffset, value.length);
  22046.       });
  22047.     };
  22048.     var attemptSelectOver = function (model, input, item) {
  22049.       if (!model.selectsOver) {
  22050.         return Optional.none();
  22051.       } else {
  22052.         var currentValue = Representing.getValue(input);
  22053.         var inputDisplay_1 = model.getDisplayText(currentValue);
  22054.         var itemValue = Representing.getValue(item);
  22055.         var itemDisplay = model.getDisplayText(itemValue);
  22056.         return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () {
  22057.           setValueFromItem(model, input, item);
  22058.           setSelectionToEnd(input, inputDisplay_1.length);
  22059.         }) : Optional.none();
  22060.       }
  22061.     };
  22062.  
  22063.     var itemExecute = constant$1('alloy.typeahead.itemexecute');
  22064.  
  22065.     var make$3 = function (detail, components, spec, externals) {
  22066.       var navigateList = function (comp, simulatedEvent, highlighter) {
  22067.         detail.previewing.set(false);
  22068.         var sandbox = Coupling.getCoupled(comp, 'sandbox');
  22069.         if (Sandboxing.isOpen(sandbox)) {
  22070.           Composing.getCurrent(sandbox).each(function (menu) {
  22071.             Highlighting.getHighlighted(menu).fold(function () {
  22072.               highlighter(menu);
  22073.             }, function () {
  22074.               dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
  22075.             });
  22076.           });
  22077.         } else {
  22078.           var onOpenSync = function (sandbox) {
  22079.             Composing.getCurrent(sandbox).each(highlighter);
  22080.           };
  22081.           open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22082.         }
  22083.       };
  22084.       var focusBehaviours$1 = focusBehaviours(detail);
  22085.       var mapFetch = function (comp) {
  22086.         return function (tdata) {
  22087.           return tdata.map(function (data) {
  22088.             var menus = values(data.menus);
  22089.             var items = bind$3(menus, function (menu) {
  22090.               return filter$2(menu.items, function (item) {
  22091.                 return item.type === 'item';
  22092.               });
  22093.             });
  22094.             var repState = Representing.getState(comp);
  22095.             repState.update(map$2(items, function (item) {
  22096.               return item.data;
  22097.             }));
  22098.             return data;
  22099.           });
  22100.         };
  22101.       };
  22102.       var behaviours = [
  22103.         Focusing.config({}),
  22104.         Representing.config({
  22105.           onSetValue: detail.onSetValue,
  22106.           store: __assign({
  22107.             mode: 'dataset',
  22108.             getDataKey: function (comp) {
  22109.               return get$5(comp.element);
  22110.             },
  22111.             getFallbackEntry: function (itemString) {
  22112.               return {
  22113.                 value: itemString,
  22114.                 meta: {}
  22115.               };
  22116.             },
  22117.             setValue: function (comp, data) {
  22118.               set$4(comp.element, detail.model.getDisplayText(data));
  22119.             }
  22120.           }, detail.initialData.map(function (d) {
  22121.             return wrap$1('initialValue', d);
  22122.           }).getOr({}))
  22123.         }),
  22124.         Streaming.config({
  22125.           stream: {
  22126.             mode: 'throttle',
  22127.             delay: detail.responseTime,
  22128.             stopEvent: false
  22129.           },
  22130.           onStream: function (component, _simulatedEvent) {
  22131.             var sandbox = Coupling.getCoupled(component, 'sandbox');
  22132.             var focusInInput = Focusing.isFocused(component);
  22133.             if (focusInInput) {
  22134.               if (get$5(component.element).length >= detail.minChars) {
  22135.                 var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  22136.                   return Highlighting.getHighlighted(menu).map(Representing.getValue);
  22137.                 });
  22138.                 detail.previewing.set(true);
  22139.                 var onOpenSync = function (_sandbox) {
  22140.                   Composing.getCurrent(sandbox).each(function (menu) {
  22141.                     previousValue_1.fold(function () {
  22142.                       if (detail.model.selectsOver) {
  22143.                         Highlighting.highlightFirst(menu);
  22144.                       }
  22145.                     }, function (pv) {
  22146.                       Highlighting.highlightBy(menu, function (item) {
  22147.                         var itemData = Representing.getValue(item);
  22148.                         return itemData.value === pv.value;
  22149.                       });
  22150.                       Highlighting.getHighlighted(menu).orThunk(function () {
  22151.                         Highlighting.highlightFirst(menu);
  22152.                         return Optional.none();
  22153.                       });
  22154.                     });
  22155.                   });
  22156.                 };
  22157.                 open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22158.               }
  22159.             }
  22160.           },
  22161.           cancelEvent: typeaheadCancel()
  22162.         }),
  22163.         Keying.config({
  22164.           mode: 'special',
  22165.           onDown: function (comp, simulatedEvent) {
  22166.             navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  22167.             return Optional.some(true);
  22168.           },
  22169.           onEscape: function (comp) {
  22170.             var sandbox = Coupling.getCoupled(comp, 'sandbox');
  22171.             if (Sandboxing.isOpen(sandbox)) {
  22172.               Sandboxing.close(sandbox);
  22173.               return Optional.some(true);
  22174.             }
  22175.             return Optional.none();
  22176.           },
  22177.           onUp: function (comp, simulatedEvent) {
  22178.             navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  22179.             return Optional.some(true);
  22180.           },
  22181.           onEnter: function (comp) {
  22182.             var sandbox = Coupling.getCoupled(comp, 'sandbox');
  22183.             var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  22184.             if (sandboxIsOpen && !detail.previewing.get()) {
  22185.               return Composing.getCurrent(sandbox).bind(function (menu) {
  22186.                 return Highlighting.getHighlighted(menu);
  22187.               }).map(function (item) {
  22188.                 emitWith(comp, itemExecute(), { item: item });
  22189.                 return true;
  22190.               });
  22191.             } else {
  22192.               var currentValue = Representing.getValue(comp);
  22193.               emit(comp, typeaheadCancel());
  22194.               detail.onExecute(sandbox, comp, currentValue);
  22195.               if (sandboxIsOpen) {
  22196.                 Sandboxing.close(sandbox);
  22197.               }
  22198.               return Optional.some(true);
  22199.             }
  22200.           }
  22201.         }),
  22202.         Toggling.config({
  22203.           toggleClass: detail.markers.openClass,
  22204.           aria: { mode: 'expanded' }
  22205.         }),
  22206.         Coupling.config({
  22207.           others: {
  22208.             sandbox: function (hotspot) {
  22209.               return makeSandbox$1(detail, hotspot, {
  22210.                 onOpen: function () {
  22211.                   return Toggling.on(hotspot);
  22212.                 },
  22213.                 onClose: function () {
  22214.                   return Toggling.off(hotspot);
  22215.                 }
  22216.               });
  22217.             }
  22218.           }
  22219.         }),
  22220.         config('typeaheadevents', [
  22221.           runOnExecute$1(function (comp) {
  22222.             var onOpenSync = noop;
  22223.             togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22224.           }),
  22225.           run$1(itemExecute(), function (comp, se) {
  22226.             var sandbox = Coupling.getCoupled(comp, 'sandbox');
  22227.             setValueFromItem(detail.model, comp, se.event.item);
  22228.             emit(comp, typeaheadCancel());
  22229.             detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
  22230.             Sandboxing.close(sandbox);
  22231.             setCursorAtEnd(comp);
  22232.           })
  22233.         ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function (typeahead) {
  22234.             var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  22235.             if (search(sandbox.element).isNone()) {
  22236.               Sandboxing.close(sandbox);
  22237.             }
  22238.           })] : []))
  22239.       ];
  22240.       return {
  22241.         uid: detail.uid,
  22242.         dom: dom(deepMerge(detail, {
  22243.           inputAttributes: {
  22244.             'role': 'combobox',
  22245.             'aria-autocomplete': 'list',
  22246.             'aria-haspopup': 'true'
  22247.           }
  22248.         })),
  22249.         behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  22250.         eventOrder: detail.eventOrder
  22251.       };
  22252.     };
  22253.  
  22254.     var schema$g = constant$1([
  22255.       option('lazySink'),
  22256.       required$1('fetch'),
  22257.       defaulted('minChars', 5),
  22258.       defaulted('responseTime', 1000),
  22259.       onHandler('onOpen'),
  22260.       defaulted('getHotspot', Optional.some),
  22261.       defaulted('getAnchorOverrides', constant$1({})),
  22262.       defaulted('layouts', Optional.none()),
  22263.       defaulted('eventOrder', {}),
  22264.       defaultedObjOf('model', {}, [
  22265.         defaulted('getDisplayText', function (itemData) {
  22266.           return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  22267.         }),
  22268.         defaulted('selectsOver', true),
  22269.         defaulted('populateFromBrowse', true)
  22270.       ]),
  22271.       onHandler('onSetValue'),
  22272.       onKeyboardHandler('onExecute'),
  22273.       onHandler('onItemExecute'),
  22274.       defaulted('inputClasses', []),
  22275.       defaulted('inputAttributes', {}),
  22276.       defaulted('inputStyles', {}),
  22277.       defaulted('matchWidth', true),
  22278.       defaulted('useMinWidth', false),
  22279.       defaulted('dismissOnBlur', true),
  22280.       markers$1(['openClass']),
  22281.       option('initialData'),
  22282.       field('typeaheadBehaviours', [
  22283.         Focusing,
  22284.         Representing,
  22285.         Streaming,
  22286.         Keying,
  22287.         Toggling,
  22288.         Coupling
  22289.       ]),
  22290.       customField('previewing', function () {
  22291.         return Cell(true);
  22292.       })
  22293.     ].concat(schema$k()).concat(sandboxFields()));
  22294.     var parts$b = constant$1([external$1({
  22295.         schema: [tieredMenuMarkers()],
  22296.         name: 'menu',
  22297.         overrides: function (detail) {
  22298.           return {
  22299.             fakeFocus: true,
  22300.             onHighlight: function (menu, item) {
  22301.               if (!detail.previewing.get()) {
  22302.                 menu.getSystem().getByUid(detail.uid).each(function (input) {
  22303.                   if (detail.model.populateFromBrowse) {
  22304.                     setValueFromItem(detail.model, input, item);
  22305.                   }
  22306.                 });
  22307.               } else {
  22308.                 menu.getSystem().getByUid(detail.uid).each(function (input) {
  22309.                   attemptSelectOver(detail.model, input, item).fold(function () {
  22310.                     return Highlighting.dehighlight(menu, item);
  22311.                   }, function (fn) {
  22312.                     return fn();
  22313.                   });
  22314.                 });
  22315.               }
  22316.               detail.previewing.set(false);
  22317.             },
  22318.             onExecute: function (menu, item) {
  22319.               return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) {
  22320.                 emitWith(typeahead, itemExecute(), { item: item });
  22321.                 return true;
  22322.               });
  22323.             },
  22324.             onHover: function (menu, item) {
  22325.               detail.previewing.set(false);
  22326.               menu.getSystem().getByUid(detail.uid).each(function (input) {
  22327.                 if (detail.model.populateFromBrowse) {
  22328.                   setValueFromItem(detail.model, input, item);
  22329.                 }
  22330.               });
  22331.             }
  22332.           };
  22333.         }
  22334.       })]);
  22335.  
  22336.     var Typeahead = composite({
  22337.       name: 'Typeahead',
  22338.       configFields: schema$g(),
  22339.       partFields: parts$b(),
  22340.       factory: make$3
  22341.     });
  22342.  
  22343.     var wrap = function (delegate) {
  22344.       var toCached = function () {
  22345.         return wrap(delegate.toCached());
  22346.       };
  22347.       var bindFuture = function (f) {
  22348.         return wrap(delegate.bind(function (resA) {
  22349.           return resA.fold(function (err) {
  22350.             return Future.pure(Result.error(err));
  22351.           }, function (a) {
  22352.             return f(a);
  22353.           });
  22354.         }));
  22355.       };
  22356.       var bindResult = function (f) {
  22357.         return wrap(delegate.map(function (resA) {
  22358.           return resA.bind(f);
  22359.         }));
  22360.       };
  22361.       var mapResult = function (f) {
  22362.         return wrap(delegate.map(function (resA) {
  22363.           return resA.map(f);
  22364.         }));
  22365.       };
  22366.       var mapError = function (f) {
  22367.         return wrap(delegate.map(function (resA) {
  22368.           return resA.mapError(f);
  22369.         }));
  22370.       };
  22371.       var foldResult = function (whenError, whenValue) {
  22372.         return delegate.map(function (res) {
  22373.           return res.fold(whenError, whenValue);
  22374.         });
  22375.       };
  22376.       var withTimeout = function (timeout, errorThunk) {
  22377.         return wrap(Future.nu(function (callback) {
  22378.           var timedOut = false;
  22379.           var timer = setTimeout(function () {
  22380.             timedOut = true;
  22381.             callback(Result.error(errorThunk()));
  22382.           }, timeout);
  22383.           delegate.get(function (result) {
  22384.             if (!timedOut) {
  22385.               clearTimeout(timer);
  22386.               callback(result);
  22387.             }
  22388.           });
  22389.         }));
  22390.       };
  22391.       return __assign(__assign({}, delegate), {
  22392.         toCached: toCached,
  22393.         bindFuture: bindFuture,
  22394.         bindResult: bindResult,
  22395.         mapResult: mapResult,
  22396.         mapError: mapError,
  22397.         foldResult: foldResult,
  22398.         withTimeout: withTimeout
  22399.       });
  22400.     };
  22401.     var nu$1 = function (worker) {
  22402.       return wrap(Future.nu(worker));
  22403.     };
  22404.     var value = function (value) {
  22405.       return wrap(Future.pure(Result.value(value)));
  22406.     };
  22407.     var error = function (error) {
  22408.       return wrap(Future.pure(Result.error(error)));
  22409.     };
  22410.     var fromResult = function (result) {
  22411.       return wrap(Future.pure(result));
  22412.     };
  22413.     var fromFuture = function (future) {
  22414.       return wrap(future.map(Result.value));
  22415.     };
  22416.     var fromPromise = function (promise) {
  22417.       return nu$1(function (completer) {
  22418.         promise.then(function (value) {
  22419.           completer(Result.value(value));
  22420.         }, function (error) {
  22421.           completer(Result.error(error));
  22422.         });
  22423.       });
  22424.     };
  22425.     var FutureResult = {
  22426.       nu: nu$1,
  22427.       wrap: wrap,
  22428.       pure: value,
  22429.       value: value,
  22430.       error: error,
  22431.       fromResult: fromResult,
  22432.       fromFuture: fromFuture,
  22433.       fromPromise: fromPromise
  22434.     };
  22435.  
  22436.     var separator$1 = { type: 'separator' };
  22437.     var toMenuItem = function (target) {
  22438.       return {
  22439.         type: 'menuitem',
  22440.         value: target.url,
  22441.         text: target.title,
  22442.         meta: { attach: target.attach },
  22443.         onAction: noop
  22444.       };
  22445.     };
  22446.     var staticMenuItem = function (title, url) {
  22447.       return {
  22448.         type: 'menuitem',
  22449.         value: url,
  22450.         text: title,
  22451.         meta: { attach: undefined },
  22452.         onAction: noop
  22453.       };
  22454.     };
  22455.     var toMenuItems = function (targets) {
  22456.       return map$2(targets, toMenuItem);
  22457.     };
  22458.     var filterLinkTargets = function (type, targets) {
  22459.       return filter$2(targets, function (target) {
  22460.         return target.type === type;
  22461.       });
  22462.     };
  22463.     var filteredTargets = function (type, targets) {
  22464.       return toMenuItems(filterLinkTargets(type, targets));
  22465.     };
  22466.     var headerTargets = function (linkInfo) {
  22467.       return filteredTargets('header', linkInfo.targets);
  22468.     };
  22469.     var anchorTargets = function (linkInfo) {
  22470.       return filteredTargets('anchor', linkInfo.targets);
  22471.     };
  22472.     var anchorTargetTop = function (linkInfo) {
  22473.       return Optional.from(linkInfo.anchorTop).map(function (url) {
  22474.         return staticMenuItem('<top>', url);
  22475.       }).toArray();
  22476.     };
  22477.     var anchorTargetBottom = function (linkInfo) {
  22478.       return Optional.from(linkInfo.anchorBottom).map(function (url) {
  22479.         return staticMenuItem('<bottom>', url);
  22480.       }).toArray();
  22481.     };
  22482.     var historyTargets = function (history) {
  22483.       return map$2(history, function (url) {
  22484.         return staticMenuItem(url, url);
  22485.       });
  22486.     };
  22487.     var joinMenuLists = function (items) {
  22488.       return foldl(items, function (a, b) {
  22489.         var bothEmpty = a.length === 0 || b.length === 0;
  22490.         return bothEmpty ? a.concat(b) : a.concat(separator$1, b);
  22491.       }, []);
  22492.     };
  22493.     var filterByQuery = function (term, menuItems) {
  22494.       var lowerCaseTerm = term.toLowerCase();
  22495.       return filter$2(menuItems, function (item) {
  22496.         var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  22497.         return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  22498.       });
  22499.     };
  22500.  
  22501.     var getItems = function (fileType, input, urlBackstage) {
  22502.       var urlInputValue = Representing.getValue(input);
  22503.       var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  22504.       var info = urlBackstage.getLinkInformation();
  22505.       return info.fold(function () {
  22506.         return [];
  22507.       }, function (linkInfo) {
  22508.         var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  22509.         return fileType === 'file' ? joinMenuLists([
  22510.           history,
  22511.           filterByQuery(term, headerTargets(linkInfo)),
  22512.           filterByQuery(term, flatten([
  22513.             anchorTargetTop(linkInfo),
  22514.             anchorTargets(linkInfo),
  22515.             anchorTargetBottom(linkInfo)
  22516.           ]))
  22517.         ]) : history;
  22518.       });
  22519.     };
  22520.     var errorId = generate$6('aria-invalid');
  22521.     var renderUrlInput = function (spec, backstage, urlBackstage) {
  22522.       var _a;
  22523.       var providersBackstage = backstage.shared.providers;
  22524.       var updateHistory = function (component) {
  22525.         var urlEntry = Representing.getValue(component);
  22526.         urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  22527.       };
  22528.       var pField = FormField.parts.field({
  22529.         factory: Typeahead,
  22530.         dismissOnBlur: true,
  22531.         inputClasses: ['tox-textfield'],
  22532.         sandboxClasses: ['tox-dialog__popups'],
  22533.         inputAttributes: {
  22534.           'aria-errormessage': errorId,
  22535.           'type': 'url'
  22536.         },
  22537.         minChars: 0,
  22538.         responseTime: 0,
  22539.         fetch: function (input) {
  22540.           var items = getItems(spec.filetype, input, urlBackstage);
  22541.           var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  22542.           return Future.pure(tdata);
  22543.         },
  22544.         getHotspot: function (comp) {
  22545.           return memUrlBox.getOpt(comp);
  22546.         },
  22547.         onSetValue: function (comp, _newValue) {
  22548.           if (comp.hasConfigured(Invalidating)) {
  22549.             Invalidating.run(comp).get(noop);
  22550.           }
  22551.         },
  22552.         typeaheadBehaviours: derive$1(flatten([
  22553.           urlBackstage.getValidationHandler().map(function (handler) {
  22554.             return Invalidating.config({
  22555.               getRoot: function (comp) {
  22556.                 return parent(comp.element);
  22557.               },
  22558.               invalidClass: 'tox-control-wrap--status-invalid',
  22559.               notify: {
  22560.                 onInvalid: function (comp, err) {
  22561.                   memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  22562.                     set$8(invalidComp.element, 'title', providersBackstage.translate(err));
  22563.                   });
  22564.                 }
  22565.               },
  22566.               validator: {
  22567.                 validate: function (input) {
  22568.                   var urlEntry = Representing.getValue(input);
  22569.                   return FutureResult.nu(function (completer) {
  22570.                     handler({
  22571.                       type: spec.filetype,
  22572.                       url: urlEntry.value
  22573.                     }, function (validation) {
  22574.                       if (validation.status === 'invalid') {
  22575.                         var err = Result.error(validation.message);
  22576.                         completer(err);
  22577.                       } else {
  22578.                         var val = Result.value(validation.message);
  22579.                         completer(val);
  22580.                       }
  22581.                     });
  22582.                   });
  22583.                 },
  22584.                 validateOnLoad: false
  22585.               }
  22586.             });
  22587.           }).toArray(),
  22588.           [
  22589.             Disabling.config({
  22590.               disabled: function () {
  22591.                 return spec.disabled || providersBackstage.isDisabled();
  22592.               }
  22593.             }),
  22594.             Tabstopping.config({}),
  22595.             config('urlinput-events', flatten([
  22596.               spec.filetype === 'file' ? [run$1(input(), function (comp) {
  22597.                   emitWith(comp, formChangeEvent, { name: spec.name });
  22598.                 })] : [],
  22599.               [
  22600.                 run$1(change(), function (comp) {
  22601.                   emitWith(comp, formChangeEvent, { name: spec.name });
  22602.                   updateHistory(comp);
  22603.                 }),
  22604.                 run$1(postPaste(), function (comp) {
  22605.                   emitWith(comp, formChangeEvent, { name: spec.name });
  22606.                   updateHistory(comp);
  22607.                 })
  22608.               ]
  22609.             ]))
  22610.           ]
  22611.         ])),
  22612.         eventOrder: (_a = {}, _a[input()] = [
  22613.           'streaming',
  22614.           'urlinput-events',
  22615.           'invalidating'
  22616.         ], _a),
  22617.         model: {
  22618.           getDisplayText: function (itemData) {
  22619.             return itemData.value;
  22620.           },
  22621.           selectsOver: false,
  22622.           populateFromBrowse: false
  22623.         },
  22624.         markers: { openClass: 'tox-textfield--popup-open' },
  22625.         lazySink: backstage.shared.getSink,
  22626.         parts: { menu: part(false, 1, 'normal') },
  22627.         onExecute: function (_menu, component, _entry) {
  22628.           emitWith(component, formSubmitEvent, {});
  22629.         },
  22630.         onItemExecute: function (typeahead, _sandbox, _item, _value) {
  22631.           updateHistory(typeahead);
  22632.           emitWith(typeahead, formChangeEvent, { name: spec.name });
  22633.         }
  22634.       });
  22635.       var pLabel = spec.label.map(function (label) {
  22636.         return renderLabel$2(label, providersBackstage);
  22637.       });
  22638.       var makeIcon = function (name, errId, icon, label) {
  22639.         if (icon === void 0) {
  22640.           icon = name;
  22641.         }
  22642.         if (label === void 0) {
  22643.           label = name;
  22644.         }
  22645.         return render$3(icon, {
  22646.           tag: 'div',
  22647.           classes: [
  22648.             'tox-icon',
  22649.             'tox-control-wrap__status-icon-' + name
  22650.           ],
  22651.           attributes: __assign({
  22652.             'title': providersBackstage.translate(label),
  22653.             'aria-live': 'polite'
  22654.           }, errId.fold(function () {
  22655.             return {};
  22656.           }, function (id) {
  22657.             return { id: id };
  22658.           }))
  22659.         }, providersBackstage.icons);
  22660.       };
  22661.       var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
  22662.       var memStatus = record({
  22663.         dom: {
  22664.           tag: 'div',
  22665.           classes: ['tox-control-wrap__status-icon-wrap']
  22666.         },
  22667.         components: [memInvalidIcon.asSpec()]
  22668.       });
  22669.       var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  22670.       var browseUrlEvent = generate$6('browser.url.event');
  22671.       var memUrlBox = record({
  22672.         dom: {
  22673.           tag: 'div',
  22674.           classes: ['tox-control-wrap']
  22675.         },
  22676.         components: [
  22677.           pField,
  22678.           memStatus.asSpec()
  22679.         ],
  22680.         behaviours: derive$1([Disabling.config({
  22681.             disabled: function () {
  22682.               return spec.disabled || providersBackstage.isDisabled();
  22683.             }
  22684.           })])
  22685.       });
  22686.       var memUrlPickerButton = record(renderButton({
  22687.         name: spec.name,
  22688.         icon: Optional.some('browse'),
  22689.         text: spec.label.getOr(''),
  22690.         disabled: spec.disabled,
  22691.         primary: false,
  22692.         borderless: true
  22693.       }, function (component) {
  22694.         return emit(component, browseUrlEvent);
  22695.       }, providersBackstage, [], ['tox-browse-url']));
  22696.       var controlHWrapper = function () {
  22697.         return {
  22698.           dom: {
  22699.             tag: 'div',
  22700.             classes: ['tox-form__controls-h-stack']
  22701.           },
  22702.           components: flatten([
  22703.             [memUrlBox.asSpec()],
  22704.             optUrlPicker.map(function () {
  22705.               return memUrlPickerButton.asSpec();
  22706.             }).toArray()
  22707.           ])
  22708.         };
  22709.       };
  22710.       var openUrlPicker = function (comp) {
  22711.         Composing.getCurrent(comp).each(function (field) {
  22712.           var componentData = Representing.getValue(field);
  22713.           var urlData = __assign({ fieldname: spec.name }, componentData);
  22714.           optUrlPicker.each(function (picker) {
  22715.             picker(urlData).get(function (chosenData) {
  22716.               Representing.setValue(field, chosenData);
  22717.               emitWith(comp, formChangeEvent, { name: spec.name });
  22718.             });
  22719.           });
  22720.         });
  22721.       };
  22722.       return FormField.sketch({
  22723.         dom: renderFormFieldDom(),
  22724.         components: pLabel.toArray().concat([controlHWrapper()]),
  22725.         fieldBehaviours: derive$1([
  22726.           Disabling.config({
  22727.             disabled: function () {
  22728.               return spec.disabled || providersBackstage.isDisabled();
  22729.             },
  22730.             onDisabled: function (comp) {
  22731.               FormField.getField(comp).each(Disabling.disable);
  22732.               memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  22733.             },
  22734.             onEnabled: function (comp) {
  22735.               FormField.getField(comp).each(Disabling.enable);
  22736.               memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  22737.             }
  22738.           }),
  22739.           receivingConfig(),
  22740.           config('url-input-events', [run$1(browseUrlEvent, openUrlPicker)])
  22741.         ])
  22742.       });
  22743.     };
  22744.  
  22745.     var renderAlertBanner = function (spec, providersBackstage) {
  22746.       return Container.sketch({
  22747.         dom: {
  22748.           tag: 'div',
  22749.           attributes: { role: 'alert' },
  22750.           classes: [
  22751.             'tox-notification',
  22752.             'tox-notification--in',
  22753.             'tox-notification--' + spec.level
  22754.           ]
  22755.         },
  22756.         components: [
  22757.           {
  22758.             dom: {
  22759.               tag: 'div',
  22760.               classes: ['tox-notification__icon']
  22761.             },
  22762.             components: [Button.sketch({
  22763.                 dom: {
  22764.                   tag: 'button',
  22765.                   classes: [
  22766.                     'tox-button',
  22767.                     'tox-button--naked',
  22768.                     'tox-button--icon'
  22769.                   ],
  22770.                   innerHtml: get$1(spec.icon, providersBackstage.icons),
  22771.                   attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  22772.                 },
  22773.                 action: function (comp) {
  22774.                   emitWith(comp, formActionEvent, {
  22775.                     name: 'alert-banner',
  22776.                     value: spec.url
  22777.                   });
  22778.                 },
  22779.                 buttonBehaviours: derive$1([addFocusableBehaviour()])
  22780.               })]
  22781.           },
  22782.           {
  22783.             dom: {
  22784.               tag: 'div',
  22785.               classes: ['tox-notification__body'],
  22786.               innerHtml: providersBackstage.translate(spec.text)
  22787.             }
  22788.           }
  22789.         ]
  22790.       });
  22791.     };
  22792.  
  22793.     var renderCheckbox = function (spec, providerBackstage) {
  22794.       var repBehaviour = Representing.config({
  22795.         store: {
  22796.           mode: 'manual',
  22797.           getValue: function (comp) {
  22798.             var el = comp.element.dom;
  22799.             return el.checked;
  22800.           },
  22801.           setValue: function (comp, value) {
  22802.             var el = comp.element.dom;
  22803.             el.checked = value;
  22804.           }
  22805.         }
  22806.       });
  22807.       var toggleCheckboxHandler = function (comp) {
  22808.         comp.element.dom.click();
  22809.         return Optional.some(true);
  22810.       };
  22811.       var pField = FormField.parts.field({
  22812.         factory: { sketch: identity$1 },
  22813.         dom: {
  22814.           tag: 'input',
  22815.           classes: ['tox-checkbox__input'],
  22816.           attributes: { type: 'checkbox' }
  22817.         },
  22818.         behaviours: derive$1([
  22819.           ComposingConfigs.self(),
  22820.           Disabling.config({
  22821.             disabled: function () {
  22822.               return spec.disabled || providerBackstage.isDisabled();
  22823.             }
  22824.           }),
  22825.           Tabstopping.config({}),
  22826.           Focusing.config({}),
  22827.           repBehaviour,
  22828.           Keying.config({
  22829.             mode: 'special',
  22830.             onEnter: toggleCheckboxHandler,
  22831.             onSpace: toggleCheckboxHandler,
  22832.             stopSpaceKeyup: true
  22833.           }),
  22834.           config('checkbox-events', [run$1(change(), function (component, _) {
  22835.               emitWith(component, formChangeEvent, { name: spec.name });
  22836.             })])
  22837.         ])
  22838.       });
  22839.       var pLabel = FormField.parts.label({
  22840.         dom: {
  22841.           tag: 'span',
  22842.           classes: ['tox-checkbox__label'],
  22843.           innerHtml: providerBackstage.translate(spec.label)
  22844.         },
  22845.         behaviours: derive$1([Unselecting.config({})])
  22846.       });
  22847.       var makeIcon = function (className) {
  22848.         var iconName = className === 'checked' ? 'selected' : 'unselected';
  22849.         return render$3(iconName, {
  22850.           tag: 'span',
  22851.           classes: [
  22852.             'tox-icon',
  22853.             'tox-checkbox-icon__' + className
  22854.           ]
  22855.         }, providerBackstage.icons);
  22856.       };
  22857.       var memIcons = record({
  22858.         dom: {
  22859.           tag: 'div',
  22860.           classes: ['tox-checkbox__icons']
  22861.         },
  22862.         components: [
  22863.           makeIcon('checked'),
  22864.           makeIcon('unchecked')
  22865.         ]
  22866.       });
  22867.       return FormField.sketch({
  22868.         dom: {
  22869.           tag: 'label',
  22870.           classes: ['tox-checkbox']
  22871.         },
  22872.         components: [
  22873.           pField,
  22874.           memIcons.asSpec(),
  22875.           pLabel
  22876.         ],
  22877.         fieldBehaviours: derive$1([
  22878.           Disabling.config({
  22879.             disabled: function () {
  22880.               return spec.disabled || providerBackstage.isDisabled();
  22881.             },
  22882.             disableClass: 'tox-checkbox--disabled',
  22883.             onDisabled: function (comp) {
  22884.               FormField.getField(comp).each(Disabling.disable);
  22885.             },
  22886.             onEnabled: function (comp) {
  22887.               FormField.getField(comp).each(Disabling.enable);
  22888.             }
  22889.           }),
  22890.           receivingConfig()
  22891.         ])
  22892.       });
  22893.     };
  22894.  
  22895.     var renderHtmlPanel = function (spec) {
  22896.       if (spec.presets === 'presentation') {
  22897.         return Container.sketch({
  22898.           dom: {
  22899.             tag: 'div',
  22900.             classes: ['tox-form__group'],
  22901.             innerHtml: spec.html
  22902.           }
  22903.         });
  22904.       } else {
  22905.         return Container.sketch({
  22906.           dom: {
  22907.             tag: 'div',
  22908.             classes: ['tox-form__group'],
  22909.             innerHtml: spec.html,
  22910.             attributes: { role: 'document' }
  22911.           },
  22912.           containerBehaviours: derive$1([
  22913.             Tabstopping.config({}),
  22914.             Focusing.config({})
  22915.           ])
  22916.         });
  22917.       }
  22918.     };
  22919.  
  22920.     var make$2 = function (render) {
  22921.       return function (parts, spec, backstage) {
  22922.         return get$e(spec, 'name').fold(function () {
  22923.           return render(spec, backstage);
  22924.         }, function (fieldName) {
  22925.           return parts.field(fieldName, render(spec, backstage));
  22926.         });
  22927.       };
  22928.     };
  22929.     var makeIframe = function (render) {
  22930.       return function (parts, spec, backstage) {
  22931.         var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  22932.         return make$2(render)(parts, iframeSpec, backstage);
  22933.       };
  22934.     };
  22935.     var factories = {
  22936.       bar: make$2(function (spec, backstage) {
  22937.         return renderBar(spec, backstage.shared);
  22938.       }),
  22939.       collection: make$2(function (spec, backstage) {
  22940.         return renderCollection(spec, backstage.shared.providers);
  22941.       }),
  22942.       alertbanner: make$2(function (spec, backstage) {
  22943.         return renderAlertBanner(spec, backstage.shared.providers);
  22944.       }),
  22945.       input: make$2(function (spec, backstage) {
  22946.         return renderInput(spec, backstage.shared.providers);
  22947.       }),
  22948.       textarea: make$2(function (spec, backstage) {
  22949.         return renderTextarea(spec, backstage.shared.providers);
  22950.       }),
  22951.       label: make$2(function (spec, backstage) {
  22952.         return renderLabel(spec, backstage.shared);
  22953.       }),
  22954.       iframe: makeIframe(function (spec, backstage) {
  22955.         return renderIFrame(spec, backstage.shared.providers);
  22956.       }),
  22957.       button: make$2(function (spec, backstage) {
  22958.         return renderDialogButton(spec, backstage.shared.providers);
  22959.       }),
  22960.       checkbox: make$2(function (spec, backstage) {
  22961.         return renderCheckbox(spec, backstage.shared.providers);
  22962.       }),
  22963.       colorinput: make$2(function (spec, backstage) {
  22964.         return renderColorInput(spec, backstage.shared, backstage.colorinput);
  22965.       }),
  22966.       colorpicker: make$2(renderColorPicker),
  22967.       dropzone: make$2(function (spec, backstage) {
  22968.         return renderDropZone(spec, backstage.shared.providers);
  22969.       }),
  22970.       grid: make$2(function (spec, backstage) {
  22971.         return renderGrid(spec, backstage.shared);
  22972.       }),
  22973.       listbox: make$2(function (spec, backstage) {
  22974.         return renderListBox(spec, backstage);
  22975.       }),
  22976.       selectbox: make$2(function (spec, backstage) {
  22977.         return renderSelectBox(spec, backstage.shared.providers);
  22978.       }),
  22979.       sizeinput: make$2(function (spec, backstage) {
  22980.         return renderSizeInput(spec, backstage.shared.providers);
  22981.       }),
  22982.       urlinput: make$2(function (spec, backstage) {
  22983.         return renderUrlInput(spec, backstage, backstage.urlinput);
  22984.       }),
  22985.       customeditor: make$2(renderCustomEditor),
  22986.       htmlpanel: make$2(renderHtmlPanel),
  22987.       imagetools: make$2(function (spec, backstage) {
  22988.         return renderImageTools(spec, backstage.shared.providers);
  22989.       }),
  22990.       table: make$2(function (spec, backstage) {
  22991.         return renderTable(spec, backstage.shared.providers);
  22992.       }),
  22993.       panel: make$2(function (spec, backstage) {
  22994.         return renderPanel(spec, backstage);
  22995.       })
  22996.     };
  22997.     var noFormParts = {
  22998.       field: function (_name, spec) {
  22999.         return spec;
  23000.       }
  23001.     };
  23002.     var interpretInForm = function (parts, spec, oldBackstage) {
  23003.       var newBackstage = deepMerge(oldBackstage, {
  23004.         shared: {
  23005.           interpreter: function (childSpec) {
  23006.             return interpretParts(parts, childSpec, newBackstage);
  23007.           }
  23008.         }
  23009.       });
  23010.       return interpretParts(parts, spec, newBackstage);
  23011.     };
  23012.     var interpretParts = function (parts, spec, backstage) {
  23013.       return get$e(factories, spec.type).fold(function () {
  23014.         console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  23015.         return spec;
  23016.       }, function (factory) {
  23017.         return factory(parts, spec, backstage);
  23018.       });
  23019.     };
  23020.     var interpretWithoutForm = function (spec, backstage) {
  23021.       var parts = noFormParts;
  23022.       return interpretParts(parts, spec, backstage);
  23023.     };
  23024.  
  23025.     var bubbleAlignments$2 = {
  23026.       valignCentre: [],
  23027.       alignCentre: [],
  23028.       alignLeft: [],
  23029.       alignRight: [],
  23030.       right: [],
  23031.       left: [],
  23032.       bottom: [],
  23033.       top: []
  23034.     };
  23035.     var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  23036.       var bubbleSize = 12;
  23037.       var overrides = { maxHeightFunction: expandable$1() };
  23038.       var editableAreaAnchor = function () {
  23039.         return {
  23040.           type: 'node',
  23041.           root: getContentContainer(contentAreaElement()),
  23042.           node: Optional.from(contentAreaElement()),
  23043.           bubble: nu$5(bubbleSize, bubbleSize, bubbleAlignments$2),
  23044.           layouts: {
  23045.             onRtl: function () {
  23046.               return [northeast];
  23047.             },
  23048.             onLtr: function () {
  23049.               return [northwest];
  23050.             }
  23051.           },
  23052.           overrides: overrides
  23053.         };
  23054.       };
  23055.       var standardAnchor = function () {
  23056.         return {
  23057.           type: 'hotspot',
  23058.           hotspot: lazyAnchorbar(),
  23059.           bubble: nu$5(-bubbleSize, bubbleSize, bubbleAlignments$2),
  23060.           layouts: {
  23061.             onRtl: function () {
  23062.               return [southeast$2];
  23063.             },
  23064.             onLtr: function () {
  23065.               return [southwest$2];
  23066.             }
  23067.           },
  23068.           overrides: overrides
  23069.         };
  23070.       };
  23071.       return function () {
  23072.         return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  23073.       };
  23074.     };
  23075.     var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  23076.       var editableAreaAnchor = function () {
  23077.         return {
  23078.           type: 'node',
  23079.           root: getContentContainer(contentAreaElement()),
  23080.           node: Optional.from(contentAreaElement()),
  23081.           layouts: {
  23082.             onRtl: function () {
  23083.               return [north];
  23084.             },
  23085.             onLtr: function () {
  23086.               return [north];
  23087.             }
  23088.           }
  23089.         };
  23090.       };
  23091.       var standardAnchor = function () {
  23092.         return {
  23093.           type: 'hotspot',
  23094.           hotspot: lazyAnchorbar(),
  23095.           layouts: {
  23096.             onRtl: function () {
  23097.               return [south$2];
  23098.             },
  23099.             onLtr: function () {
  23100.               return [south$2];
  23101.             }
  23102.           }
  23103.         };
  23104.       };
  23105.       return function () {
  23106.         return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  23107.       };
  23108.     };
  23109.     var getCursorAnchor = function (editor, bodyElement) {
  23110.       return function () {
  23111.         return {
  23112.           type: 'selection',
  23113.           root: bodyElement(),
  23114.           getSelection: function () {
  23115.             var rng = editor.selection.getRng();
  23116.             return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  23117.           }
  23118.         };
  23119.       };
  23120.     };
  23121.     var getNodeAnchor$1 = function (bodyElement) {
  23122.       return function (element) {
  23123.         return {
  23124.           type: 'node',
  23125.           root: bodyElement(),
  23126.           node: element
  23127.         };
  23128.       };
  23129.     };
  23130.     var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
  23131.       var useFixedToolbarContainer = useFixedContainer(editor);
  23132.       var bodyElement = function () {
  23133.         return SugarElement.fromDom(editor.getBody());
  23134.       };
  23135.       var contentAreaElement = function () {
  23136.         return SugarElement.fromDom(editor.getContentAreaContainer());
  23137.       };
  23138.       var lazyUseEditableAreaAnchor = function () {
  23139.         return useFixedToolbarContainer || !isToolbarTop();
  23140.       };
  23141.       return {
  23142.         inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  23143.         banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  23144.         cursor: getCursorAnchor(editor, bodyElement),
  23145.         node: getNodeAnchor$1(bodyElement)
  23146.       };
  23147.     };
  23148.  
  23149.     var colorPicker = function (editor) {
  23150.       return function (callback, value) {
  23151.         var dialog = colorPickerDialog(editor);
  23152.         dialog(callback, value);
  23153.       };
  23154.     };
  23155.     var hasCustomColors = function (editor) {
  23156.       return function () {
  23157.         return hasCustomColors$1(editor);
  23158.       };
  23159.     };
  23160.     var getColors = function (editor) {
  23161.       return function () {
  23162.         return getColors$2(editor);
  23163.       };
  23164.     };
  23165.     var getColorCols = function (editor) {
  23166.       return function () {
  23167.         return getColorCols$1(editor);
  23168.       };
  23169.     };
  23170.     var ColorInputBackstage = function (editor) {
  23171.       return {
  23172.         colorPicker: colorPicker(editor),
  23173.         hasCustomColors: hasCustomColors(editor),
  23174.         getColors: getColors(editor),
  23175.         getColorCols: getColorCols(editor)
  23176.       };
  23177.     };
  23178.  
  23179.     var isDraggableModal = function (editor) {
  23180.       return function () {
  23181.         return isDraggableModal$1(editor);
  23182.       };
  23183.     };
  23184.     var DialogBackstage = function (editor) {
  23185.       return { isDraggableModal: isDraggableModal(editor) };
  23186.     };
  23187.  
  23188.     var HeaderBackstage = function (editor) {
  23189.       var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  23190.       return {
  23191.         isPositionedAtTop: function () {
  23192.           return mode.get() === 'top';
  23193.         },
  23194.         getDockingMode: mode.get,
  23195.         setDockingMode: mode.set
  23196.       };
  23197.     };
  23198.  
  23199.     var defaultStyleFormats = [
  23200.       {
  23201.         title: 'Headings',
  23202.         items: [
  23203.           {
  23204.             title: 'Heading 1',
  23205.             format: 'h1'
  23206.           },
  23207.           {
  23208.             title: 'Heading 2',
  23209.             format: 'h2'
  23210.           },
  23211.           {
  23212.             title: 'Heading 3',
  23213.             format: 'h3'
  23214.           },
  23215.           {
  23216.             title: 'Heading 4',
  23217.             format: 'h4'
  23218.           },
  23219.           {
  23220.             title: 'Heading 5',
  23221.             format: 'h5'
  23222.           },
  23223.           {
  23224.             title: 'Heading 6',
  23225.             format: 'h6'
  23226.           }
  23227.         ]
  23228.       },
  23229.       {
  23230.         title: 'Inline',
  23231.         items: [
  23232.           {
  23233.             title: 'Bold',
  23234.             format: 'bold'
  23235.           },
  23236.           {
  23237.             title: 'Italic',
  23238.             format: 'italic'
  23239.           },
  23240.           {
  23241.             title: 'Underline',
  23242.             format: 'underline'
  23243.           },
  23244.           {
  23245.             title: 'Strikethrough',
  23246.             format: 'strikethrough'
  23247.           },
  23248.           {
  23249.             title: 'Superscript',
  23250.             format: 'superscript'
  23251.           },
  23252.           {
  23253.             title: 'Subscript',
  23254.             format: 'subscript'
  23255.           },
  23256.           {
  23257.             title: 'Code',
  23258.             format: 'code'
  23259.           }
  23260.         ]
  23261.       },
  23262.       {
  23263.         title: 'Blocks',
  23264.         items: [
  23265.           {
  23266.             title: 'Paragraph',
  23267.             format: 'p'
  23268.           },
  23269.           {
  23270.             title: 'Blockquote',
  23271.             format: 'blockquote'
  23272.           },
  23273.           {
  23274.             title: 'Div',
  23275.             format: 'div'
  23276.           },
  23277.           {
  23278.             title: 'Pre',
  23279.             format: 'pre'
  23280.           }
  23281.         ]
  23282.       },
  23283.       {
  23284.         title: 'Align',
  23285.         items: [
  23286.           {
  23287.             title: 'Left',
  23288.             format: 'alignleft'
  23289.           },
  23290.           {
  23291.             title: 'Center',
  23292.             format: 'aligncenter'
  23293.           },
  23294.           {
  23295.             title: 'Right',
  23296.             format: 'alignright'
  23297.           },
  23298.           {
  23299.             title: 'Justify',
  23300.             format: 'alignjustify'
  23301.           }
  23302.         ]
  23303.       }
  23304.     ];
  23305.     var isNestedFormat = function (format) {
  23306.       return has$2(format, 'items');
  23307.     };
  23308.     var isBlockFormat = function (format) {
  23309.       return has$2(format, 'block');
  23310.     };
  23311.     var isInlineFormat = function (format) {
  23312.       return has$2(format, 'inline');
  23313.     };
  23314.     var isSelectorFormat = function (format) {
  23315.       return has$2(format, 'selector');
  23316.     };
  23317.     var mapFormats = function (userFormats) {
  23318.       return foldl(userFormats, function (acc, fmt) {
  23319.         if (isNestedFormat(fmt)) {
  23320.           var result = mapFormats(fmt.items);
  23321.           return {
  23322.             customFormats: acc.customFormats.concat(result.customFormats),
  23323.             formats: acc.formats.concat([{
  23324.                 title: fmt.title,
  23325.                 items: result.formats
  23326.               }])
  23327.           };
  23328.         } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  23329.           var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
  23330.           var formatNameWithPrefix = 'custom-' + formatName;
  23331.           return {
  23332.             customFormats: acc.customFormats.concat([{
  23333.                 name: formatNameWithPrefix,
  23334.                 format: fmt
  23335.               }]),
  23336.             formats: acc.formats.concat([{
  23337.                 title: fmt.title,
  23338.                 format: formatNameWithPrefix,
  23339.                 icon: fmt.icon
  23340.               }])
  23341.           };
  23342.         } else {
  23343.           return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  23344.         }
  23345.       }, {
  23346.         customFormats: [],
  23347.         formats: []
  23348.       });
  23349.     };
  23350.     var registerCustomFormats = function (editor, userFormats) {
  23351.       var result = mapFormats(userFormats);
  23352.       var registerFormats = function (customFormats) {
  23353.         each$1(customFormats, function (fmt) {
  23354.           if (!editor.formatter.has(fmt.name)) {
  23355.             editor.formatter.register(fmt.name, fmt.format);
  23356.           }
  23357.         });
  23358.       };
  23359.       if (editor.formatter) {
  23360.         registerFormats(result.customFormats);
  23361.       } else {
  23362.         editor.on('init', function () {
  23363.           registerFormats(result.customFormats);
  23364.         });
  23365.       }
  23366.       return result.formats;
  23367.     };
  23368.     var getStyleFormats = function (editor) {
  23369.       return getUserStyleFormats(editor).map(function (userFormats) {
  23370.         var registeredUserFormats = registerCustomFormats(editor, userFormats);
  23371.         return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  23372.       }).getOr(defaultStyleFormats);
  23373.     };
  23374.  
  23375.     var processBasic = function (item, isSelectedFor, getPreviewFor) {
  23376.       var formatterSpec = {
  23377.         type: 'formatter',
  23378.         isSelected: isSelectedFor(item.format),
  23379.         getStylePreview: getPreviewFor(item.format)
  23380.       };
  23381.       return deepMerge(item, formatterSpec);
  23382.     };
  23383.     var register$8 = function (editor, formats, isSelectedFor, getPreviewFor) {
  23384.       var enrichSupported = function (item) {
  23385.         return processBasic(item, isSelectedFor, getPreviewFor);
  23386.       };
  23387.       var enrichMenu = function (item) {
  23388.         var submenuSpec = { type: 'submenu' };
  23389.         return deepMerge(item, submenuSpec);
  23390.       };
  23391.       var enrichCustom = function (item) {
  23392.         var formatName = isString(item.name) ? item.name : generate$6(item.title);
  23393.         var formatNameWithPrefix = 'custom-' + formatName;
  23394.         var customSpec = {
  23395.           type: 'formatter',
  23396.           format: formatNameWithPrefix,
  23397.           isSelected: isSelectedFor(formatNameWithPrefix),
  23398.           getStylePreview: getPreviewFor(formatNameWithPrefix)
  23399.         };
  23400.         var newItem = deepMerge(item, customSpec);
  23401.         editor.formatter.register(formatName, newItem);
  23402.         return newItem;
  23403.       };
  23404.       var doEnrich = function (items) {
  23405.         return map$2(items, function (item) {
  23406.           var keys$1 = keys(item);
  23407.           if (hasNonNullableKey(item, 'items')) {
  23408.             var newItems = doEnrich(item.items);
  23409.             return deepMerge(enrichMenu(item), { getStyleItems: constant$1(newItems) });
  23410.           } else if (hasNonNullableKey(item, 'format')) {
  23411.             return enrichSupported(item);
  23412.           } else if (keys$1.length === 1 && contains$2(keys$1, 'title')) {
  23413.             return deepMerge(item, { type: 'separator' });
  23414.           } else {
  23415.             return enrichCustom(item);
  23416.           }
  23417.         });
  23418.       };
  23419.       return doEnrich(formats);
  23420.     };
  23421.  
  23422.     var init$8 = function (editor) {
  23423.       var isSelectedFor = function (format) {
  23424.         return function () {
  23425.           return editor.formatter.match(format);
  23426.         };
  23427.       };
  23428.       var getPreviewFor = function (format) {
  23429.         return function () {
  23430.           var fmt = editor.formatter.get(format);
  23431.           return fmt !== undefined ? Optional.some({
  23432.             tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23433.             styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  23434.           }) : Optional.none();
  23435.         };
  23436.       };
  23437.       var flatten = function (fmt) {
  23438.         var subs = fmt.items;
  23439.         return subs !== undefined && subs.length > 0 ? bind$3(subs, flatten) : [fmt.format];
  23440.       };
  23441.       var settingsFormats = Cell([]);
  23442.       var settingsFlattenedFormats = Cell([]);
  23443.       var eventsFormats = Cell([]);
  23444.       var eventsFlattenedFormats = Cell([]);
  23445.       var replaceSettings = Cell(false);
  23446.       editor.on('PreInit', function (_e) {
  23447.         var formats = getStyleFormats(editor);
  23448.         var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor);
  23449.         settingsFormats.set(enriched);
  23450.         settingsFlattenedFormats.set(bind$3(enriched, flatten));
  23451.       });
  23452.       editor.on('addStyleModifications', function (e) {
  23453.         var modifications = register$8(editor, e.items, isSelectedFor, getPreviewFor);
  23454.         eventsFormats.set(modifications);
  23455.         replaceSettings.set(e.replace);
  23456.         eventsFlattenedFormats.set(bind$3(modifications, flatten));
  23457.       });
  23458.       var getData = function () {
  23459.         var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  23460.         var fromEvents = eventsFormats.get();
  23461.         return fromSettings.concat(fromEvents);
  23462.       };
  23463.       var getFlattenedKeys = function () {
  23464.         var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  23465.         var fromEvents = eventsFlattenedFormats.get();
  23466.         return fromSettings.concat(fromEvents);
  23467.       };
  23468.       return {
  23469.         getData: getData,
  23470.         getFlattenedKeys: getFlattenedKeys
  23471.       };
  23472.     };
  23473.  
  23474.     var isElement = function (node) {
  23475.       return isNonNullable(node) && node.nodeType === 1;
  23476.     };
  23477.     var trim = global$5.trim;
  23478.     var hasContentEditableState = function (value) {
  23479.       return function (node) {
  23480.         if (isElement(node)) {
  23481.           if (node.contentEditable === value) {
  23482.             return true;
  23483.           }
  23484.           if (node.getAttribute('data-mce-contenteditable') === value) {
  23485.             return true;
  23486.           }
  23487.         }
  23488.         return false;
  23489.       };
  23490.     };
  23491.     var isContentEditableTrue = hasContentEditableState('true');
  23492.     var isContentEditableFalse = hasContentEditableState('false');
  23493.     var create = function (type, title, url, level, attach) {
  23494.       return {
  23495.         type: type,
  23496.         title: title,
  23497.         url: url,
  23498.         level: level,
  23499.         attach: attach
  23500.       };
  23501.     };
  23502.     var isChildOfContentEditableTrue = function (node) {
  23503.       while (node = node.parentNode) {
  23504.         var value = node.contentEditable;
  23505.         if (value && value !== 'inherit') {
  23506.           return isContentEditableTrue(node);
  23507.         }
  23508.       }
  23509.       return false;
  23510.     };
  23511.     var select = function (selector, root) {
  23512.       return map$2(descendants(SugarElement.fromDom(root), selector), function (element) {
  23513.         return element.dom;
  23514.       });
  23515.     };
  23516.     var getElementText = function (elm) {
  23517.       return elm.innerText || elm.textContent;
  23518.     };
  23519.     var getOrGenerateId = function (elm) {
  23520.       return elm.id ? elm.id : generate$6('h');
  23521.     };
  23522.     var isAnchor = function (elm) {
  23523.       return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  23524.     };
  23525.     var isValidAnchor = function (elm) {
  23526.       return isAnchor(elm) && isEditable(elm);
  23527.     };
  23528.     var isHeader = function (elm) {
  23529.       return elm && /^(H[1-6])$/.test(elm.nodeName);
  23530.     };
  23531.     var isEditable = function (elm) {
  23532.       return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  23533.     };
  23534.     var isValidHeader = function (elm) {
  23535.       return isHeader(elm) && isEditable(elm);
  23536.     };
  23537.     var getLevel = function (elm) {
  23538.       return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  23539.     };
  23540.     var headerTarget = function (elm) {
  23541.       var headerId = getOrGenerateId(elm);
  23542.       var attach = function () {
  23543.         elm.id = headerId;
  23544.       };
  23545.       return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  23546.     };
  23547.     var anchorTarget = function (elm) {
  23548.       var anchorId = elm.id || elm.name;
  23549.       var anchorText = getElementText(elm);
  23550.       return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  23551.     };
  23552.     var getHeaderTargets = function (elms) {
  23553.       return map$2(filter$2(elms, isValidHeader), headerTarget);
  23554.     };
  23555.     var getAnchorTargets = function (elms) {
  23556.       return map$2(filter$2(elms, isValidAnchor), anchorTarget);
  23557.     };
  23558.     var getTargetElements = function (elm) {
  23559.       var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  23560.       return elms;
  23561.     };
  23562.     var hasTitle = function (target) {
  23563.       return trim(target.title).length > 0;
  23564.     };
  23565.     var find = function (elm) {
  23566.       var elms = getTargetElements(elm);
  23567.       return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  23568.     };
  23569.     var LinkTargets = { find: find };
  23570.  
  23571.     var STORAGE_KEY = 'tinymce-url-history';
  23572.     var HISTORY_LENGTH = 5;
  23573.     var isHttpUrl = function (url) {
  23574.       return isString(url) && /^https?/.test(url);
  23575.     };
  23576.     var isArrayOfUrl = function (a) {
  23577.       return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  23578.     };
  23579.     var isRecordOfUrlArray = function (r) {
  23580.       return isObject(r) && find$4(r, function (value) {
  23581.         return !isArrayOfUrl(value);
  23582.       }).isNone();
  23583.     };
  23584.     var getAllHistory = function () {
  23585.       var unparsedHistory = global$8.getItem(STORAGE_KEY);
  23586.       if (unparsedHistory === null) {
  23587.         return {};
  23588.       }
  23589.       var history;
  23590.       try {
  23591.         history = JSON.parse(unparsedHistory);
  23592.       } catch (e) {
  23593.         if (e instanceof SyntaxError) {
  23594.           console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  23595.           return {};
  23596.         }
  23597.         throw e;
  23598.       }
  23599.       if (!isRecordOfUrlArray(history)) {
  23600.         console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  23601.         return {};
  23602.       }
  23603.       return history;
  23604.     };
  23605.     var setAllHistory = function (history) {
  23606.       if (!isRecordOfUrlArray(history)) {
  23607.         throw new Error('Bad format for history:\n' + JSON.stringify(history));
  23608.       }
  23609.       global$8.setItem(STORAGE_KEY, JSON.stringify(history));
  23610.     };
  23611.     var getHistory = function (fileType) {
  23612.       var history = getAllHistory();
  23613.       return get$e(history, fileType).getOr([]);
  23614.     };
  23615.     var addToHistory = function (url, fileType) {
  23616.       if (!isHttpUrl(url)) {
  23617.         return;
  23618.       }
  23619.       var history = getAllHistory();
  23620.       var items = get$e(history, fileType).getOr([]);
  23621.       var itemsWithoutUrl = filter$2(items, function (item) {
  23622.         return item !== url;
  23623.       });
  23624.       history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  23625.       setAllHistory(history);
  23626.     };
  23627.  
  23628.     var isTruthy = function (value) {
  23629.       return !!value;
  23630.     };
  23631.     var makeMap = function (value) {
  23632.       return map$1(global$5.makeMap(value, /[, ]/), isTruthy);
  23633.     };
  23634.     var getPicker = function (editor) {
  23635.       return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
  23636.     };
  23637.     var getPickerTypes = function (editor) {
  23638.       var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
  23639.       var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
  23640.       var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  23641.       return getPicker(editor).fold(never, function (_picker) {
  23642.         return optTypes.fold(always, function (types) {
  23643.           return keys(types).length > 0 ? types : false;
  23644.         });
  23645.       });
  23646.     };
  23647.     var getPickerSetting = function (editor, filetype) {
  23648.       var pickerTypes = getPickerTypes(editor);
  23649.       if (isBoolean(pickerTypes)) {
  23650.         return pickerTypes ? getPicker(editor) : Optional.none();
  23651.       } else {
  23652.         return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
  23653.       }
  23654.     };
  23655.     var getUrlPicker = function (editor, filetype) {
  23656.       return getPickerSetting(editor, filetype).map(function (picker) {
  23657.         return function (entry) {
  23658.           return Future.nu(function (completer) {
  23659.             var handler = function (value, meta) {
  23660.               if (!isString(value)) {
  23661.                 throw new Error('Expected value to be string');
  23662.               }
  23663.               if (meta !== undefined && !isObject(meta)) {
  23664.                 throw new Error('Expected meta to be a object');
  23665.               }
  23666.               var r = {
  23667.                 value: value,
  23668.                 meta: meta
  23669.               };
  23670.               completer(r);
  23671.             };
  23672.             var meta = __assign({
  23673.               filetype: filetype,
  23674.               fieldname: entry.fieldname
  23675.             }, Optional.from(entry.meta).getOr({}));
  23676.             picker.call(editor, handler, entry.value, meta);
  23677.           });
  23678.         };
  23679.       });
  23680.     };
  23681.     var getTextSetting = function (value) {
  23682.       return Optional.from(value).filter(isString).getOrUndefined();
  23683.     };
  23684.     var getLinkInformation = function (editor) {
  23685.       if (noTypeaheadUrls(editor)) {
  23686.         return Optional.none();
  23687.       }
  23688.       return Optional.some({
  23689.         targets: LinkTargets.find(editor.getBody()),
  23690.         anchorTop: getTextSetting(getAnchorTop(editor)),
  23691.         anchorBottom: getTextSetting(getAnchorBottom(editor))
  23692.       });
  23693.     };
  23694.     var getValidationHandler = function (editor) {
  23695.       return Optional.from(getFilePickerValidatorHandler(editor));
  23696.     };
  23697.     var UrlInputBackstage = function (editor) {
  23698.       return {
  23699.         getHistory: getHistory,
  23700.         addToHistory: addToHistory,
  23701.         getLinkInformation: function () {
  23702.           return getLinkInformation(editor);
  23703.         },
  23704.         getValidationHandler: function () {
  23705.           return getValidationHandler(editor);
  23706.         },
  23707.         getUrlPicker: function (filetype) {
  23708.           return getUrlPicker(editor, filetype);
  23709.         }
  23710.       };
  23711.     };
  23712.  
  23713.     var init$7 = function (sink, editor, lazyAnchorbar) {
  23714.       var contextMenuState = Cell(false);
  23715.       var toolbar = HeaderBackstage(editor);
  23716.       var backstage = {
  23717.         shared: {
  23718.           providers: {
  23719.             icons: function () {
  23720.               return editor.ui.registry.getAll().icons;
  23721.             },
  23722.             menuItems: function () {
  23723.               return editor.ui.registry.getAll().menuItems;
  23724.             },
  23725.             translate: global$e.translate,
  23726.             isDisabled: function () {
  23727.               return editor.mode.isReadOnly() || editor.ui.isDisabled();
  23728.             },
  23729.             getSetting: editor.getParam.bind(editor)
  23730.           },
  23731.           interpreter: function (s) {
  23732.             return interpretWithoutForm(s, backstage);
  23733.           },
  23734.           anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  23735.           header: toolbar,
  23736.           getSink: function () {
  23737.             return Result.value(sink);
  23738.           }
  23739.         },
  23740.         urlinput: UrlInputBackstage(editor),
  23741.         styleselect: init$8(editor),
  23742.         colorinput: ColorInputBackstage(editor),
  23743.         dialog: DialogBackstage(editor),
  23744.         isContextMenuOpen: function () {
  23745.           return contextMenuState.get();
  23746.         },
  23747.         setContextMenuState: function (state) {
  23748.           return contextMenuState.set(state);
  23749.         }
  23750.       };
  23751.       return backstage;
  23752.     };
  23753.  
  23754.     var setup$b = function (editor, mothership, uiMothership) {
  23755.       var broadcastEvent = function (name, evt) {
  23756.         each$1([
  23757.           mothership,
  23758.           uiMothership
  23759.         ], function (ship) {
  23760.           ship.broadcastEvent(name, evt);
  23761.         });
  23762.       };
  23763.       var broadcastOn = function (channel, message) {
  23764.         each$1([
  23765.           mothership,
  23766.           uiMothership
  23767.         ], function (ship) {
  23768.           ship.broadcastOn([channel], message);
  23769.         });
  23770.       };
  23771.       var fireDismissPopups = function (evt) {
  23772.         return broadcastOn(dismissPopups(), { target: evt.target });
  23773.       };
  23774.       var doc = getDocument();
  23775.       var onTouchstart = bind(doc, 'touchstart', fireDismissPopups);
  23776.       var onTouchmove = bind(doc, 'touchmove', function (evt) {
  23777.         return broadcastEvent(documentTouchmove(), evt);
  23778.       });
  23779.       var onTouchend = bind(doc, 'touchend', function (evt) {
  23780.         return broadcastEvent(documentTouchend(), evt);
  23781.       });
  23782.       var onMousedown = bind(doc, 'mousedown', fireDismissPopups);
  23783.       var onMouseup = bind(doc, 'mouseup', function (evt) {
  23784.         if (evt.raw.button === 0) {
  23785.           broadcastOn(mouseReleased(), { target: evt.target });
  23786.         }
  23787.       });
  23788.       var onContentClick = function (raw) {
  23789.         return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
  23790.       };
  23791.       var onContentMouseup = function (raw) {
  23792.         if (raw.button === 0) {
  23793.           broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
  23794.         }
  23795.       };
  23796.       var onContentMousedown = function () {
  23797.         each$1(editor.editorManager.get(), function (loopEditor) {
  23798.           if (editor !== loopEditor) {
  23799.             loopEditor.fire('DismissPopups', { relatedTarget: editor });
  23800.           }
  23801.         });
  23802.       };
  23803.       var onWindowScroll = function (evt) {
  23804.         return broadcastEvent(windowScroll(), fromRawEvent(evt));
  23805.       };
  23806.       var onWindowResize = function (evt) {
  23807.         broadcastOn(repositionPopups(), {});
  23808.         broadcastEvent(windowResize(), fromRawEvent(evt));
  23809.       };
  23810.       var onEditorResize = function () {
  23811.         return broadcastOn(repositionPopups(), {});
  23812.       };
  23813.       var onEditorProgress = function (evt) {
  23814.         if (evt.state) {
  23815.           broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
  23816.         }
  23817.       };
  23818.       var onDismissPopups = function (event) {
  23819.         broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
  23820.       };
  23821.       editor.on('PostRender', function () {
  23822.         editor.on('click', onContentClick);
  23823.         editor.on('tap', onContentClick);
  23824.         editor.on('mouseup', onContentMouseup);
  23825.         editor.on('mousedown', onContentMousedown);
  23826.         editor.on('ScrollWindow', onWindowScroll);
  23827.         editor.on('ResizeWindow', onWindowResize);
  23828.         editor.on('ResizeEditor', onEditorResize);
  23829.         editor.on('AfterProgressState', onEditorProgress);
  23830.         editor.on('DismissPopups', onDismissPopups);
  23831.       });
  23832.       editor.on('remove', function () {
  23833.         editor.off('click', onContentClick);
  23834.         editor.off('tap', onContentClick);
  23835.         editor.off('mouseup', onContentMouseup);
  23836.         editor.off('mousedown', onContentMousedown);
  23837.         editor.off('ScrollWindow', onWindowScroll);
  23838.         editor.off('ResizeWindow', onWindowResize);
  23839.         editor.off('ResizeEditor', onEditorResize);
  23840.         editor.off('AfterProgressState', onEditorProgress);
  23841.         editor.off('DismissPopups', onDismissPopups);
  23842.         onMousedown.unbind();
  23843.         onTouchstart.unbind();
  23844.         onTouchmove.unbind();
  23845.         onTouchend.unbind();
  23846.         onMouseup.unbind();
  23847.       });
  23848.       editor.on('detach', function () {
  23849.         detachSystem(mothership);
  23850.         detachSystem(uiMothership);
  23851.         mothership.destroy();
  23852.         uiMothership.destroy();
  23853.       });
  23854.     };
  23855.  
  23856.     var parts$a = AlloyParts;
  23857.     var partType = PartType;
  23858.  
  23859.     var schema$f = constant$1([
  23860.       defaulted('shell', false),
  23861.       required$1('makeItem'),
  23862.       defaulted('setupItem', noop),
  23863.       SketchBehaviours.field('listBehaviours', [Replacing])
  23864.     ]);
  23865.     var customListDetail = function () {
  23866.       return { behaviours: derive$1([Replacing.config({})]) };
  23867.     };
  23868.     var itemsPart = optional({
  23869.       name: 'items',
  23870.       overrides: customListDetail
  23871.     });
  23872.     var parts$9 = constant$1([itemsPart]);
  23873.     var name = constant$1('CustomList');
  23874.  
  23875.     var factory$d = function (detail, components, _spec, _external) {
  23876.       var setItems = function (list, items) {
  23877.         getListContainer(list).fold(function () {
  23878.           console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  23879.           throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  23880.         }, function (container) {
  23881.           var itemComps = Replacing.contents(container);
  23882.           var numListsRequired = items.length;
  23883.           var numListsToAdd = numListsRequired - itemComps.length;
  23884.           var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function () {
  23885.             return detail.makeItem();
  23886.           }) : [];
  23887.           var itemsToRemove = itemComps.slice(numListsRequired);
  23888.           each$1(itemsToRemove, function (item) {
  23889.             return Replacing.remove(container, item);
  23890.           });
  23891.           each$1(itemsToAdd, function (item) {
  23892.             return Replacing.append(container, item);
  23893.           });
  23894.           var builtLists = Replacing.contents(container);
  23895.           each$1(builtLists, function (item, i) {
  23896.             detail.setupItem(list, item, items[i], i);
  23897.           });
  23898.         });
  23899.       };
  23900.       var extra = detail.shell ? {
  23901.         behaviours: [Replacing.config({})],
  23902.         components: []
  23903.       } : {
  23904.         behaviours: [],
  23905.         components: components
  23906.       };
  23907.       var getListContainer = function (component) {
  23908.         return detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
  23909.       };
  23910.       return {
  23911.         uid: detail.uid,
  23912.         dom: detail.dom,
  23913.         components: extra.components,
  23914.         behaviours: augment(detail.listBehaviours, extra.behaviours),
  23915.         apis: { setItems: setItems }
  23916.       };
  23917.     };
  23918.     var CustomList = composite({
  23919.       name: name(),
  23920.       configFields: schema$f(),
  23921.       partFields: parts$9(),
  23922.       factory: factory$d,
  23923.       apis: {
  23924.         setItems: function (apis, list, items) {
  23925.           apis.setItems(list, items);
  23926.         }
  23927.       }
  23928.     });
  23929.  
  23930.     var schema$e = constant$1([
  23931.       required$1('dom'),
  23932.       defaulted('shell', true),
  23933.       field('toolbarBehaviours', [Replacing])
  23934.     ]);
  23935.     var enhanceGroups = function () {
  23936.       return { behaviours: derive$1([Replacing.config({})]) };
  23937.     };
  23938.     var parts$8 = constant$1([optional({
  23939.         name: 'groups',
  23940.         overrides: enhanceGroups
  23941.       })]);
  23942.  
  23943.     var factory$c = function (detail, components, _spec, _externals) {
  23944.       var setGroups = function (toolbar, groups) {
  23945.         getGroupContainer(toolbar).fold(function () {
  23946.           console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  23947.           throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  23948.         }, function (container) {
  23949.           Replacing.set(container, groups);
  23950.         });
  23951.       };
  23952.       var getGroupContainer = function (component) {
  23953.         return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  23954.       };
  23955.       var extra = detail.shell ? {
  23956.         behaviours: [Replacing.config({})],
  23957.         components: []
  23958.       } : {
  23959.         behaviours: [],
  23960.         components: components
  23961.       };
  23962.       return {
  23963.         uid: detail.uid,
  23964.         dom: detail.dom,
  23965.         components: extra.components,
  23966.         behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  23967.         apis: { setGroups: setGroups },
  23968.         domModification: { attributes: { role: 'group' } }
  23969.       };
  23970.     };
  23971.     var Toolbar = composite({
  23972.       name: 'Toolbar',
  23973.       configFields: schema$e(),
  23974.       partFields: parts$8(),
  23975.       factory: factory$c,
  23976.       apis: {
  23977.         setGroups: function (apis, toolbar, groups) {
  23978.           apis.setGroups(toolbar, groups);
  23979.         }
  23980.       }
  23981.     });
  23982.  
  23983.     var setup$a = noop;
  23984.     var isDocked$2 = never;
  23985.     var getBehaviours$1 = constant$1([]);
  23986.  
  23987.     var StaticHeader = /*#__PURE__*/Object.freeze({
  23988.         __proto__: null,
  23989.         setup: setup$a,
  23990.         isDocked: isDocked$2,
  23991.         getBehaviours: getBehaviours$1
  23992.     });
  23993.  
  23994.     var getOffsetParent = function (element) {
  23995.       var isFixed = is$1(getRaw(element, 'position'), 'fixed');
  23996.       var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
  23997.       return offsetParent$1.orThunk(function () {
  23998.         var marker = SugarElement.fromTag('span');
  23999.         return parent(element).bind(function (parent) {
  24000.           append$2(parent, marker);
  24001.           var offsetParent$1 = offsetParent(marker);
  24002.           remove$5(marker);
  24003.           return offsetParent$1;
  24004.         });
  24005.       });
  24006.     };
  24007.     var getOrigin = function (element) {
  24008.       return getOffsetParent(element).map(absolute$3).getOrThunk(function () {
  24009.         return SugarPosition(0, 0);
  24010.       });
  24011.     };
  24012.  
  24013.     var morphAdt = Adt.generate([
  24014.       { static: [] },
  24015.       { absolute: ['positionCss'] },
  24016.       { fixed: ['positionCss'] }
  24017.     ]);
  24018.     var appear = function (component, contextualInfo) {
  24019.       var elem = component.element;
  24020.       add$2(elem, contextualInfo.transitionClass);
  24021.       remove$2(elem, contextualInfo.fadeOutClass);
  24022.       add$2(elem, contextualInfo.fadeInClass);
  24023.       contextualInfo.onShow(component);
  24024.     };
  24025.     var disappear = function (component, contextualInfo) {
  24026.       var elem = component.element;
  24027.       add$2(elem, contextualInfo.transitionClass);
  24028.       remove$2(elem, contextualInfo.fadeInClass);
  24029.       add$2(elem, contextualInfo.fadeOutClass);
  24030.       contextualInfo.onHide(component);
  24031.     };
  24032.     var isPartiallyVisible = function (box, viewport) {
  24033.       return box.y < viewport.bottom && box.bottom > viewport.y;
  24034.     };
  24035.     var isTopCompletelyVisible = function (box, viewport) {
  24036.       return box.y >= viewport.y;
  24037.     };
  24038.     var isBottomCompletelyVisible = function (box, viewport) {
  24039.       return box.bottom <= viewport.bottom;
  24040.     };
  24041.     var isVisibleForModes = function (modes, box, viewport) {
  24042.       return forall(modes, function (mode) {
  24043.         switch (mode) {
  24044.         case 'bottom':
  24045.           return isBottomCompletelyVisible(box, viewport);
  24046.         case 'top':
  24047.           return isTopCompletelyVisible(box, viewport);
  24048.         }
  24049.       });
  24050.     };
  24051.     var getPrior = function (elem, state) {
  24052.       return state.getInitialPos().map(function (pos) {
  24053.         return bounds(pos.bounds.x, pos.bounds.y, get$a(elem), get$b(elem));
  24054.       });
  24055.     };
  24056.     var storePrior = function (elem, box, state) {
  24057.       state.setInitialPos({
  24058.         style: getAllRaw(elem),
  24059.         position: get$c(elem, 'position') || 'static',
  24060.         bounds: box
  24061.       });
  24062.     };
  24063.     var revertToOriginal = function (elem, box, state) {
  24064.       return state.getInitialPos().bind(function (position) {
  24065.         state.clearInitialPos();
  24066.         switch (position.position) {
  24067.         case 'static':
  24068.           return Optional.some(morphAdt.static());
  24069.         case 'absolute':
  24070.           var offsetBox_1 = getOffsetParent(elem).map(box$1).getOrThunk(function () {
  24071.             return box$1(body());
  24072.           });
  24073.           return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$e(position.style, 'left').map(function (_left) {
  24074.             return box.x - offsetBox_1.x;
  24075.           }), get$e(position.style, 'top').map(function (_top) {
  24076.             return box.y - offsetBox_1.y;
  24077.           }), get$e(position.style, 'right').map(function (_right) {
  24078.             return offsetBox_1.right - box.right;
  24079.           }), get$e(position.style, 'bottom').map(function (_bottom) {
  24080.             return offsetBox_1.bottom - box.bottom;
  24081.           }))));
  24082.         default:
  24083.           return Optional.none();
  24084.         }
  24085.       });
  24086.     };
  24087.     var morphToOriginal = function (elem, viewport, state) {
  24088.       return getPrior(elem, state).filter(function (box) {
  24089.         return isVisibleForModes(state.getModes(), box, viewport);
  24090.       }).bind(function (box) {
  24091.         return revertToOriginal(elem, box, state);
  24092.       });
  24093.     };
  24094.     var morphToFixed = function (elem, viewport, state) {
  24095.       var box = box$1(elem);
  24096.       if (!isVisibleForModes(state.getModes(), box, viewport)) {
  24097.         storePrior(elem, box, state);
  24098.         var winBox = win();
  24099.         var left = box.x - winBox.x;
  24100.         var top_1 = viewport.y - winBox.y;
  24101.         var bottom = winBox.bottom - viewport.bottom;
  24102.         var isTop = box.y <= viewport.y;
  24103.         return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none())));
  24104.       } else {
  24105.         return Optional.none();
  24106.       }
  24107.     };
  24108.     var getMorph = function (component, viewport, state) {
  24109.       var elem = component.element;
  24110.       var isDocked = is$1(getRaw(elem, 'position'), 'fixed');
  24111.       return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  24112.     };
  24113.     var getMorphToOriginal = function (component, state) {
  24114.       var elem = component.element;
  24115.       return getPrior(elem, state).bind(function (box) {
  24116.         return revertToOriginal(elem, box, state);
  24117.       });
  24118.     };
  24119.  
  24120.     var morphToStatic = function (component, config, state) {
  24121.       state.setDocked(false);
  24122.       each$1([
  24123.         'left',
  24124.         'right',
  24125.         'top',
  24126.         'bottom',
  24127.         'position'
  24128.       ], function (prop) {
  24129.         return remove$6(component.element, prop);
  24130.       });
  24131.       config.onUndocked(component);
  24132.     };
  24133.     var morphToCoord = function (component, config, state, position) {
  24134.       var isDocked = position.position === 'fixed';
  24135.       state.setDocked(isDocked);
  24136.       applyPositionCss(component.element, position);
  24137.       var method = isDocked ? config.onDocked : config.onUndocked;
  24138.       method(component);
  24139.     };
  24140.     var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  24141.       if (morphToDocked === void 0) {
  24142.         morphToDocked = false;
  24143.       }
  24144.       config.contextual.each(function (contextInfo) {
  24145.         contextInfo.lazyContext(component).each(function (box) {
  24146.           var isVisible = isPartiallyVisible(box, viewport);
  24147.           if (isVisible !== state.isVisible()) {
  24148.             state.setVisible(isVisible);
  24149.             if (morphToDocked && !isVisible) {
  24150.               add$1(component.element, [contextInfo.fadeOutClass]);
  24151.               contextInfo.onHide(component);
  24152.             } else {
  24153.               var method = isVisible ? appear : disappear;
  24154.               method(component, contextInfo);
  24155.             }
  24156.           }
  24157.         });
  24158.       });
  24159.     };
  24160.     var refreshInternal = function (component, config, state) {
  24161.       var viewport = config.lazyViewport(component);
  24162.       var isDocked = state.isDocked();
  24163.       if (isDocked) {
  24164.         updateVisibility(component, config, state, viewport);
  24165.       }
  24166.       getMorph(component, viewport, state).each(function (morph) {
  24167.         morph.fold(function () {
  24168.           return morphToStatic(component, config, state);
  24169.         }, function (position) {
  24170.           return morphToCoord(component, config, state, position);
  24171.         }, function (position) {
  24172.           updateVisibility(component, config, state, viewport, true);
  24173.           morphToCoord(component, config, state, position);
  24174.         });
  24175.       });
  24176.     };
  24177.     var resetInternal = function (component, config, state) {
  24178.       var elem = component.element;
  24179.       state.setDocked(false);
  24180.       getMorphToOriginal(component, state).each(function (morph) {
  24181.         morph.fold(function () {
  24182.           return morphToStatic(component, config, state);
  24183.         }, function (position) {
  24184.           return morphToCoord(component, config, state, position);
  24185.         }, noop);
  24186.       });
  24187.       state.setVisible(true);
  24188.       config.contextual.each(function (contextInfo) {
  24189.         remove$1(elem, [
  24190.           contextInfo.fadeInClass,
  24191.           contextInfo.fadeOutClass,
  24192.           contextInfo.transitionClass
  24193.         ]);
  24194.         contextInfo.onShow(component);
  24195.       });
  24196.       refresh$4(component, config, state);
  24197.     };
  24198.     var refresh$4 = function (component, config, state) {
  24199.       if (component.getSystem().isConnected()) {
  24200.         refreshInternal(component, config, state);
  24201.       }
  24202.     };
  24203.     var reset = function (component, config, state) {
  24204.       if (state.isDocked()) {
  24205.         resetInternal(component, config, state);
  24206.       }
  24207.     };
  24208.     var isDocked$1 = function (component, config, state) {
  24209.       return state.isDocked();
  24210.     };
  24211.     var setModes = function (component, config, state, modes) {
  24212.       return state.setModes(modes);
  24213.     };
  24214.     var getModes = function (component, config, state) {
  24215.       return state.getModes();
  24216.     };
  24217.  
  24218.     var DockingApis = /*#__PURE__*/Object.freeze({
  24219.         __proto__: null,
  24220.         refresh: refresh$4,
  24221.         reset: reset,
  24222.         isDocked: isDocked$1,
  24223.         getModes: getModes,
  24224.         setModes: setModes
  24225.     });
  24226.  
  24227.     var events$5 = function (dockInfo, dockState) {
  24228.       return derive$2([
  24229.         runOnSource(transitionend(), function (component, simulatedEvent) {
  24230.           dockInfo.contextual.each(function (contextInfo) {
  24231.             if (has(component.element, contextInfo.transitionClass)) {
  24232.               remove$1(component.element, [
  24233.                 contextInfo.transitionClass,
  24234.                 contextInfo.fadeInClass
  24235.               ]);
  24236.               var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  24237.               notify(component);
  24238.             }
  24239.             simulatedEvent.stop();
  24240.           });
  24241.         }),
  24242.         run$1(windowScroll(), function (component, _) {
  24243.           refresh$4(component, dockInfo, dockState);
  24244.         }),
  24245.         run$1(windowResize(), function (component, _) {
  24246.           reset(component, dockInfo, dockState);
  24247.         })
  24248.       ]);
  24249.     };
  24250.  
  24251.     var ActiveDocking = /*#__PURE__*/Object.freeze({
  24252.         __proto__: null,
  24253.         events: events$5
  24254.     });
  24255.  
  24256.     var DockingSchema = [
  24257.       optionObjOf('contextual', [
  24258.         requiredString('fadeInClass'),
  24259.         requiredString('fadeOutClass'),
  24260.         requiredString('transitionClass'),
  24261.         requiredFunction('lazyContext'),
  24262.         onHandler('onShow'),
  24263.         onHandler('onShown'),
  24264.         onHandler('onHide'),
  24265.         onHandler('onHidden')
  24266.       ]),
  24267.       defaultedFunction('lazyViewport', win),
  24268.       defaultedArrayOf('modes', [
  24269.         'top',
  24270.         'bottom'
  24271.       ], string),
  24272.       onHandler('onDocked'),
  24273.       onHandler('onUndocked')
  24274.     ];
  24275.  
  24276.     var init$6 = function (spec) {
  24277.       var docked = Cell(false);
  24278.       var visible = Cell(true);
  24279.       var initialBounds = value$1();
  24280.       var modes = Cell(spec.modes);
  24281.       var readState = function () {
  24282.         return 'docked:  ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
  24283.       };
  24284.       return nu$8({
  24285.         isDocked: docked.get,
  24286.         setDocked: docked.set,
  24287.         getInitialPos: initialBounds.get,
  24288.         setInitialPos: initialBounds.set,
  24289.         clearInitialPos: initialBounds.clear,
  24290.         isVisible: visible.get,
  24291.         setVisible: visible.set,
  24292.         getModes: modes.get,
  24293.         setModes: modes.set,
  24294.         readState: readState
  24295.       });
  24296.     };
  24297.  
  24298.     var DockingState = /*#__PURE__*/Object.freeze({
  24299.         __proto__: null,
  24300.         init: init$6
  24301.     });
  24302.  
  24303.     var Docking = create$8({
  24304.       fields: DockingSchema,
  24305.       name: 'docking',
  24306.       active: ActiveDocking,
  24307.       apis: DockingApis,
  24308.       state: DockingState
  24309.     });
  24310.  
  24311.     var toolbarHeightChange = constant$1(generate$6('toolbar-height-change'));
  24312.  
  24313.     var visibility = {
  24314.       fadeInClass: 'tox-editor-dock-fadein',
  24315.       fadeOutClass: 'tox-editor-dock-fadeout',
  24316.       transitionClass: 'tox-editor-dock-transition'
  24317.     };
  24318.     var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  24319.     var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  24320.     var scrollFromBehindHeader = function (e, containerHeader) {
  24321.       var doc = owner$4(containerHeader);
  24322.       var viewHeight = doc.dom.defaultView.innerHeight;
  24323.       var scrollPos = get$9(doc);
  24324.       var markerElement = SugarElement.fromDom(e.elm);
  24325.       var markerPos = absolute$2(markerElement);
  24326.       var markerHeight = get$b(markerElement);
  24327.       var markerTop = markerPos.y;
  24328.       var markerBottom = markerTop + markerHeight;
  24329.       var editorHeaderPos = absolute$3(containerHeader);
  24330.       var editorHeaderHeight = get$b(containerHeader);
  24331.       var editorHeaderTop = editorHeaderPos.top;
  24332.       var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  24333.       var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
  24334.       var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
  24335.       if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  24336.         to(scrollPos.left, markerTop - editorHeaderHeight, doc);
  24337.       } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  24338.         var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  24339.         to(scrollPos.left, y, doc);
  24340.       }
  24341.     };
  24342.     var isDockedMode = function (header, mode) {
  24343.       return contains$2(Docking.getModes(header), mode);
  24344.     };
  24345.     var updateIframeContentFlow = function (header) {
  24346.       var getOccupiedHeight = function (elm) {
  24347.         return getOuter$2(elm) + (parseInt(get$c(elm, 'margin-top'), 10) || 0) + (parseInt(get$c(elm, 'margin-bottom'), 10) || 0);
  24348.       };
  24349.       var elm = header.element;
  24350.       parent(elm).each(function (parentElem) {
  24351.         var padding = 'padding-' + Docking.getModes(header)[0];
  24352.         if (Docking.isDocked(header)) {
  24353.           var parentWidth = get$a(parentElem);
  24354.           set$7(elm, 'width', parentWidth + 'px');
  24355.           set$7(parentElem, padding, getOccupiedHeight(elm) + 'px');
  24356.         } else {
  24357.           remove$6(elm, 'width');
  24358.           remove$6(parentElem, padding);
  24359.         }
  24360.       });
  24361.     };
  24362.     var updateSinkVisibility = function (sinkElem, visible) {
  24363.       if (visible) {
  24364.         remove$2(sinkElem, visibility.fadeOutClass);
  24365.         add$1(sinkElem, [
  24366.           visibility.transitionClass,
  24367.           visibility.fadeInClass
  24368.         ]);
  24369.       } else {
  24370.         remove$2(sinkElem, visibility.fadeInClass);
  24371.         add$1(sinkElem, [
  24372.           visibility.fadeOutClass,
  24373.           visibility.transitionClass
  24374.         ]);
  24375.       }
  24376.     };
  24377.     var updateEditorClasses = function (editor, docked) {
  24378.       var editorContainer = SugarElement.fromDom(editor.getContainer());
  24379.       if (docked) {
  24380.         add$2(editorContainer, editorStickyOnClass);
  24381.         remove$2(editorContainer, editorStickyOffClass);
  24382.       } else {
  24383.         add$2(editorContainer, editorStickyOffClass);
  24384.         remove$2(editorContainer, editorStickyOnClass);
  24385.       }
  24386.     };
  24387.     var restoreFocus = function (headerElem, focusedElem) {
  24388.       var ownerDoc = owner$4(focusedElem);
  24389.       active(ownerDoc).filter(function (activeElm) {
  24390.         return !eq(focusedElem, activeElm);
  24391.       }).filter(function (activeElm) {
  24392.         return eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm);
  24393.       }).each(function () {
  24394.         return focus$3(focusedElem);
  24395.       });
  24396.     };
  24397.     var findFocusedElem = function (rootElm, lazySink) {
  24398.       return search(rootElm).orThunk(function () {
  24399.         return lazySink().toOptional().bind(function (sink) {
  24400.           return search(sink.element);
  24401.         });
  24402.       });
  24403.     };
  24404.     var setup$9 = function (editor, sharedBackstage, lazyHeader) {
  24405.       if (!editor.inline) {
  24406.         if (!sharedBackstage.header.isPositionedAtTop()) {
  24407.           editor.on('ResizeEditor', function () {
  24408.             lazyHeader().each(Docking.reset);
  24409.           });
  24410.         }
  24411.         editor.on('ResizeWindow ResizeEditor', function () {
  24412.           lazyHeader().each(updateIframeContentFlow);
  24413.         });
  24414.         editor.on('SkinLoaded', function () {
  24415.           lazyHeader().each(function (comp) {
  24416.             Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  24417.           });
  24418.         });
  24419.         editor.on('FullscreenStateChanged', function () {
  24420.           lazyHeader().each(Docking.reset);
  24421.         });
  24422.       }
  24423.       editor.on('AfterScrollIntoView', function (e) {
  24424.         lazyHeader().each(function (header) {
  24425.           Docking.refresh(header);
  24426.           var headerElem = header.element;
  24427.           if (isVisible(headerElem)) {
  24428.             scrollFromBehindHeader(e, headerElem);
  24429.           }
  24430.         });
  24431.       });
  24432.       editor.on('PostRender', function () {
  24433.         updateEditorClasses(editor, false);
  24434.       });
  24435.     };
  24436.     var isDocked = function (lazyHeader) {
  24437.       return lazyHeader().map(Docking.isDocked).getOr(false);
  24438.     };
  24439.     var getIframeBehaviours = function () {
  24440.       var _a;
  24441.       return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
  24442.     };
  24443.     var getBehaviours = function (editor, sharedBackstage) {
  24444.       var focusedElm = value$1();
  24445.       var lazySink = sharedBackstage.getSink;
  24446.       var runOnSinkElement = function (f) {
  24447.         lazySink().each(function (sink) {
  24448.           return f(sink.element);
  24449.         });
  24450.       };
  24451.       var onDockingSwitch = function (comp) {
  24452.         if (!editor.inline) {
  24453.           updateIframeContentFlow(comp);
  24454.         }
  24455.         updateEditorClasses(editor, Docking.isDocked(comp));
  24456.         comp.getSystem().broadcastOn([repositionPopups()], {});
  24457.         lazySink().each(function (sink) {
  24458.           return sink.getSystem().broadcastOn([repositionPopups()], {});
  24459.         });
  24460.       };
  24461.       var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  24462.       return __spreadArray([
  24463.         Focusing.config({}),
  24464.         Docking.config({
  24465.           contextual: __assign({
  24466.             lazyContext: function (comp) {
  24467.               var headerHeight = getOuter$2(comp.element);
  24468.               var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  24469.               var box = box$1(SugarElement.fromDom(container));
  24470.               var boxHeight = box.height - headerHeight;
  24471.               var topBound = box.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  24472.               return Optional.some(bounds(box.x, topBound, box.width, boxHeight));
  24473.             },
  24474.             onShow: function () {
  24475.               runOnSinkElement(function (elem) {
  24476.                 return updateSinkVisibility(elem, true);
  24477.               });
  24478.             },
  24479.             onShown: function (comp) {
  24480.               runOnSinkElement(function (elem) {
  24481.                 return remove$1(elem, [
  24482.                   visibility.transitionClass,
  24483.                   visibility.fadeInClass
  24484.                 ]);
  24485.               });
  24486.               focusedElm.get().each(function (elem) {
  24487.                 restoreFocus(comp.element, elem);
  24488.                 focusedElm.clear();
  24489.               });
  24490.             },
  24491.             onHide: function (comp) {
  24492.               findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
  24493.               runOnSinkElement(function (elem) {
  24494.                 return updateSinkVisibility(elem, false);
  24495.               });
  24496.             },
  24497.             onHidden: function () {
  24498.               runOnSinkElement(function (elem) {
  24499.                 return remove$1(elem, [visibility.transitionClass]);
  24500.               });
  24501.             }
  24502.           }, visibility),
  24503.           lazyViewport: function (comp) {
  24504.             var win$1 = win();
  24505.             var offset = getStickyToolbarOffset(editor);
  24506.             var top = win$1.y + (isDockedMode(comp, 'top') ? offset : 0);
  24507.             var height = win$1.height - (isDockedMode(comp, 'bottom') ? offset : 0);
  24508.             return bounds(win$1.x, top, win$1.width, height);
  24509.           },
  24510.           modes: [sharedBackstage.header.getDockingMode()],
  24511.           onDocked: onDockingSwitch,
  24512.           onUndocked: onDockingSwitch
  24513.         })
  24514.       ], additionalBehaviours, true);
  24515.     };
  24516.  
  24517.     var StickyHeader = /*#__PURE__*/Object.freeze({
  24518.         __proto__: null,
  24519.         setup: setup$9,
  24520.         isDocked: isDocked,
  24521.         getBehaviours: getBehaviours
  24522.     });
  24523.  
  24524.     var renderHeader = function (spec) {
  24525.       var editor = spec.editor;
  24526.       var getBehaviours$2 = spec.sticky ? getBehaviours : getBehaviours$1;
  24527.       return {
  24528.         uid: spec.uid,
  24529.         dom: spec.dom,
  24530.         components: spec.components,
  24531.         behaviours: derive$1(getBehaviours$2(editor, spec.sharedBackstage))
  24532.       };
  24533.     };
  24534.  
  24535.     var groupToolbarButtonSchema = objOf([
  24536.       requiredString('type'),
  24537.       requiredOf('items', oneOf([
  24538.         arrOfObj([
  24539.           requiredString('name'),
  24540.           requiredArrayOf('items', string)
  24541.         ]),
  24542.         string
  24543.       ]))
  24544.     ].concat(baseToolbarButtonFields));
  24545.     var createGroupToolbarButton = function (spec) {
  24546.       return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  24547.     };
  24548.  
  24549.     var baseMenuButtonFields = [
  24550.       optionString('text'),
  24551.       optionString('tooltip'),
  24552.       optionString('icon'),
  24553.       requiredFunction('fetch'),
  24554.       defaultedFunction('onSetup', function () {
  24555.         return noop;
  24556.       })
  24557.     ];
  24558.  
  24559.     var MenuButtonSchema = objOf(__spreadArray([requiredString('type')], baseMenuButtonFields, true));
  24560.     var createMenuButton = function (spec) {
  24561.       return asRaw('menubutton', MenuButtonSchema, spec);
  24562.     };
  24563.  
  24564.     var splitButtonSchema = objOf([
  24565.       requiredString('type'),
  24566.       optionString('tooltip'),
  24567.       optionString('icon'),
  24568.       optionString('text'),
  24569.       optionFunction('select'),
  24570.       requiredFunction('fetch'),
  24571.       defaultedFunction('onSetup', function () {
  24572.         return noop;
  24573.       }),
  24574.       defaultedStringEnum('presets', 'normal', [
  24575.         'normal',
  24576.         'color',
  24577.         'listpreview'
  24578.       ]),
  24579.       defaulted('columns', 1),
  24580.       requiredFunction('onAction'),
  24581.       requiredFunction('onItemAction')
  24582.     ]);
  24583.     var createSplitButton = function (spec) {
  24584.       return asRaw('SplitButton', splitButtonSchema, spec);
  24585.     };
  24586.  
  24587.     var factory$b = function (detail, spec) {
  24588.       var setMenus = function (comp, menus) {
  24589.         var newMenus = map$2(menus, function (m) {
  24590.           var buttonSpec = {
  24591.             type: 'menubutton',
  24592.             text: m.text,
  24593.             fetch: function (callback) {
  24594.               callback(m.getItems());
  24595.             }
  24596.           };
  24597.           var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  24598.             return formatError(errInfo);
  24599.           }).getOrDie();
  24600.           return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
  24601.         });
  24602.         Replacing.set(comp, newMenus);
  24603.       };
  24604.       var apis = {
  24605.         focus: Keying.focusIn,
  24606.         setMenus: setMenus
  24607.       };
  24608.       return {
  24609.         uid: detail.uid,
  24610.         dom: detail.dom,
  24611.         components: [],
  24612.         behaviours: derive$1([
  24613.           Replacing.config({}),
  24614.           config('menubar-events', [
  24615.             runOnAttached(function (component) {
  24616.               detail.onSetup(component);
  24617.             }),
  24618.             run$1(mouseover(), function (comp, se) {
  24619.               descendant(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) {
  24620.                 closest$1(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) {
  24621.                   if (!eq(activeButton, hoveredButton)) {
  24622.                     comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  24623.                       comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  24624.                         Dropdown.expand(hoveredComp);
  24625.                         Dropdown.close(activeComp);
  24626.                         Focusing.focus(hoveredComp);
  24627.                       });
  24628.                     });
  24629.                   }
  24630.                 });
  24631.               });
  24632.             }),
  24633.             run$1(focusShifted(), function (comp, se) {
  24634.               se.event.prevFocus.bind(function (prev) {
  24635.                 return comp.getSystem().getByDom(prev).toOptional();
  24636.               }).each(function (prev) {
  24637.                 se.event.newFocus.bind(function (nu) {
  24638.                   return comp.getSystem().getByDom(nu).toOptional();
  24639.                 }).each(function (nu) {
  24640.                   if (Dropdown.isOpen(prev)) {
  24641.                     Dropdown.expand(nu);
  24642.                     Dropdown.close(prev);
  24643.                   }
  24644.                 });
  24645.               });
  24646.             })
  24647.           ]),
  24648.           Keying.config({
  24649.             mode: 'flow',
  24650.             selector: '.' + 'tox-mbtn',
  24651.             onEscape: function (comp) {
  24652.               detail.onEscape(comp);
  24653.               return Optional.some(true);
  24654.             }
  24655.           }),
  24656.           Tabstopping.config({})
  24657.         ]),
  24658.         apis: apis,
  24659.         domModification: { attributes: { role: 'menubar' } }
  24660.       };
  24661.     };
  24662.     var SilverMenubar = single({
  24663.       factory: factory$b,
  24664.       name: 'silver.Menubar',
  24665.       configFields: [
  24666.         required$1('dom'),
  24667.         required$1('uid'),
  24668.         required$1('onEscape'),
  24669.         required$1('backstage'),
  24670.         defaulted('onSetup', noop)
  24671.       ],
  24672.       apis: {
  24673.         focus: function (apis, comp) {
  24674.           apis.focus(comp);
  24675.         },
  24676.         setMenus: function (apis, comp, menus) {
  24677.           apis.setMenus(comp, menus);
  24678.         }
  24679.       }
  24680.     });
  24681.  
  24682.     var getAnimationRoot = function (component, slideConfig) {
  24683.       return slideConfig.getAnimationRoot.fold(function () {
  24684.         return component.element;
  24685.       }, function (get) {
  24686.         return get(component);
  24687.       });
  24688.     };
  24689.  
  24690.     var getDimensionProperty = function (slideConfig) {
  24691.       return slideConfig.dimension.property;
  24692.     };
  24693.     var getDimension = function (slideConfig, elem) {
  24694.       return slideConfig.dimension.getDimension(elem);
  24695.     };
  24696.     var disableTransitions = function (component, slideConfig) {
  24697.       var root = getAnimationRoot(component, slideConfig);
  24698.       remove$1(root, [
  24699.         slideConfig.shrinkingClass,
  24700.         slideConfig.growingClass
  24701.       ]);
  24702.     };
  24703.     var setShrunk = function (component, slideConfig) {
  24704.       remove$2(component.element, slideConfig.openClass);
  24705.       add$2(component.element, slideConfig.closedClass);
  24706.       set$7(component.element, getDimensionProperty(slideConfig), '0px');
  24707.       reflow(component.element);
  24708.     };
  24709.     var setGrown = function (component, slideConfig) {
  24710.       remove$2(component.element, slideConfig.closedClass);
  24711.       add$2(component.element, slideConfig.openClass);
  24712.       remove$6(component.element, getDimensionProperty(slideConfig));
  24713.     };
  24714.     var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  24715.       slideState.setCollapsed();
  24716.       set$7(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  24717.       reflow(component.element);
  24718.       disableTransitions(component, slideConfig);
  24719.       setShrunk(component, slideConfig);
  24720.       slideConfig.onStartShrink(component);
  24721.       slideConfig.onShrunk(component);
  24722.     };
  24723.     var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  24724.       var size = calculatedSize.getOrThunk(function () {
  24725.         return getDimension(slideConfig, component.element);
  24726.       });
  24727.       slideState.setCollapsed();
  24728.       set$7(component.element, getDimensionProperty(slideConfig), size);
  24729.       reflow(component.element);
  24730.       var root = getAnimationRoot(component, slideConfig);
  24731.       remove$2(root, slideConfig.growingClass);
  24732.       add$2(root, slideConfig.shrinkingClass);
  24733.       setShrunk(component, slideConfig);
  24734.       slideConfig.onStartShrink(component);
  24735.     };
  24736.     var doStartSmartShrink = function (component, slideConfig, slideState) {
  24737.       var size = getDimension(slideConfig, component.element);
  24738.       var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  24739.       shrinker(component, slideConfig, slideState, Optional.some(size));
  24740.     };
  24741.     var doStartGrow = function (component, slideConfig, slideState) {
  24742.       var root = getAnimationRoot(component, slideConfig);
  24743.       var wasShrinking = has(root, slideConfig.shrinkingClass);
  24744.       var beforeSize = getDimension(slideConfig, component.element);
  24745.       setGrown(component, slideConfig);
  24746.       var fullSize = getDimension(slideConfig, component.element);
  24747.       var startPartialGrow = function () {
  24748.         set$7(component.element, getDimensionProperty(slideConfig), beforeSize);
  24749.         reflow(component.element);
  24750.       };
  24751.       var startCompleteGrow = function () {
  24752.         setShrunk(component, slideConfig);
  24753.       };
  24754.       var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  24755.       setStartSize();
  24756.       remove$2(root, slideConfig.shrinkingClass);
  24757.       add$2(root, slideConfig.growingClass);
  24758.       setGrown(component, slideConfig);
  24759.       set$7(component.element, getDimensionProperty(slideConfig), fullSize);
  24760.       slideState.setExpanded();
  24761.       slideConfig.onStartGrow(component);
  24762.     };
  24763.     var refresh$3 = function (component, slideConfig, slideState) {
  24764.       if (slideState.isExpanded()) {
  24765.         remove$6(component.element, getDimensionProperty(slideConfig));
  24766.         var fullSize = getDimension(slideConfig, component.element);
  24767.         set$7(component.element, getDimensionProperty(slideConfig), fullSize);
  24768.       }
  24769.     };
  24770.     var grow = function (component, slideConfig, slideState) {
  24771.       if (!slideState.isExpanded()) {
  24772.         doStartGrow(component, slideConfig, slideState);
  24773.       }
  24774.     };
  24775.     var shrink = function (component, slideConfig, slideState) {
  24776.       if (slideState.isExpanded()) {
  24777.         doStartSmartShrink(component, slideConfig, slideState);
  24778.       }
  24779.     };
  24780.     var immediateShrink = function (component, slideConfig, slideState) {
  24781.       if (slideState.isExpanded()) {
  24782.         doImmediateShrink(component, slideConfig, slideState);
  24783.       }
  24784.     };
  24785.     var hasGrown = function (component, slideConfig, slideState) {
  24786.       return slideState.isExpanded();
  24787.     };
  24788.     var hasShrunk = function (component, slideConfig, slideState) {
  24789.       return slideState.isCollapsed();
  24790.     };
  24791.     var isGrowing = function (component, slideConfig, _slideState) {
  24792.       var root = getAnimationRoot(component, slideConfig);
  24793.       return has(root, slideConfig.growingClass) === true;
  24794.     };
  24795.     var isShrinking = function (component, slideConfig, _slideState) {
  24796.       var root = getAnimationRoot(component, slideConfig);
  24797.       return has(root, slideConfig.shrinkingClass) === true;
  24798.     };
  24799.     var isTransitioning = function (component, slideConfig, slideState) {
  24800.       return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  24801.     };
  24802.     var toggleGrow = function (component, slideConfig, slideState) {
  24803.       var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  24804.       f(component, slideConfig, slideState);
  24805.     };
  24806.  
  24807.     var SlidingApis = /*#__PURE__*/Object.freeze({
  24808.         __proto__: null,
  24809.         refresh: refresh$3,
  24810.         grow: grow,
  24811.         shrink: shrink,
  24812.         immediateShrink: immediateShrink,
  24813.         hasGrown: hasGrown,
  24814.         hasShrunk: hasShrunk,
  24815.         isGrowing: isGrowing,
  24816.         isShrinking: isShrinking,
  24817.         isTransitioning: isTransitioning,
  24818.         toggleGrow: toggleGrow,
  24819.         disableTransitions: disableTransitions
  24820.     });
  24821.  
  24822.     var exhibit = function (base, slideConfig, _slideState) {
  24823.       var expanded = slideConfig.expanded;
  24824.       return expanded ? nu$7({
  24825.         classes: [slideConfig.openClass],
  24826.         styles: {}
  24827.       }) : nu$7({
  24828.         classes: [slideConfig.closedClass],
  24829.         styles: wrap$1(slideConfig.dimension.property, '0px')
  24830.       });
  24831.     };
  24832.     var events$4 = function (slideConfig, slideState) {
  24833.       return derive$2([runOnSource(transitionend(), function (component, simulatedEvent) {
  24834.           var raw = simulatedEvent.event.raw;
  24835.           if (raw.propertyName === slideConfig.dimension.property) {
  24836.             disableTransitions(component, slideConfig);
  24837.             if (slideState.isExpanded()) {
  24838.               remove$6(component.element, slideConfig.dimension.property);
  24839.             }
  24840.             var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  24841.             notify(component);
  24842.           }
  24843.         })]);
  24844.     };
  24845.  
  24846.     var ActiveSliding = /*#__PURE__*/Object.freeze({
  24847.         __proto__: null,
  24848.         exhibit: exhibit,
  24849.         events: events$4
  24850.     });
  24851.  
  24852.     var SlidingSchema = [
  24853.       required$1('closedClass'),
  24854.       required$1('openClass'),
  24855.       required$1('shrinkingClass'),
  24856.       required$1('growingClass'),
  24857.       option('getAnimationRoot'),
  24858.       onHandler('onShrunk'),
  24859.       onHandler('onStartShrink'),
  24860.       onHandler('onGrown'),
  24861.       onHandler('onStartGrow'),
  24862.       defaulted('expanded', false),
  24863.       requiredOf('dimension', choose$1('property', {
  24864.         width: [
  24865.           output$1('property', 'width'),
  24866.           output$1('getDimension', function (elem) {
  24867.             return get$a(elem) + 'px';
  24868.           })
  24869.         ],
  24870.         height: [
  24871.           output$1('property', 'height'),
  24872.           output$1('getDimension', function (elem) {
  24873.             return get$b(elem) + 'px';
  24874.           })
  24875.         ]
  24876.       }))
  24877.     ];
  24878.  
  24879.     var init$5 = function (spec) {
  24880.       var state = Cell(spec.expanded);
  24881.       var readState = function () {
  24882.         return 'expanded: ' + state.get();
  24883.       };
  24884.       return nu$8({
  24885.         isExpanded: function () {
  24886.           return state.get() === true;
  24887.         },
  24888.         isCollapsed: function () {
  24889.           return state.get() === false;
  24890.         },
  24891.         setCollapsed: curry(state.set, false),
  24892.         setExpanded: curry(state.set, true),
  24893.         readState: readState
  24894.       });
  24895.     };
  24896.  
  24897.     var SlidingState = /*#__PURE__*/Object.freeze({
  24898.         __proto__: null,
  24899.         init: init$5
  24900.     });
  24901.  
  24902.     var Sliding = create$8({
  24903.       fields: SlidingSchema,
  24904.       name: 'sliding',
  24905.       active: ActiveSliding,
  24906.       apis: SlidingApis,
  24907.       state: SlidingState
  24908.     });
  24909.  
  24910.     var owner = 'container';
  24911.     var schema$d = [field('slotBehaviours', [])];
  24912.     var getPartName = function (name) {
  24913.       return '<alloy.field.' + name + '>';
  24914.     };
  24915.     var sketch = function (sSpec) {
  24916.       var parts = function () {
  24917.         var record = [];
  24918.         var slot = function (name, config) {
  24919.           record.push(name);
  24920.           return generateOne$1(owner, getPartName(name), config);
  24921.         };
  24922.         return {
  24923.           slot: slot,
  24924.           record: constant$1(record)
  24925.         };
  24926.       }();
  24927.       var spec = sSpec(parts);
  24928.       var partNames = parts.record();
  24929.       var fieldParts = map$2(partNames, function (n) {
  24930.         return required({
  24931.           name: n,
  24932.           pname: getPartName(n)
  24933.         });
  24934.       });
  24935.       return composite$1(owner, schema$d, fieldParts, make$1, spec);
  24936.     };
  24937.     var make$1 = function (detail, components) {
  24938.       var getSlotNames = function (_) {
  24939.         return getAllPartNames(detail);
  24940.       };
  24941.       var getSlot = function (container, key) {
  24942.         return getPart(container, detail, key);
  24943.       };
  24944.       var onSlot = function (f, def) {
  24945.         return function (container, key) {
  24946.           return getPart(container, detail, key).map(function (slot) {
  24947.             return f(slot, key);
  24948.           }).getOr(def);
  24949.         };
  24950.       };
  24951.       var onSlots = function (f) {
  24952.         return function (container, keys) {
  24953.           each$1(keys, function (key) {
  24954.             return f(container, key);
  24955.           });
  24956.         };
  24957.       };
  24958.       var doShowing = function (comp, _key) {
  24959.         return get$d(comp.element, 'aria-hidden') !== 'true';
  24960.       };
  24961.       var doShow = function (comp, key) {
  24962.         if (!doShowing(comp)) {
  24963.           var element = comp.element;
  24964.           remove$6(element, 'display');
  24965.           remove$7(element, 'aria-hidden');
  24966.           emitWith(comp, slotVisibility(), {
  24967.             name: key,
  24968.             visible: true
  24969.           });
  24970.         }
  24971.       };
  24972.       var doHide = function (comp, key) {
  24973.         if (doShowing(comp)) {
  24974.           var element = comp.element;
  24975.           set$7(element, 'display', 'none');
  24976.           set$8(element, 'aria-hidden', 'true');
  24977.           emitWith(comp, slotVisibility(), {
  24978.             name: key,
  24979.             visible: false
  24980.           });
  24981.         }
  24982.       };
  24983.       var isShowing = onSlot(doShowing, false);
  24984.       var hideSlot = onSlot(doHide);
  24985.       var hideSlots = onSlots(hideSlot);
  24986.       var hideAllSlots = function (container) {
  24987.         return hideSlots(container, getSlotNames());
  24988.       };
  24989.       var showSlot = onSlot(doShow);
  24990.       var apis = {
  24991.         getSlotNames: getSlotNames,
  24992.         getSlot: getSlot,
  24993.         isShowing: isShowing,
  24994.         hideSlot: hideSlot,
  24995.         hideAllSlots: hideAllSlots,
  24996.         showSlot: showSlot
  24997.       };
  24998.       return {
  24999.         uid: detail.uid,
  25000.         dom: detail.dom,
  25001.         components: components,
  25002.         behaviours: get$2(detail.slotBehaviours),
  25003.         apis: apis
  25004.       };
  25005.     };
  25006.     var slotApis = map$1({
  25007.       getSlotNames: function (apis, c) {
  25008.         return apis.getSlotNames(c);
  25009.       },
  25010.       getSlot: function (apis, c, key) {
  25011.         return apis.getSlot(c, key);
  25012.       },
  25013.       isShowing: function (apis, c, key) {
  25014.         return apis.isShowing(c, key);
  25015.       },
  25016.       hideSlot: function (apis, c, key) {
  25017.         return apis.hideSlot(c, key);
  25018.       },
  25019.       hideAllSlots: function (apis, c) {
  25020.         return apis.hideAllSlots(c);
  25021.       },
  25022.       showSlot: function (apis, c, key) {
  25023.         return apis.showSlot(c, key);
  25024.       }
  25025.     }, function (value) {
  25026.       return makeApi(value);
  25027.     });
  25028.     var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch });
  25029.  
  25030.     var sidebarSchema = objOf([
  25031.       optionString('icon'),
  25032.       optionString('tooltip'),
  25033.       defaultedFunction('onShow', noop),
  25034.       defaultedFunction('onHide', noop),
  25035.       defaultedFunction('onSetup', function () {
  25036.         return noop;
  25037.       })
  25038.     ]);
  25039.     var createSidebar = function (spec) {
  25040.       return asRaw('sidebar', sidebarSchema, spec);
  25041.     };
  25042.  
  25043.     var setup$8 = function (editor) {
  25044.       var sidebars = editor.ui.registry.getAll().sidebars;
  25045.       each$1(keys(sidebars), function (name) {
  25046.         var spec = sidebars[name];
  25047.         var isActive = function () {
  25048.           return is$1(Optional.from(editor.queryCommandValue('ToggleSidebar')), name);
  25049.         };
  25050.         editor.ui.registry.addToggleButton(name, {
  25051.           icon: spec.icon,
  25052.           tooltip: spec.tooltip,
  25053.           onAction: function (buttonApi) {
  25054.             editor.execCommand('ToggleSidebar', false, name);
  25055.             buttonApi.setActive(isActive());
  25056.           },
  25057.           onSetup: function (buttonApi) {
  25058.             var handleToggle = function () {
  25059.               return buttonApi.setActive(isActive());
  25060.             };
  25061.             editor.on('ToggleSidebar', handleToggle);
  25062.             return function () {
  25063.               editor.off('ToggleSidebar', handleToggle);
  25064.             };
  25065.           }
  25066.         });
  25067.       });
  25068.     };
  25069.     var getApi = function (comp) {
  25070.       return {
  25071.         element: function () {
  25072.           return comp.element.dom;
  25073.         }
  25074.       };
  25075.     };
  25076.     var makePanels = function (parts, panelConfigs) {
  25077.       var specs = map$2(keys(panelConfigs), function (name) {
  25078.         var spec = panelConfigs[name];
  25079.         var bridged = getOrDie(createSidebar(spec));
  25080.         return {
  25081.           name: name,
  25082.           getApi: getApi,
  25083.           onSetup: bridged.onSetup,
  25084.           onShow: bridged.onShow,
  25085.           onHide: bridged.onHide
  25086.         };
  25087.       });
  25088.       return map$2(specs, function (spec) {
  25089.         var editorOffCell = Cell(noop);
  25090.         return parts.slot(spec.name, {
  25091.           dom: {
  25092.             tag: 'div',
  25093.             classes: ['tox-sidebar__pane']
  25094.           },
  25095.           behaviours: SimpleBehaviours.unnamedEvents([
  25096.             onControlAttached(spec, editorOffCell),
  25097.             onControlDetached(spec, editorOffCell),
  25098.             run$1(slotVisibility(), function (sidepanel, se) {
  25099.               var data = se.event;
  25100.               var optSidePanelSpec = find$5(specs, function (config) {
  25101.                 return config.name === data.name;
  25102.               });
  25103.               optSidePanelSpec.each(function (sidePanelSpec) {
  25104.                 var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  25105.                 handler(sidePanelSpec.getApi(sidepanel));
  25106.               });
  25107.             })
  25108.           ])
  25109.         });
  25110.       });
  25111.     };
  25112.     var makeSidebar = function (panelConfigs) {
  25113.       return SlotContainer.sketch(function (parts) {
  25114.         return {
  25115.           dom: {
  25116.             tag: 'div',
  25117.             classes: ['tox-sidebar__pane-container']
  25118.           },
  25119.           components: makePanels(parts, panelConfigs),
  25120.           slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  25121.               return SlotContainer.hideAllSlots(slotContainer);
  25122.             })])
  25123.         };
  25124.       });
  25125.     };
  25126.     var setSidebar = function (sidebar, panelConfigs) {
  25127.       var optSlider = Composing.getCurrent(sidebar);
  25128.       optSlider.each(function (slider) {
  25129.         return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  25130.       });
  25131.     };
  25132.     var toggleSidebar = function (sidebar, name) {
  25133.       var optSlider = Composing.getCurrent(sidebar);
  25134.       optSlider.each(function (slider) {
  25135.         var optSlotContainer = Composing.getCurrent(slider);
  25136.         optSlotContainer.each(function (slotContainer) {
  25137.           if (Sliding.hasGrown(slider)) {
  25138.             if (SlotContainer.isShowing(slotContainer, name)) {
  25139.               Sliding.shrink(slider);
  25140.             } else {
  25141.               SlotContainer.hideAllSlots(slotContainer);
  25142.               SlotContainer.showSlot(slotContainer, name);
  25143.             }
  25144.           } else {
  25145.             SlotContainer.hideAllSlots(slotContainer);
  25146.             SlotContainer.showSlot(slotContainer, name);
  25147.             Sliding.grow(slider);
  25148.           }
  25149.         });
  25150.       });
  25151.     };
  25152.     var whichSidebar = function (sidebar) {
  25153.       var optSlider = Composing.getCurrent(sidebar);
  25154.       return optSlider.bind(function (slider) {
  25155.         var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  25156.         if (sidebarOpen) {
  25157.           var optSlotContainer = Composing.getCurrent(slider);
  25158.           return optSlotContainer.bind(function (slotContainer) {
  25159.             return find$5(SlotContainer.getSlotNames(slotContainer), function (name) {
  25160.               return SlotContainer.isShowing(slotContainer, name);
  25161.             });
  25162.           });
  25163.         } else {
  25164.           return Optional.none();
  25165.         }
  25166.       });
  25167.     };
  25168.     var fixSize = generate$6('FixSizeEvent');
  25169.     var autoSize = generate$6('AutoSizeEvent');
  25170.     var renderSidebar = function (spec) {
  25171.       return {
  25172.         uid: spec.uid,
  25173.         dom: {
  25174.           tag: 'div',
  25175.           classes: ['tox-sidebar'],
  25176.           attributes: { role: 'complementary' }
  25177.         },
  25178.         components: [{
  25179.             dom: {
  25180.               tag: 'div',
  25181.               classes: ['tox-sidebar__slider']
  25182.             },
  25183.             components: [],
  25184.             behaviours: derive$1([
  25185.               Tabstopping.config({}),
  25186.               Focusing.config({}),
  25187.               Sliding.config({
  25188.                 dimension: { property: 'width' },
  25189.                 closedClass: 'tox-sidebar--sliding-closed',
  25190.                 openClass: 'tox-sidebar--sliding-open',
  25191.                 shrinkingClass: 'tox-sidebar--sliding-shrinking',
  25192.                 growingClass: 'tox-sidebar--sliding-growing',
  25193.                 onShrunk: function (slider) {
  25194.                   var optSlotContainer = Composing.getCurrent(slider);
  25195.                   optSlotContainer.each(SlotContainer.hideAllSlots);
  25196.                   emit(slider, autoSize);
  25197.                 },
  25198.                 onGrown: function (slider) {
  25199.                   emit(slider, autoSize);
  25200.                 },
  25201.                 onStartGrow: function (slider) {
  25202.                   emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
  25203.                 },
  25204.                 onStartShrink: function (slider) {
  25205.                   emitWith(slider, fixSize, { width: get$a(slider.element) + 'px' });
  25206.                 }
  25207.               }),
  25208.               Replacing.config({}),
  25209.               Composing.config({
  25210.                 find: function (comp) {
  25211.                   var children = Replacing.contents(comp);
  25212.                   return head(children);
  25213.                 }
  25214.               })
  25215.             ])
  25216.           }],
  25217.         behaviours: derive$1([
  25218.           ComposingConfigs.childAt(0),
  25219.           config('sidebar-sliding-events', [
  25220.             run$1(fixSize, function (comp, se) {
  25221.               set$7(comp.element, 'width', se.event.width);
  25222.             }),
  25223.             run$1(autoSize, function (comp, _se) {
  25224.               remove$6(comp.element, 'width');
  25225.             })
  25226.           ])
  25227.         ])
  25228.       };
  25229.     };
  25230.  
  25231.     var block = function (component, config, state, getBusySpec) {
  25232.       set$8(component.element, 'aria-busy', true);
  25233.       var root = config.getRoot(component).getOr(component);
  25234.       var blockerBehaviours = derive$1([
  25235.         Keying.config({
  25236.           mode: 'special',
  25237.           onTab: function () {
  25238.             return Optional.some(true);
  25239.           },
  25240.           onShiftTab: function () {
  25241.             return Optional.some(true);
  25242.           }
  25243.         }),
  25244.         Focusing.config({})
  25245.       ]);
  25246.       var blockSpec = getBusySpec(root, blockerBehaviours);
  25247.       var blocker = root.getSystem().build(blockSpec);
  25248.       Replacing.append(root, premade(blocker));
  25249.       if (blocker.hasConfigured(Keying) && config.focus) {
  25250.         Keying.focusIn(blocker);
  25251.       }
  25252.       if (!state.isBlocked()) {
  25253.         config.onBlock(component);
  25254.       }
  25255.       state.blockWith(function () {
  25256.         return Replacing.remove(root, blocker);
  25257.       });
  25258.     };
  25259.     var unblock = function (component, config, state) {
  25260.       remove$7(component.element, 'aria-busy');
  25261.       if (state.isBlocked()) {
  25262.         config.onUnblock(component);
  25263.       }
  25264.       state.clear();
  25265.     };
  25266.  
  25267.     var BlockingApis = /*#__PURE__*/Object.freeze({
  25268.         __proto__: null,
  25269.         block: block,
  25270.         unblock: unblock
  25271.     });
  25272.  
  25273.     var BlockingSchema = [
  25274.       defaultedFunction('getRoot', Optional.none),
  25275.       defaultedBoolean('focus', true),
  25276.       onHandler('onBlock'),
  25277.       onHandler('onUnblock')
  25278.     ];
  25279.  
  25280.     var init$4 = function () {
  25281.       var blocker = destroyable();
  25282.       var blockWith = function (destroy) {
  25283.         blocker.set({ destroy: destroy });
  25284.       };
  25285.       return nu$8({
  25286.         readState: blocker.isSet,
  25287.         blockWith: blockWith,
  25288.         clear: blocker.clear,
  25289.         isBlocked: blocker.isSet
  25290.       });
  25291.     };
  25292.  
  25293.     var BlockingState = /*#__PURE__*/Object.freeze({
  25294.         __proto__: null,
  25295.         init: init$4
  25296.     });
  25297.  
  25298.     var Blocking = create$8({
  25299.       fields: BlockingSchema,
  25300.       name: 'blocking',
  25301.       apis: BlockingApis,
  25302.       state: BlockingState
  25303.     });
  25304.  
  25305.     var getBusySpec$1 = function (providerBackstage) {
  25306.       return function (_root, _behaviours) {
  25307.         return {
  25308.           dom: {
  25309.             tag: 'div',
  25310.             attributes: {
  25311.               'aria-label': providerBackstage.translate('Loading...'),
  25312.               'tabindex': '0'
  25313.             },
  25314.             classes: ['tox-throbber__busy-spinner']
  25315.           },
  25316.           components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  25317.         };
  25318.       };
  25319.     };
  25320.     var focusBusyComponent = function (throbber) {
  25321.       return Composing.getCurrent(throbber).each(function (comp) {
  25322.         return focus$3(comp.element);
  25323.       });
  25324.     };
  25325.     var toggleEditorTabIndex = function (editor, state) {
  25326.       var tabIndexAttr = 'tabindex';
  25327.       var dataTabIndexAttr = 'data-mce-' + tabIndexAttr;
  25328.       Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function (iframe) {
  25329.         if (state) {
  25330.           getOpt(iframe, tabIndexAttr).each(function (tabIndex) {
  25331.             return set$8(iframe, dataTabIndexAttr, tabIndex);
  25332.           });
  25333.           set$8(iframe, tabIndexAttr, -1);
  25334.         } else {
  25335.           remove$7(iframe, tabIndexAttr);
  25336.           getOpt(iframe, dataTabIndexAttr).each(function (tabIndex) {
  25337.             set$8(iframe, tabIndexAttr, tabIndex);
  25338.             remove$7(iframe, dataTabIndexAttr);
  25339.           });
  25340.         }
  25341.       });
  25342.     };
  25343.     var toggleThrobber = function (editor, comp, state, providerBackstage) {
  25344.       var element = comp.element;
  25345.       toggleEditorTabIndex(editor, state);
  25346.       if (state) {
  25347.         Blocking.block(comp, getBusySpec$1(providerBackstage));
  25348.         remove$6(element, 'display');
  25349.         remove$7(element, 'aria-hidden');
  25350.         if (editor.hasFocus()) {
  25351.           focusBusyComponent(comp);
  25352.         }
  25353.       } else {
  25354.         var throbberFocus = Composing.getCurrent(comp).exists(function (busyComp) {
  25355.           return hasFocus(busyComp.element);
  25356.         });
  25357.         Blocking.unblock(comp);
  25358.         set$7(element, 'display', 'none');
  25359.         set$8(element, 'aria-hidden', 'true');
  25360.         if (throbberFocus) {
  25361.           editor.focus();
  25362.         }
  25363.       }
  25364.     };
  25365.     var renderThrobber = function (spec) {
  25366.       return {
  25367.         uid: spec.uid,
  25368.         dom: {
  25369.           tag: 'div',
  25370.           attributes: { 'aria-hidden': 'true' },
  25371.           classes: ['tox-throbber'],
  25372.           styles: { display: 'none' }
  25373.         },
  25374.         behaviours: derive$1([
  25375.           Replacing.config({}),
  25376.           Blocking.config({ focus: false }),
  25377.           Composing.config({
  25378.             find: function (comp) {
  25379.               return head(comp.components());
  25380.             }
  25381.           })
  25382.         ]),
  25383.         components: []
  25384.       };
  25385.     };
  25386.     var isFocusEvent = function (event) {
  25387.       return event.type === 'focusin';
  25388.     };
  25389.     var isPasteBinTarget = function (event) {
  25390.       if (isFocusEvent(event)) {
  25391.         var node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
  25392.         return node.map(SugarElement.fromDom).filter(isElement$2).exists(function (targetElm) {
  25393.           return has(targetElm, 'mce-pastebin');
  25394.         });
  25395.       } else {
  25396.         return false;
  25397.       }
  25398.     };
  25399.     var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  25400.       var throbberState = Cell(false);
  25401.       var timer = value$1();
  25402.       var stealFocus = function (e) {
  25403.         if (throbberState.get() && !isPasteBinTarget(e)) {
  25404.           e.preventDefault();
  25405.           focusBusyComponent(lazyThrobber());
  25406.           editor.editorManager.setActive(editor);
  25407.         }
  25408.       };
  25409.       if (!editor.inline) {
  25410.         editor.on('PreInit', function () {
  25411.           editor.dom.bind(editor.getWin(), 'focusin', stealFocus);
  25412.           editor.on('BeforeExecCommand', function (e) {
  25413.             if (e.command.toLowerCase() === 'mcefocus' && e.value !== true) {
  25414.               stealFocus(e);
  25415.             }
  25416.           });
  25417.         });
  25418.       }
  25419.       var toggle = function (state) {
  25420.         if (state !== throbberState.get()) {
  25421.           throbberState.set(state);
  25422.           toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
  25423.           editor.fire('AfterProgressState', { state: state });
  25424.         }
  25425.       };
  25426.       editor.on('ProgressState', function (e) {
  25427.         timer.on(global$f.clearTimeout);
  25428.         if (isNumber(e.time)) {
  25429.           var timerId = global$f.setEditorTimeout(editor, function () {
  25430.             return toggle(e.state);
  25431.           }, e.time);
  25432.           timer.set(timerId);
  25433.         } else {
  25434.           toggle(e.state);
  25435.           timer.clear();
  25436.         }
  25437.       });
  25438.     };
  25439.  
  25440.     var generate$1 = function (xs, f) {
  25441.       var init = {
  25442.         len: 0,
  25443.         list: []
  25444.       };
  25445.       var r = foldl(xs, function (b, a) {
  25446.         var value = f(a, b.len);
  25447.         return value.fold(constant$1(b), function (v) {
  25448.           return {
  25449.             len: v.finish,
  25450.             list: b.list.concat([v])
  25451.           };
  25452.         });
  25453.       }, init);
  25454.       return r.list;
  25455.     };
  25456.  
  25457.     var output = function (within, extra, withinWidth) {
  25458.       return {
  25459.         within: within,
  25460.         extra: extra,
  25461.         withinWidth: withinWidth
  25462.       };
  25463.     };
  25464.     var apportion = function (units, total, len) {
  25465.       var parray = generate$1(units, function (unit, current) {
  25466.         var width = len(unit);
  25467.         return Optional.some({
  25468.           element: unit,
  25469.           start: current,
  25470.           finish: current + width,
  25471.           width: width
  25472.         });
  25473.       });
  25474.       var within = filter$2(parray, function (unit) {
  25475.         return unit.finish <= total;
  25476.       });
  25477.       var withinWidth = foldr(within, function (acc, el) {
  25478.         return acc + el.width;
  25479.       }, 0);
  25480.       var extra = parray.slice(within.length);
  25481.       return {
  25482.         within: within,
  25483.         extra: extra,
  25484.         withinWidth: withinWidth
  25485.       };
  25486.     };
  25487.     var toUnit = function (parray) {
  25488.       return map$2(parray, function (unit) {
  25489.         return unit.element;
  25490.       });
  25491.     };
  25492.     var fitLast = function (within, extra, withinWidth) {
  25493.       var fits = toUnit(within.concat(extra));
  25494.       return output(fits, [], withinWidth);
  25495.     };
  25496.     var overflow = function (within, extra, overflower, withinWidth) {
  25497.       var fits = toUnit(within).concat([overflower]);
  25498.       return output(fits, toUnit(extra), withinWidth);
  25499.     };
  25500.     var fitAll = function (within, extra, withinWidth) {
  25501.       return output(toUnit(within), [], withinWidth);
  25502.     };
  25503.     var tryFit = function (total, units, len) {
  25504.       var divide = apportion(units, total, len);
  25505.       return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
  25506.     };
  25507.     var partition = function (total, units, len, overflower) {
  25508.       var divide = tryFit(total, units, len).getOrThunk(function () {
  25509.         return apportion(units, total - len(overflower), len);
  25510.       });
  25511.       var within = divide.within;
  25512.       var extra = divide.extra;
  25513.       var withinWidth = divide.withinWidth;
  25514.       if (extra.length === 1 && extra[0].width <= len(overflower)) {
  25515.         return fitLast(within, extra, withinWidth);
  25516.       } else if (extra.length >= 1) {
  25517.         return overflow(within, extra, overflower, withinWidth);
  25518.       } else {
  25519.         return fitAll(within, extra, withinWidth);
  25520.       }
  25521.     };
  25522.  
  25523.     var setGroups$1 = function (toolbar, storedGroups) {
  25524.       var bGroups = map$2(storedGroups, function (g) {
  25525.         return premade(g);
  25526.       });
  25527.       Toolbar.setGroups(toolbar, bGroups);
  25528.     };
  25529.     var findFocusedComp = function (comps) {
  25530.       return findMap(comps, function (comp) {
  25531.         return search(comp.element).bind(function (focusedElm) {
  25532.           return comp.getSystem().getByDom(focusedElm).toOptional();
  25533.         });
  25534.       });
  25535.     };
  25536.     var refresh$2 = function (toolbar, detail, setOverflow) {
  25537.       var builtGroups = detail.builtGroups.get();
  25538.       if (builtGroups.length === 0) {
  25539.         return;
  25540.       }
  25541.       var primary = getPartOrDie(toolbar, detail, 'primary');
  25542.       var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  25543.       set$7(primary.element, 'visibility', 'hidden');
  25544.       var groups = builtGroups.concat([overflowGroup]);
  25545.       var focusedComp = findFocusedComp(groups);
  25546.       setOverflow([]);
  25547.       setGroups$1(primary, groups);
  25548.       var availableWidth = get$a(primary.element);
  25549.       var overflows = partition(availableWidth, detail.builtGroups.get(), function (comp) {
  25550.         return get$a(comp.element);
  25551.       }, overflowGroup);
  25552.       if (overflows.extra.length === 0) {
  25553.         Replacing.remove(primary, overflowGroup);
  25554.         setOverflow([]);
  25555.       } else {
  25556.         setGroups$1(primary, overflows.within);
  25557.         setOverflow(overflows.extra);
  25558.       }
  25559.       remove$6(primary.element, 'visibility');
  25560.       reflow(primary.element);
  25561.       focusedComp.each(Focusing.focus);
  25562.     };
  25563.  
  25564.     var schema$c = constant$1([
  25565.       field('splitToolbarBehaviours', [Coupling]),
  25566.       customField('builtGroups', function () {
  25567.         return Cell([]);
  25568.       })
  25569.     ]);
  25570.  
  25571.     var schema$b = constant$1([
  25572.       markers$1(['overflowToggledClass']),
  25573.       optionFunction('getOverflowBounds'),
  25574.       required$1('lazySink'),
  25575.       customField('overflowGroups', function () {
  25576.         return Cell([]);
  25577.       })
  25578.     ].concat(schema$c()));
  25579.     var parts$7 = constant$1([
  25580.       required({
  25581.         factory: Toolbar,
  25582.         schema: schema$e(),
  25583.         name: 'primary'
  25584.       }),
  25585.       external$1({
  25586.         schema: schema$e(),
  25587.         name: 'overflow'
  25588.       }),
  25589.       external$1({ name: 'overflow-button' }),
  25590.       external$1({ name: 'overflow-group' })
  25591.     ]);
  25592.  
  25593.     var expandable = constant$1(function (element, available) {
  25594.       setMax(element, Math.floor(available));
  25595.     });
  25596.  
  25597.     var schema$a = constant$1([
  25598.       markers$1(['toggledClass']),
  25599.       required$1('lazySink'),
  25600.       requiredFunction('fetch'),
  25601.       optionFunction('getBounds'),
  25602.       optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  25603.       schema$y()
  25604.     ]);
  25605.     var parts$6 = constant$1([
  25606.       external$1({
  25607.         name: 'button',
  25608.         overrides: function (detail) {
  25609.           return {
  25610.             dom: { attributes: { 'aria-haspopup': 'true' } },
  25611.             buttonBehaviours: derive$1([Toggling.config({
  25612.                 toggleClass: detail.markers.toggledClass,
  25613.                 aria: { mode: 'expanded' },
  25614.                 toggleOnExecute: false
  25615.               })])
  25616.           };
  25617.         }
  25618.       }),
  25619.       external$1({
  25620.         factory: Toolbar,
  25621.         schema: schema$e(),
  25622.         name: 'toolbar',
  25623.         overrides: function (detail) {
  25624.           return {
  25625.             toolbarBehaviours: derive$1([Keying.config({
  25626.                 mode: 'cyclic',
  25627.                 onEscape: function (comp) {
  25628.                   getPart(comp, detail, 'button').each(Focusing.focus);
  25629.                   return Optional.none();
  25630.                 }
  25631.               })])
  25632.           };
  25633.         }
  25634.       })
  25635.     ]);
  25636.  
  25637.     var toggle = function (button, externals) {
  25638.       var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  25639.       if (Sandboxing.isOpen(toolbarSandbox)) {
  25640.         Sandboxing.close(toolbarSandbox);
  25641.       } else {
  25642.         Sandboxing.open(toolbarSandbox, externals.toolbar());
  25643.       }
  25644.     };
  25645.     var position = function (button, toolbar, detail, layouts) {
  25646.       var bounds = detail.getBounds.map(function (bounder) {
  25647.         return bounder();
  25648.       });
  25649.       var sink = detail.lazySink(button).getOrDie();
  25650.       Positioning.positionWithinBounds(sink, toolbar, {
  25651.         anchor: {
  25652.           type: 'hotspot',
  25653.           hotspot: button,
  25654.           layouts: layouts,
  25655.           overrides: { maxWidthFunction: expandable() }
  25656.         }
  25657.       }, bounds);
  25658.     };
  25659.     var setGroups = function (button, toolbar, detail, layouts, groups) {
  25660.       Toolbar.setGroups(toolbar, groups);
  25661.       position(button, toolbar, detail, layouts);
  25662.       Toggling.on(button);
  25663.     };
  25664.     var makeSandbox = function (button, spec, detail) {
  25665.       var ariaOwner = manager();
  25666.       var onOpen = function (sandbox, toolbar) {
  25667.         detail.fetch().get(function (groups) {
  25668.           setGroups(button, toolbar, detail, spec.layouts, groups);
  25669.           ariaOwner.link(button.element);
  25670.           Keying.focusIn(toolbar);
  25671.         });
  25672.       };
  25673.       var onClose = function () {
  25674.         Toggling.off(button);
  25675.         Focusing.focus(button);
  25676.         ariaOwner.unlink(button.element);
  25677.       };
  25678.       return {
  25679.         dom: {
  25680.           tag: 'div',
  25681.           attributes: { id: ariaOwner.id }
  25682.         },
  25683.         behaviours: derive$1([
  25684.           Keying.config({
  25685.             mode: 'special',
  25686.             onEscape: function (comp) {
  25687.               Sandboxing.close(comp);
  25688.               return Optional.some(true);
  25689.             }
  25690.           }),
  25691.           Sandboxing.config({
  25692.             onOpen: onOpen,
  25693.             onClose: onClose,
  25694.             isPartOf: function (container, data, queryElem) {
  25695.               return isPartOf$1(data, queryElem) || isPartOf$1(button, queryElem);
  25696.             },
  25697.             getAttachPoint: function () {
  25698.               return detail.lazySink(button).getOrDie();
  25699.             }
  25700.           }),
  25701.           Receiving.config({
  25702.             channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
  25703.               return { fireEventInstead: { event: fe.event } };
  25704.             }).getOr({})))), receivingChannel({
  25705.               doReposition: function () {
  25706.                 Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  25707.                   position(button, toolbar, detail, spec.layouts);
  25708.                 });
  25709.               }
  25710.             }))
  25711.           })
  25712.         ])
  25713.       };
  25714.     };
  25715.     var factory$a = function (detail, components, spec, externals) {
  25716.       return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  25717.         action: function (button) {
  25718.           toggle(button, externals);
  25719.         },
  25720.         buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  25721.             others: {
  25722.               toolbarSandbox: function (button) {
  25723.                 return makeSandbox(button, spec, detail);
  25724.               }
  25725.             }
  25726.           })])
  25727.       }))), {
  25728.         apis: {
  25729.           setGroups: function (button, groups) {
  25730.             Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  25731.               setGroups(button, toolbar, detail, spec.layouts, groups);
  25732.             });
  25733.           },
  25734.           reposition: function (button) {
  25735.             Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  25736.               position(button, toolbar, detail, spec.layouts);
  25737.             });
  25738.           },
  25739.           toggle: function (button) {
  25740.             toggle(button, externals);
  25741.           },
  25742.           getToolbar: function (button) {
  25743.             return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  25744.           },
  25745.           isOpen: function (button) {
  25746.             return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
  25747.           }
  25748.         }
  25749.       });
  25750.     };
  25751.     var FloatingToolbarButton = composite({
  25752.       name: 'FloatingToolbarButton',
  25753.       factory: factory$a,
  25754.       configFields: schema$a(),
  25755.       partFields: parts$6(),
  25756.       apis: {
  25757.         setGroups: function (apis, button, groups) {
  25758.           apis.setGroups(button, groups);
  25759.         },
  25760.         reposition: function (apis, button) {
  25761.           apis.reposition(button);
  25762.         },
  25763.         toggle: function (apis, button) {
  25764.           apis.toggle(button);
  25765.         },
  25766.         getToolbar: function (apis, button) {
  25767.           return apis.getToolbar(button);
  25768.         },
  25769.         isOpen: function (apis, button) {
  25770.           return apis.isOpen(button);
  25771.         }
  25772.       }
  25773.     });
  25774.  
  25775.     var schema$9 = constant$1([
  25776.       required$1('items'),
  25777.       markers$1(['itemSelector']),
  25778.       field('tgroupBehaviours', [Keying])
  25779.     ]);
  25780.     var parts$5 = constant$1([group({
  25781.         name: 'items',
  25782.         unit: 'item'
  25783.       })]);
  25784.  
  25785.     var factory$9 = function (detail, components, _spec, _externals) {
  25786.       return {
  25787.         uid: detail.uid,
  25788.         dom: detail.dom,
  25789.         components: components,
  25790.         behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  25791.             mode: 'flow',
  25792.             selector: detail.markers.itemSelector
  25793.           })]),
  25794.         domModification: { attributes: { role: 'toolbar' } }
  25795.       };
  25796.     };
  25797.     var ToolbarGroup = composite({
  25798.       name: 'ToolbarGroup',
  25799.       configFields: schema$9(),
  25800.       partFields: parts$5(),
  25801.       factory: factory$9
  25802.     });
  25803.  
  25804.     var buildGroups = function (comps) {
  25805.       return map$2(comps, function (g) {
  25806.         return premade(g);
  25807.       });
  25808.     };
  25809.     var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  25810.       refresh$2(toolbar, detail, function (overflowGroups) {
  25811.         detail.overflowGroups.set(overflowGroups);
  25812.         memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  25813.           FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  25814.         });
  25815.       });
  25816.     };
  25817.     var factory$8 = function (detail, components, spec, externals) {
  25818.       var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  25819.         fetch: function () {
  25820.           return Future.nu(function (resolve) {
  25821.             resolve(buildGroups(detail.overflowGroups.get()));
  25822.           });
  25823.         },
  25824.         layouts: {
  25825.           onLtr: function () {
  25826.             return [
  25827.               southwest$2,
  25828.               southeast$2
  25829.             ];
  25830.           },
  25831.           onRtl: function () {
  25832.             return [
  25833.               southeast$2,
  25834.               southwest$2
  25835.             ];
  25836.           },
  25837.           onBottomLtr: function () {
  25838.             return [
  25839.               northwest$2,
  25840.               northeast$2
  25841.             ];
  25842.           },
  25843.           onBottomRtl: function () {
  25844.             return [
  25845.               northeast$2,
  25846.               northwest$2
  25847.             ];
  25848.           }
  25849.         },
  25850.         getBounds: spec.getOverflowBounds,
  25851.         lazySink: detail.lazySink,
  25852.         fireDismissalEventInstead: {},
  25853.         markers: { toggledClass: detail.markers.overflowToggledClass },
  25854.         parts: {
  25855.           button: externals['overflow-button'](),
  25856.           toolbar: externals.overflow()
  25857.         }
  25858.       }));
  25859.       return {
  25860.         uid: detail.uid,
  25861.         dom: detail.dom,
  25862.         components: components,
  25863.         behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  25864.             others: {
  25865.               overflowGroup: function () {
  25866.                 return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  25867.               }
  25868.             }
  25869.           })]),
  25870.         apis: {
  25871.           setGroups: function (toolbar, groups) {
  25872.             detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
  25873.             refresh$1(toolbar, memFloatingToolbarButton, detail);
  25874.           },
  25875.           refresh: function (toolbar) {
  25876.             return refresh$1(toolbar, memFloatingToolbarButton, detail);
  25877.           },
  25878.           toggle: function (toolbar) {
  25879.             memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  25880.               FloatingToolbarButton.toggle(floatingToolbarButton);
  25881.             });
  25882.           },
  25883.           isOpen: function (toolbar) {
  25884.             return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
  25885.           },
  25886.           reposition: function (toolbar) {
  25887.             memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  25888.               FloatingToolbarButton.reposition(floatingToolbarButton);
  25889.             });
  25890.           },
  25891.           getOverflow: function (toolbar) {
  25892.             return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
  25893.           }
  25894.         },
  25895.         domModification: { attributes: { role: 'group' } }
  25896.       };
  25897.     };
  25898.     var SplitFloatingToolbar = composite({
  25899.       name: 'SplitFloatingToolbar',
  25900.       configFields: schema$b(),
  25901.       partFields: parts$7(),
  25902.       factory: factory$8,
  25903.       apis: {
  25904.         setGroups: function (apis, toolbar, groups) {
  25905.           apis.setGroups(toolbar, groups);
  25906.         },
  25907.         refresh: function (apis, toolbar) {
  25908.           apis.refresh(toolbar);
  25909.         },
  25910.         reposition: function (apis, toolbar) {
  25911.           apis.reposition(toolbar);
  25912.         },
  25913.         toggle: function (apis, toolbar) {
  25914.           apis.toggle(toolbar);
  25915.         },
  25916.         isOpen: function (apis, toolbar) {
  25917.           return apis.isOpen(toolbar);
  25918.         },
  25919.         getOverflow: function (apis, toolbar) {
  25920.           return apis.getOverflow(toolbar);
  25921.         }
  25922.       }
  25923.     });
  25924.  
  25925.     var schema$8 = constant$1([
  25926.       markers$1([
  25927.         'closedClass',
  25928.         'openClass',
  25929.         'shrinkingClass',
  25930.         'growingClass',
  25931.         'overflowToggledClass'
  25932.       ]),
  25933.       onHandler('onOpened'),
  25934.       onHandler('onClosed')
  25935.     ].concat(schema$c()));
  25936.     var parts$4 = constant$1([
  25937.       required({
  25938.         factory: Toolbar,
  25939.         schema: schema$e(),
  25940.         name: 'primary'
  25941.       }),
  25942.       required({
  25943.         factory: Toolbar,
  25944.         schema: schema$e(),
  25945.         name: 'overflow',
  25946.         overrides: function (detail) {
  25947.           return {
  25948.             toolbarBehaviours: derive$1([
  25949.               Sliding.config({
  25950.                 dimension: { property: 'height' },
  25951.                 closedClass: detail.markers.closedClass,
  25952.                 openClass: detail.markers.openClass,
  25953.                 shrinkingClass: detail.markers.shrinkingClass,
  25954.                 growingClass: detail.markers.growingClass,
  25955.                 onShrunk: function (comp) {
  25956.                   getPart(comp, detail, 'overflow-button').each(function (button) {
  25957.                     Toggling.off(button);
  25958.                     Focusing.focus(button);
  25959.                   });
  25960.                   detail.onClosed(comp);
  25961.                 },
  25962.                 onGrown: function (comp) {
  25963.                   Keying.focusIn(comp);
  25964.                   detail.onOpened(comp);
  25965.                 },
  25966.                 onStartGrow: function (comp) {
  25967.                   getPart(comp, detail, 'overflow-button').each(Toggling.on);
  25968.                 }
  25969.               }),
  25970.               Keying.config({
  25971.                 mode: 'acyclic',
  25972.                 onEscape: function (comp) {
  25973.                   getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  25974.                   return Optional.some(true);
  25975.                 }
  25976.               })
  25977.             ])
  25978.           };
  25979.         }
  25980.       }),
  25981.       external$1({
  25982.         name: 'overflow-button',
  25983.         overrides: function (detail) {
  25984.           return {
  25985.             buttonBehaviours: derive$1([Toggling.config({
  25986.                 toggleClass: detail.markers.overflowToggledClass,
  25987.                 aria: { mode: 'pressed' },
  25988.                 toggleOnExecute: false
  25989.               })])
  25990.           };
  25991.         }
  25992.       }),
  25993.       external$1({ name: 'overflow-group' })
  25994.     ]);
  25995.  
  25996.     var isOpen = function (toolbar, detail) {
  25997.       return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
  25998.     };
  25999.     var toggleToolbar = function (toolbar, detail) {
  26000.       getPart(toolbar, detail, 'overflow-button').bind(function () {
  26001.         return getPart(toolbar, detail, 'overflow');
  26002.       }).each(function (overf) {
  26003.         refresh(toolbar, detail);
  26004.         Sliding.toggleGrow(overf);
  26005.       });
  26006.     };
  26007.     var refresh = function (toolbar, detail) {
  26008.       getPart(toolbar, detail, 'overflow').each(function (overflow) {
  26009.         refresh$2(toolbar, detail, function (groups) {
  26010.           var builtGroups = map$2(groups, function (g) {
  26011.             return premade(g);
  26012.           });
  26013.           Toolbar.setGroups(overflow, builtGroups);
  26014.         });
  26015.         getPart(toolbar, detail, 'overflow-button').each(function (button) {
  26016.           if (Sliding.hasGrown(overflow)) {
  26017.             Toggling.on(button);
  26018.           }
  26019.         });
  26020.         Sliding.refresh(overflow);
  26021.       });
  26022.     };
  26023.     var factory$7 = function (detail, components, spec, externals) {
  26024.       var toolbarToggleEvent = 'alloy.toolbar.toggle';
  26025.       var doSetGroups = function (toolbar, groups) {
  26026.         var built = map$2(groups, toolbar.getSystem().build);
  26027.         detail.builtGroups.set(built);
  26028.       };
  26029.       return {
  26030.         uid: detail.uid,
  26031.         dom: detail.dom,
  26032.         components: components,
  26033.         behaviours: augment(detail.splitToolbarBehaviours, [
  26034.           Coupling.config({
  26035.             others: {
  26036.               overflowGroup: function (toolbar) {
  26037.                 return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  26038.                   items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  26039.                       action: function (_button) {
  26040.                         emit(toolbar, toolbarToggleEvent);
  26041.                       }
  26042.                     }))]
  26043.                 }));
  26044.               }
  26045.             }
  26046.           }),
  26047.           config('toolbar-toggle-events', [run$1(toolbarToggleEvent, function (toolbar) {
  26048.               toggleToolbar(toolbar, detail);
  26049.             })])
  26050.         ]),
  26051.         apis: {
  26052.           setGroups: function (toolbar, groups) {
  26053.             doSetGroups(toolbar, groups);
  26054.             refresh(toolbar, detail);
  26055.           },
  26056.           refresh: function (toolbar) {
  26057.             return refresh(toolbar, detail);
  26058.           },
  26059.           toggle: function (toolbar) {
  26060.             return toggleToolbar(toolbar, detail);
  26061.           },
  26062.           isOpen: function (toolbar) {
  26063.             return isOpen(toolbar, detail);
  26064.           }
  26065.         },
  26066.         domModification: { attributes: { role: 'group' } }
  26067.       };
  26068.     };
  26069.     var SplitSlidingToolbar = composite({
  26070.       name: 'SplitSlidingToolbar',
  26071.       configFields: schema$8(),
  26072.       partFields: parts$4(),
  26073.       factory: factory$7,
  26074.       apis: {
  26075.         setGroups: function (apis, toolbar, groups) {
  26076.           apis.setGroups(toolbar, groups);
  26077.         },
  26078.         refresh: function (apis, toolbar) {
  26079.           apis.refresh(toolbar);
  26080.         },
  26081.         toggle: function (apis, toolbar) {
  26082.           apis.toggle(toolbar);
  26083.         },
  26084.         isOpen: function (apis, toolbar) {
  26085.           return apis.isOpen(toolbar);
  26086.         }
  26087.       }
  26088.     });
  26089.  
  26090.     var renderToolbarGroupCommon = function (toolbarGroup) {
  26091.       var attributes = toolbarGroup.title.fold(function () {
  26092.         return {};
  26093.       }, function (title) {
  26094.         return { attributes: { title: title } };
  26095.       });
  26096.       return {
  26097.         dom: __assign({
  26098.           tag: 'div',
  26099.           classes: ['tox-toolbar__group']
  26100.         }, attributes),
  26101.         components: [ToolbarGroup.parts.items({})],
  26102.         items: toolbarGroup.items,
  26103.         markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  26104.         tgroupBehaviours: derive$1([
  26105.           Tabstopping.config({}),
  26106.           Focusing.config({})
  26107.         ])
  26108.       };
  26109.     };
  26110.     var renderToolbarGroup = function (toolbarGroup) {
  26111.       return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  26112.     };
  26113.     var getToolbarbehaviours = function (toolbarSpec, modeName) {
  26114.       var onAttached = runOnAttached(function (component) {
  26115.         var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
  26116.         Toolbar.setGroups(component, groups);
  26117.       });
  26118.       return derive$1([
  26119.         DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
  26120.         receivingConfig(),
  26121.         Keying.config({
  26122.           mode: modeName,
  26123.           onEscape: toolbarSpec.onEscape,
  26124.           selector: '.tox-toolbar__group'
  26125.         }),
  26126.         config('toolbar-events', [onAttached])
  26127.       ]);
  26128.     };
  26129.     var renderMoreToolbarCommon = function (toolbarSpec) {
  26130.       var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  26131.       return {
  26132.         uid: toolbarSpec.uid,
  26133.         dom: {
  26134.           tag: 'div',
  26135.           classes: ['tox-toolbar-overlord']
  26136.         },
  26137.         parts: {
  26138.           'overflow-group': renderToolbarGroupCommon({
  26139.             title: Optional.none(),
  26140.             items: []
  26141.           }),
  26142.           'overflow-button': renderIconButtonSpec({
  26143.             name: 'more',
  26144.             icon: Optional.some('more-drawer'),
  26145.             disabled: false,
  26146.             tooltip: Optional.some('More...'),
  26147.             primary: false,
  26148.             borderless: false
  26149.           }, Optional.none(), toolbarSpec.providers)
  26150.         },
  26151.         splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  26152.       };
  26153.     };
  26154.     var renderFloatingMoreToolbar = function (toolbarSpec) {
  26155.       var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  26156.       var overflowXOffset = 4;
  26157.       var primary = SplitFloatingToolbar.parts.primary({
  26158.         dom: {
  26159.           tag: 'div',
  26160.           classes: ['tox-toolbar__primary']
  26161.         }
  26162.       });
  26163.       return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  26164.         lazySink: toolbarSpec.getSink,
  26165.         getOverflowBounds: function () {
  26166.           var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
  26167.           var headerBounds = absolute$2(headerElem);
  26168.           var docElem = documentElement(headerElem);
  26169.           var docBounds = absolute$2(docElem);
  26170.           var height = Math.max(docElem.dom.scrollHeight, docBounds.height);
  26171.           return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  26172.         },
  26173.         parts: __assign(__assign({}, baseSpec.parts), {
  26174.           overflow: {
  26175.             dom: {
  26176.               tag: 'div',
  26177.               classes: ['tox-toolbar__overflow'],
  26178.               attributes: toolbarSpec.attributes
  26179.             }
  26180.           }
  26181.         }),
  26182.         components: [primary],
  26183.         markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  26184.       }));
  26185.     };
  26186.     var renderSlidingMoreToolbar = function (toolbarSpec) {
  26187.       var primary = SplitSlidingToolbar.parts.primary({
  26188.         dom: {
  26189.           tag: 'div',
  26190.           classes: ['tox-toolbar__primary']
  26191.         }
  26192.       });
  26193.       var overflow = SplitSlidingToolbar.parts.overflow({
  26194.         dom: {
  26195.           tag: 'div',
  26196.           classes: ['tox-toolbar__overflow']
  26197.         }
  26198.       });
  26199.       var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  26200.       return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  26201.         components: [
  26202.           primary,
  26203.           overflow
  26204.         ],
  26205.         markers: {
  26206.           openClass: 'tox-toolbar__overflow--open',
  26207.           closedClass: 'tox-toolbar__overflow--closed',
  26208.           growingClass: 'tox-toolbar__overflow--growing',
  26209.           shrinkingClass: 'tox-toolbar__overflow--shrinking',
  26210.           overflowToggledClass: 'tox-tbtn--enabled'
  26211.         },
  26212.         onOpened: function (comp) {
  26213.           comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  26214.         },
  26215.         onClosed: function (comp) {
  26216.           comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  26217.         }
  26218.       }));
  26219.     };
  26220.     var renderToolbar = function (toolbarSpec) {
  26221.       var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  26222.       return Toolbar.sketch({
  26223.         uid: toolbarSpec.uid,
  26224.         dom: {
  26225.           tag: 'div',
  26226.           classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  26227.         },
  26228.         components: [Toolbar.parts.groups({})],
  26229.         toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  26230.       });
  26231.     };
  26232.  
  26233.     var factory$6 = function (detail, components, _spec) {
  26234.       var apis = {
  26235.         getSocket: function (comp) {
  26236.           return parts$a.getPart(comp, detail, 'socket');
  26237.         },
  26238.         setSidebar: function (comp, panelConfigs) {
  26239.           parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  26240.             return setSidebar(sidebar, panelConfigs);
  26241.           });
  26242.         },
  26243.         toggleSidebar: function (comp, name) {
  26244.           parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  26245.             return toggleSidebar(sidebar, name);
  26246.           });
  26247.         },
  26248.         whichSidebar: function (comp) {
  26249.           return parts$a.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  26250.         },
  26251.         getHeader: function (comp) {
  26252.           return parts$a.getPart(comp, detail, 'header');
  26253.         },
  26254.         getToolbar: function (comp) {
  26255.           return parts$a.getPart(comp, detail, 'toolbar');
  26256.         },
  26257.         setToolbar: function (comp, groups) {
  26258.           parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  26259.             toolbar.getApis().setGroups(toolbar, groups);
  26260.           });
  26261.         },
  26262.         setToolbars: function (comp, toolbars) {
  26263.           parts$a.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  26264.             CustomList.setItems(mToolbar, toolbars);
  26265.           });
  26266.         },
  26267.         refreshToolbar: function (comp) {
  26268.           var toolbar = parts$a.getPart(comp, detail, 'toolbar');
  26269.           toolbar.each(function (toolbar) {
  26270.             return toolbar.getApis().refresh(toolbar);
  26271.           });
  26272.         },
  26273.         toggleToolbarDrawer: function (comp) {
  26274.           parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  26275.             mapFrom(toolbar.getApis().toggle, function (toggle) {
  26276.               return toggle(toolbar);
  26277.             });
  26278.           });
  26279.         },
  26280.         isToolbarDrawerToggled: function (comp) {
  26281.           return parts$a.getPart(comp, detail, 'toolbar').bind(function (toolbar) {
  26282.             return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) {
  26283.               return isOpen(toolbar);
  26284.             });
  26285.           }).getOr(false);
  26286.         },
  26287.         getThrobber: function (comp) {
  26288.           return parts$a.getPart(comp, detail, 'throbber');
  26289.         },
  26290.         focusToolbar: function (comp) {
  26291.           var optToolbar = parts$a.getPart(comp, detail, 'toolbar').orThunk(function () {
  26292.             return parts$a.getPart(comp, detail, 'multiple-toolbar');
  26293.           });
  26294.           optToolbar.each(function (toolbar) {
  26295.             Keying.focusIn(toolbar);
  26296.           });
  26297.         },
  26298.         setMenubar: function (comp, menus) {
  26299.           parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  26300.             SilverMenubar.setMenus(menubar, menus);
  26301.           });
  26302.         },
  26303.         focusMenubar: function (comp) {
  26304.           parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  26305.             SilverMenubar.focus(menubar);
  26306.           });
  26307.         }
  26308.       };
  26309.       return {
  26310.         uid: detail.uid,
  26311.         dom: detail.dom,
  26312.         components: components,
  26313.         apis: apis,
  26314.         behaviours: detail.behaviours
  26315.       };
  26316.     };
  26317.     var partMenubar = partType.optional({
  26318.       factory: SilverMenubar,
  26319.       name: 'menubar',
  26320.       schema: [required$1('backstage')]
  26321.     });
  26322.     var toolbarFactory = function (spec) {
  26323.       if (spec.type === ToolbarMode.sliding) {
  26324.         return renderSlidingMoreToolbar;
  26325.       } else if (spec.type === ToolbarMode.floating) {
  26326.         return renderFloatingMoreToolbar;
  26327.       } else {
  26328.         return renderToolbar;
  26329.       }
  26330.     };
  26331.     var partMultipleToolbar = partType.optional({
  26332.       factory: {
  26333.         sketch: function (spec) {
  26334.           return CustomList.sketch({
  26335.             uid: spec.uid,
  26336.             dom: spec.dom,
  26337.             listBehaviours: derive$1([Keying.config({
  26338.                 mode: 'acyclic',
  26339.                 selector: '.tox-toolbar'
  26340.               })]),
  26341.             makeItem: function () {
  26342.               return renderToolbar({
  26343.                 type: spec.type,
  26344.                 uid: generate$6('multiple-toolbar-item'),
  26345.                 cyclicKeying: false,
  26346.                 initGroups: [],
  26347.                 providers: spec.providers,
  26348.                 onEscape: function () {
  26349.                   spec.onEscape();
  26350.                   return Optional.some(true);
  26351.                 }
  26352.               });
  26353.             },
  26354.             setupItem: function (_mToolbar, tc, data, _index) {
  26355.               Toolbar.setGroups(tc, data);
  26356.             },
  26357.             shell: true
  26358.           });
  26359.         }
  26360.       },
  26361.       name: 'multiple-toolbar',
  26362.       schema: [
  26363.         required$1('dom'),
  26364.         required$1('onEscape')
  26365.       ]
  26366.     });
  26367.     var partToolbar = partType.optional({
  26368.       factory: {
  26369.         sketch: function (spec) {
  26370.           var renderer = toolbarFactory(spec);
  26371.           var toolbarSpec = {
  26372.             type: spec.type,
  26373.             uid: spec.uid,
  26374.             onEscape: function () {
  26375.               spec.onEscape();
  26376.               return Optional.some(true);
  26377.             },
  26378.             cyclicKeying: false,
  26379.             initGroups: [],
  26380.             getSink: spec.getSink,
  26381.             providers: spec.providers,
  26382.             moreDrawerData: {
  26383.               lazyToolbar: spec.lazyToolbar,
  26384.               lazyMoreButton: spec.lazyMoreButton,
  26385.               lazyHeader: spec.lazyHeader
  26386.             },
  26387.             attributes: spec.attributes
  26388.           };
  26389.           return renderer(toolbarSpec);
  26390.         }
  26391.       },
  26392.       name: 'toolbar',
  26393.       schema: [
  26394.         required$1('dom'),
  26395.         required$1('onEscape'),
  26396.         required$1('getSink')
  26397.       ]
  26398.     });
  26399.     var partHeader = partType.optional({
  26400.       factory: { sketch: renderHeader },
  26401.       name: 'header',
  26402.       schema: [required$1('dom')]
  26403.     });
  26404.     var partSocket = partType.optional({
  26405.       name: 'socket',
  26406.       schema: [required$1('dom')]
  26407.     });
  26408.     var partSidebar = partType.optional({
  26409.       factory: { sketch: renderSidebar },
  26410.       name: 'sidebar',
  26411.       schema: [required$1('dom')]
  26412.     });
  26413.     var partThrobber = partType.optional({
  26414.       factory: { sketch: renderThrobber },
  26415.       name: 'throbber',
  26416.       schema: [required$1('dom')]
  26417.     });
  26418.     var OuterContainer = composite({
  26419.       name: 'OuterContainer',
  26420.       factory: factory$6,
  26421.       configFields: [
  26422.         required$1('dom'),
  26423.         required$1('behaviours')
  26424.       ],
  26425.       partFields: [
  26426.         partHeader,
  26427.         partMenubar,
  26428.         partToolbar,
  26429.         partMultipleToolbar,
  26430.         partSocket,
  26431.         partSidebar,
  26432.         partThrobber
  26433.       ],
  26434.       apis: {
  26435.         getSocket: function (apis, comp) {
  26436.           return apis.getSocket(comp);
  26437.         },
  26438.         setSidebar: function (apis, comp, panelConfigs) {
  26439.           apis.setSidebar(comp, panelConfigs);
  26440.         },
  26441.         toggleSidebar: function (apis, comp, name) {
  26442.           apis.toggleSidebar(comp, name);
  26443.         },
  26444.         whichSidebar: function (apis, comp) {
  26445.           return apis.whichSidebar(comp);
  26446.         },
  26447.         getHeader: function (apis, comp) {
  26448.           return apis.getHeader(comp);
  26449.         },
  26450.         getToolbar: function (apis, comp) {
  26451.           return apis.getToolbar(comp);
  26452.         },
  26453.         setToolbar: function (apis, comp, grps) {
  26454.           var groups = map$2(grps, function (grp) {
  26455.             return renderToolbarGroup(grp);
  26456.           });
  26457.           apis.setToolbar(comp, groups);
  26458.         },
  26459.         setToolbars: function (apis, comp, ts) {
  26460.           var renderedToolbars = map$2(ts, function (g) {
  26461.             return map$2(g, renderToolbarGroup);
  26462.           });
  26463.           apis.setToolbars(comp, renderedToolbars);
  26464.         },
  26465.         refreshToolbar: function (apis, comp) {
  26466.           return apis.refreshToolbar(comp);
  26467.         },
  26468.         toggleToolbarDrawer: function (apis, comp) {
  26469.           apis.toggleToolbarDrawer(comp);
  26470.         },
  26471.         isToolbarDrawerToggled: function (apis, comp) {
  26472.           return apis.isToolbarDrawerToggled(comp);
  26473.         },
  26474.         getThrobber: function (apis, comp) {
  26475.           return apis.getThrobber(comp);
  26476.         },
  26477.         setMenubar: function (apis, comp, menus) {
  26478.           apis.setMenubar(comp, menus);
  26479.         },
  26480.         focusMenubar: function (apis, comp) {
  26481.           apis.focusMenubar(comp);
  26482.         },
  26483.         focusToolbar: function (apis, comp) {
  26484.           apis.focusToolbar(comp);
  26485.         }
  26486.       }
  26487.     });
  26488.  
  26489.     var defaultMenubar = 'file edit view insert format tools table help';
  26490.     var defaultMenus = {
  26491.       file: {
  26492.         title: 'File',
  26493.         items: 'newdocument restoredraft | preview | export print | deleteallconversations'
  26494.       },
  26495.       edit: {
  26496.         title: 'Edit',
  26497.         items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  26498.       },
  26499.       view: {
  26500.         title: 'View',
  26501.         items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  26502.       },
  26503.       insert: {
  26504.         title: 'Insert',
  26505.         items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  26506.       },
  26507.       format: {
  26508.         title: 'Format',
  26509.         items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat'
  26510.       },
  26511.       tools: {
  26512.         title: 'Tools',
  26513.         items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  26514.       },
  26515.       table: {
  26516.         title: 'Table',
  26517.         items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  26518.       },
  26519.       help: {
  26520.         title: 'Help',
  26521.         items: 'help'
  26522.       }
  26523.     };
  26524.     var make = function (menu, registry, editor) {
  26525.       var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  26526.       return {
  26527.         text: menu.title,
  26528.         getItems: function () {
  26529.           return bind$3(menu.items, function (i) {
  26530.             var itemName = i.toLowerCase();
  26531.             if (itemName.trim().length === 0) {
  26532.               return [];
  26533.             } else if (exists(removedMenuItems, function (removedMenuItem) {
  26534.                 return removedMenuItem === itemName;
  26535.               })) {
  26536.               return [];
  26537.             } else if (itemName === 'separator' || itemName === '|') {
  26538.               return [{ type: 'separator' }];
  26539.             } else if (registry.menuItems[itemName]) {
  26540.               return [registry.menuItems[itemName]];
  26541.             } else {
  26542.               return [];
  26543.             }
  26544.           });
  26545.         }
  26546.       };
  26547.     };
  26548.     var parseItemsString = function (items) {
  26549.       if (typeof items === 'string') {
  26550.         return items.split(' ');
  26551.       }
  26552.       return items;
  26553.     };
  26554.     var identifyMenus = function (editor, registry) {
  26555.       var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  26556.       var userDefinedMenus = keys(registry.menus).length > 0;
  26557.       var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  26558.       var validMenus = filter$2(menubar, function (menuName) {
  26559.         var isDefaultMenu = has$2(defaultMenus, menuName);
  26560.         if (userDefinedMenus) {
  26561.           return isDefaultMenu || get$e(registry.menus, menuName).exists(function (menu) {
  26562.             return has$2(menu, 'items');
  26563.           });
  26564.         } else {
  26565.           return isDefaultMenu;
  26566.         }
  26567.       });
  26568.       var menus = map$2(validMenus, function (menuName) {
  26569.         var menuData = rawMenuData[menuName];
  26570.         return make({
  26571.           title: menuData.title,
  26572.           items: parseItemsString(menuData.items)
  26573.         }, registry, editor);
  26574.       });
  26575.       return filter$2(menus, function (menu) {
  26576.         var isNotSeparator = function (item) {
  26577.           return item.type !== 'separator';
  26578.         };
  26579.         return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  26580.       });
  26581.     };
  26582.  
  26583.     var fireSkinLoaded = function (editor) {
  26584.       var done = function () {
  26585.         editor._skinLoaded = true;
  26586.         fireSkinLoaded$1(editor);
  26587.       };
  26588.       return function () {
  26589.         if (editor.initialized) {
  26590.           done();
  26591.         } else {
  26592.           editor.on('init', done);
  26593.         }
  26594.       };
  26595.     };
  26596.     var fireSkinLoadError = function (editor, err) {
  26597.       return function () {
  26598.         return fireSkinLoadError$1(editor, { message: err });
  26599.       };
  26600.     };
  26601.  
  26602.     var loadStylesheet = function (editor, stylesheetUrl, styleSheetLoader) {
  26603.       return new global$c(function (resolve, reject) {
  26604.         styleSheetLoader.load(stylesheetUrl, resolve, reject);
  26605.         editor.on('remove', function () {
  26606.           return styleSheetLoader.unload(stylesheetUrl);
  26607.         });
  26608.       });
  26609.     };
  26610.     var loadUiSkins = function (editor, skinUrl) {
  26611.       var skinUiCss = skinUrl + '/skin.min.css';
  26612.       return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
  26613.     };
  26614.     var loadShadowDomUiSkins = function (editor, skinUrl) {
  26615.       var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
  26616.       if (isInShadowRoot$1) {
  26617.         var shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css';
  26618.         return loadStylesheet(editor, shadowDomSkinCss, global$b.DOM.styleSheetLoader);
  26619.       } else {
  26620.         return global$c.resolve();
  26621.       }
  26622.     };
  26623.     var loadSkin = function (isInline, editor) {
  26624.       var skinUrl = getSkinUrl(editor);
  26625.       if (skinUrl) {
  26626.         editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  26627.       }
  26628.       if (isSkinDisabled(editor) === false && isString(skinUrl)) {
  26629.         global$c.all([
  26630.           loadUiSkins(editor, skinUrl),
  26631.           loadShadowDomUiSkins(editor, skinUrl)
  26632.         ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, 'Skin could not be loaded'));
  26633.       } else {
  26634.         fireSkinLoaded(editor)();
  26635.       }
  26636.     };
  26637.     var iframe = curry(loadSkin, false);
  26638.     var inline = curry(loadSkin, true);
  26639.  
  26640.     var onSetupFormatToggle = function (editor, name) {
  26641.       return function (api) {
  26642.         var boundCallback = unbindable();
  26643.         var init = function () {
  26644.           api.setActive(editor.formatter.match(name));
  26645.           var binding = editor.formatter.formatChanged(name, api.setActive);
  26646.           boundCallback.set(binding);
  26647.         };
  26648.         editor.initialized ? init() : editor.once('init', init);
  26649.         return function () {
  26650.           editor.off('init', init);
  26651.           boundCallback.clear();
  26652.         };
  26653.       };
  26654.     };
  26655.     var onSetupEvent = function (editor, event, f) {
  26656.       return function (api) {
  26657.         var handleEvent = function () {
  26658.           return f(api);
  26659.         };
  26660.         var init = function () {
  26661.           f(api);
  26662.           editor.on(event, handleEvent);
  26663.         };
  26664.         editor.initialized ? init() : editor.once('init', init);
  26665.         return function () {
  26666.           editor.off('init', init);
  26667.           editor.off(event, handleEvent);
  26668.         };
  26669.       };
  26670.     };
  26671.     var onActionToggleFormat$1 = function (editor) {
  26672.       return function (rawItem) {
  26673.         return function () {
  26674.           editor.undoManager.transact(function () {
  26675.             editor.focus();
  26676.             editor.execCommand('mceToggleFormat', false, rawItem.format);
  26677.           });
  26678.         };
  26679.       };
  26680.     };
  26681.     var onActionExecCommand = function (editor, command) {
  26682.       return function () {
  26683.         return editor.execCommand(command);
  26684.       };
  26685.     };
  26686.  
  26687.     var generateSelectItems = function (_editor, backstage, spec) {
  26688.       var generateItem = function (rawItem, response, disabled, value) {
  26689.         var translatedText = backstage.shared.providers.translate(rawItem.title);
  26690.         if (rawItem.type === 'separator') {
  26691.           return Optional.some({
  26692.             type: 'separator',
  26693.             text: translatedText
  26694.           });
  26695.         } else if (rawItem.type === 'submenu') {
  26696.           var items = bind$3(rawItem.getStyleItems(), function (si) {
  26697.             return validate(si, response, value);
  26698.           });
  26699.           if (response === 0 && items.length <= 0) {
  26700.             return Optional.none();
  26701.           } else {
  26702.             return Optional.some({
  26703.               type: 'nestedmenuitem',
  26704.               text: translatedText,
  26705.               disabled: items.length <= 0,
  26706.               getSubmenuItems: function () {
  26707.                 return bind$3(rawItem.getStyleItems(), function (si) {
  26708.                   return validate(si, response, value);
  26709.                 });
  26710.               }
  26711.             });
  26712.           }
  26713.         } else {
  26714.           return Optional.some(__assign({
  26715.             type: 'togglemenuitem',
  26716.             text: translatedText,
  26717.             icon: rawItem.icon,
  26718.             active: rawItem.isSelected(value),
  26719.             disabled: disabled,
  26720.             onAction: spec.onAction(rawItem)
  26721.           }, rawItem.getStylePreview().fold(function () {
  26722.             return {};
  26723.           }, function (preview) {
  26724.             return { meta: { style: preview } };
  26725.           })));
  26726.         }
  26727.       };
  26728.       var validate = function (item, response, value) {
  26729.         var invalid = item.type === 'formatter' && spec.isInvalid(item);
  26730.         if (response === 0) {
  26731.           return invalid ? [] : generateItem(item, response, false, value).toArray();
  26732.         } else {
  26733.           return generateItem(item, response, invalid, value).toArray();
  26734.         }
  26735.       };
  26736.       var validateItems = function (preItems) {
  26737.         var value = spec.getCurrentValue();
  26738.         var response = spec.shouldHide ? 0 : 1;
  26739.         return bind$3(preItems, function (item) {
  26740.           return validate(item, response, value);
  26741.         });
  26742.       };
  26743.       var getFetch = function (backstage, getStyleItems) {
  26744.         return function (comp, callback) {
  26745.           var preItems = getStyleItems();
  26746.           var items = validateItems(preItems);
  26747.           var menu = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  26748.           callback(menu);
  26749.         };
  26750.       };
  26751.       return {
  26752.         validateItems: validateItems,
  26753.         getFetch: getFetch
  26754.       };
  26755.     };
  26756.     var createMenuItems = function (editor, backstage, spec) {
  26757.       var dataset = spec.dataset;
  26758.       var getStyleItems = dataset.type === 'basic' ? function () {
  26759.         return map$2(dataset.data, function (d) {
  26760.           return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  26761.         });
  26762.       } : dataset.getData;
  26763.       return {
  26764.         items: generateSelectItems(editor, backstage, spec),
  26765.         getStyleItems: getStyleItems
  26766.       };
  26767.     };
  26768.     var createSelectButton = function (editor, backstage, spec) {
  26769.       var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  26770.       var getApi = function (comp) {
  26771.         return { getComponent: constant$1(comp) };
  26772.       };
  26773.       var onSetup = onSetupEvent(editor, 'NodeChange', function (api) {
  26774.         var comp = api.getComponent();
  26775.         spec.updateText(comp);
  26776.       });
  26777.       return renderCommonDropdown({
  26778.         text: spec.icon.isSome() ? Optional.none() : spec.text,
  26779.         icon: spec.icon,
  26780.         tooltip: Optional.from(spec.tooltip),
  26781.         role: Optional.none(),
  26782.         fetch: items.getFetch(backstage, getStyleItems),
  26783.         onSetup: onSetup,
  26784.         getApi: getApi,
  26785.         columns: 1,
  26786.         presets: 'normal',
  26787.         classes: spec.icon.isSome() ? [] : ['bespoke'],
  26788.         dropdownBehaviours: []
  26789.       }, 'tox-tbtn', backstage.shared);
  26790.     };
  26791.  
  26792.     var process = function (rawFormats) {
  26793.       return map$2(rawFormats, function (item) {
  26794.         var title = item, format = item;
  26795.         var values = item.split('=');
  26796.         if (values.length > 1) {
  26797.           title = values[0];
  26798.           format = values[1];
  26799.         }
  26800.         return {
  26801.           title: title,
  26802.           format: format
  26803.         };
  26804.       });
  26805.     };
  26806.     var buildBasicStaticDataset = function (data) {
  26807.       return {
  26808.         type: 'basic',
  26809.         data: data
  26810.       };
  26811.     };
  26812.     var Delimiter;
  26813.     (function (Delimiter) {
  26814.       Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  26815.       Delimiter[Delimiter['Space'] = 1] = 'Space';
  26816.     }(Delimiter || (Delimiter = {})));
  26817.     var split = function (rawFormats, delimiter) {
  26818.       if (delimiter === Delimiter.SemiColon) {
  26819.         return rawFormats.replace(/;$/, '').split(';');
  26820.       } else {
  26821.         return rawFormats.split(' ');
  26822.       }
  26823.     };
  26824.     var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  26825.       var rawFormats = editor.getParam(settingName, defaults, 'string');
  26826.       var data = process(split(rawFormats, delimiter));
  26827.       return {
  26828.         type: 'basic',
  26829.         data: data
  26830.       };
  26831.     };
  26832.  
  26833.     var alignMenuItems = [
  26834.       {
  26835.         title: 'Left',
  26836.         icon: 'align-left',
  26837.         format: 'alignleft',
  26838.         command: 'JustifyLeft'
  26839.       },
  26840.       {
  26841.         title: 'Center',
  26842.         icon: 'align-center',
  26843.         format: 'aligncenter',
  26844.         command: 'JustifyCenter'
  26845.       },
  26846.       {
  26847.         title: 'Right',
  26848.         icon: 'align-right',
  26849.         format: 'alignright',
  26850.         command: 'JustifyRight'
  26851.       },
  26852.       {
  26853.         title: 'Justify',
  26854.         icon: 'align-justify',
  26855.         format: 'alignjustify',
  26856.         command: 'JustifyFull'
  26857.       }
  26858.     ];
  26859.     var getSpec$4 = function (editor) {
  26860.       var getMatchingValue = function () {
  26861.         return find$5(alignMenuItems, function (item) {
  26862.           return editor.formatter.match(item.format);
  26863.         });
  26864.       };
  26865.       var isSelectedFor = function (format) {
  26866.         return function () {
  26867.           return editor.formatter.match(format);
  26868.         };
  26869.       };
  26870.       var getPreviewFor = function (_format) {
  26871.         return Optional.none;
  26872.       };
  26873.       var updateSelectMenuIcon = function (comp) {
  26874.         var match = getMatchingValue();
  26875.         var alignment = match.fold(constant$1('left'), function (item) {
  26876.           return item.title.toLowerCase();
  26877.         });
  26878.         emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  26879.       };
  26880.       var dataset = buildBasicStaticDataset(alignMenuItems);
  26881.       var onAction = function (rawItem) {
  26882.         return function () {
  26883.           return find$5(alignMenuItems, function (item) {
  26884.             return item.format === rawItem.format;
  26885.           }).each(function (item) {
  26886.             return editor.execCommand(item.command);
  26887.           });
  26888.         };
  26889.       };
  26890.       return {
  26891.         tooltip: 'Align',
  26892.         text: Optional.none(),
  26893.         icon: Optional.some('align-left'),
  26894.         isSelectedFor: isSelectedFor,
  26895.         getCurrentValue: Optional.none,
  26896.         getPreviewFor: getPreviewFor,
  26897.         onAction: onAction,
  26898.         updateText: updateSelectMenuIcon,
  26899.         dataset: dataset,
  26900.         shouldHide: false,
  26901.         isInvalid: function (item) {
  26902.           return !editor.formatter.canApply(item.format);
  26903.         }
  26904.       };
  26905.     };
  26906.     var createAlignSelect = function (editor, backstage) {
  26907.       return createSelectButton(editor, backstage, getSpec$4(editor));
  26908.     };
  26909.     var alignSelectMenu = function (editor, backstage) {
  26910.       var menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
  26911.       editor.ui.registry.addNestedMenuItem('align', {
  26912.         text: backstage.shared.providers.translate('Align'),
  26913.         getSubmenuItems: function () {
  26914.           return menuItems.items.validateItems(menuItems.getStyleItems());
  26915.         }
  26916.       });
  26917.     };
  26918.  
  26919.     var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
  26920.     var systemStackFonts = [
  26921.       '-apple-system',
  26922.       'Segoe UI',
  26923.       'Roboto',
  26924.       'Helvetica Neue',
  26925.       'sans-serif'
  26926.     ];
  26927.     var splitFonts = function (fontFamily) {
  26928.       var fonts = fontFamily.split(/\s*,\s*/);
  26929.       return map$2(fonts, function (font) {
  26930.         return font.replace(/^['"]+|['"]+$/g, '');
  26931.       });
  26932.     };
  26933.     var isSystemFontStack = function (fontFamily) {
  26934.       var matchesSystemStack = function () {
  26935.         var fonts = splitFonts(fontFamily.toLowerCase());
  26936.         return forall(systemStackFonts, function (font) {
  26937.           return fonts.indexOf(font.toLowerCase()) > -1;
  26938.         });
  26939.       };
  26940.       return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  26941.     };
  26942.     var getSpec$3 = function (editor) {
  26943.       var systemFont = 'System Font';
  26944.       var getMatchingValue = function () {
  26945.         var getFirstFont = function (fontFamily) {
  26946.           return fontFamily ? splitFonts(fontFamily)[0] : '';
  26947.         };
  26948.         var fontFamily = editor.queryCommandValue('FontName');
  26949.         var items = dataset.data;
  26950.         var font = fontFamily ? fontFamily.toLowerCase() : '';
  26951.         var matchOpt = find$5(items, function (item) {
  26952.           var format = item.format;
  26953.           return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  26954.         }).orThunk(function () {
  26955.           return someIf(isSystemFontStack(font), {
  26956.             title: systemFont,
  26957.             format: font
  26958.           });
  26959.         });
  26960.         return {
  26961.           matchOpt: matchOpt,
  26962.           font: fontFamily
  26963.         };
  26964.       };
  26965.       var isSelectedFor = function (item) {
  26966.         return function (valueOpt) {
  26967.           return valueOpt.exists(function (value) {
  26968.             return value.format === item;
  26969.           });
  26970.         };
  26971.       };
  26972.       var getCurrentValue = function () {
  26973.         var matchOpt = getMatchingValue().matchOpt;
  26974.         return matchOpt;
  26975.       };
  26976.       var getPreviewFor = function (item) {
  26977.         return function () {
  26978.           return Optional.some({
  26979.             tag: 'div',
  26980.             styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  26981.           });
  26982.         };
  26983.       };
  26984.       var onAction = function (rawItem) {
  26985.         return function () {
  26986.           editor.undoManager.transact(function () {
  26987.             editor.focus();
  26988.             editor.execCommand('FontName', false, rawItem.format);
  26989.           });
  26990.         };
  26991.       };
  26992.       var updateSelectMenuText = function (comp) {
  26993.         var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  26994.         var text = matchOpt.fold(constant$1(font), function (item) {
  26995.           return item.title;
  26996.         });
  26997.         emitWith(comp, updateMenuText, { text: text });
  26998.       };
  26999.       var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  27000.       return {
  27001.         tooltip: 'Fonts',
  27002.         text: Optional.some(systemFont),
  27003.         icon: Optional.none(),
  27004.         isSelectedFor: isSelectedFor,
  27005.         getCurrentValue: getCurrentValue,
  27006.         getPreviewFor: getPreviewFor,
  27007.         onAction: onAction,
  27008.         updateText: updateSelectMenuText,
  27009.         dataset: dataset,
  27010.         shouldHide: false,
  27011.         isInvalid: never
  27012.       };
  27013.     };
  27014.     var createFontSelect = function (editor, backstage) {
  27015.       return createSelectButton(editor, backstage, getSpec$3(editor));
  27016.     };
  27017.     var fontSelectMenu = function (editor, backstage) {
  27018.       var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  27019.       editor.ui.registry.addNestedMenuItem('fontformats', {
  27020.         text: backstage.shared.providers.translate('Fonts'),
  27021.         getSubmenuItems: function () {
  27022.           return menuItems.items.validateItems(menuItems.getStyleItems());
  27023.         }
  27024.       });
  27025.     };
  27026.  
  27027.     var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  27028.     var legacyFontSizes = {
  27029.       '8pt': '1',
  27030.       '10pt': '2',
  27031.       '12pt': '3',
  27032.       '14pt': '4',
  27033.       '18pt': '5',
  27034.       '24pt': '6',
  27035.       '36pt': '7'
  27036.     };
  27037.     var keywordFontSizes = {
  27038.       'xx-small': '7pt',
  27039.       'x-small': '8pt',
  27040.       'small': '10pt',
  27041.       'medium': '12pt',
  27042.       'large': '14pt',
  27043.       'x-large': '18pt',
  27044.       'xx-large': '24pt'
  27045.     };
  27046.     var round = function (number, precision) {
  27047.       var factor = Math.pow(10, precision);
  27048.       return Math.round(number * factor) / factor;
  27049.     };
  27050.     var toPt = function (fontSize, precision) {
  27051.       if (/[0-9.]+px$/.test(fontSize)) {
  27052.         return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  27053.       } else {
  27054.         return get$e(keywordFontSizes, fontSize).getOr(fontSize);
  27055.       }
  27056.     };
  27057.     var toLegacy = function (fontSize) {
  27058.       return get$e(legacyFontSizes, fontSize).getOr('');
  27059.     };
  27060.     var getSpec$2 = function (editor) {
  27061.       var getMatchingValue = function () {
  27062.         var matchOpt = Optional.none();
  27063.         var items = dataset.data;
  27064.         var fontSize = editor.queryCommandValue('FontSize');
  27065.         if (fontSize) {
  27066.           var _loop_1 = function (precision) {
  27067.             var pt = toPt(fontSize, precision);
  27068.             var legacy = toLegacy(pt);
  27069.             matchOpt = find$5(items, function (item) {
  27070.               return item.format === fontSize || item.format === pt || item.format === legacy;
  27071.             });
  27072.           };
  27073.           for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  27074.             _loop_1(precision);
  27075.           }
  27076.         }
  27077.         return {
  27078.           matchOpt: matchOpt,
  27079.           size: fontSize
  27080.         };
  27081.       };
  27082.       var isSelectedFor = function (item) {
  27083.         return function (valueOpt) {
  27084.           return valueOpt.exists(function (value) {
  27085.             return value.format === item;
  27086.           });
  27087.         };
  27088.       };
  27089.       var getCurrentValue = function () {
  27090.         var matchOpt = getMatchingValue().matchOpt;
  27091.         return matchOpt;
  27092.       };
  27093.       var getPreviewFor = constant$1(Optional.none);
  27094.       var onAction = function (rawItem) {
  27095.         return function () {
  27096.           editor.undoManager.transact(function () {
  27097.             editor.focus();
  27098.             editor.execCommand('FontSize', false, rawItem.format);
  27099.           });
  27100.         };
  27101.       };
  27102.       var updateSelectMenuText = function (comp) {
  27103.         var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  27104.         var text = matchOpt.fold(constant$1(size), function (match) {
  27105.           return match.title;
  27106.         });
  27107.         emitWith(comp, updateMenuText, { text: text });
  27108.       };
  27109.       var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  27110.       return {
  27111.         tooltip: 'Font sizes',
  27112.         text: Optional.some('12pt'),
  27113.         icon: Optional.none(),
  27114.         isSelectedFor: isSelectedFor,
  27115.         getPreviewFor: getPreviewFor,
  27116.         getCurrentValue: getCurrentValue,
  27117.         onAction: onAction,
  27118.         updateText: updateSelectMenuText,
  27119.         dataset: dataset,
  27120.         shouldHide: false,
  27121.         isInvalid: never
  27122.       };
  27123.     };
  27124.     var createFontsizeSelect = function (editor, backstage) {
  27125.       return createSelectButton(editor, backstage, getSpec$2(editor));
  27126.     };
  27127.     var fontsizeSelectMenu = function (editor, backstage) {
  27128.       var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  27129.       editor.ui.registry.addNestedMenuItem('fontsizes', {
  27130.         text: 'Font sizes',
  27131.         getSubmenuItems: function () {
  27132.           return menuItems.items.validateItems(menuItems.getStyleItems());
  27133.         }
  27134.       });
  27135.     };
  27136.  
  27137.     var findNearest = function (editor, getStyles) {
  27138.       var styles = getStyles();
  27139.       var formats = map$2(styles, function (style) {
  27140.         return style.format;
  27141.       });
  27142.       return Optional.from(editor.formatter.closest(formats)).bind(function (fmt) {
  27143.         return find$5(styles, function (data) {
  27144.           return data.format === fmt;
  27145.         });
  27146.       }).orThunk(function () {
  27147.         return someIf(editor.formatter.match('p'), {
  27148.           title: 'Paragraph',
  27149.           format: 'p'
  27150.         });
  27151.       });
  27152.     };
  27153.  
  27154.     var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  27155.     var getSpec$1 = function (editor) {
  27156.       var fallbackFormat = 'Paragraph';
  27157.       var isSelectedFor = function (format) {
  27158.         return function () {
  27159.           return editor.formatter.match(format);
  27160.         };
  27161.       };
  27162.       var getPreviewFor = function (format) {
  27163.         return function () {
  27164.           var fmt = editor.formatter.get(format);
  27165.           return Optional.some({
  27166.             tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  27167.             styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  27168.           });
  27169.         };
  27170.       };
  27171.       var updateSelectMenuText = function (comp) {
  27172.         var detectedFormat = findNearest(editor, function () {
  27173.           return dataset.data;
  27174.         });
  27175.         var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  27176.           return fmt.title;
  27177.         });
  27178.         emitWith(comp, updateMenuText, { text: text });
  27179.       };
  27180.       var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  27181.       return {
  27182.         tooltip: 'Blocks',
  27183.         text: Optional.some(fallbackFormat),
  27184.         icon: Optional.none(),
  27185.         isSelectedFor: isSelectedFor,
  27186.         getCurrentValue: Optional.none,
  27187.         getPreviewFor: getPreviewFor,
  27188.         onAction: onActionToggleFormat$1(editor),
  27189.         updateText: updateSelectMenuText,
  27190.         dataset: dataset,
  27191.         shouldHide: false,
  27192.         isInvalid: function (item) {
  27193.           return !editor.formatter.canApply(item.format);
  27194.         }
  27195.       };
  27196.     };
  27197.     var createFormatSelect = function (editor, backstage) {
  27198.       return createSelectButton(editor, backstage, getSpec$1(editor));
  27199.     };
  27200.     var formatSelectMenu = function (editor, backstage) {
  27201.       var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  27202.       editor.ui.registry.addNestedMenuItem('blockformats', {
  27203.         text: 'Blocks',
  27204.         getSubmenuItems: function () {
  27205.           return menuItems.items.validateItems(menuItems.getStyleItems());
  27206.         }
  27207.       });
  27208.     };
  27209.  
  27210.     var getSpec = function (editor, dataset) {
  27211.       var fallbackFormat = 'Paragraph';
  27212.       var isSelectedFor = function (format) {
  27213.         return function () {
  27214.           return editor.formatter.match(format);
  27215.         };
  27216.       };
  27217.       var getPreviewFor = function (format) {
  27218.         return function () {
  27219.           var fmt = editor.formatter.get(format);
  27220.           return fmt !== undefined ? Optional.some({
  27221.             tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  27222.             styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  27223.           }) : Optional.none();
  27224.         };
  27225.       };
  27226.       var updateSelectMenuText = function (comp) {
  27227.         var getFormatItems = function (fmt) {
  27228.           var subs = fmt.items;
  27229.           return subs !== undefined && subs.length > 0 ? bind$3(subs, getFormatItems) : [{
  27230.               title: fmt.title,
  27231.               format: fmt.format
  27232.             }];
  27233.         };
  27234.         var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
  27235.         var detectedFormat = findNearest(editor, constant$1(flattenedItems));
  27236.         var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  27237.           return fmt.title;
  27238.         });
  27239.         emitWith(comp, updateMenuText, { text: text });
  27240.       };
  27241.       return {
  27242.         tooltip: 'Formats',
  27243.         text: Optional.some(fallbackFormat),
  27244.         icon: Optional.none(),
  27245.         isSelectedFor: isSelectedFor,
  27246.         getCurrentValue: Optional.none,
  27247.         getPreviewFor: getPreviewFor,
  27248.         onAction: onActionToggleFormat$1(editor),
  27249.         updateText: updateSelectMenuText,
  27250.         shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  27251.         isInvalid: function (item) {
  27252.           return !editor.formatter.canApply(item.format);
  27253.         },
  27254.         dataset: dataset
  27255.       };
  27256.     };
  27257.     var createStyleSelect = function (editor, backstage) {
  27258.       var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  27259.       return createSelectButton(editor, backstage, getSpec(editor, dataset));
  27260.     };
  27261.     var styleSelectMenu = function (editor, backstage) {
  27262.       var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  27263.       var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset));
  27264.       editor.ui.registry.addNestedMenuItem('formats', {
  27265.         text: 'Formats',
  27266.         getSubmenuItems: function () {
  27267.           return menuItems.items.validateItems(menuItems.getStyleItems());
  27268.         }
  27269.       });
  27270.     };
  27271.  
  27272.     var events$3 = function (reflectingConfig, reflectingState) {
  27273.       var update = function (component, data) {
  27274.         reflectingConfig.updateState.each(function (updateState) {
  27275.           var newState = updateState(component, data);
  27276.           reflectingState.set(newState);
  27277.         });
  27278.         reflectingConfig.renderComponents.each(function (renderComponents) {
  27279.           var newComponents = renderComponents(data, reflectingState.get());
  27280.           var newChildren = map$2(newComponents, component.getSystem().build);
  27281.           replaceChildren(component, newChildren);
  27282.         });
  27283.       };
  27284.       return derive$2([
  27285.         run$1(receive(), function (component, message) {
  27286.           var receivingData = message;
  27287.           if (!receivingData.universal) {
  27288.             var channel = reflectingConfig.channel;
  27289.             if (contains$2(receivingData.channels, channel)) {
  27290.               update(component, receivingData.data);
  27291.             }
  27292.           }
  27293.         }),
  27294.         runOnAttached(function (comp, _se) {
  27295.           reflectingConfig.initialData.each(function (rawData) {
  27296.             update(comp, rawData);
  27297.           });
  27298.         })
  27299.       ]);
  27300.     };
  27301.  
  27302.     var ActiveReflecting = /*#__PURE__*/Object.freeze({
  27303.         __proto__: null,
  27304.         events: events$3
  27305.     });
  27306.  
  27307.     var getState = function (component, replaceConfig, reflectState) {
  27308.       return reflectState;
  27309.     };
  27310.  
  27311.     var ReflectingApis = /*#__PURE__*/Object.freeze({
  27312.         __proto__: null,
  27313.         getState: getState
  27314.     });
  27315.  
  27316.     var ReflectingSchema = [
  27317.       required$1('channel'),
  27318.       option('renderComponents'),
  27319.       option('updateState'),
  27320.       option('initialData')
  27321.     ];
  27322.  
  27323.     var init$3 = function () {
  27324.       var cell = Cell(Optional.none());
  27325.       var clear = function () {
  27326.         return cell.set(Optional.none());
  27327.       };
  27328.       var readState = function () {
  27329.         return cell.get().getOr('none');
  27330.       };
  27331.       return {
  27332.         readState: readState,
  27333.         get: cell.get,
  27334.         set: cell.set,
  27335.         clear: clear
  27336.       };
  27337.     };
  27338.  
  27339.     var ReflectingState = /*#__PURE__*/Object.freeze({
  27340.         __proto__: null,
  27341.         init: init$3
  27342.     });
  27343.  
  27344.     var Reflecting = create$8({
  27345.       fields: ReflectingSchema,
  27346.       name: 'reflecting',
  27347.       active: ActiveReflecting,
  27348.       apis: ReflectingApis,
  27349.       state: ReflectingState
  27350.     });
  27351.  
  27352.     var schema$7 = constant$1([
  27353.       required$1('toggleClass'),
  27354.       required$1('fetch'),
  27355.       onStrictHandler('onExecute'),
  27356.       defaulted('getHotspot', Optional.some),
  27357.       defaulted('getAnchorOverrides', constant$1({})),
  27358.       schema$y(),
  27359.       onStrictHandler('onItemExecute'),
  27360.       option('lazySink'),
  27361.       required$1('dom'),
  27362.       onHandler('onOpen'),
  27363.       field('splitDropdownBehaviours', [
  27364.         Coupling,
  27365.         Keying,
  27366.         Focusing
  27367.       ]),
  27368.       defaulted('matchWidth', false),
  27369.       defaulted('useMinWidth', false),
  27370.       defaulted('eventOrder', {}),
  27371.       option('role')
  27372.     ].concat(sandboxFields()));
  27373.     var arrowPart = required({
  27374.       factory: Button,
  27375.       schema: [required$1('dom')],
  27376.       name: 'arrow',
  27377.       defaults: function () {
  27378.         return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  27379.       },
  27380.       overrides: function (detail) {
  27381.         return {
  27382.           dom: {
  27383.             tag: 'span',
  27384.             attributes: { role: 'presentation' }
  27385.           },
  27386.           action: function (arrow) {
  27387.             arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  27388.           },
  27389.           buttonBehaviours: derive$1([Toggling.config({
  27390.               toggleOnExecute: false,
  27391.               toggleClass: detail.toggleClass
  27392.             })])
  27393.         };
  27394.       }
  27395.     });
  27396.     var buttonPart = required({
  27397.       factory: Button,
  27398.       schema: [required$1('dom')],
  27399.       name: 'button',
  27400.       defaults: function () {
  27401.         return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  27402.       },
  27403.       overrides: function (detail) {
  27404.         return {
  27405.           dom: {
  27406.             tag: 'span',
  27407.             attributes: { role: 'presentation' }
  27408.           },
  27409.           action: function (btn) {
  27410.             btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  27411.               detail.onExecute(splitDropdown, btn);
  27412.             });
  27413.           }
  27414.         };
  27415.       }
  27416.     });
  27417.     var parts$3 = constant$1([
  27418.       arrowPart,
  27419.       buttonPart,
  27420.       optional({
  27421.         factory: {
  27422.           sketch: function (spec) {
  27423.             return {
  27424.               uid: spec.uid,
  27425.               dom: {
  27426.                 tag: 'span',
  27427.                 styles: { display: 'none' },
  27428.                 attributes: { 'aria-hidden': 'true' },
  27429.                 innerHtml: spec.text
  27430.               }
  27431.             };
  27432.           }
  27433.         },
  27434.         schema: [required$1('text')],
  27435.         name: 'aria-descriptor'
  27436.       }),
  27437.       external$1({
  27438.         schema: [tieredMenuMarkers()],
  27439.         name: 'menu',
  27440.         defaults: function (detail) {
  27441.           return {
  27442.             onExecute: function (tmenu, item) {
  27443.               tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  27444.                 detail.onItemExecute(splitDropdown, tmenu, item);
  27445.               });
  27446.             }
  27447.           };
  27448.         }
  27449.       }),
  27450.       partType$1()
  27451.     ]);
  27452.  
  27453.     var factory$5 = function (detail, components, spec, externals) {
  27454.       var _a;
  27455.       var switchToMenu = function (sandbox) {
  27456.         Composing.getCurrent(sandbox).each(function (current) {
  27457.           Highlighting.highlightFirst(current);
  27458.           Keying.focusIn(current);
  27459.         });
  27460.       };
  27461.       var action = function (component) {
  27462.         var onOpenSync = switchToMenu;
  27463.         togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  27464.       };
  27465.       var openMenu = function (comp) {
  27466.         action(comp);
  27467.         return Optional.some(true);
  27468.       };
  27469.       var executeOnButton = function (comp) {
  27470.         var button = getPartOrDie(comp, detail, 'button');
  27471.         emitExecute(button);
  27472.         return Optional.some(true);
  27473.       };
  27474.       var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function (component, _simulatedEvent) {
  27475.           var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  27476.           ariaDescriptor.each(function (descriptor) {
  27477.             var descriptorId = generate$6('aria');
  27478.             set$8(descriptor.element, 'id', descriptorId);
  27479.             set$8(component.element, 'aria-describedby', descriptorId);
  27480.           });
  27481.         })])), events$a(Optional.some(action)));
  27482.       var apis = {
  27483.         repositionMenus: function (comp) {
  27484.           if (Toggling.isOn(comp)) {
  27485.             repositionMenus(comp);
  27486.           }
  27487.         }
  27488.       };
  27489.       return {
  27490.         uid: detail.uid,
  27491.         dom: detail.dom,
  27492.         components: components,
  27493.         apis: apis,
  27494.         eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  27495.           'disabling',
  27496.           'toggling',
  27497.           'alloy.base.behaviour'
  27498.         ], _a)),
  27499.         events: buttonEvents,
  27500.         behaviours: augment(detail.splitDropdownBehaviours, [
  27501.           Coupling.config({
  27502.             others: {
  27503.               sandbox: function (hotspot) {
  27504.                 var arrow = getPartOrDie(hotspot, detail, 'arrow');
  27505.                 var extras = {
  27506.                   onOpen: function () {
  27507.                     Toggling.on(arrow);
  27508.                     Toggling.on(hotspot);
  27509.                   },
  27510.                   onClose: function () {
  27511.                     Toggling.off(arrow);
  27512.                     Toggling.off(hotspot);
  27513.                   }
  27514.                 };
  27515.                 return makeSandbox$1(detail, hotspot, extras);
  27516.               }
  27517.             }
  27518.           }),
  27519.           Keying.config({
  27520.             mode: 'special',
  27521.             onSpace: executeOnButton,
  27522.             onEnter: executeOnButton,
  27523.             onDown: openMenu
  27524.           }),
  27525.           Focusing.config({}),
  27526.           Toggling.config({
  27527.             toggleOnExecute: false,
  27528.             aria: { mode: 'expanded' }
  27529.           })
  27530.         ]),
  27531.         domModification: {
  27532.           attributes: {
  27533.             'role': detail.role.getOr('button'),
  27534.             'aria-haspopup': true
  27535.           }
  27536.         }
  27537.       };
  27538.     };
  27539.     var SplitDropdown = composite({
  27540.       name: 'SplitDropdown',
  27541.       configFields: schema$7(),
  27542.       partFields: parts$3(),
  27543.       factory: factory$5,
  27544.       apis: {
  27545.         repositionMenus: function (apis, comp) {
  27546.           return apis.repositionMenus(comp);
  27547.         }
  27548.       }
  27549.     });
  27550.  
  27551.     var getButtonApi = function (component) {
  27552.       return {
  27553.         isDisabled: function () {
  27554.           return Disabling.isDisabled(component);
  27555.         },
  27556.         setDisabled: function (state) {
  27557.           return Disabling.set(component, state);
  27558.         }
  27559.       };
  27560.     };
  27561.     var getToggleApi = function (component) {
  27562.       return {
  27563.         setActive: function (state) {
  27564.           Toggling.set(component, state);
  27565.         },
  27566.         isActive: function () {
  27567.           return Toggling.isOn(component);
  27568.         },
  27569.         isDisabled: function () {
  27570.           return Disabling.isDisabled(component);
  27571.         },
  27572.         setDisabled: function (state) {
  27573.           return Disabling.set(component, state);
  27574.         }
  27575.       };
  27576.     };
  27577.     var getTooltipAttributes = function (tooltip, providersBackstage) {
  27578.       return tooltip.map(function (tooltip) {
  27579.         return {
  27580.           'aria-label': providersBackstage.translate(tooltip),
  27581.           'title': providersBackstage.translate(tooltip)
  27582.         };
  27583.       }).getOr({});
  27584.     };
  27585.     var focusButtonEvent = generate$6('focus-button');
  27586.     var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  27587.       var _d;
  27588.       return {
  27589.         dom: {
  27590.           tag: 'button',
  27591.           classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []),
  27592.           attributes: getTooltipAttributes(tooltip, providersBackstage)
  27593.         },
  27594.         components: componentRenderPipeline([
  27595.           icon.map(function (iconName) {
  27596.             return renderIconFromPack(iconName, providersBackstage.icons);
  27597.           }),
  27598.           text.map(function (text) {
  27599.             return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  27600.           })
  27601.         ]),
  27602.         eventOrder: (_d = {}, _d[mousedown()] = [
  27603.           'focusing',
  27604.           'alloy.base.behaviour',
  27605.           'common-button-display-events'
  27606.         ], _d),
  27607.         buttonBehaviours: derive$1([
  27608.           DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
  27609.           receivingConfig(),
  27610.           config('common-button-display-events', [run$1(mousedown(), function (button, se) {
  27611.               se.event.prevent();
  27612.               emit(button, focusButtonEvent);
  27613.             })])
  27614.         ].concat(receiver.map(function (r) {
  27615.           return Reflecting.config({
  27616.             channel: r,
  27617.             initialData: {
  27618.               icon: icon,
  27619.               text: text
  27620.             },
  27621.             renderComponents: function (data, _state) {
  27622.               return componentRenderPipeline([
  27623.                 data.icon.map(function (iconName) {
  27624.                   return renderIconFromPack(iconName, providersBackstage.icons);
  27625.                 }),
  27626.                 data.text.map(function (text) {
  27627.                   return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  27628.                 })
  27629.               ]);
  27630.             }
  27631.           });
  27632.         }).toArray()).concat(behaviours.getOr([])))
  27633.       };
  27634.     };
  27635.     var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  27636.       var sharedBackstage = backstage.shared;
  27637.       return FloatingToolbarButton.sketch({
  27638.         lazySink: sharedBackstage.getSink,
  27639.         fetch: function () {
  27640.           return Future.nu(function (resolve) {
  27641.             resolve(map$2(identifyButtons(spec.items), renderToolbarGroup));
  27642.           });
  27643.         },
  27644.         markers: { toggledClass: 'tox-tbtn--enabled' },
  27645.         parts: {
  27646.           button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
  27647.           toolbar: {
  27648.             dom: {
  27649.               tag: 'div',
  27650.               classes: ['tox-toolbar__overflow'],
  27651.               attributes: attributes
  27652.             }
  27653.           }
  27654.         }
  27655.       });
  27656.     };
  27657.     var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  27658.       var editorOffCell = Cell(noop);
  27659.       var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
  27660.       return Button.sketch({
  27661.         dom: structure.dom,
  27662.         components: structure.components,
  27663.         eventOrder: toolbarButtonEventOrder,
  27664.         buttonBehaviours: derive$1([
  27665.           config('toolbar-button-events', [
  27666.             onToolbarButtonExecute({
  27667.               onAction: spec.onAction,
  27668.               getApi: specialisation.getApi
  27669.             }),
  27670.             onControlAttached(specialisation, editorOffCell),
  27671.             onControlDetached(specialisation, editorOffCell)
  27672.           ]),
  27673.           DisablingConfigs.toolbarButton(function () {
  27674.             return spec.disabled || providersBackstage.isDisabled();
  27675.           }),
  27676.           receivingConfig()
  27677.         ].concat(specialisation.toolbarButtonBehaviours))
  27678.       });
  27679.     };
  27680.     var renderToolbarButton = function (spec, providersBackstage) {
  27681.       return renderToolbarButtonWith(spec, providersBackstage, []);
  27682.     };
  27683.     var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  27684.       return renderCommonToolbarButton(spec, {
  27685.         toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  27686.         getApi: getButtonApi,
  27687.         onSetup: spec.onSetup
  27688.       }, providersBackstage);
  27689.     };
  27690.     var renderToolbarToggleButton = function (spec, providersBackstage) {
  27691.       return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  27692.     };
  27693.     var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  27694.       return deepMerge(renderCommonToolbarButton(spec, {
  27695.         toolbarButtonBehaviours: [
  27696.           Replacing.config({}),
  27697.           Toggling.config({
  27698.             toggleClass: 'tox-tbtn--enabled',
  27699.             aria: { mode: 'pressed' },
  27700.             toggleOnExecute: false
  27701.           })
  27702.         ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  27703.         getApi: getToggleApi,
  27704.         onSetup: spec.onSetup
  27705.       }, providersBackstage));
  27706.     };
  27707.     var fetchChoices = function (getApi, spec, providersBackstage) {
  27708.       return function (comp) {
  27709.         return Future.nu(function (callback) {
  27710.           return spec.fetch(callback);
  27711.         }).map(function (items) {
  27712.           return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  27713.             spec.onItemAction(getApi(comp), value);
  27714.           }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
  27715.             movement: deriveMenuMovement(spec.columns, spec.presets),
  27716.             menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  27717.                 detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
  27718.                   var numRows = _d.numRows, numColumns = _d.numColumns;
  27719.                   Keying.setGridSize(comp, numRows, numColumns);
  27720.                 });
  27721.               })])
  27722.           })));
  27723.         });
  27724.       };
  27725.     };
  27726.     var renderSplitButton = function (spec, sharedBackstage) {
  27727.       var _d;
  27728.       var displayChannel = generate$6('channel-update-split-dropdown-display');
  27729.       var getApi = function (comp) {
  27730.         return {
  27731.           isDisabled: function () {
  27732.             return Disabling.isDisabled(comp);
  27733.           },
  27734.           setDisabled: function (state) {
  27735.             return Disabling.set(comp, state);
  27736.           },
  27737.           setIconFill: function (id, value) {
  27738.             descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  27739.               set$8(underlinePath, 'fill', value);
  27740.             });
  27741.           },
  27742.           setIconStroke: function (id, value) {
  27743.             descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  27744.               set$8(underlinePath, 'stroke', value);
  27745.             });
  27746.           },
  27747.           setActive: function (state) {
  27748.             set$8(comp.element, 'aria-pressed', state);
  27749.             descendant(comp.element, 'span').each(function (button) {
  27750.               comp.getSystem().getByDom(button).each(function (buttonComp) {
  27751.                 return Toggling.set(buttonComp, state);
  27752.               });
  27753.             });
  27754.           },
  27755.           isActive: function () {
  27756.             return descendant(comp.element, 'span').exists(function (button) {
  27757.               return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  27758.             });
  27759.           }
  27760.         };
  27761.       };
  27762.       var editorOffCell = Cell(noop);
  27763.       var specialisation = {
  27764.         getApi: getApi,
  27765.         onSetup: spec.onSetup
  27766.       };
  27767.       return SplitDropdown.sketch({
  27768.         dom: {
  27769.           tag: 'div',
  27770.           classes: ['tox-split-button'],
  27771.           attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  27772.         },
  27773.         onExecute: function (button) {
  27774.           spec.onAction(getApi(button));
  27775.         },
  27776.         onItemExecute: function (_a, _b, _c) {
  27777.         },
  27778.         splitDropdownBehaviours: derive$1([
  27779.           DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  27780.           receivingConfig(),
  27781.           config('split-dropdown-events', [
  27782.             run$1(focusButtonEvent, Focusing.focus),
  27783.             onControlAttached(specialisation, editorOffCell),
  27784.             onControlDetached(specialisation, editorOffCell)
  27785.           ]),
  27786.           Unselecting.config({})
  27787.         ]),
  27788.         eventOrder: (_d = {}, _d[attachedToDom()] = [
  27789.           'alloy.base.behaviour',
  27790.           'split-dropdown-events'
  27791.         ], _d),
  27792.         toggleClass: 'tox-tbtn--enabled',
  27793.         lazySink: sharedBackstage.getSink,
  27794.         fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  27795.         parts: { menu: part(false, spec.columns, spec.presets) },
  27796.         components: [
  27797.           SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
  27798.               toggleClass: 'tox-tbtn--enabled',
  27799.               toggleOnExecute: false
  27800.             })]), sharedBackstage.providers)),
  27801.           SplitDropdown.parts.arrow({
  27802.             dom: {
  27803.               tag: 'button',
  27804.               classes: [
  27805.                 'tox-tbtn',
  27806.                 'tox-split-button__chevron'
  27807.               ],
  27808.               innerHtml: get$1('chevron-down', sharedBackstage.providers.icons)
  27809.             },
  27810.             buttonBehaviours: derive$1([
  27811.               DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  27812.               receivingConfig(),
  27813.               addFocusableBehaviour()
  27814.             ])
  27815.           }),
  27816.           SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  27817.         ]
  27818.       });
  27819.     };
  27820.  
  27821.     var defaultToolbar = [
  27822.       {
  27823.         name: 'history',
  27824.         items: [
  27825.           'undo',
  27826.           'redo'
  27827.         ]
  27828.       },
  27829.       {
  27830.         name: 'styles',
  27831.         items: ['styleselect']
  27832.       },
  27833.       {
  27834.         name: 'formatting',
  27835.         items: [
  27836.           'bold',
  27837.           'italic'
  27838.         ]
  27839.       },
  27840.       {
  27841.         name: 'alignment',
  27842.         items: [
  27843.           'alignleft',
  27844.           'aligncenter',
  27845.           'alignright',
  27846.           'alignjustify'
  27847.         ]
  27848.       },
  27849.       {
  27850.         name: 'indentation',
  27851.         items: [
  27852.           'outdent',
  27853.           'indent'
  27854.         ]
  27855.       },
  27856.       {
  27857.         name: 'permanent pen',
  27858.         items: ['permanentpen']
  27859.       },
  27860.       {
  27861.         name: 'comments',
  27862.         items: ['addcomment']
  27863.       }
  27864.     ];
  27865.     var renderFromBridge = function (bridgeBuilder, render) {
  27866.       return function (spec, extras, editor) {
  27867.         var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  27868.           return formatError(errInfo);
  27869.         }).getOrDie();
  27870.         return render(internal, extras, editor);
  27871.       };
  27872.     };
  27873.     var types = {
  27874.       button: renderFromBridge(createToolbarButton, function (s, extras) {
  27875.         return renderToolbarButton(s, extras.backstage.shared.providers);
  27876.       }),
  27877.       togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  27878.         return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  27879.       }),
  27880.       menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  27881.         return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none());
  27882.       }),
  27883.       splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  27884.         return renderSplitButton(s, extras.backstage.shared);
  27885.       }),
  27886.       grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  27887.         var _a;
  27888.         var buttons = editor.ui.registry.getAll().buttons;
  27889.         var identify = function (toolbar) {
  27890.           return identifyButtons(editor, {
  27891.             buttons: buttons,
  27892.             toolbar: toolbar,
  27893.             allowToolbarGroups: false
  27894.           }, extras, Optional.none());
  27895.         };
  27896.         var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  27897.         switch (getToolbarMode(editor)) {
  27898.         case ToolbarMode.floating:
  27899.           return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  27900.         default:
  27901.           throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  27902.         }
  27903.       }),
  27904.       styleSelectButton: function (editor, extras) {
  27905.         return createStyleSelect(editor, extras.backstage);
  27906.       },
  27907.       fontsizeSelectButton: function (editor, extras) {
  27908.         return createFontsizeSelect(editor, extras.backstage);
  27909.       },
  27910.       fontSelectButton: function (editor, extras) {
  27911.         return createFontSelect(editor, extras.backstage);
  27912.       },
  27913.       formatButton: function (editor, extras) {
  27914.         return createFormatSelect(editor, extras.backstage);
  27915.       },
  27916.       alignMenuButton: function (editor, extras) {
  27917.         return createAlignSelect(editor, extras.backstage);
  27918.       }
  27919.     };
  27920.     var extractFrom = function (spec, extras, editor) {
  27921.       return get$e(types, spec.type).fold(function () {
  27922.         console.error('skipping button defined by', spec);
  27923.         return Optional.none();
  27924.       }, function (render) {
  27925.         return Optional.some(render(spec, extras, editor));
  27926.       });
  27927.     };
  27928.     var bespokeButtons = {
  27929.       styleselect: types.styleSelectButton,
  27930.       fontsizeselect: types.fontsizeSelectButton,
  27931.       fontselect: types.fontSelectButton,
  27932.       formatselect: types.formatButton,
  27933.       align: types.alignMenuButton
  27934.     };
  27935.     var removeUnusedDefaults = function (buttons) {
  27936.       var filteredItemGroups = map$2(defaultToolbar, function (group) {
  27937.         var items = filter$2(group.items, function (subItem) {
  27938.           return has$2(buttons, subItem) || has$2(bespokeButtons, subItem);
  27939.         });
  27940.         return {
  27941.           name: group.name,
  27942.           items: items
  27943.         };
  27944.       });
  27945.       return filter$2(filteredItemGroups, function (group) {
  27946.         return group.items.length > 0;
  27947.       });
  27948.     };
  27949.     var convertStringToolbar = function (strToolbar) {
  27950.       var groupsStrings = strToolbar.split('|');
  27951.       return map$2(groupsStrings, function (g) {
  27952.         return { items: g.trim().split(' ') };
  27953.       });
  27954.     };
  27955.     var isToolbarGroupSettingArray = function (toolbar) {
  27956.       return isArrayOf(toolbar, function (t) {
  27957.         return has$2(t, 'name') && has$2(t, 'items');
  27958.       });
  27959.     };
  27960.     var createToolbar = function (toolbarConfig) {
  27961.       var toolbar = toolbarConfig.toolbar;
  27962.       var buttons = toolbarConfig.buttons;
  27963.       if (toolbar === false) {
  27964.         return [];
  27965.       } else if (toolbar === undefined || toolbar === true) {
  27966.         return removeUnusedDefaults(buttons);
  27967.       } else if (isString(toolbar)) {
  27968.         return convertStringToolbar(toolbar);
  27969.       } else if (isToolbarGroupSettingArray(toolbar)) {
  27970.         return toolbar;
  27971.       } else {
  27972.         console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  27973.         return [];
  27974.       }
  27975.     };
  27976.     var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  27977.       return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  27978.         return prefixes.bind(function (ps) {
  27979.           return findMap(ps, function (prefix) {
  27980.             return get$e(buttons, prefix + toolbarItem.toLowerCase());
  27981.           });
  27982.         });
  27983.       }).fold(function () {
  27984.         return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  27985.           return r(editor, extras);
  27986.         }).orThunk(function () {
  27987.           return Optional.none();
  27988.         });
  27989.       }, function (spec) {
  27990.         if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  27991.           console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  27992.           return Optional.none();
  27993.         } else {
  27994.           return extractFrom(spec, extras, editor);
  27995.         }
  27996.       });
  27997.     };
  27998.     var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  27999.       var toolbarGroups = createToolbar(toolbarConfig);
  28000.       var groups = map$2(toolbarGroups, function (group) {
  28001.         var items = bind$3(group.items, function (toolbarItem) {
  28002.           return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  28003.         });
  28004.         return {
  28005.           title: Optional.from(editor.translate(group.name)),
  28006.           items: items
  28007.         };
  28008.       });
  28009.       return filter$2(groups, function (group) {
  28010.         return group.items.length > 0;
  28011.       });
  28012.     };
  28013.  
  28014.     var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  28015.       var comp = uiComponents.outerContainer;
  28016.       var toolbarConfig = rawUiConfig.toolbar;
  28017.       var toolbarButtonsConfig = rawUiConfig.buttons;
  28018.       if (isArrayOf(toolbarConfig, isString)) {
  28019.         var toolbars = toolbarConfig.map(function (t) {
  28020.           var config = {
  28021.             toolbar: t,
  28022.             buttons: toolbarButtonsConfig,
  28023.             allowToolbarGroups: rawUiConfig.allowToolbarGroups
  28024.           };
  28025.           return identifyButtons(editor, config, { backstage: backstage }, Optional.none());
  28026.         });
  28027.         OuterContainer.setToolbars(comp, toolbars);
  28028.       } else {
  28029.         OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none()));
  28030.       }
  28031.     };
  28032.  
  28033.     var detection = detect$1();
  28034.     var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  28035.     var setupEvents$1 = function (editor, uiComponents) {
  28036.       var dom = editor.dom;
  28037.       var contentWindow = editor.getWin();
  28038.       var initialDocEle = editor.getDoc().documentElement;
  28039.       var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  28040.       var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  28041.       var resizeWindow = function () {
  28042.         var outer = lastWindowDimensions.get();
  28043.         if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
  28044.           lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  28045.           fireResizeContent(editor);
  28046.         }
  28047.       };
  28048.       var resizeDocument = function () {
  28049.         var docEle = editor.getDoc().documentElement;
  28050.         var inner = lastDocumentDimensions.get();
  28051.         if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
  28052.           lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
  28053.           fireResizeContent(editor);
  28054.         }
  28055.       };
  28056.       var scroll = function (e) {
  28057.         return fireScrollContent(editor, e);
  28058.       };
  28059.       dom.bind(contentWindow, 'resize', resizeWindow);
  28060.       dom.bind(contentWindow, 'scroll', scroll);
  28061.       var elementLoad = capture(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
  28062.       var mothership = uiComponents.uiMothership.element;
  28063.       editor.on('hide', function () {
  28064.         set$7(mothership, 'display', 'none');
  28065.       });
  28066.       editor.on('show', function () {
  28067.         remove$6(mothership, 'display');
  28068.       });
  28069.       editor.on('NodeChange', resizeDocument);
  28070.       editor.on('remove', function () {
  28071.         elementLoad.unbind();
  28072.         dom.unbind(contentWindow, 'resize', resizeWindow);
  28073.         dom.unbind(contentWindow, 'scroll', scroll);
  28074.         contentWindow = null;
  28075.       });
  28076.     };
  28077.     var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  28078.       var lastToolbarWidth = Cell(0);
  28079.       var outerContainer = uiComponents.outerContainer;
  28080.       iframe(editor);
  28081.       var eTargetNode = SugarElement.fromDom(args.targetNode);
  28082.       var uiRoot = getContentContainer(getRootNode(eTargetNode));
  28083.       attachSystemAfter(eTargetNode, uiComponents.mothership);
  28084.       attachSystem(uiRoot, uiComponents.uiMothership);
  28085.       editor.on('PostRender', function () {
  28086.         setToolbar(editor, uiComponents, rawUiConfig, backstage);
  28087.         lastToolbarWidth.set(editor.getWin().innerWidth);
  28088.         OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  28089.         OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
  28090.         setupEvents$1(editor, uiComponents);
  28091.       });
  28092.       var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
  28093.       if (isiOS12) {
  28094.         setAll(socket.element, {
  28095.           'overflow': 'scroll',
  28096.           '-webkit-overflow-scrolling': 'touch'
  28097.         });
  28098.         var limit = first(function () {
  28099.           editor.fire('ScrollContent');
  28100.         }, 20);
  28101.         var unbinder = bind(socket.element, 'scroll', limit.throttle);
  28102.         editor.on('remove', unbinder.unbind);
  28103.       }
  28104.       setupReadonlyModeSwitch(editor, uiComponents);
  28105.       editor.addCommand('ToggleSidebar', function (_ui, value) {
  28106.         OuterContainer.toggleSidebar(outerContainer, value);
  28107.         editor.fire('ToggleSidebar');
  28108.       });
  28109.       editor.addQueryValueHandler('ToggleSidebar', function () {
  28110.         return OuterContainer.whichSidebar(outerContainer);
  28111.       });
  28112.       var toolbarMode = getToolbarMode(editor);
  28113.       var refreshDrawer = function () {
  28114.         OuterContainer.refreshToolbar(uiComponents.outerContainer);
  28115.       };
  28116.       if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  28117.         editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  28118.           var width = editor.getWin().innerWidth;
  28119.           if (width !== lastToolbarWidth.get()) {
  28120.             refreshDrawer();
  28121.             lastToolbarWidth.set(width);
  28122.           }
  28123.         });
  28124.       }
  28125.       var api = {
  28126.         enable: function () {
  28127.           broadcastReadonly(uiComponents, false);
  28128.         },
  28129.         disable: function () {
  28130.           broadcastReadonly(uiComponents, true);
  28131.         },
  28132.         isDisabled: function () {
  28133.           return Disabling.isDisabled(outerContainer);
  28134.         }
  28135.       };
  28136.       return {
  28137.         iframeContainer: socket.element.dom,
  28138.         editorContainer: outerContainer.element.dom,
  28139.         api: api
  28140.       };
  28141.     };
  28142.  
  28143.     var Iframe = /*#__PURE__*/Object.freeze({
  28144.         __proto__: null,
  28145.         render: render$1
  28146.     });
  28147.  
  28148.     var parseToInt = function (val) {
  28149.       var re = /^[0-9\.]+(|px)$/i;
  28150.       if (re.test('' + val)) {
  28151.         return Optional.some(parseInt('' + val, 10));
  28152.       }
  28153.       return Optional.none();
  28154.     };
  28155.     var numToPx = function (val) {
  28156.       return isNumber(val) ? val + 'px' : val;
  28157.     };
  28158.     var calcCappedSize = function (size, minSize, maxSize) {
  28159.       var minOverride = minSize.filter(function (min) {
  28160.         return size < min;
  28161.       });
  28162.       var maxOverride = maxSize.filter(function (max) {
  28163.         return size > max;
  28164.       });
  28165.       return minOverride.or(maxOverride).getOr(size);
  28166.     };
  28167.  
  28168.     var getHeight = function (editor) {
  28169.       var baseHeight = getHeightSetting(editor);
  28170.       var minHeight = getMinHeightSetting(editor);
  28171.       var maxHeight = getMaxHeightSetting(editor);
  28172.       return parseToInt(baseHeight).map(function (height) {
  28173.         return calcCappedSize(height, minHeight, maxHeight);
  28174.       });
  28175.     };
  28176.     var getHeightWithFallback = function (editor) {
  28177.       var height = getHeight(editor);
  28178.       return height.getOr(getHeightSetting(editor));
  28179.     };
  28180.     var getWidth = function (editor) {
  28181.       var baseWidth = getWidthSetting(editor);
  28182.       var minWidth = getMinWidthSetting(editor);
  28183.       var maxWidth = getMaxWidthSetting(editor);
  28184.       return parseToInt(baseWidth).map(function (width) {
  28185.         return calcCappedSize(width, minWidth, maxWidth);
  28186.       });
  28187.     };
  28188.     var getWidthWithFallback = function (editor) {
  28189.       var width = getWidth(editor);
  28190.       return width.getOr(getWidthSetting(editor));
  28191.     };
  28192.  
  28193.     var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
  28194.       var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  28195.       var DOM = global$b.DOM;
  28196.       var useFixedToolbarContainer = useFixedContainer(editor);
  28197.       var isSticky = isStickyToolbar(editor);
  28198.       var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor));
  28199.       var headerBackstage = backstage.shared.header;
  28200.       var isPositionedAtTop = headerBackstage.isPositionedAtTop;
  28201.       var toolbarMode = getToolbarMode(editor);
  28202.       var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  28203.       var visible = Cell(false);
  28204.       var isVisible = function () {
  28205.         return visible.get() && !editor.removed;
  28206.       };
  28207.       var calcToolbarOffset = function (toolbar) {
  28208.         return isSplitToolbar ? toolbar.fold(constant$1(0), function (tbar) {
  28209.           return tbar.components().length > 1 ? get$b(tbar.components()[1].element) : 0;
  28210.         }) : 0;
  28211.       };
  28212.       var calcMode = function (container) {
  28213.         switch (getToolbarLocation(editor)) {
  28214.         case ToolbarLocation.auto:
  28215.           var toolbar_1 = OuterContainer.getToolbar(outerContainer);
  28216.           var offset = calcToolbarOffset(toolbar_1);
  28217.           var toolbarHeight = get$b(container.element) - offset;
  28218.           var targetBounds = box$1(targetElm);
  28219.           var roomAtTop = targetBounds.y > toolbarHeight;
  28220.           if (roomAtTop) {
  28221.             return 'top';
  28222.           } else {
  28223.             var doc = documentElement(targetElm);
  28224.             var docHeight = Math.max(doc.dom.scrollHeight, get$b(doc));
  28225.             var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  28226.             if (roomAtBottom) {
  28227.               return 'bottom';
  28228.             } else {
  28229.               var winBounds = win();
  28230.               var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  28231.               return isRoomAtBottomViewport ? 'bottom' : 'top';
  28232.             }
  28233.           }
  28234.         case ToolbarLocation.bottom:
  28235.           return 'bottom';
  28236.         case ToolbarLocation.top:
  28237.         default:
  28238.           return 'top';
  28239.         }
  28240.       };
  28241.       var setupMode = function (mode) {
  28242.         var container = floatContainer.get();
  28243.         Docking.setModes(container, [mode]);
  28244.         headerBackstage.setDockingMode(mode);
  28245.         var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  28246.         set$8(container.element, Attribute, verticalDir);
  28247.       };
  28248.       var updateChromeWidth = function () {
  28249.         var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  28250.           var bodyMargin = parseToInt(get$c(body(), 'margin-left')).getOr(0);
  28251.           return get$a(body()) - absolute$3(targetElm).left + bodyMargin;
  28252.         });
  28253.         set$7(floatContainer.get().element, 'max-width', maxWidth + 'px');
  28254.       };
  28255.       var updateChromePosition = function () {
  28256.         var toolbar = OuterContainer.getToolbar(outerContainer);
  28257.         var offset = calcToolbarOffset(toolbar);
  28258.         var targetBounds = box$1(targetElm);
  28259.         var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$b(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
  28260.         setAll(outerContainer.element, {
  28261.           position: 'absolute',
  28262.           top: Math.round(top) + 'px',
  28263.           left: Math.round(targetBounds.x) + 'px'
  28264.         });
  28265.       };
  28266.       var repositionPopups$1 = function () {
  28267.         uiMothership.broadcastOn([repositionPopups()], {});
  28268.       };
  28269.       var updateChromeUi = function (resetDocking) {
  28270.         if (resetDocking === void 0) {
  28271.           resetDocking = false;
  28272.         }
  28273.         if (!isVisible()) {
  28274.           return;
  28275.         }
  28276.         if (!useFixedToolbarContainer) {
  28277.           updateChromeWidth();
  28278.         }
  28279.         if (isSplitToolbar) {
  28280.           OuterContainer.refreshToolbar(outerContainer);
  28281.         }
  28282.         if (!useFixedToolbarContainer) {
  28283.           updateChromePosition();
  28284.         }
  28285.         if (isSticky) {
  28286.           var floatContainerComp = floatContainer.get();
  28287.           resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  28288.         }
  28289.         repositionPopups$1();
  28290.       };
  28291.       var updateMode = function (updateUi) {
  28292.         if (updateUi === void 0) {
  28293.           updateUi = true;
  28294.         }
  28295.         if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  28296.           return;
  28297.         }
  28298.         var currentMode = headerBackstage.getDockingMode();
  28299.         var newMode = calcMode(floatContainer.get());
  28300.         if (newMode !== currentMode) {
  28301.           setupMode(newMode);
  28302.           if (updateUi) {
  28303.             updateChromeUi(true);
  28304.           }
  28305.         }
  28306.       };
  28307.       var show = function () {
  28308.         visible.set(true);
  28309.         set$7(outerContainer.element, 'display', 'flex');
  28310.         DOM.addClass(editor.getBody(), 'mce-edit-focus');
  28311.         remove$6(uiMothership.element, 'display');
  28312.         updateMode(false);
  28313.         updateChromeUi();
  28314.       };
  28315.       var hide = function () {
  28316.         visible.set(false);
  28317.         if (uiComponents.outerContainer) {
  28318.           set$7(outerContainer.element, 'display', 'none');
  28319.           DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  28320.         }
  28321.         set$7(uiMothership.element, 'display', 'none');
  28322.       };
  28323.       return {
  28324.         isVisible: isVisible,
  28325.         isPositionedAtTop: isPositionedAtTop,
  28326.         show: show,
  28327.         hide: hide,
  28328.         update: updateChromeUi,
  28329.         updateMode: updateMode,
  28330.         repositionPopups: repositionPopups$1
  28331.       };
  28332.     };
  28333.  
  28334.     var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
  28335.       var bounds = box$1(targetElm);
  28336.       return {
  28337.         pos: isToolbarTop ? bounds.y : bounds.bottom,
  28338.         bounds: bounds
  28339.       };
  28340.     };
  28341.     var setupEvents = function (editor, targetElm, ui, toolbarPersist) {
  28342.       var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  28343.       var resizeContent = function (e) {
  28344.         var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
  28345.         var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
  28346.         var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  28347.         prevPosAndBounds.set({
  28348.           pos: pos,
  28349.           bounds: bounds
  28350.         });
  28351.         if (hasResized) {
  28352.           fireResizeContent(editor, e);
  28353.         }
  28354.         if (ui.isVisible()) {
  28355.           if (prevPos !== pos) {
  28356.             ui.update(true);
  28357.           } else if (hasResized) {
  28358.             ui.updateMode();
  28359.             ui.repositionPopups();
  28360.           }
  28361.         }
  28362.       };
  28363.       if (!toolbarPersist) {
  28364.         editor.on('activate', ui.show);
  28365.         editor.on('deactivate', ui.hide);
  28366.       }
  28367.       editor.on('SkinLoaded ResizeWindow', function () {
  28368.         return ui.update(true);
  28369.       });
  28370.       editor.on('NodeChange keydown', function (e) {
  28371.         global$f.requestAnimationFrame(function () {
  28372.           return resizeContent(e);
  28373.         });
  28374.       });
  28375.       editor.on('ScrollWindow', function () {
  28376.         return ui.updateMode();
  28377.       });
  28378.       var elementLoad = unbindable();
  28379.       elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
  28380.       editor.on('remove', function () {
  28381.         elementLoad.clear();
  28382.       });
  28383.     };
  28384.     var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  28385.       var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  28386.       var floatContainer = Cell(null);
  28387.       var targetElm = SugarElement.fromDom(args.targetNode);
  28388.       var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  28389.       var toolbarPersist = isToolbarPersist(editor);
  28390.       inline(editor);
  28391.       var render = function () {
  28392.         if (floatContainer.get()) {
  28393.           ui.show();
  28394.           return;
  28395.         }
  28396.         floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  28397.         var uiContainer = getUiContainer(editor);
  28398.         attachSystem(uiContainer, mothership);
  28399.         attachSystem(uiContainer, uiMothership);
  28400.         setToolbar(editor, uiComponents, rawUiConfig, backstage);
  28401.         OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  28402.         ui.show();
  28403.         setupEvents(editor, targetElm, ui, toolbarPersist);
  28404.         editor.nodeChanged();
  28405.       };
  28406.       editor.on('show', render);
  28407.       editor.on('hide', ui.hide);
  28408.       if (!toolbarPersist) {
  28409.         editor.on('focus', render);
  28410.         editor.on('blur', ui.hide);
  28411.       }
  28412.       editor.on('init', function () {
  28413.         if (editor.hasFocus() || toolbarPersist) {
  28414.           render();
  28415.         }
  28416.       });
  28417.       setupReadonlyModeSwitch(editor, uiComponents);
  28418.       var api = {
  28419.         show: function () {
  28420.           ui.show();
  28421.         },
  28422.         hide: function () {
  28423.           ui.hide();
  28424.         },
  28425.         enable: function () {
  28426.           broadcastReadonly(uiComponents, false);
  28427.         },
  28428.         disable: function () {
  28429.           broadcastReadonly(uiComponents, true);
  28430.         },
  28431.         isDisabled: function () {
  28432.           return Disabling.isDisabled(outerContainer);
  28433.         }
  28434.       };
  28435.       return {
  28436.         editorContainer: outerContainer.element.dom,
  28437.         api: api
  28438.       };
  28439.     };
  28440.  
  28441.     var Inline = /*#__PURE__*/Object.freeze({
  28442.         __proto__: null,
  28443.         render: render
  28444.     });
  28445.  
  28446.     var showContextToolbarEvent = 'contexttoolbar-show';
  28447.     var hideContextToolbarEvent = 'contexttoolbar-hide';
  28448.  
  28449.     var getFormApi = function (input) {
  28450.       return {
  28451.         hide: function () {
  28452.           return emit(input, sandboxClose());
  28453.         },
  28454.         getValue: function () {
  28455.           return Representing.getValue(input);
  28456.         }
  28457.       };
  28458.     };
  28459.     var runOnExecute = function (memInput, original) {
  28460.       return run$1(internalToolbarButtonExecute, function (comp, se) {
  28461.         var input = memInput.get(comp);
  28462.         var formApi = getFormApi(input);
  28463.         original.onAction(formApi, se.event.buttonApi);
  28464.       });
  28465.     };
  28466.     var renderContextButton = function (memInput, button, extras) {
  28467.       var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  28468.       var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  28469.         type: 'button',
  28470.         onAction: noop
  28471.       })));
  28472.       return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  28473.     };
  28474.     var renderContextToggleButton = function (memInput, button, extras) {
  28475.       var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  28476.       var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  28477.         type: 'togglebutton',
  28478.         onAction: noop
  28479.       })));
  28480.       return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  28481.     };
  28482.     var generateOne = function (memInput, button, providersBackstage) {
  28483.       var extras = { backstage: { shared: { providers: providersBackstage } } };
  28484.       if (button.type === 'contextformtogglebutton') {
  28485.         return renderContextToggleButton(memInput, button, extras);
  28486.       } else {
  28487.         return renderContextButton(memInput, button, extras);
  28488.       }
  28489.     };
  28490.     var generate = function (memInput, buttons, providersBackstage) {
  28491.       var mementos = map$2(buttons, function (button) {
  28492.         return record(generateOne(memInput, button, providersBackstage));
  28493.       });
  28494.       var asSpecs = function () {
  28495.         return map$2(mementos, function (mem) {
  28496.           return mem.asSpec();
  28497.         });
  28498.       };
  28499.       var findPrimary = function (compInSystem) {
  28500.         return findMap(buttons, function (button, i) {
  28501.           if (button.primary) {
  28502.             return Optional.from(mementos[i]).bind(function (mem) {
  28503.               return mem.getOpt(compInSystem);
  28504.             }).filter(not(Disabling.isDisabled));
  28505.           } else {
  28506.             return Optional.none();
  28507.           }
  28508.         });
  28509.       };
  28510.       return {
  28511.         asSpecs: asSpecs,
  28512.         findPrimary: findPrimary
  28513.       };
  28514.     };
  28515.  
  28516.     var buildInitGroups = function (ctx, providers) {
  28517.       var inputAttributes = ctx.label.fold(function () {
  28518.         return {};
  28519.       }, function (label) {
  28520.         return { 'aria-label': label };
  28521.       });
  28522.       var memInput = record(Input.sketch({
  28523.         inputClasses: [
  28524.           'tox-toolbar-textfield',
  28525.           'tox-toolbar-nav-js'
  28526.         ],
  28527.         data: ctx.initValue(),
  28528.         inputAttributes: inputAttributes,
  28529.         selectOnFocus: true,
  28530.         inputBehaviours: derive$1([Keying.config({
  28531.             mode: 'special',
  28532.             onEnter: function (input) {
  28533.               return commands.findPrimary(input).map(function (primary) {
  28534.                 emitExecute(primary);
  28535.                 return true;
  28536.               });
  28537.             },
  28538.             onLeft: function (comp, se) {
  28539.               se.cut();
  28540.               return Optional.none();
  28541.             },
  28542.             onRight: function (comp, se) {
  28543.               se.cut();
  28544.               return Optional.none();
  28545.             }
  28546.           })])
  28547.       }));
  28548.       var commands = generate(memInput, ctx.commands, providers);
  28549.       return [
  28550.         {
  28551.           title: Optional.none(),
  28552.           items: [memInput.asSpec()]
  28553.         },
  28554.         {
  28555.           title: Optional.none(),
  28556.           items: commands.asSpecs()
  28557.         }
  28558.       ];
  28559.     };
  28560.     var renderContextForm = function (toolbarType, ctx, providers) {
  28561.       return renderToolbar({
  28562.         type: toolbarType,
  28563.         uid: generate$6('context-toolbar'),
  28564.         initGroups: buildInitGroups(ctx, providers),
  28565.         onEscape: Optional.none,
  28566.         cyclicKeying: true,
  28567.         providers: providers
  28568.       });
  28569.     };
  28570.     var ContextForm = {
  28571.       renderContextForm: renderContextForm,
  28572.       buildInitGroups: buildInitGroups
  28573.     };
  28574.  
  28575.     var isVerticalOverlap = function (a, b, threshold) {
  28576.       if (threshold === void 0) {
  28577.         threshold = 0.01;
  28578.       }
  28579.       return b.bottom - a.y >= threshold && a.bottom - b.y >= threshold;
  28580.     };
  28581.     var getRangeRect = function (rng) {
  28582.       var rect = rng.getBoundingClientRect();
  28583.       if (rect.height <= 0 && rect.width <= 0) {
  28584.         var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
  28585.         var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
  28586.         return elm.filter(isElement$2).map(function (e) {
  28587.           return e.dom.getBoundingClientRect();
  28588.         }).getOr(rect);
  28589.       } else {
  28590.         return rect;
  28591.       }
  28592.     };
  28593.     var getSelectionBounds = function (editor) {
  28594.       var rng = editor.selection.getRng();
  28595.       var rect = getRangeRect(rng);
  28596.       if (editor.inline) {
  28597.         var scroll_1 = get$9();
  28598.         return bounds(scroll_1.left + rect.left, scroll_1.top + rect.top, rect.width, rect.height);
  28599.       } else {
  28600.         var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
  28601.         return bounds(bodyPos.x + rect.left, bodyPos.y + rect.top, rect.width, rect.height);
  28602.       }
  28603.     };
  28604.     var getAnchorElementBounds = function (editor, lastElement) {
  28605.       return lastElement.filter(inBody).map(absolute$2).getOrThunk(function () {
  28606.         return getSelectionBounds(editor);
  28607.       });
  28608.     };
  28609.     var getHorizontalBounds = function (contentAreaBox, viewportBounds, margin) {
  28610.       var x = Math.max(contentAreaBox.x + margin, viewportBounds.x);
  28611.       var right = Math.min(contentAreaBox.right - margin, viewportBounds.right);
  28612.       return {
  28613.         x: x,
  28614.         width: right - x
  28615.       };
  28616.     };
  28617.     var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) {
  28618.       var container = SugarElement.fromDom(editor.getContainer());
  28619.       var header = descendant(container, '.tox-editor-header').getOr(container);
  28620.       var headerBox = box$1(header);
  28621.       var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  28622.       var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  28623.       if (editor.inline && isToolbarAbove) {
  28624.         return {
  28625.           y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  28626.           bottom: viewportBounds.bottom
  28627.         };
  28628.       }
  28629.       if (editor.inline && !isToolbarAbove) {
  28630.         return {
  28631.           y: viewportBounds.y,
  28632.           bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  28633.         };
  28634.       }
  28635.       var containerBounds = toolbarType === 'line' ? box$1(container) : contentAreaBox;
  28636.       if (isToolbarAbove) {
  28637.         return {
  28638.           y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  28639.           bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
  28640.         };
  28641.       }
  28642.       return {
  28643.         y: Math.max(containerBounds.y + margin, viewportBounds.y),
  28644.         bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  28645.       };
  28646.     };
  28647.     var getContextToolbarBounds = function (editor, sharedBackstage, toolbarType, margin) {
  28648.       if (margin === void 0) {
  28649.         margin = 0;
  28650.       }
  28651.       var viewportBounds = getBounds$3(window);
  28652.       var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  28653.       var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  28654.       var _a = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x = _a.x, width = _a.width;
  28655.       if (editor.inline && !toolbarOrMenubarEnabled) {
  28656.         return bounds(x, viewportBounds.y, width, viewportBounds.height);
  28657.       } else {
  28658.         var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  28659.         var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y = _b.y, bottom = _b.bottom;
  28660.         return bounds(x, y, width, bottom - y);
  28661.       }
  28662.     };
  28663.  
  28664.     var bubbleSize$1 = 12;
  28665.     var bubbleAlignments$1 = {
  28666.       valignCentre: [],
  28667.       alignCentre: [],
  28668.       alignLeft: ['tox-pop--align-left'],
  28669.       alignRight: ['tox-pop--align-right'],
  28670.       right: ['tox-pop--right'],
  28671.       left: ['tox-pop--left'],
  28672.       bottom: ['tox-pop--bottom'],
  28673.       top: ['tox-pop--top'],
  28674.       inset: ['tox-pop--inset']
  28675.     };
  28676.     var anchorOverrides = {
  28677.       maxHeightFunction: expandable$1(),
  28678.       maxWidthFunction: expandable()
  28679.     };
  28680.     var isEntireElementSelected = function (editor, elem) {
  28681.       var rng = editor.selection.getRng();
  28682.       var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  28683.       return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem);
  28684.     };
  28685.     var preservePosition = function (elem, position, f) {
  28686.       var currentPosition = getRaw(elem, 'position');
  28687.       set$7(elem, 'position', position);
  28688.       var result = f(elem);
  28689.       currentPosition.each(function (pos) {
  28690.         return set$7(elem, 'position', pos);
  28691.       });
  28692.       return result;
  28693.     };
  28694.     var shouldUseInsetLayouts = function (position) {
  28695.       return position === 'node';
  28696.     };
  28697.     var determineInsetLayout = function (editor, contextbar, elem, data, bounds) {
  28698.       var selectionBounds = getSelectionBounds(editor);
  28699.       var isSameAnchorElement = data.lastElement().exists(function (prev) {
  28700.         return eq(elem, prev);
  28701.       });
  28702.       if (isEntireElementSelected(editor, elem)) {
  28703.         return isSameAnchorElement ? preserve : north;
  28704.       } else if (isSameAnchorElement) {
  28705.         return preservePosition(contextbar, data.getMode(), function () {
  28706.           var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
  28707.           return isOverlapping && !data.isReposition() ? flip$2 : preserve;
  28708.         });
  28709.       } else {
  28710.         var yBounds = data.getMode() === 'fixed' ? bounds.y + get$9().top : bounds.y;
  28711.         var contextbarHeight = get$b(contextbar) + bubbleSize$1;
  28712.         return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
  28713.       }
  28714.     };
  28715.     var getAnchorSpec$2 = function (editor, mobile, data, position) {
  28716.       var smartInsetLayout = function (elem) {
  28717.         return function (anchor, element, bubbles, placee, bounds) {
  28718.           var layout = determineInsetLayout(editor, placee, elem, data, bounds);
  28719.           var newAnchor = __assign(__assign({}, anchor), {
  28720.             y: bounds.y,
  28721.             height: bounds.height
  28722.           });
  28723.           return __assign(__assign({}, layout(newAnchor, element, bubbles, placee, bounds)), { alwaysFit: true });
  28724.         };
  28725.       };
  28726.       var getInsetLayouts = function (elem) {
  28727.         return shouldUseInsetLayouts(position) ? [smartInsetLayout(elem)] : [];
  28728.       };
  28729.       var desktopAnchorSpecLayouts = {
  28730.         onLtr: function (elem) {
  28731.           return [
  28732.             north$2,
  28733.             south$2,
  28734.             northeast$2,
  28735.             southeast$2,
  28736.             northwest$2,
  28737.             southwest$2
  28738.           ].concat(getInsetLayouts(elem));
  28739.         },
  28740.         onRtl: function (elem) {
  28741.           return [
  28742.             north$2,
  28743.             south$2,
  28744.             northwest$2,
  28745.             southwest$2,
  28746.             northeast$2,
  28747.             southeast$2
  28748.           ].concat(getInsetLayouts(elem));
  28749.         }
  28750.       };
  28751.       var mobileAnchorSpecLayouts = {
  28752.         onLtr: function (elem) {
  28753.           return [
  28754.             south$2,
  28755.             southeast$2,
  28756.             southwest$2,
  28757.             northeast$2,
  28758.             northwest$2,
  28759.             north$2
  28760.           ].concat(getInsetLayouts(elem));
  28761.         },
  28762.         onRtl: function (elem) {
  28763.           return [
  28764.             south$2,
  28765.             southwest$2,
  28766.             southeast$2,
  28767.             northwest$2,
  28768.             northeast$2,
  28769.             north$2
  28770.           ].concat(getInsetLayouts(elem));
  28771.         }
  28772.       };
  28773.       return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
  28774.     };
  28775.     var getAnchorLayout = function (editor, position, isTouch, data) {
  28776.       if (position === 'line') {
  28777.         return {
  28778.           bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
  28779.           layouts: {
  28780.             onLtr: function () {
  28781.               return [east$2];
  28782.             },
  28783.             onRtl: function () {
  28784.               return [west$2];
  28785.             }
  28786.           },
  28787.           overrides: anchorOverrides
  28788.         };
  28789.       } else {
  28790.         return {
  28791.           bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
  28792.           layouts: getAnchorSpec$2(editor, isTouch, data, position),
  28793.           overrides: anchorOverrides
  28794.         };
  28795.       }
  28796.     };
  28797.  
  28798.     var matchTargetWith = function (elem, candidates) {
  28799.       var ctxs = filter$2(candidates, function (toolbarApi) {
  28800.         return toolbarApi.predicate(elem.dom);
  28801.       });
  28802.       var _a = partition$3(ctxs, function (t) {
  28803.           return t.type === 'contexttoolbar';
  28804.         }), pass = _a.pass, fail = _a.fail;
  28805.       return {
  28806.         contextToolbars: pass,
  28807.         contextForms: fail
  28808.       };
  28809.     };
  28810.     var filterByPositionForStartNode = function (toolbars) {
  28811.       if (toolbars.length <= 1) {
  28812.         return toolbars;
  28813.       } else {
  28814.         var doesPositionExist = function (value) {
  28815.           return exists(toolbars, function (t) {
  28816.             return t.position === value;
  28817.           });
  28818.         };
  28819.         var filterToolbarsByPosition = function (value) {
  28820.           return filter$2(toolbars, function (t) {
  28821.             return t.position === value;
  28822.           });
  28823.         };
  28824.         var hasSelectionToolbars = doesPositionExist('selection');
  28825.         var hasNodeToolbars = doesPositionExist('node');
  28826.         if (hasSelectionToolbars || hasNodeToolbars) {
  28827.           if (hasNodeToolbars && hasSelectionToolbars) {
  28828.             var nodeToolbars = filterToolbarsByPosition('node');
  28829.             var selectionToolbars = map$2(filterToolbarsByPosition('selection'), function (t) {
  28830.               return __assign(__assign({}, t), { position: 'node' });
  28831.             });
  28832.             return nodeToolbars.concat(selectionToolbars);
  28833.           } else {
  28834.             return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  28835.           }
  28836.         } else {
  28837.           return filterToolbarsByPosition('line');
  28838.         }
  28839.       }
  28840.     };
  28841.     var filterByPositionForAncestorNode = function (toolbars) {
  28842.       if (toolbars.length <= 1) {
  28843.         return toolbars;
  28844.       } else {
  28845.         var findPosition_1 = function (value) {
  28846.           return find$5(toolbars, function (t) {
  28847.             return t.position === value;
  28848.           });
  28849.         };
  28850.         var basePosition = findPosition_1('selection').orThunk(function () {
  28851.           return findPosition_1('node');
  28852.         }).orThunk(function () {
  28853.           return findPosition_1('line');
  28854.         }).map(function (t) {
  28855.           return t.position;
  28856.         });
  28857.         return basePosition.fold(function () {
  28858.           return [];
  28859.         }, function (pos) {
  28860.           return filter$2(toolbars, function (t) {
  28861.             return t.position === pos;
  28862.           });
  28863.         });
  28864.       }
  28865.     };
  28866.     var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
  28867.       var nodeMatches = matchTargetWith(elem, nodeCandidates);
  28868.       if (nodeMatches.contextForms.length > 0) {
  28869.         return Optional.some({
  28870.           elem: elem,
  28871.           toolbars: [nodeMatches.contextForms[0]]
  28872.         });
  28873.       } else {
  28874.         var editorMatches = matchTargetWith(elem, editorCandidates);
  28875.         if (editorMatches.contextForms.length > 0) {
  28876.           return Optional.some({
  28877.             elem: elem,
  28878.             toolbars: [editorMatches.contextForms[0]]
  28879.           });
  28880.         } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  28881.           var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  28882.           return Optional.some({
  28883.             elem: elem,
  28884.             toolbars: toolbars
  28885.           });
  28886.         } else {
  28887.           return Optional.none();
  28888.         }
  28889.       }
  28890.     };
  28891.     var matchAncestor = function (isRoot, startNode, scopes) {
  28892.       if (isRoot(startNode)) {
  28893.         return Optional.none();
  28894.       } else {
  28895.         return ancestor$2(startNode, function (ancestorElem) {
  28896.           if (isElement$2(ancestorElem)) {
  28897.             var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
  28898.             var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  28899.             return toolbars.length > 0 ? Optional.some({
  28900.               elem: ancestorElem,
  28901.               toolbars: toolbars
  28902.             }) : Optional.none();
  28903.           } else {
  28904.             return Optional.none();
  28905.           }
  28906.         }, isRoot);
  28907.       }
  28908.     };
  28909.     var lookup$1 = function (scopes, editor) {
  28910.       var rootElem = SugarElement.fromDom(editor.getBody());
  28911.       var isRoot = function (elem) {
  28912.         return eq(elem, rootElem);
  28913.       };
  28914.       var isOutsideRoot = function (startNode) {
  28915.         return !isRoot(startNode) && !contains(rootElem, startNode);
  28916.       };
  28917.       var startNode = SugarElement.fromDom(editor.selection.getNode());
  28918.       if (isOutsideRoot(startNode)) {
  28919.         return Optional.none();
  28920.       }
  28921.       return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
  28922.         return matchAncestor(isRoot, startNode, scopes);
  28923.       });
  28924.     };
  28925.  
  28926.     var categorise = function (contextToolbars, navigate) {
  28927.       var forms = {};
  28928.       var inNodeScope = [];
  28929.       var inEditorScope = [];
  28930.       var formNavigators = {};
  28931.       var lookupTable = {};
  28932.       var registerForm = function (key, toolbarSpec) {
  28933.         var contextForm = getOrDie(createContextForm(toolbarSpec));
  28934.         forms[key] = contextForm;
  28935.         contextForm.launch.map(function (launch) {
  28936.           formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), {
  28937.             type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  28938.             onAction: function () {
  28939.               navigate(contextForm);
  28940.             }
  28941.           });
  28942.         });
  28943.         if (contextForm.scope === 'editor') {
  28944.           inEditorScope.push(contextForm);
  28945.         } else {
  28946.           inNodeScope.push(contextForm);
  28947.         }
  28948.         lookupTable[key] = contextForm;
  28949.       };
  28950.       var registerToolbar = function (key, toolbarSpec) {
  28951.         createContextToolbar(toolbarSpec).each(function (contextToolbar) {
  28952.           if (toolbarSpec.scope === 'editor') {
  28953.             inEditorScope.push(contextToolbar);
  28954.           } else {
  28955.             inNodeScope.push(contextToolbar);
  28956.           }
  28957.           lookupTable[key] = contextToolbar;
  28958.         });
  28959.       };
  28960.       var keys$1 = keys(contextToolbars);
  28961.       each$1(keys$1, function (key) {
  28962.         var toolbarApi = contextToolbars[key];
  28963.         if (toolbarApi.type === 'contextform') {
  28964.           registerForm(key, toolbarApi);
  28965.         } else if (toolbarApi.type === 'contexttoolbar') {
  28966.           registerToolbar(key, toolbarApi);
  28967.         }
  28968.       });
  28969.       return {
  28970.         forms: forms,
  28971.         inNodeScope: inNodeScope,
  28972.         inEditorScope: inEditorScope,
  28973.         lookupTable: lookupTable,
  28974.         formNavigators: formNavigators
  28975.       };
  28976.     };
  28977.  
  28978.     var forwardSlideEvent = generate$6('forward-slide');
  28979.     var backSlideEvent = generate$6('backward-slide');
  28980.     var changeSlideEvent = generate$6('change-slide-event');
  28981.     var resizingClass = 'tox-pop--resizing';
  28982.     var renderContextToolbar = function (spec) {
  28983.       var stack = Cell([]);
  28984.       return InlineView.sketch({
  28985.         dom: {
  28986.           tag: 'div',
  28987.           classes: ['tox-pop']
  28988.         },
  28989.         fireDismissalEventInstead: { event: 'doNotDismissYet' },
  28990.         onShow: function (comp) {
  28991.           stack.set([]);
  28992.           InlineView.getContent(comp).each(function (c) {
  28993.             remove$6(c.element, 'visibility');
  28994.           });
  28995.           remove$2(comp.element, resizingClass);
  28996.           remove$6(comp.element, 'width');
  28997.         },
  28998.         inlineBehaviours: derive$1([
  28999.           config('context-toolbar-events', [
  29000.             runOnSource(transitionend(), function (comp, se) {
  29001.               if (se.event.raw.propertyName === 'width') {
  29002.                 remove$2(comp.element, resizingClass);
  29003.                 remove$6(comp.element, 'width');
  29004.               }
  29005.             }),
  29006.             run$1(changeSlideEvent, function (comp, se) {
  29007.               var elem = comp.element;
  29008.               remove$6(elem, 'width');
  29009.               var currentWidth = get$a(elem);
  29010.               InlineView.setContent(comp, se.event.contents);
  29011.               add$2(elem, resizingClass);
  29012.               var newWidth = get$a(elem);
  29013.               set$7(elem, 'width', currentWidth + 'px');
  29014.               InlineView.getContent(comp).each(function (newContents) {
  29015.                 se.event.focus.bind(function (f) {
  29016.                   focus$3(f);
  29017.                   return search(elem);
  29018.                 }).orThunk(function () {
  29019.                   Keying.focusIn(newContents);
  29020.                   return active(getRootNode(elem));
  29021.                 });
  29022.               });
  29023.               global$f.setTimeout(function () {
  29024.                 set$7(comp.element, 'width', newWidth + 'px');
  29025.               }, 0);
  29026.             }),
  29027.             run$1(forwardSlideEvent, function (comp, se) {
  29028.               InlineView.getContent(comp).each(function (oldContents) {
  29029.                 stack.set(stack.get().concat([{
  29030.                     bar: oldContents,
  29031.                     focus: active(getRootNode(comp.element))
  29032.                   }]));
  29033.               });
  29034.               emitWith(comp, changeSlideEvent, {
  29035.                 contents: se.event.forwardContents,
  29036.                 focus: Optional.none()
  29037.               });
  29038.             }),
  29039.             run$1(backSlideEvent, function (comp, _se) {
  29040.               last$2(stack.get()).each(function (last) {
  29041.                 stack.set(stack.get().slice(0, stack.get().length - 1));
  29042.                 emitWith(comp, changeSlideEvent, {
  29043.                   contents: premade(last.bar),
  29044.                   focus: last.focus
  29045.                 });
  29046.               });
  29047.             })
  29048.           ]),
  29049.           Keying.config({
  29050.             mode: 'special',
  29051.             onEscape: function (comp) {
  29052.               return last$2(stack.get()).fold(function () {
  29053.                 return spec.onEscape();
  29054.               }, function (_) {
  29055.                 emit(comp, backSlideEvent);
  29056.                 return Optional.some(true);
  29057.               });
  29058.             }
  29059.           })
  29060.         ]),
  29061.         lazySink: function () {
  29062.           return Result.value(spec.sink);
  29063.         }
  29064.       });
  29065.     };
  29066.  
  29067.     var transitionClass = 'tox-pop--transition';
  29068.     var register$7 = function (editor, registryContextToolbars, sink, extras) {
  29069.       var backstage = extras.backstage;
  29070.       var sharedBackstage = backstage.shared;
  29071.       var isTouch = detect$1().deviceType.isTouch;
  29072.       var lastElement = value$1();
  29073.       var lastTrigger = value$1();
  29074.       var lastContextPosition = value$1();
  29075.       var contextbar = build$1(renderContextToolbar({
  29076.         sink: sink,
  29077.         onEscape: function () {
  29078.           editor.focus();
  29079.           return Optional.some(true);
  29080.         }
  29081.       }));
  29082.       var getBounds = function () {
  29083.         var position = lastContextPosition.get().getOr('node');
  29084.         var margin = shouldUseInsetLayouts(position) ? 1 : 0;
  29085.         return getContextToolbarBounds(editor, sharedBackstage, position, margin);
  29086.       };
  29087.       var canLaunchToolbar = function () {
  29088.         return !editor.removed && !(isTouch() && backstage.isContextMenuOpen());
  29089.       };
  29090.       var isSameLaunchElement = function (elem) {
  29091.         return is$1(lift2(elem, lastElement.get(), eq), true);
  29092.       };
  29093.       var shouldContextToolbarHide = function () {
  29094.         if (!canLaunchToolbar()) {
  29095.           return true;
  29096.         } else {
  29097.           var contextToolbarBounds = getBounds();
  29098.           var anchorBounds = is$1(lastContextPosition.get(), 'node') ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
  29099.           return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
  29100.         }
  29101.       };
  29102.       var close = function () {
  29103.         lastElement.clear();
  29104.         lastTrigger.clear();
  29105.         lastContextPosition.clear();
  29106.         InlineView.hide(contextbar);
  29107.       };
  29108.       var hideOrRepositionIfNecessary = function () {
  29109.         if (InlineView.isOpen(contextbar)) {
  29110.           var contextBarEle = contextbar.element;
  29111.           remove$6(contextBarEle, 'display');
  29112.           if (shouldContextToolbarHide()) {
  29113.             set$7(contextBarEle, 'display', 'none');
  29114.           } else {
  29115.             lastTrigger.set(0);
  29116.             InlineView.reposition(contextbar);
  29117.           }
  29118.         }
  29119.       };
  29120.       var wrapInPopDialog = function (toolbarSpec) {
  29121.         return {
  29122.           dom: {
  29123.             tag: 'div',
  29124.             classes: ['tox-pop__dialog']
  29125.           },
  29126.           components: [toolbarSpec],
  29127.           behaviours: derive$1([
  29128.             Keying.config({ mode: 'acyclic' }),
  29129.             config('pop-dialog-wrap-events', [
  29130.               runOnAttached(function (comp) {
  29131.                 editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  29132.                   return Keying.focusIn(comp);
  29133.                 });
  29134.               }),
  29135.               runOnDetached(function (_comp) {
  29136.                 editor.shortcuts.remove('ctrl+F9');
  29137.               })
  29138.             ])
  29139.           ])
  29140.         };
  29141.       };
  29142.       var getScopes = cached(function () {
  29143.         return categorise(registryContextToolbars, function (toolbarApi) {
  29144.           var alloySpec = buildToolbar([toolbarApi]);
  29145.           emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  29146.         });
  29147.       });
  29148.       var buildContextToolbarGroups = function (allButtons, ctx) {
  29149.         return identifyButtons(editor, {
  29150.           buttons: allButtons,
  29151.           toolbar: ctx.items,
  29152.           allowToolbarGroups: false
  29153.         }, extras, Optional.some(['form:']));
  29154.       };
  29155.       var buildContextFormGroups = function (ctx, providers) {
  29156.         return ContextForm.buildInitGroups(ctx, providers);
  29157.       };
  29158.       var buildToolbar = function (toolbars) {
  29159.         var buttons = editor.ui.registry.getAll().buttons;
  29160.         var scopes = getScopes();
  29161.         var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  29162.         var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  29163.         var initGroups = flatten(map$2(toolbars, function (ctx) {
  29164.           return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers);
  29165.         }));
  29166.         return renderToolbar({
  29167.           type: toolbarType,
  29168.           uid: generate$6('context-toolbar'),
  29169.           initGroups: initGroups,
  29170.           onEscape: Optional.none,
  29171.           cyclicKeying: true,
  29172.           providers: sharedBackstage.providers
  29173.         });
  29174.       };
  29175.       var getAnchor = function (position, element) {
  29176.         var anchorage = position === 'node' ? sharedBackstage.anchors.node(element) : sharedBackstage.anchors.cursor();
  29177.         var anchorLayout = getAnchorLayout(editor, position, isTouch(), {
  29178.           lastElement: lastElement.get,
  29179.           isReposition: function () {
  29180.             return is$1(lastTrigger.get(), 0);
  29181.           },
  29182.           getMode: function () {
  29183.             return Positioning.getMode(sink);
  29184.           }
  29185.         });
  29186.         return deepMerge(anchorage, anchorLayout);
  29187.       };
  29188.       var launchContext = function (toolbarApi, elem) {
  29189.         launchContextToolbar.cancel();
  29190.         if (!canLaunchToolbar()) {
  29191.           return;
  29192.         }
  29193.         var toolbarSpec = buildToolbar(toolbarApi);
  29194.         var position = toolbarApi[0].position;
  29195.         var anchor = getAnchor(position, elem);
  29196.         lastContextPosition.set(position);
  29197.         lastTrigger.set(1);
  29198.         var contextBarEle = contextbar.element;
  29199.         remove$6(contextBarEle, 'display');
  29200.         if (!isSameLaunchElement(elem)) {
  29201.           remove$2(contextBarEle, transitionClass);
  29202.           Positioning.reset(sink, contextbar);
  29203.         }
  29204.         InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
  29205.           anchor: anchor,
  29206.           transition: {
  29207.             classes: [transitionClass],
  29208.             mode: 'placement'
  29209.           }
  29210.         }, function () {
  29211.           return Optional.some(getBounds());
  29212.         });
  29213.         elem.fold(lastElement.clear, lastElement.set);
  29214.         if (shouldContextToolbarHide()) {
  29215.           set$7(contextBarEle, 'display', 'none');
  29216.         }
  29217.       };
  29218.       var launchContextToolbar = last(function () {
  29219.         if (!editor.hasFocus() || editor.removed) {
  29220.           return;
  29221.         }
  29222.         if (has(contextbar.element, transitionClass)) {
  29223.           launchContextToolbar.throttle();
  29224.         } else {
  29225.           var scopes = getScopes();
  29226.           lookup$1(scopes, editor).fold(close, function (info) {
  29227.             launchContext(info.toolbars, Optional.some(info.elem));
  29228.           });
  29229.         }
  29230.       }, 17);
  29231.       editor.on('init', function () {
  29232.         editor.on('remove', close);
  29233.         editor.on('ScrollContent ScrollWindow ObjectResized ResizeEditor longpress', hideOrRepositionIfNecessary);
  29234.         editor.on('click keyup focus SetContent', launchContextToolbar.throttle);
  29235.         editor.on(hideContextToolbarEvent, close);
  29236.         editor.on(showContextToolbarEvent, function (e) {
  29237.           var scopes = getScopes();
  29238.           get$e(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  29239.             launchContext([ctx], someIf(e.target !== editor, e.target));
  29240.             InlineView.getContent(contextbar).each(Keying.focusIn);
  29241.           });
  29242.         });
  29243.         editor.on('focusout', function (_e) {
  29244.           global$f.setEditorTimeout(editor, function () {
  29245.             if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
  29246.               close();
  29247.             }
  29248.           }, 0);
  29249.         });
  29250.         editor.on('SwitchMode', function () {
  29251.           if (editor.mode.isReadOnly()) {
  29252.             close();
  29253.           }
  29254.         });
  29255.         editor.on('AfterProgressState', function (event) {
  29256.           if (event.state) {
  29257.             close();
  29258.           } else if (editor.hasFocus()) {
  29259.             launchContextToolbar.throttle();
  29260.           }
  29261.         });
  29262.         editor.on('NodeChange', function (_e) {
  29263.           search(contextbar.element).fold(launchContextToolbar.throttle, noop);
  29264.         });
  29265.       });
  29266.     };
  29267.  
  29268.     var register$6 = function (editor) {
  29269.       var alignToolbarButtons = [
  29270.         {
  29271.           name: 'alignleft',
  29272.           text: 'Align left',
  29273.           cmd: 'JustifyLeft',
  29274.           icon: 'align-left'
  29275.         },
  29276.         {
  29277.           name: 'aligncenter',
  29278.           text: 'Align center',
  29279.           cmd: 'JustifyCenter',
  29280.           icon: 'align-center'
  29281.         },
  29282.         {
  29283.           name: 'alignright',
  29284.           text: 'Align right',
  29285.           cmd: 'JustifyRight',
  29286.           icon: 'align-right'
  29287.         },
  29288.         {
  29289.           name: 'alignjustify',
  29290.           text: 'Justify',
  29291.           cmd: 'JustifyFull',
  29292.           icon: 'align-justify'
  29293.         }
  29294.       ];
  29295.       each$1(alignToolbarButtons, function (item) {
  29296.         editor.ui.registry.addToggleButton(item.name, {
  29297.           tooltip: item.text,
  29298.           icon: item.icon,
  29299.           onAction: onActionExecCommand(editor, item.cmd),
  29300.           onSetup: onSetupFormatToggle(editor, item.name)
  29301.         });
  29302.       });
  29303.       editor.ui.registry.addButton('alignnone', {
  29304.         tooltip: 'No alignment',
  29305.         icon: 'align-none',
  29306.         onAction: onActionExecCommand(editor, 'JustifyNone')
  29307.       });
  29308.     };
  29309.  
  29310.     var units = {
  29311.       unsupportedLength: [
  29312.         'em',
  29313.         'ex',
  29314.         'cap',
  29315.         'ch',
  29316.         'ic',
  29317.         'rem',
  29318.         'lh',
  29319.         'rlh',
  29320.         'vw',
  29321.         'vh',
  29322.         'vi',
  29323.         'vb',
  29324.         'vmin',
  29325.         'vmax',
  29326.         'cm',
  29327.         'mm',
  29328.         'Q',
  29329.         'in',
  29330.         'pc',
  29331.         'pt',
  29332.         'px'
  29333.       ],
  29334.       fixed: [
  29335.         'px',
  29336.         'pt'
  29337.       ],
  29338.       relative: ['%'],
  29339.       empty: ['']
  29340.     };
  29341.     var pattern = function () {
  29342.       var decimalDigits = '[0-9]+';
  29343.       var signedInteger = '[+-]?' + decimalDigits;
  29344.       var exponentPart = '[eE]' + signedInteger;
  29345.       var dot = '\\.';
  29346.       var opt = function (input) {
  29347.         return '(?:' + input + ')?';
  29348.       };
  29349.       var unsignedDecimalLiteral = [
  29350.         'Infinity',
  29351.         decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  29352.         dot + decimalDigits + opt(exponentPart),
  29353.         decimalDigits + opt(exponentPart)
  29354.       ].join('|');
  29355.       var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  29356.       return new RegExp('^(' + float + ')(.*)$');
  29357.     }();
  29358.     var isUnit = function (unit, accepted) {
  29359.       return exists(accepted, function (acc) {
  29360.         return exists(units[acc], function (check) {
  29361.           return unit === check;
  29362.         });
  29363.       });
  29364.     };
  29365.     var parse = function (input, accepted) {
  29366.       var match = Optional.from(pattern.exec(input));
  29367.       return match.bind(function (array) {
  29368.         var value = Number(array[1]);
  29369.         var unitRaw = array[2];
  29370.         if (isUnit(unitRaw, accepted)) {
  29371.           return Optional.some({
  29372.             value: value,
  29373.             unit: unitRaw
  29374.           });
  29375.         } else {
  29376.           return Optional.none();
  29377.         }
  29378.       });
  29379.     };
  29380.     var normalise = function (input, accepted) {
  29381.       return parse(input, accepted).map(function (_a) {
  29382.         var value = _a.value, unit = _a.unit;
  29383.         return value + unit;
  29384.       });
  29385.     };
  29386.  
  29387.     var registerController = function (editor, spec) {
  29388.       var getMenuItems = function () {
  29389.         var options = spec.getOptions(editor);
  29390.         var initial = spec.getCurrent(editor).map(spec.hash);
  29391.         var current = value$1();
  29392.         return map$2(options, function (value) {
  29393.           return {
  29394.             type: 'togglemenuitem',
  29395.             text: spec.display(value),
  29396.             onSetup: function (api) {
  29397.               var setActive = function (active) {
  29398.                 if (active) {
  29399.                   current.on(function (oldApi) {
  29400.                     return oldApi.setActive(false);
  29401.                   });
  29402.                   current.set(api);
  29403.                 }
  29404.                 api.setActive(active);
  29405.               };
  29406.               setActive(is$1(initial, spec.hash(value)));
  29407.               var unbindWatcher = spec.watcher(editor, value, setActive);
  29408.               return function () {
  29409.                 current.clear();
  29410.                 unbindWatcher();
  29411.               };
  29412.             },
  29413.             onAction: function () {
  29414.               return spec.setCurrent(editor, value);
  29415.             }
  29416.           };
  29417.         });
  29418.       };
  29419.       editor.ui.registry.addMenuButton(spec.name, {
  29420.         tooltip: spec.text,
  29421.         icon: spec.icon,
  29422.         fetch: function (callback) {
  29423.           return callback(getMenuItems());
  29424.         },
  29425.         onSetup: spec.onToolbarSetup
  29426.       });
  29427.       editor.ui.registry.addNestedMenuItem(spec.name, {
  29428.         type: 'nestedmenuitem',
  29429.         text: spec.text,
  29430.         getSubmenuItems: getMenuItems,
  29431.         onSetup: spec.onMenuSetup
  29432.       });
  29433.     };
  29434.     var lineHeightSpec = {
  29435.       name: 'lineheight',
  29436.       text: 'Line height',
  29437.       icon: 'line-height',
  29438.       getOptions: getLineHeightFormats,
  29439.       hash: function (input) {
  29440.         return normalise(input, [
  29441.           'fixed',
  29442.           'relative',
  29443.           'empty'
  29444.         ]).getOr(input);
  29445.       },
  29446.       display: identity$1,
  29447.       watcher: function (editor, value, callback) {
  29448.         return editor.formatter.formatChanged('lineheight', callback, false, { value: value }).unbind;
  29449.       },
  29450.       getCurrent: function (editor) {
  29451.         return Optional.from(editor.queryCommandValue('LineHeight'));
  29452.       },
  29453.       setCurrent: function (editor, value) {
  29454.         return editor.execCommand('LineHeight', false, value);
  29455.       }
  29456.     };
  29457.     var languageSpec = function (editor) {
  29458.       var settingsOpt = Optional.from(getContentLanguages(editor));
  29459.       return settingsOpt.map(function (settings) {
  29460.         return {
  29461.           name: 'language',
  29462.           text: 'Language',
  29463.           icon: 'language',
  29464.           getOptions: constant$1(settings),
  29465.           hash: function (input) {
  29466.             return isUndefined(input.customCode) ? input.code : input.code + '/' + input.customCode;
  29467.           },
  29468.           display: function (input) {
  29469.             return input.title;
  29470.           },
  29471.           watcher: function (editor, value, callback) {
  29472.             return editor.formatter.formatChanged('lang', callback, false, {
  29473.               value: value.code,
  29474.               customValue: value.customCode
  29475.             }).unbind;
  29476.           },
  29477.           getCurrent: function (editor) {
  29478.             var node = SugarElement.fromDom(editor.selection.getNode());
  29479.             return closest$4(node, function (n) {
  29480.               return Optional.some(n).filter(isElement$2).bind(function (ele) {
  29481.                 var codeOpt = getOpt(ele, 'lang');
  29482.                 return codeOpt.map(function (code) {
  29483.                   var customCode = getOpt(ele, 'data-mce-lang').getOrUndefined();
  29484.                   return {
  29485.                     code: code,
  29486.                     customCode: customCode,
  29487.                     title: ''
  29488.                   };
  29489.                 });
  29490.               });
  29491.             });
  29492.           },
  29493.           setCurrent: function (editor, lang) {
  29494.             return editor.execCommand('Lang', false, lang);
  29495.           },
  29496.           onToolbarSetup: function (api) {
  29497.             var unbinder = unbindable();
  29498.             api.setActive(editor.formatter.match('lang', {}, undefined, true));
  29499.             unbinder.set(editor.formatter.formatChanged('lang', api.setActive, true));
  29500.             return unbinder.clear;
  29501.           }
  29502.         };
  29503.       });
  29504.     };
  29505.     var register$5 = function (editor) {
  29506.       registerController(editor, lineHeightSpec);
  29507.       languageSpec(editor).each(function (spec) {
  29508.         return registerController(editor, spec);
  29509.       });
  29510.     };
  29511.  
  29512.     var register$4 = function (editor, backstage) {
  29513.       alignSelectMenu(editor, backstage);
  29514.       fontSelectMenu(editor, backstage);
  29515.       styleSelectMenu(editor, backstage);
  29516.       formatSelectMenu(editor, backstage);
  29517.       fontsizeSelectMenu(editor, backstage);
  29518.     };
  29519.  
  29520.     var onSetupOutdentState = function (editor) {
  29521.       return onSetupEvent(editor, 'NodeChange', function (api) {
  29522.         api.setDisabled(!editor.queryCommandState('outdent'));
  29523.       });
  29524.     };
  29525.     var registerButtons$2 = function (editor) {
  29526.       editor.ui.registry.addButton('outdent', {
  29527.         tooltip: 'Decrease indent',
  29528.         icon: 'outdent',
  29529.         onSetup: onSetupOutdentState(editor),
  29530.         onAction: onActionExecCommand(editor, 'outdent')
  29531.       });
  29532.       editor.ui.registry.addButton('indent', {
  29533.         tooltip: 'Increase indent',
  29534.         icon: 'indent',
  29535.         onAction: onActionExecCommand(editor, 'indent')
  29536.       });
  29537.     };
  29538.     var register$3 = function (editor) {
  29539.       registerButtons$2(editor);
  29540.     };
  29541.  
  29542.     var onActionToggleFormat = function (editor, fmt) {
  29543.       return function () {
  29544.         editor.execCommand('mceToggleFormat', false, fmt);
  29545.       };
  29546.     };
  29547.     var registerFormatButtons = function (editor) {
  29548.       global$5.each([
  29549.         {
  29550.           name: 'bold',
  29551.           text: 'Bold',
  29552.           icon: 'bold'
  29553.         },
  29554.         {
  29555.           name: 'italic',
  29556.           text: 'Italic',
  29557.           icon: 'italic'
  29558.         },
  29559.         {
  29560.           name: 'underline',
  29561.           text: 'Underline',
  29562.           icon: 'underline'
  29563.         },
  29564.         {
  29565.           name: 'strikethrough',
  29566.           text: 'Strikethrough',
  29567.           icon: 'strike-through'
  29568.         },
  29569.         {
  29570.           name: 'subscript',
  29571.           text: 'Subscript',
  29572.           icon: 'subscript'
  29573.         },
  29574.         {
  29575.           name: 'superscript',
  29576.           text: 'Superscript',
  29577.           icon: 'superscript'
  29578.         }
  29579.       ], function (btn, _idx) {
  29580.         editor.ui.registry.addToggleButton(btn.name, {
  29581.           tooltip: btn.text,
  29582.           icon: btn.icon,
  29583.           onSetup: onSetupFormatToggle(editor, btn.name),
  29584.           onAction: onActionToggleFormat(editor, btn.name)
  29585.         });
  29586.       });
  29587.       for (var i = 1; i <= 6; i++) {
  29588.         var name_1 = 'h' + i;
  29589.         editor.ui.registry.addToggleButton(name_1, {
  29590.           text: name_1.toUpperCase(),
  29591.           tooltip: 'Heading ' + i,
  29592.           onSetup: onSetupFormatToggle(editor, name_1),
  29593.           onAction: onActionToggleFormat(editor, name_1)
  29594.         });
  29595.       }
  29596.     };
  29597.     var registerCommandButtons = function (editor) {
  29598.       global$5.each([
  29599.         {
  29600.           name: 'cut',
  29601.           text: 'Cut',
  29602.           action: 'Cut',
  29603.           icon: 'cut'
  29604.         },
  29605.         {
  29606.           name: 'copy',
  29607.           text: 'Copy',
  29608.           action: 'Copy',
  29609.           icon: 'copy'
  29610.         },
  29611.         {
  29612.           name: 'paste',
  29613.           text: 'Paste',
  29614.           action: 'Paste',
  29615.           icon: 'paste'
  29616.         },
  29617.         {
  29618.           name: 'help',
  29619.           text: 'Help',
  29620.           action: 'mceHelp',
  29621.           icon: 'help'
  29622.         },
  29623.         {
  29624.           name: 'selectall',
  29625.           text: 'Select all',
  29626.           action: 'SelectAll',
  29627.           icon: 'select-all'
  29628.         },
  29629.         {
  29630.           name: 'newdocument',
  29631.           text: 'New document',
  29632.           action: 'mceNewDocument',
  29633.           icon: 'new-document'
  29634.         },
  29635.         {
  29636.           name: 'removeformat',
  29637.           text: 'Clear formatting',
  29638.           action: 'RemoveFormat',
  29639.           icon: 'remove-formatting'
  29640.         },
  29641.         {
  29642.           name: 'remove',
  29643.           text: 'Remove',
  29644.           action: 'Delete',
  29645.           icon: 'remove'
  29646.         }
  29647.       ], function (btn) {
  29648.         editor.ui.registry.addButton(btn.name, {
  29649.           tooltip: btn.text,
  29650.           icon: btn.icon,
  29651.           onAction: onActionExecCommand(editor, btn.action)
  29652.         });
  29653.       });
  29654.     };
  29655.     var registerCommandToggleButtons = function (editor) {
  29656.       global$5.each([{
  29657.           name: 'blockquote',
  29658.           text: 'Blockquote',
  29659.           action: 'mceBlockQuote',
  29660.           icon: 'quote'
  29661.         }], function (btn) {
  29662.         editor.ui.registry.addToggleButton(btn.name, {
  29663.           tooltip: btn.text,
  29664.           icon: btn.icon,
  29665.           onAction: onActionExecCommand(editor, btn.action),
  29666.           onSetup: onSetupFormatToggle(editor, btn.name)
  29667.         });
  29668.       });
  29669.     };
  29670.     var registerButtons$1 = function (editor) {
  29671.       registerFormatButtons(editor);
  29672.       registerCommandButtons(editor);
  29673.       registerCommandToggleButtons(editor);
  29674.     };
  29675.     var registerMenuItems$2 = function (editor) {
  29676.       global$5.each([
  29677.         {
  29678.           name: 'bold',
  29679.           text: 'Bold',
  29680.           action: 'Bold',
  29681.           icon: 'bold',
  29682.           shortcut: 'Meta+B'
  29683.         },
  29684.         {
  29685.           name: 'italic',
  29686.           text: 'Italic',
  29687.           action: 'Italic',
  29688.           icon: 'italic',
  29689.           shortcut: 'Meta+I'
  29690.         },
  29691.         {
  29692.           name: 'underline',
  29693.           text: 'Underline',
  29694.           action: 'Underline',
  29695.           icon: 'underline',
  29696.           shortcut: 'Meta+U'
  29697.         },
  29698.         {
  29699.           name: 'strikethrough',
  29700.           text: 'Strikethrough',
  29701.           action: 'Strikethrough',
  29702.           icon: 'strike-through',
  29703.           shortcut: ''
  29704.         },
  29705.         {
  29706.           name: 'subscript',
  29707.           text: 'Subscript',
  29708.           action: 'Subscript',
  29709.           icon: 'subscript',
  29710.           shortcut: ''
  29711.         },
  29712.         {
  29713.           name: 'superscript',
  29714.           text: 'Superscript',
  29715.           action: 'Superscript',
  29716.           icon: 'superscript',
  29717.           shortcut: ''
  29718.         },
  29719.         {
  29720.           name: 'removeformat',
  29721.           text: 'Clear formatting',
  29722.           action: 'RemoveFormat',
  29723.           icon: 'remove-formatting',
  29724.           shortcut: ''
  29725.         },
  29726.         {
  29727.           name: 'newdocument',
  29728.           text: 'New document',
  29729.           action: 'mceNewDocument',
  29730.           icon: 'new-document',
  29731.           shortcut: ''
  29732.         },
  29733.         {
  29734.           name: 'cut',
  29735.           text: 'Cut',
  29736.           action: 'Cut',
  29737.           icon: 'cut',
  29738.           shortcut: 'Meta+X'
  29739.         },
  29740.         {
  29741.           name: 'copy',
  29742.           text: 'Copy',
  29743.           action: 'Copy',
  29744.           icon: 'copy',
  29745.           shortcut: 'Meta+C'
  29746.         },
  29747.         {
  29748.           name: 'paste',
  29749.           text: 'Paste',
  29750.           action: 'Paste',
  29751.           icon: 'paste',
  29752.           shortcut: 'Meta+V'
  29753.         },
  29754.         {
  29755.           name: 'selectall',
  29756.           text: 'Select all',
  29757.           action: 'SelectAll',
  29758.           icon: 'select-all',
  29759.           shortcut: 'Meta+A'
  29760.         }
  29761.       ], function (btn) {
  29762.         editor.ui.registry.addMenuItem(btn.name, {
  29763.           text: btn.text,
  29764.           icon: btn.icon,
  29765.           shortcut: btn.shortcut,
  29766.           onAction: onActionExecCommand(editor, btn.action)
  29767.         });
  29768.       });
  29769.       editor.ui.registry.addMenuItem('codeformat', {
  29770.         text: 'Code',
  29771.         icon: 'sourcecode',
  29772.         onAction: onActionToggleFormat(editor, 'code')
  29773.       });
  29774.     };
  29775.     var register$2 = function (editor) {
  29776.       registerButtons$1(editor);
  29777.       registerMenuItems$2(editor);
  29778.     };
  29779.  
  29780.     var onSetupUndoRedoState = function (editor, type) {
  29781.       return onSetupEvent(editor, 'Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function (api) {
  29782.         api.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type]());
  29783.       });
  29784.     };
  29785.     var registerMenuItems$1 = function (editor) {
  29786.       editor.ui.registry.addMenuItem('undo', {
  29787.         text: 'Undo',
  29788.         icon: 'undo',
  29789.         shortcut: 'Meta+Z',
  29790.         onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  29791.         onAction: onActionExecCommand(editor, 'undo')
  29792.       });
  29793.       editor.ui.registry.addMenuItem('redo', {
  29794.         text: 'Redo',
  29795.         icon: 'redo',
  29796.         shortcut: 'Meta+Y',
  29797.         onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  29798.         onAction: onActionExecCommand(editor, 'redo')
  29799.       });
  29800.     };
  29801.     var registerButtons = function (editor) {
  29802.       editor.ui.registry.addButton('undo', {
  29803.         tooltip: 'Undo',
  29804.         icon: 'undo',
  29805.         disabled: true,
  29806.         onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  29807.         onAction: onActionExecCommand(editor, 'undo')
  29808.       });
  29809.       editor.ui.registry.addButton('redo', {
  29810.         tooltip: 'Redo',
  29811.         icon: 'redo',
  29812.         disabled: true,
  29813.         onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  29814.         onAction: onActionExecCommand(editor, 'redo')
  29815.       });
  29816.     };
  29817.     var register$1 = function (editor) {
  29818.       registerMenuItems$1(editor);
  29819.       registerButtons(editor);
  29820.     };
  29821.  
  29822.     var onSetupVisualAidState = function (editor) {
  29823.       return onSetupEvent(editor, 'VisualAid', function (api) {
  29824.         api.setActive(editor.hasVisual);
  29825.       });
  29826.     };
  29827.     var registerMenuItems = function (editor) {
  29828.       editor.ui.registry.addToggleMenuItem('visualaid', {
  29829.         text: 'Visual aids',
  29830.         onSetup: onSetupVisualAidState(editor),
  29831.         onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  29832.       });
  29833.     };
  29834.     var registerToolbarButton = function (editor) {
  29835.       editor.ui.registry.addButton('visualaid', {
  29836.         tooltip: 'Visual aids',
  29837.         text: 'Visual aids',
  29838.         onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  29839.       });
  29840.     };
  29841.     var register = function (editor) {
  29842.       registerToolbarButton(editor);
  29843.       registerMenuItems(editor);
  29844.     };
  29845.  
  29846.     var setup$6 = function (editor, backstage) {
  29847.       register$6(editor);
  29848.       register$2(editor);
  29849.       register$4(editor, backstage);
  29850.       register$1(editor);
  29851.       register$a(editor);
  29852.       register(editor);
  29853.       register$3(editor);
  29854.       register$5(editor);
  29855.     };
  29856.  
  29857.     var nu = function (x, y) {
  29858.       return {
  29859.         type: 'makeshift',
  29860.         x: x,
  29861.         y: y
  29862.       };
  29863.     };
  29864.     var transpose = function (pos, dx, dy) {
  29865.       return nu(pos.x + dx, pos.y + dy);
  29866.     };
  29867.     var isTouchEvent = function (e) {
  29868.       return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  29869.     };
  29870.     var fromPageXY = function (e) {
  29871.       if (isTouchEvent(e)) {
  29872.         var touch = e.touches[0];
  29873.         return nu(touch.pageX, touch.pageY);
  29874.       } else {
  29875.         return nu(e.pageX, e.pageY);
  29876.       }
  29877.     };
  29878.     var fromClientXY = function (e) {
  29879.       if (isTouchEvent(e)) {
  29880.         var touch = e.touches[0];
  29881.         return nu(touch.clientX, touch.clientY);
  29882.       } else {
  29883.         return nu(e.clientX, e.clientY);
  29884.       }
  29885.     };
  29886.     var transposeContentAreaContainer = function (element, pos) {
  29887.       var containerPos = global$b.DOM.getPos(element);
  29888.       return transpose(pos, containerPos.x, containerPos.y);
  29889.     };
  29890.     var getPointAnchor = function (editor, e) {
  29891.       if (e.type === 'contextmenu' || e.type === 'longpress') {
  29892.         if (editor.inline) {
  29893.           return fromPageXY(e);
  29894.         } else {
  29895.           return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  29896.         }
  29897.       } else {
  29898.         return getSelectionAnchor(editor);
  29899.       }
  29900.     };
  29901.     var getSelectionAnchor = function (editor) {
  29902.       return {
  29903.         type: 'selection',
  29904.         root: SugarElement.fromDom(editor.selection.getNode())
  29905.       };
  29906.     };
  29907.     var getNodeAnchor = function (editor) {
  29908.       return {
  29909.         type: 'node',
  29910.         node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
  29911.         root: SugarElement.fromDom(editor.getBody())
  29912.       };
  29913.     };
  29914.     var getAnchorSpec$1 = function (editor, e, anchorType) {
  29915.       switch (anchorType) {
  29916.       case 'node':
  29917.         return getNodeAnchor(editor);
  29918.       case 'point':
  29919.         return getPointAnchor(editor, e);
  29920.       case 'selection':
  29921.         return getSelectionAnchor(editor);
  29922.       }
  29923.     };
  29924.  
  29925.     var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  29926.       var items = buildMenu();
  29927.       var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  29928.       build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  29929.         e.preventDefault();
  29930.         InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
  29931.           menu: { markers: markers('normal') },
  29932.           data: menuData
  29933.         });
  29934.       });
  29935.     };
  29936.  
  29937.     var layouts = {
  29938.       onLtr: function () {
  29939.         return [
  29940.           south$2,
  29941.           southeast$2,
  29942.           southwest$2,
  29943.           northeast$2,
  29944.           northwest$2,
  29945.           north$2,
  29946.           north,
  29947.           south,
  29948.           northeast,
  29949.           southeast,
  29950.           northwest,
  29951.           southwest
  29952.         ];
  29953.       },
  29954.       onRtl: function () {
  29955.         return [
  29956.           south$2,
  29957.           southwest$2,
  29958.           southeast$2,
  29959.           northwest$2,
  29960.           northeast$2,
  29961.           north$2,
  29962.           north,
  29963.           south,
  29964.           northwest,
  29965.           southwest,
  29966.           northeast,
  29967.           southeast
  29968.         ];
  29969.       }
  29970.     };
  29971.     var bubbleSize = 12;
  29972.     var bubbleAlignments = {
  29973.       valignCentre: [],
  29974.       alignCentre: [],
  29975.       alignLeft: ['tox-pop--align-left'],
  29976.       alignRight: ['tox-pop--align-right'],
  29977.       right: ['tox-pop--right'],
  29978.       left: ['tox-pop--left'],
  29979.       bottom: ['tox-pop--bottom'],
  29980.       top: ['tox-pop--top']
  29981.     };
  29982.     var isTouchWithinSelection = function (editor, e) {
  29983.       var selection = editor.selection;
  29984.       if (selection.isCollapsed() || e.touches.length < 1) {
  29985.         return false;
  29986.       } else {
  29987.         var touch_1 = e.touches[0];
  29988.         var rng = selection.getRng();
  29989.         var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
  29990.         return rngRectOpt.exists(function (rngRect) {
  29991.           return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
  29992.         });
  29993.       }
  29994.     };
  29995.     var setupiOSOverrides = function (editor) {
  29996.       var originalSelection = editor.selection.getRng();
  29997.       var selectionReset = function () {
  29998.         global$f.setEditorTimeout(editor, function () {
  29999.           editor.selection.setRng(originalSelection);
  30000.         }, 10);
  30001.         unbindEventListeners();
  30002.       };
  30003.       editor.once('touchend', selectionReset);
  30004.       var preventMousedown = function (e) {
  30005.         e.preventDefault();
  30006.         e.stopImmediatePropagation();
  30007.       };
  30008.       editor.on('mousedown', preventMousedown, true);
  30009.       var clearSelectionReset = function () {
  30010.         return unbindEventListeners();
  30011.       };
  30012.       editor.once('longpresscancel', clearSelectionReset);
  30013.       var unbindEventListeners = function () {
  30014.         editor.off('touchend', selectionReset);
  30015.         editor.off('longpresscancel', clearSelectionReset);
  30016.         editor.off('mousedown', preventMousedown);
  30017.       };
  30018.     };
  30019.     var getAnchorSpec = function (editor, e, anchorType) {
  30020.       var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  30021.       var bubbleYOffset = anchorType === 'point' ? bubbleSize : 0;
  30022.       return __assign({
  30023.         bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
  30024.         layouts: layouts,
  30025.         overrides: {
  30026.           maxWidthFunction: expandable(),
  30027.           maxHeightFunction: expandable$1()
  30028.         }
  30029.       }, anchorSpec);
  30030.     };
  30031.     var show = function (editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) {
  30032.       var anchorSpec = getAnchorSpec(editor, e, anchorType);
  30033.       build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  30034.         e.preventDefault();
  30035.         InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
  30036.           menu: {
  30037.             markers: markers('normal'),
  30038.             highlightImmediately: highlightImmediately
  30039.           },
  30040.           data: menuData,
  30041.           type: 'horizontal'
  30042.         }, function () {
  30043.           return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === 'node' ? 'node' : 'selection'));
  30044.         });
  30045.         editor.fire(hideContextToolbarEvent);
  30046.       });
  30047.     };
  30048.     var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  30049.       var detection = detect$1();
  30050.       var isiOS = detection.os.isiOS();
  30051.       var isOSX = detection.os.isOSX();
  30052.       var isAndroid = detection.os.isAndroid();
  30053.       var isTouch = detection.deviceType.isTouch();
  30054.       var shouldHighlightImmediately = function () {
  30055.         return !(isAndroid || isiOS || isOSX && isTouch);
  30056.       };
  30057.       var open = function () {
  30058.         var items = buildMenu();
  30059.         show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
  30060.       };
  30061.       if ((isOSX || isiOS) && anchorType !== 'node') {
  30062.         var openiOS_1 = function () {
  30063.           setupiOSOverrides(editor);
  30064.           open();
  30065.         };
  30066.         if (isTouchWithinSelection(editor, e)) {
  30067.           openiOS_1();
  30068.         } else {
  30069.           editor.once('selectionchange', openiOS_1);
  30070.           editor.once('touchend', function () {
  30071.             return editor.off('selectionchange', openiOS_1);
  30072.           });
  30073.         }
  30074.       } else {
  30075.         open();
  30076.       }
  30077.     };
  30078.  
  30079.     var patchPipeConfig = function (config) {
  30080.       return typeof config === 'string' ? config.split(/[ ,]/) : config;
  30081.     };
  30082.     var shouldNeverUseNative = function (editor) {
  30083.       return editor.getParam('contextmenu_never_use_native', false, 'boolean');
  30084.     };
  30085.     var getMenuItems = function (editor, name, defaultItems) {
  30086.       var contextMenus = editor.ui.registry.getAll().contextMenus;
  30087.       return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () {
  30088.         return filter$2(patchPipeConfig(defaultItems), function (item) {
  30089.           return has$2(contextMenus, item);
  30090.         });
  30091.       });
  30092.     };
  30093.     var isContextMenuDisabled = function (editor) {
  30094.       return editor.getParam('contextmenu') === false;
  30095.     };
  30096.     var getContextMenu = function (editor) {
  30097.       return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  30098.     };
  30099.     var getAvoidOverlapSelector = function (editor) {
  30100.       return editor.getParam('contextmenu_avoid_overlap', '', 'string');
  30101.     };
  30102.  
  30103.     var isSeparator = function (item) {
  30104.       return isString(item) ? item === '|' : item.type === 'separator';
  30105.     };
  30106.     var separator = { type: 'separator' };
  30107.     var makeContextItem = function (item) {
  30108.       var commonMenuItem = function (item) {
  30109.         return {
  30110.           text: item.text,
  30111.           icon: item.icon,
  30112.           disabled: item.disabled,
  30113.           shortcut: item.shortcut
  30114.         };
  30115.       };
  30116.       if (isString(item)) {
  30117.         return item;
  30118.       } else {
  30119.         switch (item.type) {
  30120.         case 'separator':
  30121.           return separator;
  30122.         case 'submenu':
  30123.           return __assign(__assign({ type: 'nestedmenuitem' }, commonMenuItem(item)), {
  30124.             getSubmenuItems: function () {
  30125.               var items = item.getSubmenuItems();
  30126.               if (isString(items)) {
  30127.                 return items;
  30128.               } else {
  30129.                 return map$2(items, makeContextItem);
  30130.               }
  30131.             }
  30132.           });
  30133.         default:
  30134.           return __assign(__assign({ type: 'menuitem' }, commonMenuItem(item)), { onAction: noarg(item.onAction) });
  30135.         }
  30136.       }
  30137.     };
  30138.     var addContextMenuGroup = function (xs, groupItems) {
  30139.       if (groupItems.length === 0) {
  30140.         return xs;
  30141.       }
  30142.       var lastMenuItem = last$2(xs).filter(function (item) {
  30143.         return !isSeparator(item);
  30144.       });
  30145.       var before = lastMenuItem.fold(function () {
  30146.         return [];
  30147.       }, function (_) {
  30148.         return [separator];
  30149.       });
  30150.       return xs.concat(before).concat(groupItems).concat([separator]);
  30151.     };
  30152.     var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  30153.       var sections = foldl(menuConfig, function (acc, name) {
  30154.         return get$e(contextMenus, name.toLowerCase()).map(function (menu) {
  30155.           var items = menu.update(selectedElement);
  30156.           if (isString(items)) {
  30157.             return addContextMenuGroup(acc, items.split(' '));
  30158.           } else if (items.length > 0) {
  30159.             var allItems = map$2(items, makeContextItem);
  30160.             return addContextMenuGroup(acc, allItems);
  30161.           } else {
  30162.             return acc;
  30163.           }
  30164.         }).getOrThunk(function () {
  30165.           return acc.concat([name]);
  30166.         });
  30167.       }, []);
  30168.       if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
  30169.         sections.pop();
  30170.       }
  30171.       return sections;
  30172.     };
  30173.     var isNativeOverrideKeyEvent = function (editor, e) {
  30174.       return e.ctrlKey && !shouldNeverUseNative(editor);
  30175.     };
  30176.     var isTriggeredByKeyboard = function (editor, e) {
  30177.       return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  30178.     };
  30179.     var getSelectedElement = function (editor, e) {
  30180.       return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
  30181.     };
  30182.     var getAnchorType = function (editor, e) {
  30183.       var selector = getAvoidOverlapSelector(editor);
  30184.       var anchorType = isTriggeredByKeyboard(editor, e) ? 'selection' : 'point';
  30185.       if (isNotEmpty(selector)) {
  30186.         var target = getSelectedElement(editor, e);
  30187.         var selectorExists = closest(SugarElement.fromDom(target), selector);
  30188.         return selectorExists ? 'node' : anchorType;
  30189.       } else {
  30190.         return anchorType;
  30191.       }
  30192.     };
  30193.     var setup$5 = function (editor, lazySink, backstage) {
  30194.       var detection = detect$1();
  30195.       var isTouch = detection.deviceType.isTouch;
  30196.       var contextmenu = build$1(InlineView.sketch({
  30197.         dom: { tag: 'div' },
  30198.         lazySink: lazySink,
  30199.         onEscape: function () {
  30200.           return editor.focus();
  30201.         },
  30202.         onShow: function () {
  30203.           return backstage.setContextMenuState(true);
  30204.         },
  30205.         onHide: function () {
  30206.           return backstage.setContextMenuState(false);
  30207.         },
  30208.         fireDismissalEventInstead: {},
  30209.         inlineBehaviours: derive$1([config('dismissContextMenu', [run$1(dismissRequested(), function (comp, _se) {
  30210.               Sandboxing.close(comp);
  30211.               editor.focus();
  30212.             })])])
  30213.       }));
  30214.       var hideContextMenu = function (_e) {
  30215.         return InlineView.hide(contextmenu);
  30216.       };
  30217.       var showContextMenu = function (e) {
  30218.         if (shouldNeverUseNative(editor)) {
  30219.           e.preventDefault();
  30220.         }
  30221.         if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  30222.           return;
  30223.         }
  30224.         var anchorType = getAnchorType(editor, e);
  30225.         var buildMenu = function () {
  30226.           var selectedElement = getSelectedElement(editor, e);
  30227.           var registry = editor.ui.registry.getAll();
  30228.           var menuConfig = getContextMenu(editor);
  30229.           return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  30230.         };
  30231.         var initAndShow$2 = isTouch() ? initAndShow : initAndShow$1;
  30232.         initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType);
  30233.       };
  30234.       editor.on('init', function () {
  30235.         var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  30236.         editor.on(hideEvents, hideContextMenu);
  30237.         editor.on('longpress contextmenu', showContextMenu);
  30238.       });
  30239.     };
  30240.  
  30241.     var adt = Adt.generate([
  30242.       {
  30243.         offset: [
  30244.           'x',
  30245.           'y'
  30246.         ]
  30247.       },
  30248.       {
  30249.         absolute: [
  30250.           'x',
  30251.           'y'
  30252.         ]
  30253.       },
  30254.       {
  30255.         fixed: [
  30256.           'x',
  30257.           'y'
  30258.         ]
  30259.       }
  30260.     ]);
  30261.     var subtract = function (change) {
  30262.       return function (point) {
  30263.         return point.translate(-change.left, -change.top);
  30264.       };
  30265.     };
  30266.     var add = function (change) {
  30267.       return function (point) {
  30268.         return point.translate(change.left, change.top);
  30269.       };
  30270.     };
  30271.     var transform = function (changes) {
  30272.       return function (x, y) {
  30273.         return foldl(changes, function (rest, f) {
  30274.           return f(rest);
  30275.         }, SugarPosition(x, y));
  30276.       };
  30277.     };
  30278.     var asFixed = function (coord, scroll, origin) {
  30279.       return coord.fold(transform([
  30280.         add(origin),
  30281.         subtract(scroll)
  30282.       ]), transform([subtract(scroll)]), transform([]));
  30283.     };
  30284.     var asAbsolute = function (coord, scroll, origin) {
  30285.       return coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)]));
  30286.     };
  30287.     var asOffset = function (coord, scroll, origin) {
  30288.       return coord.fold(transform([]), transform([subtract(origin)]), transform([
  30289.         add(scroll),
  30290.         subtract(origin)
  30291.       ]));
  30292.     };
  30293.     var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  30294.       var a1 = asAbsolute(coord1, scroll, origin);
  30295.       var a2 = asAbsolute(coord2, scroll, origin);
  30296.       return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
  30297.     };
  30298.     var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  30299.       var a1 = asAbsolute(coord1, scroll, origin);
  30300.       var a2 = asAbsolute(coord2, scroll, origin);
  30301.       var left = Math.abs(a1.left - a2.left);
  30302.       var top = Math.abs(a1.top - a2.top);
  30303.       return SugarPosition(left, top);
  30304.     };
  30305.     var toStyles = function (coord, scroll, origin) {
  30306.       var stylesOpt = coord.fold(function (x, y) {
  30307.         return {
  30308.           position: Optional.some('absolute'),
  30309.           left: Optional.some(x + 'px'),
  30310.           top: Optional.some(y + 'px')
  30311.         };
  30312.       }, function (x, y) {
  30313.         return {
  30314.           position: Optional.some('absolute'),
  30315.           left: Optional.some(x - origin.left + 'px'),
  30316.           top: Optional.some(y - origin.top + 'px')
  30317.         };
  30318.       }, function (x, y) {
  30319.         return {
  30320.           position: Optional.some('fixed'),
  30321.           left: Optional.some(x + 'px'),
  30322.           top: Optional.some(y + 'px')
  30323.         };
  30324.       });
  30325.       return __assign({
  30326.         right: Optional.none(),
  30327.         bottom: Optional.none()
  30328.       }, stylesOpt);
  30329.     };
  30330.     var translate = function (coord, deltaX, deltaY) {
  30331.       return coord.fold(function (x, y) {
  30332.         return offset(x + deltaX, y + deltaY);
  30333.       }, function (x, y) {
  30334.         return absolute(x + deltaX, y + deltaY);
  30335.       }, function (x, y) {
  30336.         return fixed(x + deltaX, y + deltaY);
  30337.       });
  30338.     };
  30339.     var absorb = function (partialCoord, originalCoord, scroll, origin) {
  30340.       var absorbOne = function (stencil, nu) {
  30341.         return function (optX, optY) {
  30342.           var original = stencil(originalCoord, scroll, origin);
  30343.           return nu(optX.getOr(original.left), optY.getOr(original.top));
  30344.         };
  30345.       };
  30346.       return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
  30347.     };
  30348.     var offset = adt.offset;
  30349.     var absolute = adt.absolute;
  30350.     var fixed = adt.fixed;
  30351.  
  30352.     var parseAttrToInt = function (element, name) {
  30353.       var value = get$d(element, name);
  30354.       return isUndefined(value) ? NaN : parseInt(value, 10);
  30355.     };
  30356.     var get = function (component, snapsInfo) {
  30357.       var element = component.element;
  30358.       var x = parseAttrToInt(element, snapsInfo.leftAttr);
  30359.       var y = parseAttrToInt(element, snapsInfo.topAttr);
  30360.       return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
  30361.     };
  30362.     var set = function (component, snapsInfo, pt) {
  30363.       var element = component.element;
  30364.       set$8(element, snapsInfo.leftAttr, pt.left + 'px');
  30365.       set$8(element, snapsInfo.topAttr, pt.top + 'px');
  30366.     };
  30367.     var clear = function (component, snapsInfo) {
  30368.       var element = component.element;
  30369.       remove$7(element, snapsInfo.leftAttr);
  30370.       remove$7(element, snapsInfo.topAttr);
  30371.     };
  30372.  
  30373.     var getCoords = function (component, snapInfo, coord, delta) {
  30374.       return get(component, snapInfo).fold(function () {
  30375.         return coord;
  30376.       }, function (fixed$1) {
  30377.         return fixed(fixed$1.left + delta.left, fixed$1.top + delta.top);
  30378.       });
  30379.     };
  30380.     var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  30381.       var newCoord = getCoords(component, snapInfo, coord, delta);
  30382.       var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  30383.       var fixedCoord = asFixed(newCoord, scroll, origin);
  30384.       set(component, snapInfo, fixedCoord);
  30385.       return snap.fold(function () {
  30386.         return {
  30387.           coord: fixed(fixedCoord.left, fixedCoord.top),
  30388.           extra: Optional.none()
  30389.         };
  30390.       }, function (spanned) {
  30391.         return {
  30392.           coord: spanned.output,
  30393.           extra: spanned.extra
  30394.         };
  30395.       });
  30396.     };
  30397.     var stopDrag = function (component, snapInfo) {
  30398.       clear(component, snapInfo);
  30399.     };
  30400.     var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  30401.       return findMap(snaps, function (snap) {
  30402.         var sensor = snap.sensor;
  30403.         var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  30404.         return inRange ? Optional.some({
  30405.           output: absorb(snap.output, newCoord, scroll, origin),
  30406.           extra: snap.extra
  30407.         }) : Optional.none();
  30408.       });
  30409.     };
  30410.     var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  30411.       var snaps = snapInfo.getSnapPoints(component);
  30412.       var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  30413.       return matchSnap.orThunk(function () {
  30414.         var bestSnap = foldl(snaps, function (acc, snap) {
  30415.           var sensor = snap.sensor;
  30416.           var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  30417.           return acc.deltas.fold(function () {
  30418.             return {
  30419.               deltas: Optional.some(deltas),
  30420.               snap: Optional.some(snap)
  30421.             };
  30422.           }, function (bestDeltas) {
  30423.             var currAvg = (deltas.left + deltas.top) / 2;
  30424.             var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
  30425.             if (currAvg <= bestAvg) {
  30426.               return {
  30427.                 deltas: Optional.some(deltas),
  30428.                 snap: Optional.some(snap)
  30429.               };
  30430.             } else {
  30431.               return acc;
  30432.             }
  30433.           });
  30434.         }, {
  30435.           deltas: Optional.none(),
  30436.           snap: Optional.none()
  30437.         });
  30438.         return bestSnap.snap.map(function (snap) {
  30439.           return {
  30440.             output: absorb(snap.output, newCoord, scroll, origin),
  30441.             extra: snap.extra
  30442.           };
  30443.         });
  30444.       });
  30445.     };
  30446.     var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  30447.       var snaps = snapInfo.getSnapPoints(component);
  30448.       return findMatchingSnap(snaps, newCoord, scroll, origin);
  30449.     };
  30450.     var snapTo$1 = function (snap, scroll, origin) {
  30451.       return {
  30452.         coord: absorb(snap.output, snap.output, scroll, origin),
  30453.         extra: snap.extra
  30454.       };
  30455.     };
  30456.  
  30457.     var snapTo = function (component, dragConfig, _state, snap) {
  30458.       var target = dragConfig.getTarget(component.element);
  30459.       if (dragConfig.repositionTarget) {
  30460.         var doc = owner$4(component.element);
  30461.         var scroll_1 = get$9(doc);
  30462.         var origin_1 = getOrigin(target);
  30463.         var snapPin = snapTo$1(snap, scroll_1, origin_1);
  30464.         var styles = toStyles(snapPin.coord, scroll_1, origin_1);
  30465.         setOptions(target, styles);
  30466.       }
  30467.     };
  30468.  
  30469.     var DraggingApis = /*#__PURE__*/Object.freeze({
  30470.         __proto__: null,
  30471.         snapTo: snapTo
  30472.     });
  30473.  
  30474.     var initialAttribute = 'data-initial-z-index';
  30475.     var resetZIndex = function (blocker) {
  30476.       parent(blocker.element).filter(isElement$2).each(function (root) {
  30477.         getOpt(root, initialAttribute).fold(function () {
  30478.           return remove$6(root, 'z-index');
  30479.         }, function (zIndex) {
  30480.           return set$7(root, 'z-index', zIndex);
  30481.         });
  30482.         remove$7(root, initialAttribute);
  30483.       });
  30484.     };
  30485.     var changeZIndex = function (blocker) {
  30486.       parent(blocker.element).filter(isElement$2).each(function (root) {
  30487.         getRaw(root, 'z-index').each(function (zindex) {
  30488.           set$8(root, initialAttribute, zindex);
  30489.         });
  30490.         set$7(root, 'z-index', get$c(blocker.element, 'z-index'));
  30491.       });
  30492.     };
  30493.     var instigate = function (anyComponent, blocker) {
  30494.       anyComponent.getSystem().addToGui(blocker);
  30495.       changeZIndex(blocker);
  30496.     };
  30497.     var discard = function (blocker) {
  30498.       resetZIndex(blocker);
  30499.       blocker.getSystem().removeFromGui(blocker);
  30500.     };
  30501.     var createComponent = function (component, blockerClass, blockerEvents) {
  30502.       return component.getSystem().build(Container.sketch({
  30503.         dom: {
  30504.           styles: {
  30505.             'left': '0px',
  30506.             'top': '0px',
  30507.             'width': '100%',
  30508.             'height': '100%',
  30509.             'position': 'fixed',
  30510.             'z-index': '1000000000000000'
  30511.           },
  30512.           classes: [blockerClass]
  30513.         },
  30514.         events: blockerEvents
  30515.       }));
  30516.     };
  30517.  
  30518.     var SnapSchema = optionObjOf('snaps', [
  30519.       required$1('getSnapPoints'),
  30520.       onHandler('onSensor'),
  30521.       required$1('leftAttr'),
  30522.       required$1('topAttr'),
  30523.       defaulted('lazyViewport', win),
  30524.       defaulted('mustSnap', false)
  30525.     ]);
  30526.  
  30527.     var schema$6 = [
  30528.       defaulted('useFixed', never),
  30529.       required$1('blockerClass'),
  30530.       defaulted('getTarget', identity$1),
  30531.       defaulted('onDrag', noop),
  30532.       defaulted('repositionTarget', true),
  30533.       defaulted('onDrop', noop),
  30534.       defaultedFunction('getBounds', win),
  30535.       SnapSchema
  30536.     ];
  30537.  
  30538.     var getCurrentCoord = function (target) {
  30539.       return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  30540.         var nu = position === 'fixed' ? fixed : offset;
  30541.         return nu(parseInt(left, 10), parseInt(top, 10));
  30542.       }).getOrThunk(function () {
  30543.         var location = absolute$3(target);
  30544.         return absolute(location.left, location.top);
  30545.       });
  30546.     };
  30547.     var clampCoords = function (component, coords, scroll, origin, startData) {
  30548.       var bounds = startData.bounds;
  30549.       var absoluteCoord = asAbsolute(coords, scroll, origin);
  30550.       var newX = clamp$1(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
  30551.       var newY = clamp$1(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
  30552.       var newCoords = absolute(newX, newY);
  30553.       return coords.fold(function () {
  30554.         var offset$1 = asOffset(newCoords, scroll, origin);
  30555.         return offset(offset$1.left, offset$1.top);
  30556.       }, constant$1(newCoords), function () {
  30557.         var fixed$1 = asFixed(newCoords, scroll, origin);
  30558.         return fixed(fixed$1.left, fixed$1.top);
  30559.       });
  30560.     };
  30561.     var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  30562.       var newCoord = optSnaps.fold(function () {
  30563.         var translated = translate(currentCoord, delta.left, delta.top);
  30564.         var fixedCoord = asFixed(translated, scroll, origin);
  30565.         return fixed(fixedCoord.left, fixedCoord.top);
  30566.       }, function (snapInfo) {
  30567.         var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  30568.         snapping.extra.each(function (extra) {
  30569.           snapInfo.onSensor(component, extra);
  30570.         });
  30571.         return snapping.coord;
  30572.       });
  30573.       return clampCoords(component, newCoord, scroll, origin, startData);
  30574.     };
  30575.     var dragBy = function (component, dragConfig, startData, delta) {
  30576.       var target = dragConfig.getTarget(component.element);
  30577.       if (dragConfig.repositionTarget) {
  30578.         var doc = owner$4(component.element);
  30579.         var scroll_1 = get$9(doc);
  30580.         var origin_1 = getOrigin(target);
  30581.         var currentCoord = getCurrentCoord(target);
  30582.         var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
  30583.         var styles = toStyles(newCoord, scroll_1, origin_1);
  30584.         setOptions(target, styles);
  30585.       }
  30586.       dragConfig.onDrag(component, target, delta);
  30587.     };
  30588.  
  30589.     var calcStartData = function (dragConfig, comp) {
  30590.       return {
  30591.         bounds: dragConfig.getBounds(),
  30592.         height: getOuter$2(comp.element),
  30593.         width: getOuter$1(comp.element)
  30594.       };
  30595.     };
  30596.     var move = function (component, dragConfig, dragState, dragMode, event) {
  30597.       var delta = dragState.update(dragMode, event);
  30598.       var dragStartData = dragState.getStartData().getOrThunk(function () {
  30599.         return calcStartData(dragConfig, component);
  30600.       });
  30601.       delta.each(function (dlt) {
  30602.         dragBy(component, dragConfig, dragStartData, dlt);
  30603.       });
  30604.     };
  30605.     var stop = function (component, blocker, dragConfig, dragState) {
  30606.       blocker.each(discard);
  30607.       dragConfig.snaps.each(function (snapInfo) {
  30608.         stopDrag(component, snapInfo);
  30609.       });
  30610.       var target = dragConfig.getTarget(component.element);
  30611.       dragState.reset();
  30612.       dragConfig.onDrop(component, target);
  30613.     };
  30614.     var handlers = function (events) {
  30615.       return function (dragConfig, dragState) {
  30616.         var updateStartState = function (comp) {
  30617.           dragState.setStartData(calcStartData(dragConfig, comp));
  30618.         };
  30619.         return derive$2(__spreadArray([run$1(windowScroll(), function (comp) {
  30620.             dragState.getStartData().each(function () {
  30621.               return updateStartState(comp);
  30622.             });
  30623.           })], events(dragConfig, dragState, updateStartState), true));
  30624.       };
  30625.     };
  30626.  
  30627.     var init$2 = function (dragApi) {
  30628.       return derive$2([
  30629.         run$1(mousedown(), dragApi.forceDrop),
  30630.         run$1(mouseup(), dragApi.drop),
  30631.         run$1(mousemove(), function (comp, simulatedEvent) {
  30632.           dragApi.move(simulatedEvent.event);
  30633.         }),
  30634.         run$1(mouseout(), dragApi.delayDrop)
  30635.       ]);
  30636.     };
  30637.  
  30638.     var getData$1 = function (event) {
  30639.       return Optional.from(SugarPosition(event.x, event.y));
  30640.     };
  30641.     var getDelta$1 = function (old, nu) {
  30642.       return SugarPosition(nu.left - old.left, nu.top - old.top);
  30643.     };
  30644.  
  30645.     var MouseData = /*#__PURE__*/Object.freeze({
  30646.         __proto__: null,
  30647.         getData: getData$1,
  30648.         getDelta: getDelta$1
  30649.     });
  30650.  
  30651.     var events$2 = function (dragConfig, dragState, updateStartState) {
  30652.       return [run$1(mousedown(), function (component, simulatedEvent) {
  30653.           var raw = simulatedEvent.event.raw;
  30654.           if (raw.button !== 0) {
  30655.             return;
  30656.           }
  30657.           simulatedEvent.stop();
  30658.           var stop$1 = function () {
  30659.             return stop(component, Optional.some(blocker), dragConfig, dragState);
  30660.           };
  30661.           var delayDrop = DelayedFunction(stop$1, 200);
  30662.           var dragApi = {
  30663.             drop: stop$1,
  30664.             delayDrop: delayDrop.schedule,
  30665.             forceDrop: stop$1,
  30666.             move: function (event) {
  30667.               delayDrop.cancel();
  30668.               move(component, dragConfig, dragState, MouseData, event);
  30669.             }
  30670.           };
  30671.           var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
  30672.           var start = function () {
  30673.             updateStartState(component);
  30674.             instigate(component, blocker);
  30675.           };
  30676.           start();
  30677.         })];
  30678.     };
  30679.     var schema$5 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$2) })], false);
  30680.  
  30681.     var init$1 = function (dragApi) {
  30682.       return derive$2([
  30683.         run$1(touchstart(), dragApi.forceDrop),
  30684.         run$1(touchend(), dragApi.drop),
  30685.         run$1(touchcancel(), dragApi.drop),
  30686.         run$1(touchmove(), function (comp, simulatedEvent) {
  30687.           dragApi.move(simulatedEvent.event);
  30688.         })
  30689.       ]);
  30690.     };
  30691.  
  30692.     var getDataFrom = function (touches) {
  30693.       var touch = touches[0];
  30694.       return Optional.some(SugarPosition(touch.clientX, touch.clientY));
  30695.     };
  30696.     var getData = function (event) {
  30697.       var raw = event.raw;
  30698.       var touches = raw.touches;
  30699.       return touches.length === 1 ? getDataFrom(touches) : Optional.none();
  30700.     };
  30701.     var getDelta = function (old, nu) {
  30702.       return SugarPosition(nu.left - old.left, nu.top - old.top);
  30703.     };
  30704.  
  30705.     var TouchData = /*#__PURE__*/Object.freeze({
  30706.         __proto__: null,
  30707.         getData: getData,
  30708.         getDelta: getDelta
  30709.     });
  30710.  
  30711.     var events$1 = function (dragConfig, dragState, updateStartState) {
  30712.       var blockerSingleton = value$1();
  30713.       var stopBlocking = function (component) {
  30714.         stop(component, blockerSingleton.get(), dragConfig, dragState);
  30715.         blockerSingleton.clear();
  30716.       };
  30717.       return [
  30718.         run$1(touchstart(), function (component, simulatedEvent) {
  30719.           simulatedEvent.stop();
  30720.           var stop = function () {
  30721.             return stopBlocking(component);
  30722.           };
  30723.           var dragApi = {
  30724.             drop: stop,
  30725.             delayDrop: noop,
  30726.             forceDrop: stop,
  30727.             move: function (event) {
  30728.               move(component, dragConfig, dragState, TouchData, event);
  30729.             }
  30730.           };
  30731.           var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
  30732.           blockerSingleton.set(blocker);
  30733.           var start = function () {
  30734.             updateStartState(component);
  30735.             instigate(component, blocker);
  30736.           };
  30737.           start();
  30738.         }),
  30739.         run$1(touchmove(), function (component, simulatedEvent) {
  30740.           simulatedEvent.stop();
  30741.           move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
  30742.         }),
  30743.         run$1(touchend(), function (component, simulatedEvent) {
  30744.           simulatedEvent.stop();
  30745.           stopBlocking(component);
  30746.         }),
  30747.         run$1(touchcancel(), stopBlocking)
  30748.       ];
  30749.     };
  30750.     var schema$4 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$1) })], false);
  30751.  
  30752.     var events = function (dragConfig, dragState, updateStartState) {
  30753.       return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState), true), events$1(dragConfig, dragState, updateStartState), true);
  30754.     };
  30755.     var schema$3 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events) })], false);
  30756.  
  30757.     var mouse = schema$5;
  30758.     var touch = schema$4;
  30759.     var mouseOrTouch = schema$3;
  30760.  
  30761.     var DraggingBranches = /*#__PURE__*/Object.freeze({
  30762.         __proto__: null,
  30763.         mouse: mouse,
  30764.         touch: touch,
  30765.         mouseOrTouch: mouseOrTouch
  30766.     });
  30767.  
  30768.     var init = function () {
  30769.       var previous = Optional.none();
  30770.       var startData = Optional.none();
  30771.       var reset = function () {
  30772.         previous = Optional.none();
  30773.         startData = Optional.none();
  30774.       };
  30775.       var calculateDelta = function (mode, nu) {
  30776.         var result = previous.map(function (old) {
  30777.           return mode.getDelta(old, nu);
  30778.         });
  30779.         previous = Optional.some(nu);
  30780.         return result;
  30781.       };
  30782.       var update = function (mode, dragEvent) {
  30783.         return mode.getData(dragEvent).bind(function (nuData) {
  30784.           return calculateDelta(mode, nuData);
  30785.         });
  30786.       };
  30787.       var setStartData = function (data) {
  30788.         startData = Optional.some(data);
  30789.       };
  30790.       var getStartData = function () {
  30791.         return startData;
  30792.       };
  30793.       var readState = constant$1({});
  30794.       return nu$8({
  30795.         readState: readState,
  30796.         reset: reset,
  30797.         update: update,
  30798.         getStartData: getStartData,
  30799.         setStartData: setStartData
  30800.       });
  30801.     };
  30802.  
  30803.     var DragState = /*#__PURE__*/Object.freeze({
  30804.         __proto__: null,
  30805.         init: init
  30806.     });
  30807.  
  30808.     var Dragging = createModes({
  30809.       branchKey: 'mode',
  30810.       branches: DraggingBranches,
  30811.       name: 'dragging',
  30812.       active: {
  30813.         events: function (dragConfig, dragState) {
  30814.           var dragger = dragConfig.dragger;
  30815.           return dragger.handlers(dragConfig, dragState);
  30816.         }
  30817.       },
  30818.       extra: {
  30819.         snap: function (sConfig) {
  30820.           return {
  30821.             sensor: sConfig.sensor,
  30822.             range: sConfig.range,
  30823.             output: sConfig.output,
  30824.             extra: Optional.from(sConfig.extra)
  30825.           };
  30826.         }
  30827.       },
  30828.       state: DragState,
  30829.       apis: DraggingApis
  30830.     });
  30831.  
  30832.     var snapWidth = 40;
  30833.     var snapOffset = snapWidth / 2;
  30834.     var calcSnap = function (selectorOpt, td, x, y, width, height) {
  30835.       return selectorOpt.fold(function () {
  30836.         return Dragging.snap({
  30837.           sensor: absolute(x - snapOffset, y - snapOffset),
  30838.           range: SugarPosition(width, height),
  30839.           output: absolute(Optional.some(x), Optional.some(y)),
  30840.           extra: { td: td }
  30841.         });
  30842.       }, function (selectorHandle) {
  30843.         var sensorLeft = x - snapOffset;
  30844.         var sensorTop = y - snapOffset;
  30845.         var sensorWidth = snapWidth;
  30846.         var sensorHeight = snapWidth;
  30847.         var rect = selectorHandle.element.dom.getBoundingClientRect();
  30848.         return Dragging.snap({
  30849.           sensor: absolute(sensorLeft, sensorTop),
  30850.           range: SugarPosition(sensorWidth, sensorHeight),
  30851.           output: absolute(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
  30852.           extra: { td: td }
  30853.         });
  30854.       });
  30855.     };
  30856.     var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  30857.       var isSameCell = function (cellOpt, td) {
  30858.         return cellOpt.exists(function (currentTd) {
  30859.           return eq(currentTd, td);
  30860.         });
  30861.       };
  30862.       return {
  30863.         getSnapPoints: getSnapPoints,
  30864.         leftAttr: 'data-drag-left',
  30865.         topAttr: 'data-drag-top',
  30866.         onSensor: function (component, extra) {
  30867.           var td = extra.td;
  30868.           if (!isSameCell(cell.get(), td)) {
  30869.             cell.set(td);
  30870.             onChange(td);
  30871.           }
  30872.         },
  30873.         mustSnap: true
  30874.       };
  30875.     };
  30876.     var createSelector = function (snaps) {
  30877.       return record(Button.sketch({
  30878.         dom: {
  30879.           tag: 'div',
  30880.           classes: ['tox-selector']
  30881.         },
  30882.         buttonBehaviours: derive$1([
  30883.           Dragging.config({
  30884.             mode: 'mouseOrTouch',
  30885.             blockerClass: 'blocker',
  30886.             snaps: snaps
  30887.           }),
  30888.           Unselecting.config({})
  30889.         ]),
  30890.         eventOrder: {
  30891.           mousedown: [
  30892.             'dragging',
  30893.             'alloy.base.behaviour'
  30894.           ],
  30895.           touchstart: [
  30896.             'dragging',
  30897.             'alloy.base.behaviour'
  30898.           ]
  30899.         }
  30900.       }));
  30901.     };
  30902.     var setup$4 = function (editor, sink) {
  30903.       var tlTds = Cell([]);
  30904.       var brTds = Cell([]);
  30905.       var isVisible = Cell(false);
  30906.       var startCell = value$1();
  30907.       var finishCell = value$1();
  30908.       var getTopLeftSnap = function (td) {
  30909.         var box = absolute$2(td);
  30910.         return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  30911.       };
  30912.       var getTopLeftSnaps = function () {
  30913.         return map$2(tlTds.get(), function (td) {
  30914.           return getTopLeftSnap(td);
  30915.         });
  30916.       };
  30917.       var getBottomRightSnap = function (td) {
  30918.         var box = absolute$2(td);
  30919.         return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  30920.       };
  30921.       var getBottomRightSnaps = function () {
  30922.         return map$2(brTds.get(), function (td) {
  30923.           return getBottomRightSnap(td);
  30924.         });
  30925.       };
  30926.       var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  30927.         finishCell.get().each(function (finish) {
  30928.           editor.fire('TableSelectorChange', {
  30929.             start: start,
  30930.             finish: finish
  30931.           });
  30932.         });
  30933.       });
  30934.       var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  30935.         startCell.get().each(function (start) {
  30936.           editor.fire('TableSelectorChange', {
  30937.             start: start,
  30938.             finish: finish
  30939.           });
  30940.         });
  30941.       });
  30942.       var memTopLeft = createSelector(topLeftSnaps);
  30943.       var memBottomRight = createSelector(bottomRightSnaps);
  30944.       var topLeft = build$1(memTopLeft.asSpec());
  30945.       var bottomRight = build$1(memBottomRight.asSpec());
  30946.       var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  30947.         var cellRect = cell.dom.getBoundingClientRect();
  30948.         remove$6(selector.element, 'display');
  30949.         var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
  30950.         var aboveViewport = isAbove(cellRect);
  30951.         var belowViewport = isBelow(cellRect, viewportHeight);
  30952.         if (aboveViewport || belowViewport) {
  30953.           set$7(selector.element, 'display', 'none');
  30954.         }
  30955.       };
  30956.       var snapTo = function (selector, cell, getSnapConfig, pos) {
  30957.         var snap = getSnapConfig(cell);
  30958.         Dragging.snapTo(selector, snap);
  30959.         var isAbove = function (rect) {
  30960.           return rect[pos] < 0;
  30961.         };
  30962.         var isBelow = function (rect, viewportHeight) {
  30963.           return rect[pos] > viewportHeight;
  30964.         };
  30965.         showOrHideHandle(selector, cell, isAbove, isBelow);
  30966.       };
  30967.       var snapTopLeft = function (cell) {
  30968.         return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  30969.       };
  30970.       var snapLastTopLeft = function () {
  30971.         return startCell.get().each(snapTopLeft);
  30972.       };
  30973.       var snapBottomRight = function (cell) {
  30974.         return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  30975.       };
  30976.       var snapLastBottomRight = function () {
  30977.         return finishCell.get().each(snapBottomRight);
  30978.       };
  30979.       if (detect$1().deviceType.isTouch()) {
  30980.         editor.on('TableSelectionChange', function (e) {
  30981.           if (!isVisible.get()) {
  30982.             attach(sink, topLeft);
  30983.             attach(sink, bottomRight);
  30984.             isVisible.set(true);
  30985.           }
  30986.           startCell.set(e.start);
  30987.           finishCell.set(e.finish);
  30988.           e.otherCells.each(function (otherCells) {
  30989.             tlTds.set(otherCells.upOrLeftCells);
  30990.             brTds.set(otherCells.downOrRightCells);
  30991.             snapTopLeft(e.start);
  30992.             snapBottomRight(e.finish);
  30993.           });
  30994.         });
  30995.         editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  30996.           snapLastTopLeft();
  30997.           snapLastBottomRight();
  30998.         });
  30999.         editor.on('TableSelectionClear', function () {
  31000.           if (isVisible.get()) {
  31001.             detach(topLeft);
  31002.             detach(bottomRight);
  31003.             isVisible.set(false);
  31004.           }
  31005.           startCell.clear();
  31006.           finishCell.clear();
  31007.         });
  31008.       }
  31009.     };
  31010.  
  31011.     var isHidden = function (elm) {
  31012.       if (elm.nodeType === 1) {
  31013.         if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  31014.           return true;
  31015.         }
  31016.         if (elm.getAttribute('data-mce-type') === 'bookmark') {
  31017.           return true;
  31018.         }
  31019.       }
  31020.       return false;
  31021.     };
  31022.     var renderElementPath = function (editor, settings, providersBackstage) {
  31023.       if (!settings.delimiter) {
  31024.         settings.delimiter = '\xBB';
  31025.       }
  31026.       var getDataPath = function (data) {
  31027.         var parts = data || [];
  31028.         var newPathElements = map$2(parts, function (part, index) {
  31029.           return Button.sketch({
  31030.             dom: {
  31031.               tag: 'div',
  31032.               classes: ['tox-statusbar__path-item'],
  31033.               attributes: {
  31034.                 'role': 'button',
  31035.                 'data-index': index,
  31036.                 'tab-index': -1,
  31037.                 'aria-level': index + 1
  31038.               },
  31039.               innerHtml: part.name
  31040.             },
  31041.             action: function (_btn) {
  31042.               editor.focus();
  31043.               editor.selection.select(part.element);
  31044.               editor.nodeChanged();
  31045.             },
  31046.             buttonBehaviours: derive$1([
  31047.               DisablingConfigs.button(providersBackstage.isDisabled),
  31048.               receivingConfig()
  31049.             ])
  31050.           });
  31051.         });
  31052.         var divider = {
  31053.           dom: {
  31054.             tag: 'div',
  31055.             classes: ['tox-statusbar__path-divider'],
  31056.             attributes: { 'aria-hidden': true },
  31057.             innerHtml: ' ' + settings.delimiter + ' '
  31058.           }
  31059.         };
  31060.         return foldl(newPathElements.slice(1), function (acc, element) {
  31061.           var newAcc = acc;
  31062.           newAcc.push(divider);
  31063.           newAcc.push(element);
  31064.           return newAcc;
  31065.         }, [newPathElements[0]]);
  31066.       };
  31067.       var updatePath = function (parents) {
  31068.         var newPath = [];
  31069.         var i = parents.length;
  31070.         while (i-- > 0) {
  31071.           var parent_1 = parents[i];
  31072.           if (parent_1.nodeType === 1 && !isHidden(parent_1)) {
  31073.             var args = editor.fire('ResolveName', {
  31074.               name: parent_1.nodeName.toLowerCase(),
  31075.               target: parent_1
  31076.             });
  31077.             if (!args.isDefaultPrevented()) {
  31078.               newPath.push({
  31079.                 name: args.name,
  31080.                 element: parent_1
  31081.               });
  31082.             }
  31083.             if (args.isPropagationStopped()) {
  31084.               break;
  31085.             }
  31086.           }
  31087.         }
  31088.         return newPath;
  31089.       };
  31090.       return {
  31091.         dom: {
  31092.           tag: 'div',
  31093.           classes: ['tox-statusbar__path'],
  31094.           attributes: { role: 'navigation' }
  31095.         },
  31096.         behaviours: derive$1([
  31097.           Keying.config({
  31098.             mode: 'flow',
  31099.             selector: 'div[role=button]'
  31100.           }),
  31101.           Disabling.config({ disabled: providersBackstage.isDisabled }),
  31102.           receivingConfig(),
  31103.           Tabstopping.config({}),
  31104.           Replacing.config({}),
  31105.           config('elementPathEvents', [runOnAttached(function (comp, _e) {
  31106.               editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  31107.                 return Keying.focusIn(comp);
  31108.               });
  31109.               editor.on('NodeChange', function (e) {
  31110.                 var newPath = updatePath(e.parents);
  31111.                 if (newPath.length > 0) {
  31112.                   Replacing.set(comp, getDataPath(newPath));
  31113.                 } else {
  31114.                   Replacing.set(comp, []);
  31115.                 }
  31116.               });
  31117.             })])
  31118.         ]),
  31119.         components: []
  31120.       };
  31121.     };
  31122.  
  31123.     var ResizeTypes;
  31124.     (function (ResizeTypes) {
  31125.       ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  31126.       ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  31127.       ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  31128.     }(ResizeTypes || (ResizeTypes = {})));
  31129.     var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  31130.       var dimensions = {};
  31131.       dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
  31132.       if (resizeType === ResizeTypes.Both) {
  31133.         dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
  31134.       }
  31135.       return dimensions;
  31136.     };
  31137.     var resize = function (editor, deltas, resizeType) {
  31138.       var container = SugarElement.fromDom(editor.getContainer());
  31139.       var dimensions = getDimensions(editor, deltas, resizeType, get$b(container), get$a(container));
  31140.       each(dimensions, function (val, dim) {
  31141.         return set$7(container, dim, numToPx(val));
  31142.       });
  31143.       fireResizeEditor(editor);
  31144.     };
  31145.  
  31146.     var getResizeType = function (editor) {
  31147.       var fallback = !editor.hasPlugin('autoresize');
  31148.       var resize = editor.getParam('resize', fallback);
  31149.       if (resize === false) {
  31150.         return ResizeTypes.None;
  31151.       } else if (resize === 'both') {
  31152.         return ResizeTypes.Both;
  31153.       } else {
  31154.         return ResizeTypes.Vertical;
  31155.       }
  31156.     };
  31157.     var keyboardHandler = function (editor, resizeType, x, y) {
  31158.       var scale = 20;
  31159.       var delta = SugarPosition(x * scale, y * scale);
  31160.       resize(editor, delta, resizeType);
  31161.       return Optional.some(true);
  31162.     };
  31163.     var renderResizeHandler = function (editor, providersBackstage) {
  31164.       var resizeType = getResizeType(editor);
  31165.       if (resizeType === ResizeTypes.None) {
  31166.         return Optional.none();
  31167.       }
  31168.       return Optional.some(render$3('resize-handle', {
  31169.         tag: 'div',
  31170.         classes: ['tox-statusbar__resize-handle'],
  31171.         attributes: { title: providersBackstage.translate('Resize') },
  31172.         behaviours: [
  31173.           Dragging.config({
  31174.             mode: 'mouse',
  31175.             repositionTarget: false,
  31176.             onDrag: function (_comp, _target, delta) {
  31177.               return resize(editor, delta, resizeType);
  31178.             },
  31179.             blockerClass: 'tox-blocker'
  31180.           }),
  31181.           Keying.config({
  31182.             mode: 'special',
  31183.             onLeft: function () {
  31184.               return keyboardHandler(editor, resizeType, -1, 0);
  31185.             },
  31186.             onRight: function () {
  31187.               return keyboardHandler(editor, resizeType, 1, 0);
  31188.             },
  31189.             onUp: function () {
  31190.               return keyboardHandler(editor, resizeType, 0, -1);
  31191.             },
  31192.             onDown: function () {
  31193.               return keyboardHandler(editor, resizeType, 0, 1);
  31194.             }
  31195.           }),
  31196.           Tabstopping.config({}),
  31197.           Focusing.config({})
  31198.         ]
  31199.       }, providersBackstage.icons));
  31200.     };
  31201.  
  31202.     var renderWordCount = function (editor, providersBackstage) {
  31203.       var _a;
  31204.       var replaceCountText = function (comp, count, mode) {
  31205.         return Replacing.set(comp, [text$1(providersBackstage.translate([
  31206.             '{0} ' + mode,
  31207.             count[mode]
  31208.           ]))]);
  31209.       };
  31210.       return Button.sketch({
  31211.         dom: {
  31212.           tag: 'button',
  31213.           classes: ['tox-statusbar__wordcount']
  31214.         },
  31215.         components: [],
  31216.         buttonBehaviours: derive$1([
  31217.           DisablingConfigs.button(providersBackstage.isDisabled),
  31218.           receivingConfig(),
  31219.           Tabstopping.config({}),
  31220.           Replacing.config({}),
  31221.           Representing.config({
  31222.             store: {
  31223.               mode: 'memory',
  31224.               initialValue: {
  31225.                 mode: 'words',
  31226.                 count: {
  31227.                   words: 0,
  31228.                   characters: 0
  31229.                 }
  31230.               }
  31231.             }
  31232.           }),
  31233.           config('wordcount-events', [
  31234.             runOnExecute$1(function (comp) {
  31235.               var currentVal = Representing.getValue(comp);
  31236.               var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  31237.               Representing.setValue(comp, {
  31238.                 mode: newMode,
  31239.                 count: currentVal.count
  31240.               });
  31241.               replaceCountText(comp, currentVal.count, newMode);
  31242.             }),
  31243.             runOnAttached(function (comp) {
  31244.               editor.on('wordCountUpdate', function (e) {
  31245.                 var mode = Representing.getValue(comp).mode;
  31246.                 Representing.setValue(comp, {
  31247.                   mode: mode,
  31248.                   count: e.wordCount
  31249.                 });
  31250.                 replaceCountText(comp, e.wordCount, mode);
  31251.               });
  31252.             })
  31253.           ])
  31254.         ]),
  31255.         eventOrder: (_a = {}, _a[execute$5()] = [
  31256.           'disabling',
  31257.           'alloy.base.behaviour',
  31258.           'wordcount-events'
  31259.         ], _a)
  31260.       });
  31261.     };
  31262.  
  31263.     var renderStatusbar = function (editor, providersBackstage) {
  31264.       var renderBranding = function () {
  31265.         var label = global$e.translate([
  31266.           'Powered by {0}',
  31267.           'Tiny'
  31268.         ]);
  31269.         var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce&amp;utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + '</a>';
  31270.         return {
  31271.           dom: {
  31272.             tag: 'span',
  31273.             classes: ['tox-statusbar__branding'],
  31274.             innerHtml: linkHtml
  31275.           }
  31276.         };
  31277.       };
  31278.       var getTextComponents = function () {
  31279.         var components = [];
  31280.         if (editor.getParam('elementpath', true, 'boolean')) {
  31281.           components.push(renderElementPath(editor, {}, providersBackstage));
  31282.         }
  31283.         if (editor.hasPlugin('wordcount')) {
  31284.           components.push(renderWordCount(editor, providersBackstage));
  31285.         }
  31286.         if (editor.getParam('branding', true, 'boolean')) {
  31287.           components.push(renderBranding());
  31288.         }
  31289.         if (components.length > 0) {
  31290.           return [{
  31291.               dom: {
  31292.                 tag: 'div',
  31293.                 classes: ['tox-statusbar__text-container']
  31294.               },
  31295.               components: components
  31296.             }];
  31297.         }
  31298.         return [];
  31299.       };
  31300.       var getComponents = function () {
  31301.         var components = getTextComponents();
  31302.         var resizeHandler = renderResizeHandler(editor, providersBackstage);
  31303.         return components.concat(resizeHandler.toArray());
  31304.       };
  31305.       return {
  31306.         dom: {
  31307.           tag: 'div',
  31308.           classes: ['tox-statusbar']
  31309.         },
  31310.         components: getComponents()
  31311.       };
  31312.     };
  31313.  
  31314.     var setup$3 = function (editor) {
  31315.       var _a;
  31316.       var isInline = editor.inline;
  31317.       var mode = isInline ? Inline : Iframe;
  31318.       var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  31319.       var lazyOuterContainer = Optional.none();
  31320.       var platform = detect$1();
  31321.       var isIE = platform.browser.isIE();
  31322.       var platformClasses = isIE ? ['tox-platform-ie'] : [];
  31323.       var isTouch = platform.deviceType.isTouch();
  31324.       var touchPlatformClass = 'tox-platform-touch';
  31325.       var deviceClasses = isTouch ? [touchPlatformClass] : [];
  31326.       var isToolbarBottom = isToolbarLocationBottom(editor);
  31327.       var uiContainer = getUiContainer(editor);
  31328.       var dirAttributes = global$e.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  31329.       var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
  31330.       var lazyHeader = function () {
  31331.         return lazyOuterContainer.bind(OuterContainer.getHeader);
  31332.       };
  31333.       var isHeaderDocked = function () {
  31334.         return header.isDocked(lazyHeader);
  31335.       };
  31336.       var resizeUiMothership = function () {
  31337.         set$7(uiMothership.element, 'width', document.body.clientWidth + 'px');
  31338.       };
  31339.       var makeSinkDefinition = function () {
  31340.         var isGridUiContainer = eq(body(), uiContainer) && get$c(uiContainer, 'display') === 'grid';
  31341.         var sinkSpec = {
  31342.           dom: __assign({
  31343.             tag: 'div',
  31344.             classes: [
  31345.               'tox',
  31346.               'tox-silver-sink',
  31347.               'tox-tinymce-aux'
  31348.             ].concat(platformClasses).concat(deviceClasses)
  31349.           }, dirAttributes),
  31350.           behaviours: derive$1([Positioning.config({
  31351.               useFixed: function () {
  31352.                 return isHeaderDocked();
  31353.               }
  31354.             })])
  31355.         };
  31356.         var reactiveWidthSpec = {
  31357.           dom: { styles: { width: document.body.clientWidth + 'px' } },
  31358.           events: derive$2([run$1(windowResize(), resizeUiMothership)])
  31359.         };
  31360.         return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
  31361.       };
  31362.       var sink = build$1(makeSinkDefinition());
  31363.       var lazySink = function () {
  31364.         return Result.value(sink);
  31365.       };
  31366.       var memAnchorBar = record({
  31367.         dom: {
  31368.           tag: 'div',
  31369.           classes: ['tox-anchorbar']
  31370.         }
  31371.       });
  31372.       var lazyAnchorBar = function () {
  31373.         return lazyOuterContainer.bind(function (container) {
  31374.           return memAnchorBar.getOpt(container);
  31375.         }).getOrDie('Could not find a anchor bar element');
  31376.       };
  31377.       var lazyToolbar = function () {
  31378.         return lazyOuterContainer.bind(function (container) {
  31379.           return OuterContainer.getToolbar(container);
  31380.         }).getOrDie('Could not find more toolbar element');
  31381.       };
  31382.       var lazyThrobber = function () {
  31383.         return lazyOuterContainer.bind(function (container) {
  31384.           return OuterContainer.getThrobber(container);
  31385.         }).getOrDie('Could not find throbber element');
  31386.       };
  31387.       var backstage = init$7(sink, editor, lazyAnchorBar);
  31388.       var partMenubar = OuterContainer.parts.menubar({
  31389.         dom: {
  31390.           tag: 'div',
  31391.           classes: ['tox-menubar']
  31392.         },
  31393.         backstage: backstage,
  31394.         onEscape: function () {
  31395.           editor.focus();
  31396.         }
  31397.       });
  31398.       var toolbarMode = getToolbarMode(editor);
  31399.       var partToolbar = OuterContainer.parts.toolbar(__assign({
  31400.         dom: {
  31401.           tag: 'div',
  31402.           classes: ['tox-toolbar']
  31403.         },
  31404.         getSink: lazySink,
  31405.         providers: backstage.shared.providers,
  31406.         onEscape: function () {
  31407.           editor.focus();
  31408.         },
  31409.         type: toolbarMode,
  31410.         lazyToolbar: lazyToolbar,
  31411.         lazyHeader: function () {
  31412.           return lazyHeader().getOrDie('Could not find header element');
  31413.         }
  31414.       }, verticalDirAttributes));
  31415.       var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
  31416.         dom: {
  31417.           tag: 'div',
  31418.           classes: ['tox-toolbar-overlord']
  31419.         },
  31420.         providers: backstage.shared.providers,
  31421.         onEscape: function () {
  31422.           editor.focus();
  31423.         },
  31424.         type: toolbarMode
  31425.       });
  31426.       var partSocket = OuterContainer.parts.socket({
  31427.         dom: {
  31428.           tag: 'div',
  31429.           classes: ['tox-edit-area']
  31430.         }
  31431.       });
  31432.       var partSidebar = OuterContainer.parts.sidebar({
  31433.         dom: {
  31434.           tag: 'div',
  31435.           classes: ['tox-sidebar']
  31436.         }
  31437.       });
  31438.       var partThrobber = OuterContainer.parts.throbber({
  31439.         dom: {
  31440.           tag: 'div',
  31441.           classes: ['tox-throbber']
  31442.         },
  31443.         backstage: backstage
  31444.       });
  31445.       var sb = editor.getParam('statusbar', true, 'boolean');
  31446.       var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
  31447.       var socketSidebarContainer = {
  31448.         dom: {
  31449.           tag: 'div',
  31450.           classes: ['tox-sidebar-wrap']
  31451.         },
  31452.         components: [
  31453.           partSocket,
  31454.           partSidebar
  31455.         ]
  31456.       };
  31457.       var hasMultipleToolbar = isMultipleToolbars(editor);
  31458.       var hasToolbar = isToolbarEnabled(editor);
  31459.       var hasMenubar = isMenubarEnabled(editor);
  31460.       var getPartToolbar = function () {
  31461.         if (hasMultipleToolbar) {
  31462.           return [partMultipleToolbar];
  31463.         } else if (hasToolbar) {
  31464.           return [partToolbar];
  31465.         } else {
  31466.           return [];
  31467.         }
  31468.       };
  31469.       var partHeader = OuterContainer.parts.header({
  31470.         dom: __assign({
  31471.           tag: 'div',
  31472.           classes: ['tox-editor-header']
  31473.         }, verticalDirAttributes),
  31474.         components: flatten([
  31475.           hasMenubar ? [partMenubar] : [],
  31476.           getPartToolbar(),
  31477.           useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  31478.         ]),
  31479.         sticky: isStickyToolbar(editor),
  31480.         editor: editor,
  31481.         sharedBackstage: backstage.shared
  31482.       });
  31483.       var editorComponents = flatten([
  31484.         isToolbarBottom ? [] : [partHeader],
  31485.         isInline ? [] : [socketSidebarContainer],
  31486.         isToolbarBottom ? [partHeader] : []
  31487.       ]);
  31488.       var editorContainer = {
  31489.         dom: {
  31490.           tag: 'div',
  31491.           classes: ['tox-editor-container']
  31492.         },
  31493.         components: editorComponents
  31494.       };
  31495.       var containerComponents = flatten([
  31496.         [editorContainer],
  31497.         isInline ? [] : statusbar.toArray(),
  31498.         [partThrobber]
  31499.       ]);
  31500.       var isHidden = isDistractionFree(editor);
  31501.       var attributes = __assign(__assign({ role: 'application' }, global$e.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  31502.       var outerContainer = build$1(OuterContainer.sketch({
  31503.         dom: {
  31504.           tag: 'div',
  31505.           classes: [
  31506.             'tox',
  31507.             'tox-tinymce'
  31508.           ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
  31509.           styles: __assign({ visibility: 'hidden' }, isHidden ? {
  31510.             opacity: '0',
  31511.             border: '0'
  31512.           } : {}),
  31513.           attributes: attributes
  31514.         },
  31515.         components: containerComponents,
  31516.         behaviours: derive$1([
  31517.           receivingConfig(),
  31518.           Disabling.config({ disableClass: 'tox-tinymce--disabled' }),
  31519.           Keying.config({
  31520.             mode: 'cyclic',
  31521.             selector: '.tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a, .tox-statusbar__resize-handle'
  31522.           })
  31523.         ])
  31524.       }));
  31525.       lazyOuterContainer = Optional.some(outerContainer);
  31526.       editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  31527.         OuterContainer.focusMenubar(outerContainer);
  31528.       });
  31529.       editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  31530.         OuterContainer.focusToolbar(outerContainer);
  31531.       });
  31532.       editor.addCommand('ToggleToolbarDrawer', function () {
  31533.         OuterContainer.toggleToolbarDrawer(outerContainer);
  31534.       });
  31535.       editor.addQueryStateHandler('ToggleToolbarDrawer', function () {
  31536.         return OuterContainer.isToolbarDrawerToggled(outerContainer);
  31537.       });
  31538.       var mothership = takeover(outerContainer);
  31539.       var uiMothership = takeover(sink);
  31540.       setup$b(editor, mothership, uiMothership);
  31541.       var getUi = function () {
  31542.         var channels = {
  31543.           broadcastAll: uiMothership.broadcast,
  31544.           broadcastOn: uiMothership.broadcastOn,
  31545.           register: noop
  31546.         };
  31547.         return { channels: channels };
  31548.       };
  31549.       var setEditorSize = function () {
  31550.         var parsedHeight = numToPx(getHeightWithFallback(editor));
  31551.         var parsedWidth = numToPx(getWidthWithFallback(editor));
  31552.         if (!editor.inline) {
  31553.           if (isValidValue('div', 'width', parsedWidth)) {
  31554.             set$7(outerContainer.element, 'width', parsedWidth);
  31555.           }
  31556.           if (isValidValue('div', 'height', parsedHeight)) {
  31557.             set$7(outerContainer.element, 'height', parsedHeight);
  31558.           } else {
  31559.             set$7(outerContainer.element, 'height', '200px');
  31560.           }
  31561.         }
  31562.         return parsedHeight;
  31563.       };
  31564.       var renderUI = function () {
  31565.         header.setup(editor, backstage.shared, lazyHeader);
  31566.         setup$6(editor, backstage);
  31567.         setup$5(editor, lazySink, backstage);
  31568.         setup$8(editor);
  31569.         setup$7(editor, lazyThrobber, backstage.shared);
  31570.         map$1(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  31571.           editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  31572.         });
  31573.         var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  31574.         var toolbarOpt = getMultipleToolbarsSetting(editor);
  31575.         var rawUiConfig = {
  31576.           menuItems: menuItems,
  31577.           menus: getMenus(editor),
  31578.           menubar: getMenubar(editor),
  31579.           toolbar: toolbarOpt.getOrThunk(function () {
  31580.             return getToolbar(editor);
  31581.           }),
  31582.           allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  31583.           buttons: buttons,
  31584.           sidebar: sidebars
  31585.         };
  31586.         register$7(editor, contextToolbars, sink, { backstage: backstage });
  31587.         setup$4(editor, sink);
  31588.         var elm = editor.getElement();
  31589.         var height = setEditorSize();
  31590.         var uiComponents = {
  31591.           mothership: mothership,
  31592.           uiMothership: uiMothership,
  31593.           outerContainer: outerContainer
  31594.         };
  31595.         var args = {
  31596.           targetNode: elm,
  31597.           height: height
  31598.         };
  31599.         return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  31600.       };
  31601.       return {
  31602.         mothership: mothership,
  31603.         uiMothership: uiMothership,
  31604.         backstage: backstage,
  31605.         renderUI: renderUI,
  31606.         getUi: getUi
  31607.       };
  31608.     };
  31609.  
  31610.     var describedBy = function (describedElement, describeElement) {
  31611.       var describeId = Optional.from(get$d(describedElement, 'id')).fold(function () {
  31612.         var id = generate$6('dialog-describe');
  31613.         set$8(describeElement, 'id', id);
  31614.         return id;
  31615.       }, identity$1);
  31616.       set$8(describedElement, 'aria-describedby', describeId);
  31617.     };
  31618.  
  31619.     var labelledBy = function (labelledElement, labelElement) {
  31620.       var labelId = getOpt(labelledElement, 'id').fold(function () {
  31621.         var id = generate$6('dialog-label');
  31622.         set$8(labelElement, 'id', id);
  31623.         return id;
  31624.       }, identity$1);
  31625.       set$8(labelledElement, 'aria-labelledby', labelId);
  31626.     };
  31627.  
  31628.     var schema$2 = constant$1([
  31629.       required$1('lazySink'),
  31630.       option('dragBlockClass'),
  31631.       defaultedFunction('getBounds', win),
  31632.       defaulted('useTabstopAt', always),
  31633.       defaulted('eventOrder', {}),
  31634.       field('modalBehaviours', [Keying]),
  31635.       onKeyboardHandler('onExecute'),
  31636.       onStrictKeyboardHandler('onEscape')
  31637.     ]);
  31638.     var basic = { sketch: identity$1 };
  31639.     var parts$2 = constant$1([
  31640.       optional({
  31641.         name: 'draghandle',
  31642.         overrides: function (detail, spec) {
  31643.           return {
  31644.             behaviours: derive$1([Dragging.config({
  31645.                 mode: 'mouse',
  31646.                 getTarget: function (handle) {
  31647.                   return ancestor(handle, '[role="dialog"]').getOr(handle);
  31648.                 },
  31649.                 blockerClass: detail.dragBlockClass.getOrDie(new Error('The drag blocker class was not specified for a dialog with a drag handle: \n' + JSON.stringify(spec, null, 2)).message),
  31650.                 getBounds: detail.getDragBounds
  31651.               })])
  31652.           };
  31653.         }
  31654.       }),
  31655.       required({
  31656.         schema: [required$1('dom')],
  31657.         name: 'title'
  31658.       }),
  31659.       required({
  31660.         factory: basic,
  31661.         schema: [required$1('dom')],
  31662.         name: 'close'
  31663.       }),
  31664.       required({
  31665.         factory: basic,
  31666.         schema: [required$1('dom')],
  31667.         name: 'body'
  31668.       }),
  31669.       optional({
  31670.         factory: basic,
  31671.         schema: [required$1('dom')],
  31672.         name: 'footer'
  31673.       }),
  31674.       external$1({
  31675.         factory: {
  31676.           sketch: function (spec, detail) {
  31677.             return __assign(__assign({}, spec), {
  31678.               dom: detail.dom,
  31679.               components: detail.components
  31680.             });
  31681.           }
  31682.         },
  31683.         schema: [
  31684.           defaulted('dom', {
  31685.             tag: 'div',
  31686.             styles: {
  31687.               position: 'fixed',
  31688.               left: '0px',
  31689.               top: '0px',
  31690.               right: '0px',
  31691.               bottom: '0px'
  31692.             }
  31693.           }),
  31694.           defaulted('components', [])
  31695.         ],
  31696.         name: 'blocker'
  31697.       })
  31698.     ]);
  31699.  
  31700.     var factory$4 = function (detail, components, spec, externals) {
  31701.       var _a;
  31702.       var dialogComp = value$1();
  31703.       var showDialog = function (dialog) {
  31704.         dialogComp.set(dialog);
  31705.         var sink = detail.lazySink(dialog).getOrDie();
  31706.         var externalBlocker = externals.blocker();
  31707.         var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  31708.           components: externalBlocker.components.concat([premade(dialog)]),
  31709.           behaviours: derive$1([
  31710.             Focusing.config({}),
  31711.             config('dialog-blocker-events', [runOnSource(focusin(), function () {
  31712.                 Keying.focusIn(dialog);
  31713.               })])
  31714.           ])
  31715.         }));
  31716.         attach(sink, blocker);
  31717.         Keying.focusIn(dialog);
  31718.       };
  31719.       var hideDialog = function (dialog) {
  31720.         dialogComp.clear();
  31721.         parent(dialog.element).each(function (blockerDom) {
  31722.           dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  31723.             detach(blocker);
  31724.           });
  31725.         });
  31726.       };
  31727.       var getDialogBody = function (dialog) {
  31728.         return getPartOrDie(dialog, detail, 'body');
  31729.       };
  31730.       var getDialogFooter = function (dialog) {
  31731.         return getPartOrDie(dialog, detail, 'footer');
  31732.       };
  31733.       var setBusy = function (dialog, getBusySpec) {
  31734.         Blocking.block(dialog, getBusySpec);
  31735.       };
  31736.       var setIdle = function (dialog) {
  31737.         Blocking.unblock(dialog);
  31738.       };
  31739.       var modalEventsId = generate$6('modal-events');
  31740.       var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a));
  31741.       return {
  31742.         uid: detail.uid,
  31743.         dom: detail.dom,
  31744.         components: components,
  31745.         apis: {
  31746.           show: showDialog,
  31747.           hide: hideDialog,
  31748.           getBody: getDialogBody,
  31749.           getFooter: getDialogFooter,
  31750.           setIdle: setIdle,
  31751.           setBusy: setBusy
  31752.         },
  31753.         eventOrder: eventOrder,
  31754.         domModification: {
  31755.           attributes: {
  31756.             'role': 'dialog',
  31757.             'aria-modal': 'true'
  31758.           }
  31759.         },
  31760.         behaviours: augment(detail.modalBehaviours, [
  31761.           Replacing.config({}),
  31762.           Keying.config({
  31763.             mode: 'cyclic',
  31764.             onEnter: detail.onExecute,
  31765.             onEscape: detail.onEscape,
  31766.             useTabstopAt: detail.useTabstopAt
  31767.           }),
  31768.           Blocking.config({ getRoot: dialogComp.get }),
  31769.           config(modalEventsId, [runOnAttached(function (c) {
  31770.               labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
  31771.               describedBy(c.element, getPartOrDie(c, detail, 'body').element);
  31772.             })])
  31773.         ])
  31774.       };
  31775.     };
  31776.     var ModalDialog = composite({
  31777.       name: 'ModalDialog',
  31778.       configFields: schema$2(),
  31779.       partFields: parts$2(),
  31780.       factory: factory$4,
  31781.       apis: {
  31782.         show: function (apis, dialog) {
  31783.           apis.show(dialog);
  31784.         },
  31785.         hide: function (apis, dialog) {
  31786.           apis.hide(dialog);
  31787.         },
  31788.         getBody: function (apis, dialog) {
  31789.           return apis.getBody(dialog);
  31790.         },
  31791.         getFooter: function (apis, dialog) {
  31792.           return apis.getFooter(dialog);
  31793.         },
  31794.         setBusy: function (apis, dialog, getBusySpec) {
  31795.           apis.setBusy(dialog, getBusySpec);
  31796.         },
  31797.         setIdle: function (apis, dialog) {
  31798.           apis.setIdle(dialog);
  31799.         }
  31800.       }
  31801.     });
  31802.  
  31803.     var dialogToggleMenuItemSchema = objOf([
  31804.       requiredString('type'),
  31805.       requiredString('name')
  31806.     ].concat(commonMenuItemFields));
  31807.     var dialogToggleMenuItemDataProcessor = boolean;
  31808.  
  31809.     var baseFooterButtonFields = [
  31810.       field$1('name', 'name', defaultedThunk(function () {
  31811.         return generate$6('button-name');
  31812.       }), string),
  31813.       optionString('icon'),
  31814.       defaultedStringEnum('align', 'end', [
  31815.         'start',
  31816.         'end'
  31817.       ]),
  31818.       defaultedBoolean('primary', false),
  31819.       defaultedBoolean('disabled', false)
  31820.     ];
  31821.     var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields, true), [requiredString('text')], false);
  31822.     var normalFooterButtonFields = __spreadArray([requiredStringEnum('type', [
  31823.         'submit',
  31824.         'cancel',
  31825.         'custom'
  31826.       ])], dialogFooterButtonFields, true);
  31827.     var menuFooterButtonFields = __spreadArray([
  31828.       requiredStringEnum('type', ['menu']),
  31829.       optionString('text'),
  31830.       optionString('tooltip'),
  31831.       optionString('icon'),
  31832.       requiredArrayOf('items', dialogToggleMenuItemSchema)
  31833.     ], baseFooterButtonFields, true);
  31834.     var dialogFooterButtonSchema = choose$1('type', {
  31835.       submit: normalFooterButtonFields,
  31836.       cancel: normalFooterButtonFields,
  31837.       custom: normalFooterButtonFields,
  31838.       menu: menuFooterButtonFields
  31839.     });
  31840.  
  31841.     var alertBannerFields = [
  31842.       requiredString('type'),
  31843.       requiredString('text'),
  31844.       requiredStringEnum('level', [
  31845.         'info',
  31846.         'warn',
  31847.         'error',
  31848.         'success'
  31849.       ]),
  31850.       requiredString('icon'),
  31851.       defaulted('url', '')
  31852.     ];
  31853.     var alertBannerSchema = objOf(alertBannerFields);
  31854.  
  31855.     var createBarFields = function (itemsField) {
  31856.       return [
  31857.         requiredString('type'),
  31858.         itemsField
  31859.       ];
  31860.     };
  31861.  
  31862.     var buttonFields = [
  31863.       requiredString('type'),
  31864.       requiredString('text'),
  31865.       defaultedBoolean('disabled', false),
  31866.       defaultedBoolean('primary', false),
  31867.       field$1('name', 'name', defaultedThunk(function () {
  31868.         return generate$6('button-name');
  31869.       }), string),
  31870.       optionString('icon'),
  31871.       defaultedBoolean('borderless', false)
  31872.     ];
  31873.     var buttonSchema = objOf(buttonFields);
  31874.  
  31875.     var checkboxFields = [
  31876.       requiredString('type'),
  31877.       requiredString('name'),
  31878.       requiredString('label'),
  31879.       defaultedBoolean('disabled', false)
  31880.     ];
  31881.     var checkboxSchema = objOf(checkboxFields);
  31882.     var checkboxDataProcessor = boolean;
  31883.  
  31884.     var formComponentFields = [
  31885.       requiredString('type'),
  31886.       requiredString('name')
  31887.     ];
  31888.     var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  31889.  
  31890.     var collectionFields = formComponentWithLabelFields.concat([defaulted('columns', 'auto')]);
  31891.     var collectionSchema = objOf(collectionFields);
  31892.     var collectionDataProcessor = arrOfObj([
  31893.       requiredString('value'),
  31894.       requiredString('text'),
  31895.       requiredString('icon')
  31896.     ]);
  31897.  
  31898.     var colorInputFields = formComponentWithLabelFields;
  31899.     var colorInputSchema = objOf(colorInputFields);
  31900.     var colorInputDataProcessor = string;
  31901.  
  31902.     var colorPickerFields = formComponentWithLabelFields;
  31903.     var colorPickerSchema = objOf(colorPickerFields);
  31904.     var colorPickerDataProcessor = string;
  31905.  
  31906.     var customEditorFields = formComponentFields.concat([
  31907.       defaultedString('tag', 'textarea'),
  31908.       requiredString('scriptId'),
  31909.       requiredString('scriptUrl'),
  31910.       defaultedPostMsg('settings', undefined)
  31911.     ]);
  31912.     var customEditorFieldsOld = formComponentFields.concat([
  31913.       defaultedString('tag', 'textarea'),
  31914.       requiredFunction('init')
  31915.     ]);
  31916.     var customEditorSchema = valueOf(function (v) {
  31917.       return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  31918.         return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  31919.       });
  31920.     });
  31921.     var customEditorDataProcessor = string;
  31922.  
  31923.     var dropZoneFields = formComponentWithLabelFields;
  31924.     var dropZoneSchema = objOf(dropZoneFields);
  31925.     var dropZoneDataProcessor = arrOfVal();
  31926.  
  31927.     var createGridFields = function (itemsField) {
  31928.       return [
  31929.         requiredString('type'),
  31930.         requiredNumber('columns'),
  31931.         itemsField
  31932.       ];
  31933.     };
  31934.  
  31935.     var htmlPanelFields = [
  31936.       requiredString('type'),
  31937.       requiredString('html'),
  31938.       defaultedStringEnum('presets', 'presentation', [
  31939.         'presentation',
  31940.         'document'
  31941.       ])
  31942.     ];
  31943.     var htmlPanelSchema = objOf(htmlPanelFields);
  31944.  
  31945.     var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  31946.     var iframeSchema = objOf(iframeFields);
  31947.     var iframeDataProcessor = string;
  31948.  
  31949.     var imageToolsFields = formComponentWithLabelFields.concat([requiredOf('currentState', objOf([
  31950.         required$1('blob'),
  31951.         requiredString('url')
  31952.       ]))]);
  31953.     var imageToolsSchema = objOf(imageToolsFields);
  31954.  
  31955.     var inputFields = formComponentWithLabelFields.concat([
  31956.       optionString('inputMode'),
  31957.       optionString('placeholder'),
  31958.       defaultedBoolean('maximized', false),
  31959.       defaultedBoolean('disabled', false)
  31960.     ]);
  31961.     var inputSchema = objOf(inputFields);
  31962.     var inputDataProcessor = string;
  31963.  
  31964.     var createLabelFields = function (itemsField) {
  31965.       return [
  31966.         requiredString('type'),
  31967.         requiredString('label'),
  31968.         itemsField
  31969.       ];
  31970.     };
  31971.  
  31972.     var listBoxSingleItemFields = [
  31973.       requiredString('text'),
  31974.       requiredString('value')
  31975.     ];
  31976.     var listBoxNestedItemFields = [
  31977.       requiredString('text'),
  31978.       requiredArrayOf('items', thunkOf('items', function () {
  31979.         return listBoxItemSchema;
  31980.       }))
  31981.     ];
  31982.     var listBoxItemSchema = oneOf([
  31983.       objOf(listBoxSingleItemFields),
  31984.       objOf(listBoxNestedItemFields)
  31985.     ]);
  31986.     var listBoxFields = formComponentWithLabelFields.concat([
  31987.       requiredArrayOf('items', listBoxItemSchema),
  31988.       defaultedBoolean('disabled', false)
  31989.     ]);
  31990.     var listBoxSchema = objOf(listBoxFields);
  31991.     var listBoxDataProcessor = string;
  31992.  
  31993.     var selectBoxFields = formComponentWithLabelFields.concat([
  31994.       requiredArrayOfObj('items', [
  31995.         requiredString('text'),
  31996.         requiredString('value')
  31997.       ]),
  31998.       defaultedNumber('size', 1),
  31999.       defaultedBoolean('disabled', false)
  32000.     ]);
  32001.     var selectBoxSchema = objOf(selectBoxFields);
  32002.     var selectBoxDataProcessor = string;
  32003.  
  32004.     var sizeInputFields = formComponentWithLabelFields.concat([
  32005.       defaultedBoolean('constrain', true),
  32006.       defaultedBoolean('disabled', false)
  32007.     ]);
  32008.     var sizeInputSchema = objOf(sizeInputFields);
  32009.     var sizeInputDataProcessor = objOf([
  32010.       requiredString('width'),
  32011.       requiredString('height')
  32012.     ]);
  32013.  
  32014.     var tableFields = [
  32015.       requiredString('type'),
  32016.       requiredArrayOf('header', string),
  32017.       requiredArrayOf('cells', arrOf(string))
  32018.     ];
  32019.     var tableSchema = objOf(tableFields);
  32020.  
  32021.     var textAreaFields = formComponentWithLabelFields.concat([
  32022.       optionString('placeholder'),
  32023.       defaultedBoolean('maximized', false),
  32024.       defaultedBoolean('disabled', false)
  32025.     ]);
  32026.     var textAreaSchema = objOf(textAreaFields);
  32027.     var textAreaDataProcessor = string;
  32028.  
  32029.     var urlInputFields = formComponentWithLabelFields.concat([
  32030.       defaultedStringEnum('filetype', 'file', [
  32031.         'image',
  32032.         'media',
  32033.         'file'
  32034.       ]),
  32035.       defaulted('disabled', false)
  32036.     ]);
  32037.     var urlInputSchema = objOf(urlInputFields);
  32038.     var urlInputDataProcessor = objOf([
  32039.       requiredString('value'),
  32040.       defaulted('meta', {})
  32041.     ]);
  32042.  
  32043.     var createItemsField = function (name) {
  32044.       return field$1('items', 'items', required$2(), arrOf(valueOf(function (v) {
  32045.         return asRaw('Checking item of ' + name, itemSchema, v).fold(function (sErr) {
  32046.           return Result.error(formatError(sErr));
  32047.         }, function (passValue) {
  32048.           return Result.value(passValue);
  32049.         });
  32050.       })));
  32051.     };
  32052.     var itemSchema = valueThunk(function () {
  32053.       return choose$2('type', {
  32054.         alertbanner: alertBannerSchema,
  32055.         bar: objOf(createBarFields(createItemsField('bar'))),
  32056.         button: buttonSchema,
  32057.         checkbox: checkboxSchema,
  32058.         colorinput: colorInputSchema,
  32059.         colorpicker: colorPickerSchema,
  32060.         dropzone: dropZoneSchema,
  32061.         grid: objOf(createGridFields(createItemsField('grid'))),
  32062.         iframe: iframeSchema,
  32063.         input: inputSchema,
  32064.         listbox: listBoxSchema,
  32065.         selectbox: selectBoxSchema,
  32066.         sizeinput: sizeInputSchema,
  32067.         textarea: textAreaSchema,
  32068.         urlinput: urlInputSchema,
  32069.         customeditor: customEditorSchema,
  32070.         htmlpanel: htmlPanelSchema,
  32071.         imagetools: imageToolsSchema,
  32072.         collection: collectionSchema,
  32073.         label: objOf(createLabelFields(createItemsField('label'))),
  32074.         table: tableSchema,
  32075.         panel: panelSchema
  32076.       });
  32077.     });
  32078.     var panelFields = [
  32079.       requiredString('type'),
  32080.       defaulted('classes', []),
  32081.       requiredArrayOf('items', itemSchema)
  32082.     ];
  32083.     var panelSchema = objOf(panelFields);
  32084.  
  32085.     var tabFields = [
  32086.       field$1('name', 'name', defaultedThunk(function () {
  32087.         return generate$6('tab-name');
  32088.       }), string),
  32089.       requiredString('title'),
  32090.       requiredArrayOf('items', itemSchema)
  32091.     ];
  32092.     var tabPanelFields = [
  32093.       requiredString('type'),
  32094.       requiredArrayOfObj('tabs', tabFields)
  32095.     ];
  32096.     var tabPanelSchema = objOf(tabPanelFields);
  32097.  
  32098.     var dialogButtonFields = dialogFooterButtonFields;
  32099.     var dialogButtonSchema = dialogFooterButtonSchema;
  32100.     var dialogSchema = objOf([
  32101.       requiredString('title'),
  32102.       requiredOf('body', choose$2('type', {
  32103.         panel: panelSchema,
  32104.         tabpanel: tabPanelSchema
  32105.       })),
  32106.       defaultedString('size', 'normal'),
  32107.       requiredArrayOf('buttons', dialogButtonSchema),
  32108.       defaulted('initialData', {}),
  32109.       defaultedFunction('onAction', noop),
  32110.       defaultedFunction('onChange', noop),
  32111.       defaultedFunction('onSubmit', noop),
  32112.       defaultedFunction('onClose', noop),
  32113.       defaultedFunction('onCancel', noop),
  32114.       defaulted('onTabChange', noop)
  32115.     ]);
  32116.     var createDialog = function (spec) {
  32117.       return asRaw('dialog', dialogSchema, spec);
  32118.     };
  32119.  
  32120.     var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum('type', [
  32121.         'cancel',
  32122.         'custom'
  32123.       ])], dialogButtonFields, true));
  32124.     var urlDialogSchema = objOf([
  32125.       requiredString('title'),
  32126.       requiredString('url'),
  32127.       optionNumber('height'),
  32128.       optionNumber('width'),
  32129.       optionArrayOf('buttons', urlDialogButtonSchema),
  32130.       defaultedFunction('onAction', noop),
  32131.       defaultedFunction('onCancel', noop),
  32132.       defaultedFunction('onClose', noop),
  32133.       defaultedFunction('onMessage', noop)
  32134.     ]);
  32135.     var createUrlDialog = function (spec) {
  32136.       return asRaw('dialog', urlDialogSchema, spec);
  32137.     };
  32138.  
  32139.     var getAllObjects = function (obj) {
  32140.       if (isObject(obj)) {
  32141.         return [obj].concat(bind$3(values(obj), getAllObjects));
  32142.       } else if (isArray(obj)) {
  32143.         return bind$3(obj, getAllObjects);
  32144.       } else {
  32145.         return [];
  32146.       }
  32147.     };
  32148.  
  32149.     var isNamedItem = function (obj) {
  32150.       return isString(obj.type) && isString(obj.name);
  32151.     };
  32152.     var dataProcessors = {
  32153.       checkbox: checkboxDataProcessor,
  32154.       colorinput: colorInputDataProcessor,
  32155.       colorpicker: colorPickerDataProcessor,
  32156.       dropzone: dropZoneDataProcessor,
  32157.       input: inputDataProcessor,
  32158.       iframe: iframeDataProcessor,
  32159.       sizeinput: sizeInputDataProcessor,
  32160.       selectbox: selectBoxDataProcessor,
  32161.       listbox: listBoxDataProcessor,
  32162.       size: sizeInputDataProcessor,
  32163.       textarea: textAreaDataProcessor,
  32164.       urlinput: urlInputDataProcessor,
  32165.       customeditor: customEditorDataProcessor,
  32166.       collection: collectionDataProcessor,
  32167.       togglemenuitem: dialogToggleMenuItemDataProcessor
  32168.     };
  32169.     var getDataProcessor = function (item) {
  32170.       return Optional.from(dataProcessors[item.type]);
  32171.     };
  32172.     var getNamedItems = function (structure) {
  32173.       return filter$2(getAllObjects(structure), isNamedItem);
  32174.     };
  32175.  
  32176.     var createDataValidator = function (structure) {
  32177.       var namedItems = getNamedItems(structure);
  32178.       var fields = bind$3(namedItems, function (item) {
  32179.         return getDataProcessor(item).fold(function () {
  32180.           return [];
  32181.         }, function (schema) {
  32182.           return [requiredOf(item.name, schema)];
  32183.         });
  32184.       });
  32185.       return objOf(fields);
  32186.     };
  32187.  
  32188.     var extract = function (structure) {
  32189.       var internalDialog = getOrDie(createDialog(structure));
  32190.       var dataValidator = createDataValidator(structure);
  32191.       var initialData = structure.initialData;
  32192.       return {
  32193.         internalDialog: internalDialog,
  32194.         dataValidator: dataValidator,
  32195.         initialData: initialData
  32196.       };
  32197.     };
  32198.     var DialogManager = {
  32199.       open: function (factory, structure) {
  32200.         var extraction = extract(structure);
  32201.         return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  32202.       },
  32203.       openUrl: function (factory, structure) {
  32204.         var internalDialog = getOrDie(createUrlDialog(structure));
  32205.         return factory(internalDialog);
  32206.       },
  32207.       redial: function (structure) {
  32208.         return extract(structure);
  32209.       }
  32210.     };
  32211.  
  32212.     var toValidValues = function (values) {
  32213.       var errors = [];
  32214.       var result = {};
  32215.       each(values, function (value, name) {
  32216.         value.fold(function () {
  32217.           errors.push(name);
  32218.         }, function (v) {
  32219.           result[name] = v;
  32220.         });
  32221.       });
  32222.       return errors.length > 0 ? Result.error(errors) : Result.value(result);
  32223.     };
  32224.  
  32225.     var renderBodyPanel = function (spec, backstage) {
  32226.       var memForm = record(Form.sketch(function (parts) {
  32227.         return {
  32228.           dom: {
  32229.             tag: 'div',
  32230.             classes: ['tox-form'].concat(spec.classes)
  32231.           },
  32232.           components: map$2(spec.items, function (item) {
  32233.             return interpretInForm(parts, item, backstage);
  32234.           })
  32235.         };
  32236.       }));
  32237.       return {
  32238.         dom: {
  32239.           tag: 'div',
  32240.           classes: ['tox-dialog__body']
  32241.         },
  32242.         components: [{
  32243.             dom: {
  32244.               tag: 'div',
  32245.               classes: ['tox-dialog__body-content']
  32246.             },
  32247.             components: [memForm.asSpec()]
  32248.           }],
  32249.         behaviours: derive$1([
  32250.           Keying.config({
  32251.             mode: 'acyclic',
  32252.             useTabstopAt: not(isPseudoStop)
  32253.           }),
  32254.           ComposingConfigs.memento(memForm),
  32255.           RepresentingConfigs.memento(memForm, {
  32256.             postprocess: function (formValue) {
  32257.               return toValidValues(formValue).fold(function (err) {
  32258.                 console.error(err);
  32259.                 return {};
  32260.               }, identity$1);
  32261.             }
  32262.           })
  32263.         ])
  32264.       };
  32265.     };
  32266.  
  32267.     var factory$3 = function (detail, _spec) {
  32268.       return {
  32269.         uid: detail.uid,
  32270.         dom: detail.dom,
  32271.         components: detail.components,
  32272.         events: events$a(detail.action),
  32273.         behaviours: augment(detail.tabButtonBehaviours, [
  32274.           Focusing.config({}),
  32275.           Keying.config({
  32276.             mode: 'execution',
  32277.             useSpace: true,
  32278.             useEnter: true
  32279.           }),
  32280.           Representing.config({
  32281.             store: {
  32282.               mode: 'memory',
  32283.               initialValue: detail.value
  32284.             }
  32285.           })
  32286.         ]),
  32287.         domModification: detail.domModification
  32288.       };
  32289.     };
  32290.     var TabButton = single({
  32291.       name: 'TabButton',
  32292.       configFields: [
  32293.         defaulted('uid', undefined),
  32294.         required$1('value'),
  32295.         field$1('dom', 'dom', mergeWithThunk(function () {
  32296.           return {
  32297.             attributes: {
  32298.               'role': 'tab',
  32299.               'id': generate$6('aria'),
  32300.               'aria-selected': 'false'
  32301.             }
  32302.           };
  32303.         }), anyValue()),
  32304.         option('action'),
  32305.         defaulted('domModification', {}),
  32306.         field('tabButtonBehaviours', [
  32307.           Focusing,
  32308.           Keying,
  32309.           Representing
  32310.         ]),
  32311.         required$1('view')
  32312.       ],
  32313.       factory: factory$3
  32314.     });
  32315.  
  32316.     var schema$1 = constant$1([
  32317.       required$1('tabs'),
  32318.       required$1('dom'),
  32319.       defaulted('clickToDismiss', false),
  32320.       field('tabbarBehaviours', [
  32321.         Highlighting,
  32322.         Keying
  32323.       ]),
  32324.       markers$1([
  32325.         'tabClass',
  32326.         'selectedClass'
  32327.       ])
  32328.     ]);
  32329.     var tabsPart = group({
  32330.       factory: TabButton,
  32331.       name: 'tabs',
  32332.       unit: 'tab',
  32333.       overrides: function (barDetail) {
  32334.         var dismissTab$1 = function (tabbar, button) {
  32335.           Highlighting.dehighlight(tabbar, button);
  32336.           emitWith(tabbar, dismissTab(), {
  32337.             tabbar: tabbar,
  32338.             button: button
  32339.           });
  32340.         };
  32341.         var changeTab$1 = function (tabbar, button) {
  32342.           Highlighting.highlight(tabbar, button);
  32343.           emitWith(tabbar, changeTab(), {
  32344.             tabbar: tabbar,
  32345.             button: button
  32346.           });
  32347.         };
  32348.         return {
  32349.           action: function (button) {
  32350.             var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  32351.             var activeButton = Highlighting.isHighlighted(tabbar, button);
  32352.             var response = function () {
  32353.               if (activeButton && barDetail.clickToDismiss) {
  32354.                 return dismissTab$1;
  32355.               } else if (!activeButton) {
  32356.                 return changeTab$1;
  32357.               } else {
  32358.                 return noop;
  32359.               }
  32360.             }();
  32361.             response(tabbar, button);
  32362.           },
  32363.           domModification: { classes: [barDetail.markers.tabClass] }
  32364.         };
  32365.       }
  32366.     });
  32367.     var parts$1 = constant$1([tabsPart]);
  32368.  
  32369.     var factory$2 = function (detail, components, _spec, _externals) {
  32370.       return {
  32371.         'uid': detail.uid,
  32372.         'dom': detail.dom,
  32373.         components: components,
  32374.         'debug.sketcher': 'Tabbar',
  32375.         'domModification': { attributes: { role: 'tablist' } },
  32376.         'behaviours': augment(detail.tabbarBehaviours, [
  32377.           Highlighting.config({
  32378.             highlightClass: detail.markers.selectedClass,
  32379.             itemClass: detail.markers.tabClass,
  32380.             onHighlight: function (tabbar, tab) {
  32381.               set$8(tab.element, 'aria-selected', 'true');
  32382.             },
  32383.             onDehighlight: function (tabbar, tab) {
  32384.               set$8(tab.element, 'aria-selected', 'false');
  32385.             }
  32386.           }),
  32387.           Keying.config({
  32388.             mode: 'flow',
  32389.             getInitial: function (tabbar) {
  32390.               return Highlighting.getHighlighted(tabbar).map(function (tab) {
  32391.                 return tab.element;
  32392.               });
  32393.             },
  32394.             selector: '.' + detail.markers.tabClass,
  32395.             executeOnMove: true
  32396.           })
  32397.         ])
  32398.       };
  32399.     };
  32400.     var Tabbar = composite({
  32401.       name: 'Tabbar',
  32402.       configFields: schema$1(),
  32403.       partFields: parts$1(),
  32404.       factory: factory$2
  32405.     });
  32406.  
  32407.     var factory$1 = function (detail, _spec) {
  32408.       return {
  32409.         uid: detail.uid,
  32410.         dom: detail.dom,
  32411.         behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  32412.         domModification: { attributes: { role: 'tabpanel' } }
  32413.       };
  32414.     };
  32415.     var Tabview = single({
  32416.       name: 'Tabview',
  32417.       configFields: [field('tabviewBehaviours', [Replacing])],
  32418.       factory: factory$1
  32419.     });
  32420.  
  32421.     var schema = constant$1([
  32422.       defaulted('selectFirst', true),
  32423.       onHandler('onChangeTab'),
  32424.       onHandler('onDismissTab'),
  32425.       defaulted('tabs', []),
  32426.       field('tabSectionBehaviours', [])
  32427.     ]);
  32428.     var barPart = required({
  32429.       factory: Tabbar,
  32430.       schema: [
  32431.         required$1('dom'),
  32432.         requiredObjOf('markers', [
  32433.           required$1('tabClass'),
  32434.           required$1('selectedClass')
  32435.         ])
  32436.       ],
  32437.       name: 'tabbar',
  32438.       defaults: function (detail) {
  32439.         return { tabs: detail.tabs };
  32440.       }
  32441.     });
  32442.     var viewPart = required({
  32443.       factory: Tabview,
  32444.       name: 'tabview'
  32445.     });
  32446.     var parts = constant$1([
  32447.       barPart,
  32448.       viewPart
  32449.     ]);
  32450.  
  32451.     var factory = function (detail, components, _spec, _externals) {
  32452.       var changeTab$1 = function (button) {
  32453.         var tabValue = Representing.getValue(button);
  32454.         getPart(button, detail, 'tabview').each(function (tabview) {
  32455.           var tabWithValue = find$5(detail.tabs, function (t) {
  32456.             return t.value === tabValue;
  32457.           });
  32458.           tabWithValue.each(function (tabData) {
  32459.             var panel = tabData.view();
  32460.             getOpt(button.element, 'id').each(function (id) {
  32461.               set$8(tabview.element, 'aria-labelledby', id);
  32462.             });
  32463.             Replacing.set(tabview, panel);
  32464.             detail.onChangeTab(tabview, button, panel);
  32465.           });
  32466.         });
  32467.       };
  32468.       var changeTabBy = function (section, byPred) {
  32469.         getPart(section, detail, 'tabbar').each(function (tabbar) {
  32470.           byPred(tabbar).each(emitExecute);
  32471.         });
  32472.       };
  32473.       return {
  32474.         uid: detail.uid,
  32475.         dom: detail.dom,
  32476.         components: components,
  32477.         behaviours: get$2(detail.tabSectionBehaviours),
  32478.         events: derive$2(flatten([
  32479.           detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
  32480.               changeTabBy(section, Highlighting.getFirst);
  32481.             })] : [],
  32482.           [
  32483.             run$1(changeTab(), function (section, simulatedEvent) {
  32484.               var button = simulatedEvent.event.button;
  32485.               changeTab$1(button);
  32486.             }),
  32487.             run$1(dismissTab(), function (section, simulatedEvent) {
  32488.               var button = simulatedEvent.event.button;
  32489.               detail.onDismissTab(section, button);
  32490.             })
  32491.           ]
  32492.         ])),
  32493.         apis: {
  32494.           getViewItems: function (section) {
  32495.             return getPart(section, detail, 'tabview').map(function (tabview) {
  32496.               return Replacing.contents(tabview);
  32497.             }).getOr([]);
  32498.           },
  32499.           showTab: function (section, tabKey) {
  32500.             var getTabIfNotActive = function (tabbar) {
  32501.               var candidates = Highlighting.getCandidates(tabbar);
  32502.               var optTab = find$5(candidates, function (c) {
  32503.                 return Representing.getValue(c) === tabKey;
  32504.               });
  32505.               return optTab.filter(function (tab) {
  32506.                 return !Highlighting.isHighlighted(tabbar, tab);
  32507.               });
  32508.             };
  32509.             changeTabBy(section, getTabIfNotActive);
  32510.           }
  32511.         }
  32512.       };
  32513.     };
  32514.     var TabSection = composite({
  32515.       name: 'TabSection',
  32516.       configFields: schema(),
  32517.       partFields: parts(),
  32518.       factory: factory,
  32519.       apis: {
  32520.         getViewItems: function (apis, component) {
  32521.           return apis.getViewItems(component);
  32522.         },
  32523.         showTab: function (apis, component, tabKey) {
  32524.           apis.showTab(component, tabKey);
  32525.         }
  32526.       }
  32527.     });
  32528.  
  32529.     var measureHeights = function (allTabs, tabview, tabviewComp) {
  32530.       return map$2(allTabs, function (_tab, i) {
  32531.         Replacing.set(tabviewComp, allTabs[i].view());
  32532.         var rect = tabview.dom.getBoundingClientRect();
  32533.         Replacing.set(tabviewComp, []);
  32534.         return rect.height;
  32535.       });
  32536.     };
  32537.     var getMaxHeight = function (heights) {
  32538.       return head(sort(heights, function (a, b) {
  32539.         if (a > b) {
  32540.           return -1;
  32541.         } else if (a < b) {
  32542.           return +1;
  32543.         } else {
  32544.           return 0;
  32545.         }
  32546.       }));
  32547.     };
  32548.     var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  32549.       var documentElement$1 = documentElement(dialog).dom;
  32550.       var rootElm = ancestor(dialog, '.tox-dialog-wrap').getOr(dialog);
  32551.       var isFixed = get$c(rootElm, 'position') === 'fixed';
  32552.       var maxHeight;
  32553.       if (isFixed) {
  32554.         maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
  32555.       } else {
  32556.         maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  32557.       }
  32558.       var tabviewHeight = get$b(tabview);
  32559.       var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$a(tablist);
  32560.       var currentTabHeight = isTabListBeside ? Math.max(get$b(tablist), tabviewHeight) : tabviewHeight;
  32561.       var dialogTopMargin = parseInt(get$c(dialog, 'margin-top'), 10) || 0;
  32562.       var dialogBottomMargin = parseInt(get$c(dialog, 'margin-bottom'), 10) || 0;
  32563.       var dialogHeight = get$b(dialog) + dialogTopMargin + dialogBottomMargin;
  32564.       var chromeHeight = dialogHeight - currentTabHeight;
  32565.       return maxHeight - chromeHeight;
  32566.     };
  32567.     var showTab = function (allTabs, comp) {
  32568.       head(allTabs).each(function (tab) {
  32569.         return TabSection.showTab(comp, tab.value);
  32570.       });
  32571.     };
  32572.     var setTabviewHeight = function (tabview, height) {
  32573.       set$7(tabview, 'height', height + 'px');
  32574.       if (!detect$1().browser.isIE()) {
  32575.         set$7(tabview, 'flex-basis', height + 'px');
  32576.       } else {
  32577.         remove$6(tabview, 'flex-basis');
  32578.       }
  32579.     };
  32580.     var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  32581.       ancestor(dialogBody, '[role="dialog"]').each(function (dialog) {
  32582.         descendant(dialog, '[role="tablist"]').each(function (tablist) {
  32583.           maxTabHeight.get().map(function (height) {
  32584.             set$7(tabview, 'height', '0');
  32585.             set$7(tabview, 'flex-basis', '0');
  32586.             return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  32587.           }).each(function (height) {
  32588.             setTabviewHeight(tabview, height);
  32589.           });
  32590.         });
  32591.       });
  32592.     };
  32593.     var getTabview = function (dialog) {
  32594.       return descendant(dialog, '[role="tabpanel"]');
  32595.     };
  32596.     var setMode = function (allTabs) {
  32597.       var smartTabHeight = function () {
  32598.         var maxTabHeight = value$1();
  32599.         var extraEvents = [
  32600.           runOnAttached(function (comp) {
  32601.             var dialog = comp.element;
  32602.             getTabview(dialog).each(function (tabview) {
  32603.               set$7(tabview, 'visibility', 'hidden');
  32604.               comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) {
  32605.                 var heights = measureHeights(allTabs, tabview, tabviewComp);
  32606.                 var maxTabHeightOpt = getMaxHeight(heights);
  32607.                 maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
  32608.               });
  32609.               updateTabviewHeight(dialog, tabview, maxTabHeight);
  32610.               remove$6(tabview, 'visibility');
  32611.               showTab(allTabs, comp);
  32612.               global$f.requestAnimationFrame(function () {
  32613.                 updateTabviewHeight(dialog, tabview, maxTabHeight);
  32614.               });
  32615.             });
  32616.           }),
  32617.           run$1(windowResize(), function (comp) {
  32618.             var dialog = comp.element;
  32619.             getTabview(dialog).each(function (tabview) {
  32620.               updateTabviewHeight(dialog, tabview, maxTabHeight);
  32621.             });
  32622.           }),
  32623.           run$1(formResizeEvent, function (comp, _se) {
  32624.             var dialog = comp.element;
  32625.             getTabview(dialog).each(function (tabview) {
  32626.               var oldFocus = active(getRootNode(tabview));
  32627.               set$7(tabview, 'visibility', 'hidden');
  32628.               var oldHeight = getRaw(tabview, 'height').map(function (h) {
  32629.                 return parseInt(h, 10);
  32630.               });
  32631.               remove$6(tabview, 'height');
  32632.               remove$6(tabview, 'flex-basis');
  32633.               var newHeight = tabview.dom.getBoundingClientRect().height;
  32634.               var hasGrown = oldHeight.forall(function (h) {
  32635.                 return newHeight > h;
  32636.               });
  32637.               if (hasGrown) {
  32638.                 maxTabHeight.set(newHeight);
  32639.                 updateTabviewHeight(dialog, tabview, maxTabHeight);
  32640.               } else {
  32641.                 oldHeight.each(function (h) {
  32642.                   setTabviewHeight(tabview, h);
  32643.                 });
  32644.               }
  32645.               remove$6(tabview, 'visibility');
  32646.               oldFocus.each(focus$3);
  32647.             });
  32648.           })
  32649.         ];
  32650.         var selectFirst = false;
  32651.         return {
  32652.           extraEvents: extraEvents,
  32653.           selectFirst: selectFirst
  32654.         };
  32655.       }();
  32656.       var naiveTabHeight = function () {
  32657.         var extraEvents = [];
  32658.         var selectFirst = true;
  32659.         return {
  32660.           extraEvents: extraEvents,
  32661.           selectFirst: selectFirst
  32662.         };
  32663.       }();
  32664.       return {
  32665.         smartTabHeight: smartTabHeight,
  32666.         naiveTabHeight: naiveTabHeight
  32667.       };
  32668.     };
  32669.  
  32670.     var SendDataToSectionChannel = 'send-data-to-section';
  32671.     var SendDataToViewChannel = 'send-data-to-view';
  32672.     var renderTabPanel = function (spec, backstage) {
  32673.       var storedValue = Cell({});
  32674.       var updateDataWithForm = function (form) {
  32675.         var formData = Representing.getValue(form);
  32676.         var validData = toValidValues(formData).getOr({});
  32677.         var currentData = storedValue.get();
  32678.         var newData = deepMerge(currentData, validData);
  32679.         storedValue.set(newData);
  32680.       };
  32681.       var setDataOnForm = function (form) {
  32682.         var tabData = storedValue.get();
  32683.         Representing.setValue(form, tabData);
  32684.       };
  32685.       var oldTab = Cell(null);
  32686.       var allTabs = map$2(spec.tabs, function (tab) {
  32687.         return {
  32688.           value: tab.name,
  32689.           dom: {
  32690.             tag: 'div',
  32691.             classes: ['tox-dialog__body-nav-item'],
  32692.             innerHtml: backstage.shared.providers.translate(tab.title)
  32693.           },
  32694.           view: function () {
  32695.             return [Form.sketch(function (parts) {
  32696.                 return {
  32697.                   dom: {
  32698.                     tag: 'div',
  32699.                     classes: ['tox-form']
  32700.                   },
  32701.                   components: map$2(tab.items, function (item) {
  32702.                     return interpretInForm(parts, item, backstage);
  32703.                   }),
  32704.                   formBehaviours: derive$1([
  32705.                     Keying.config({
  32706.                       mode: 'acyclic',
  32707.                       useTabstopAt: not(isPseudoStop)
  32708.                     }),
  32709.                     config('TabView.form.events', [
  32710.                       runOnAttached(setDataOnForm),
  32711.                       runOnDetached(updateDataWithForm)
  32712.                     ]),
  32713.                     Receiving.config({
  32714.                       channels: wrapAll([
  32715.                         {
  32716.                           key: SendDataToSectionChannel,
  32717.                           value: { onReceive: updateDataWithForm }
  32718.                         },
  32719.                         {
  32720.                           key: SendDataToViewChannel,
  32721.                           value: { onReceive: setDataOnForm }
  32722.                         }
  32723.                       ])
  32724.                     })
  32725.                   ])
  32726.                 };
  32727.               })];
  32728.           }
  32729.         };
  32730.       });
  32731.       var tabMode = setMode(allTabs).smartTabHeight;
  32732.       return TabSection.sketch({
  32733.         dom: {
  32734.           tag: 'div',
  32735.           classes: ['tox-dialog__body']
  32736.         },
  32737.         onChangeTab: function (section, button, _viewItems) {
  32738.           var name = Representing.getValue(button);
  32739.           emitWith(section, formTabChangeEvent, {
  32740.             name: name,
  32741.             oldName: oldTab.get()
  32742.           });
  32743.           oldTab.set(name);
  32744.         },
  32745.         tabs: allTabs,
  32746.         components: [
  32747.           TabSection.parts.tabbar({
  32748.             dom: {
  32749.               tag: 'div',
  32750.               classes: ['tox-dialog__body-nav']
  32751.             },
  32752.             components: [Tabbar.parts.tabs({})],
  32753.             markers: {
  32754.               tabClass: 'tox-tab',
  32755.               selectedClass: 'tox-dialog__body-nav-item--active'
  32756.             },
  32757.             tabbarBehaviours: derive$1([Tabstopping.config({})])
  32758.           }),
  32759.           TabSection.parts.tabview({
  32760.             dom: {
  32761.               tag: 'div',
  32762.               classes: ['tox-dialog__body-content']
  32763.             }
  32764.           })
  32765.         ],
  32766.         selectFirst: tabMode.selectFirst,
  32767.         tabSectionBehaviours: derive$1([
  32768.           config('tabpanel', tabMode.extraEvents),
  32769.           Keying.config({ mode: 'acyclic' }),
  32770.           Composing.config({
  32771.             find: function (comp) {
  32772.               return head(TabSection.getViewItems(comp));
  32773.             }
  32774.           }),
  32775.           Representing.config({
  32776.             store: {
  32777.               mode: 'manual',
  32778.               getValue: function (tsection) {
  32779.                 tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  32780.                 return storedValue.get();
  32781.               },
  32782.               setValue: function (tsection, value) {
  32783.                 storedValue.set(value);
  32784.                 tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  32785.               }
  32786.             }
  32787.           })
  32788.         ])
  32789.       });
  32790.     };
  32791.  
  32792.     var dialogChannel = generate$6('update-dialog');
  32793.     var titleChannel = generate$6('update-title');
  32794.     var bodyChannel = generate$6('update-body');
  32795.     var footerChannel = generate$6('update-footer');
  32796.     var bodySendMessageChannel = generate$6('body-send-message');
  32797.  
  32798.     var renderBody = function (spec, id, backstage, ariaAttrs) {
  32799.       var renderComponents = function (incoming) {
  32800.         switch (incoming.body.type) {
  32801.         case 'tabpanel': {
  32802.             return [renderTabPanel(incoming.body, backstage)];
  32803.           }
  32804.         default: {
  32805.             return [renderBodyPanel(incoming.body, backstage)];
  32806.           }
  32807.         }
  32808.       };
  32809.       var updateState = function (_comp, incoming) {
  32810.         return Optional.some({
  32811.           isTabPanel: function () {
  32812.             return incoming.body.type === 'tabpanel';
  32813.           }
  32814.         });
  32815.       };
  32816.       var ariaAttributes = { 'aria-live': 'polite' };
  32817.       return {
  32818.         dom: {
  32819.           tag: 'div',
  32820.           classes: ['tox-dialog__content-js'],
  32821.           attributes: __assign(__assign({}, id.map(function (x) {
  32822.             return { id: x };
  32823.           }).getOr({})), ariaAttrs ? ariaAttributes : {})
  32824.         },
  32825.         components: [],
  32826.         behaviours: derive$1([
  32827.           ComposingConfigs.childAt(0),
  32828.           Reflecting.config({
  32829.             channel: bodyChannel,
  32830.             updateState: updateState,
  32831.             renderComponents: renderComponents,
  32832.             initialData: spec
  32833.           })
  32834.         ])
  32835.       };
  32836.     };
  32837.     var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  32838.       return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
  32839.     };
  32840.     var renderModalBody = function (spec, backstage) {
  32841.       var bodySpec = renderBody(spec, Optional.none(), backstage, false);
  32842.       return ModalDialog.parts.body(bodySpec);
  32843.     };
  32844.     var renderIframeBody = function (spec) {
  32845.       var bodySpec = {
  32846.         dom: {
  32847.           tag: 'div',
  32848.           classes: ['tox-dialog__content-js']
  32849.         },
  32850.         components: [{
  32851.             dom: {
  32852.               tag: 'div',
  32853.               classes: ['tox-dialog__body-iframe']
  32854.             },
  32855.             components: [craft({
  32856.                 dom: {
  32857.                   tag: 'iframe',
  32858.                   attributes: { src: spec.url }
  32859.                 },
  32860.                 behaviours: derive$1([
  32861.                   Tabstopping.config({}),
  32862.                   Focusing.config({})
  32863.                 ])
  32864.               })]
  32865.           }],
  32866.         behaviours: derive$1([Keying.config({
  32867.             mode: 'acyclic',
  32868.             useTabstopAt: not(isPseudoStop)
  32869.           })])
  32870.       };
  32871.       return ModalDialog.parts.body(bodySpec);
  32872.     };
  32873.  
  32874.     var isTouch = global$9.deviceType.isTouch();
  32875.     var hiddenHeader = function (title, close) {
  32876.       return {
  32877.         dom: {
  32878.           tag: 'div',
  32879.           styles: { display: 'none' },
  32880.           classes: ['tox-dialog__header']
  32881.         },
  32882.         components: [
  32883.           title,
  32884.           close
  32885.         ]
  32886.       };
  32887.     };
  32888.     var pClose = function (onClose, providersBackstage) {
  32889.       return ModalDialog.parts.close(Button.sketch({
  32890.         dom: {
  32891.           tag: 'button',
  32892.           classes: [
  32893.             'tox-button',
  32894.             'tox-button--icon',
  32895.             'tox-button--naked'
  32896.           ],
  32897.           attributes: {
  32898.             'type': 'button',
  32899.             'aria-label': providersBackstage.translate('Close')
  32900.           }
  32901.         },
  32902.         action: onClose,
  32903.         buttonBehaviours: derive$1([Tabstopping.config({})])
  32904.       }));
  32905.     };
  32906.     var pUntitled = function () {
  32907.       return ModalDialog.parts.title({
  32908.         dom: {
  32909.           tag: 'div',
  32910.           classes: ['tox-dialog__title'],
  32911.           innerHtml: '',
  32912.           styles: { display: 'none' }
  32913.         }
  32914.       });
  32915.     };
  32916.     var pBodyMessage = function (message, providersBackstage) {
  32917.       return ModalDialog.parts.body({
  32918.         dom: {
  32919.           tag: 'div',
  32920.           classes: ['tox-dialog__body']
  32921.         },
  32922.         components: [{
  32923.             dom: {
  32924.               tag: 'div',
  32925.               classes: ['tox-dialog__body-content']
  32926.             },
  32927.             components: [{ dom: fromHtml('<p>' + sanitizeHtmlString(providersBackstage.translate(message)) + '</p>') }]
  32928.           }]
  32929.       });
  32930.     };
  32931.     var pFooter = function (buttons) {
  32932.       return ModalDialog.parts.footer({
  32933.         dom: {
  32934.           tag: 'div',
  32935.           classes: ['tox-dialog__footer']
  32936.         },
  32937.         components: buttons
  32938.       });
  32939.     };
  32940.     var pFooterGroup = function (startButtons, endButtons) {
  32941.       return [
  32942.         Container.sketch({
  32943.           dom: {
  32944.             tag: 'div',
  32945.             classes: ['tox-dialog__footer-start']
  32946.           },
  32947.           components: startButtons
  32948.         }),
  32949.         Container.sketch({
  32950.           dom: {
  32951.             tag: 'div',
  32952.             classes: ['tox-dialog__footer-end']
  32953.           },
  32954.           components: endButtons
  32955.         })
  32956.       ];
  32957.     };
  32958.     var renderDialog$1 = function (spec) {
  32959.       var _a;
  32960.       var dialogClass = 'tox-dialog';
  32961.       var blockerClass = dialogClass + '-wrap';
  32962.       var blockerBackdropClass = blockerClass + '__backdrop';
  32963.       var scrollLockClass = dialogClass + '__disable-scroll';
  32964.       return ModalDialog.sketch({
  32965.         lazySink: spec.lazySink,
  32966.         onEscape: function (comp) {
  32967.           spec.onEscape(comp);
  32968.           return Optional.some(true);
  32969.         },
  32970.         useTabstopAt: function (elem) {
  32971.           return !isPseudoStop(elem);
  32972.         },
  32973.         dom: {
  32974.           tag: 'div',
  32975.           classes: [dialogClass].concat(spec.extraClasses),
  32976.           styles: __assign({ position: 'relative' }, spec.extraStyles)
  32977.         },
  32978.         components: __spreadArray([
  32979.           spec.header,
  32980.           spec.body
  32981.         ], spec.footer.toArray(), true),
  32982.         parts: {
  32983.           blocker: {
  32984.             dom: fromHtml('<div class="' + blockerClass + '"></div>'),
  32985.             components: [{
  32986.                 dom: {
  32987.                   tag: 'div',
  32988.                   classes: isTouch ? [
  32989.                     blockerBackdropClass,
  32990.                     blockerBackdropClass + '--opaque'
  32991.                   ] : [blockerBackdropClass]
  32992.                 }
  32993.               }]
  32994.           }
  32995.         },
  32996.         dragBlockClass: blockerClass,
  32997.         modalBehaviours: derive$1(__spreadArray([
  32998.           Focusing.config({}),
  32999.           config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  33000.               Keying.focusIn(comp);
  33001.             })])),
  33002.           config('scroll-lock', [
  33003.             runOnAttached(function () {
  33004.               add$2(body(), scrollLockClass);
  33005.             }),
  33006.             runOnDetached(function () {
  33007.               remove$2(body(), scrollLockClass);
  33008.             })
  33009.           ])
  33010.         ], spec.extraBehaviours, true)),
  33011.         eventOrder: __assign((_a = {}, _a[execute$5()] = ['dialog-events'], _a[attachedToDom()] = [
  33012.           'scroll-lock',
  33013.           'dialog-events',
  33014.           'alloy.base.behaviour'
  33015.         ], _a[detachedFromDom()] = [
  33016.           'alloy.base.behaviour',
  33017.           'dialog-events',
  33018.           'scroll-lock'
  33019.         ], _a), spec.eventOrder)
  33020.       });
  33021.     };
  33022.  
  33023.     var renderClose = function (providersBackstage) {
  33024.       return Button.sketch({
  33025.         dom: {
  33026.           tag: 'button',
  33027.           classes: [
  33028.             'tox-button',
  33029.             'tox-button--icon',
  33030.             'tox-button--naked'
  33031.           ],
  33032.           attributes: {
  33033.             'type': 'button',
  33034.             'aria-label': providersBackstage.translate('Close'),
  33035.             'title': providersBackstage.translate('Close')
  33036.           }
  33037.         },
  33038.         components: [render$3('close', {
  33039.             tag: 'div',
  33040.             classes: ['tox-icon']
  33041.           }, providersBackstage.icons)],
  33042.         action: function (comp) {
  33043.           emit(comp, formCancelEvent);
  33044.         }
  33045.       });
  33046.     };
  33047.     var renderTitle = function (spec, id, providersBackstage) {
  33048.       var renderComponents = function (data) {
  33049.         return [text$1(providersBackstage.translate(data.title))];
  33050.       };
  33051.       return {
  33052.         dom: {
  33053.           tag: 'div',
  33054.           classes: ['tox-dialog__title'],
  33055.           attributes: __assign({}, id.map(function (x) {
  33056.             return { id: x };
  33057.           }).getOr({}))
  33058.         },
  33059.         components: renderComponents(spec),
  33060.         behaviours: derive$1([Reflecting.config({
  33061.             channel: titleChannel,
  33062.             renderComponents: renderComponents
  33063.           })])
  33064.       };
  33065.     };
  33066.     var renderDragHandle = function () {
  33067.       return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') };
  33068.     };
  33069.     var renderInlineHeader = function (spec, titleId, providersBackstage) {
  33070.       return Container.sketch({
  33071.         dom: fromHtml('<div class="tox-dialog__header"></div>'),
  33072.         components: [
  33073.           renderTitle(spec, Optional.some(titleId), providersBackstage),
  33074.           renderDragHandle(),
  33075.           renderClose(providersBackstage)
  33076.         ],
  33077.         containerBehaviours: derive$1([Dragging.config({
  33078.             mode: 'mouse',
  33079.             blockerClass: 'blocker',
  33080.             getTarget: function (handle) {
  33081.               return closest$1(handle, '[role="dialog"]').getOrDie();
  33082.             },
  33083.             snaps: {
  33084.               getSnapPoints: function () {
  33085.                 return [];
  33086.               },
  33087.               leftAttr: 'data-drag-left',
  33088.               topAttr: 'data-drag-top'
  33089.             }
  33090.           })])
  33091.       });
  33092.     };
  33093.     var renderModalHeader = function (spec, providersBackstage) {
  33094.       var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
  33095.       var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
  33096.       var pClose = ModalDialog.parts.close(renderClose(providersBackstage));
  33097.       var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  33098.       return Container.sketch({
  33099.         dom: fromHtml('<div class="tox-dialog__header"></div>'),
  33100.         components: components
  33101.       });
  33102.     };
  33103.  
  33104.     var getHeader = function (title, backstage) {
  33105.       return renderModalHeader({
  33106.         title: backstage.shared.providers.translate(title),
  33107.         draggable: backstage.dialog.isDraggableModal()
  33108.       }, backstage.shared.providers);
  33109.     };
  33110.     var getBusySpec = function (message, bs, providers) {
  33111.       return {
  33112.         dom: {
  33113.           tag: 'div',
  33114.           classes: ['tox-dialog__busy-spinner'],
  33115.           attributes: { 'aria-label': providers.translate(message) },
  33116.           styles: {
  33117.             left: '0px',
  33118.             right: '0px',
  33119.             bottom: '0px',
  33120.             top: '0px',
  33121.             position: 'absolute'
  33122.           }
  33123.         },
  33124.         behaviours: bs,
  33125.         components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  33126.       };
  33127.     };
  33128.     var getEventExtras = function (lazyDialog, providers, extra) {
  33129.       return {
  33130.         onClose: function () {
  33131.           return extra.closeWindow();
  33132.         },
  33133.         onBlock: function (blockEvent) {
  33134.           ModalDialog.setBusy(lazyDialog(), function (_comp, bs) {
  33135.             return getBusySpec(blockEvent.message, bs, providers);
  33136.           });
  33137.         },
  33138.         onUnblock: function () {
  33139.           ModalDialog.setIdle(lazyDialog());
  33140.         }
  33141.       };
  33142.     };
  33143.     var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  33144.       var _a;
  33145.       var updateState = function (_comp, incoming) {
  33146.         return Optional.some(incoming);
  33147.       };
  33148.       return build$1(renderDialog$1(__assign(__assign({}, spec), {
  33149.         lazySink: backstage.shared.getSink,
  33150.         extraBehaviours: __spreadArray([
  33151.           Reflecting.config({
  33152.             channel: dialogChannel,
  33153.             updateState: updateState,
  33154.             initialData: initialData
  33155.           }),
  33156.           RepresentingConfigs.memory({})
  33157.         ], spec.extraBehaviours, true),
  33158.         onEscape: function (comp) {
  33159.           emit(comp, formCancelEvent);
  33160.         },
  33161.         dialogEvents: dialogEvents,
  33162.         eventOrder: (_a = {}, _a[receive()] = [
  33163.           Reflecting.name(),
  33164.           Receiving.name()
  33165.         ], _a[attachedToDom()] = [
  33166.           'scroll-lock',
  33167.           Reflecting.name(),
  33168.           'messages',
  33169.           'dialog-events',
  33170.           'alloy.base.behaviour'
  33171.         ], _a[detachedFromDom()] = [
  33172.           'alloy.base.behaviour',
  33173.           'dialog-events',
  33174.           'messages',
  33175.           Reflecting.name(),
  33176.           'scroll-lock'
  33177.         ], _a)
  33178.       })));
  33179.     };
  33180.     var mapMenuButtons = function (buttons) {
  33181.       var mapItems = function (button) {
  33182.         var items = map$2(button.items, function (item) {
  33183.           var cell = Cell(false);
  33184.           return __assign(__assign({}, item), { storage: cell });
  33185.         });
  33186.         return __assign(__assign({}, button), { items: items });
  33187.       };
  33188.       return map$2(buttons, function (button) {
  33189.         if (button.type === 'menu') {
  33190.           return mapItems(button);
  33191.         }
  33192.         return button;
  33193.       });
  33194.     };
  33195.     var extractCellsToObject = function (buttons) {
  33196.       return foldl(buttons, function (acc, button) {
  33197.         if (button.type === 'menu') {
  33198.           var menuButton = button;
  33199.           return foldl(menuButton.items, function (innerAcc, item) {
  33200.             innerAcc[item.name] = item.storage;
  33201.             return innerAcc;
  33202.           }, acc);
  33203.         }
  33204.         return acc;
  33205.       }, {});
  33206.     };
  33207.  
  33208.     var initCommonEvents = function (fireApiEvent, extras) {
  33209.       return [
  33210.         runWithTarget(focusin(), onFocus),
  33211.         fireApiEvent(formCloseEvent, function (_api, spec) {
  33212.           extras.onClose();
  33213.           spec.onClose();
  33214.         }),
  33215.         fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  33216.           spec.onCancel(api);
  33217.           emit(self, formCloseEvent);
  33218.         }),
  33219.         run$1(formUnblockEvent, function (_c, _se) {
  33220.           return extras.onUnblock();
  33221.         }),
  33222.         run$1(formBlockEvent, function (_c, se) {
  33223.           return extras.onBlock(se.event);
  33224.         })
  33225.       ];
  33226.     };
  33227.     var initUrlDialog = function (getInstanceApi, extras) {
  33228.       var fireApiEvent = function (eventName, f) {
  33229.         return run$1(eventName, function (c, se) {
  33230.           withSpec(c, function (spec, _c) {
  33231.             f(getInstanceApi(), spec, se.event, c);
  33232.           });
  33233.         });
  33234.       };
  33235.       var withSpec = function (c, f) {
  33236.         Reflecting.getState(c).get().each(function (currentDialog) {
  33237.           f(currentDialog, c);
  33238.         });
  33239.       };
  33240.       return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [fireApiEvent(formActionEvent, function (api, spec, event) {
  33241.           spec.onAction(api, { name: event.name });
  33242.         })], false);
  33243.     };
  33244.     var initDialog = function (getInstanceApi, extras, getSink) {
  33245.       var fireApiEvent = function (eventName, f) {
  33246.         return run$1(eventName, function (c, se) {
  33247.           withSpec(c, function (spec, _c) {
  33248.             f(getInstanceApi(), spec, se.event, c);
  33249.           });
  33250.         });
  33251.       };
  33252.       var withSpec = function (c, f) {
  33253.         Reflecting.getState(c).get().each(function (currentDialogInit) {
  33254.           f(currentDialogInit.internalDialog, c);
  33255.         });
  33256.       };
  33257.       return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [
  33258.         fireApiEvent(formSubmitEvent, function (api, spec) {
  33259.           return spec.onSubmit(api);
  33260.         }),
  33261.         fireApiEvent(formChangeEvent, function (api, spec, event) {
  33262.           spec.onChange(api, { name: event.name });
  33263.         }),
  33264.         fireApiEvent(formActionEvent, function (api, spec, event, component) {
  33265.           var focusIn = function () {
  33266.             return Keying.focusIn(component);
  33267.           };
  33268.           var isDisabled = function (focused) {
  33269.             return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
  33270.               return val === 'true';
  33271.             });
  33272.           };
  33273.           var rootNode = getRootNode(component.element);
  33274.           var current = active(rootNode);
  33275.           spec.onAction(api, {
  33276.             name: event.name,
  33277.             value: event.value
  33278.           });
  33279.           active(rootNode).fold(focusIn, function (focused) {
  33280.             if (isDisabled(focused)) {
  33281.               focusIn();
  33282.             } else if (current.exists(function (cur) {
  33283.                 return contains(focused, cur) && isDisabled(cur);
  33284.               })) {
  33285.               focusIn();
  33286.             } else {
  33287.               getSink().toOptional().filter(function (sink) {
  33288.                 return !contains(sink.element, focused);
  33289.               }).each(focusIn);
  33290.             }
  33291.           });
  33292.         }),
  33293.         fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  33294.           spec.onTabChange(api, {
  33295.             newTabName: event.name,
  33296.             oldTabName: event.oldName
  33297.           });
  33298.         }),
  33299.         runOnDetached(function (component) {
  33300.           var api = getInstanceApi();
  33301.           Representing.setValue(component, api.getData());
  33302.         })
  33303.       ], false);
  33304.     };
  33305.     var SilverDialogEvents = {
  33306.       initUrlDialog: initUrlDialog,
  33307.       initDialog: initDialog
  33308.     };
  33309.  
  33310.     var makeButton = function (button, backstage) {
  33311.       return renderFooterButton(button, button.type, backstage);
  33312.     };
  33313.     var lookup = function (compInSystem, footerButtons, buttonName) {
  33314.       return find$5(footerButtons, function (button) {
  33315.         return button.name === buttonName;
  33316.       }).bind(function (memButton) {
  33317.         return memButton.memento.getOpt(compInSystem);
  33318.       });
  33319.     };
  33320.     var renderComponents = function (_data, state) {
  33321.       var footerButtons = state.map(function (s) {
  33322.         return s.footerButtons;
  33323.       }).getOr([]);
  33324.       var buttonGroups = partition$3(footerButtons, function (button) {
  33325.         return button.align === 'start';
  33326.       });
  33327.       var makeGroup = function (edge, buttons) {
  33328.         return Container.sketch({
  33329.           dom: {
  33330.             tag: 'div',
  33331.             classes: ['tox-dialog__footer-' + edge]
  33332.           },
  33333.           components: map$2(buttons, function (button) {
  33334.             return button.memento.asSpec();
  33335.           })
  33336.         });
  33337.       };
  33338.       var startButtons = makeGroup('start', buttonGroups.pass);
  33339.       var endButtons = makeGroup('end', buttonGroups.fail);
  33340.       return [
  33341.         startButtons,
  33342.         endButtons
  33343.       ];
  33344.     };
  33345.     var renderFooter = function (initSpec, backstage) {
  33346.       var updateState = function (_comp, data) {
  33347.         var footerButtons = map$2(data.buttons, function (button) {
  33348.           var memButton = record(makeButton(button, backstage));
  33349.           return {
  33350.             name: button.name,
  33351.             align: button.align,
  33352.             memento: memButton
  33353.           };
  33354.         });
  33355.         var lookupByName = function (compInSystem, buttonName) {
  33356.           return lookup(compInSystem, footerButtons, buttonName);
  33357.         };
  33358.         return Optional.some({
  33359.           lookupByName: lookupByName,
  33360.           footerButtons: footerButtons
  33361.         });
  33362.       };
  33363.       return {
  33364.         dom: fromHtml('<div class="tox-dialog__footer"></div>'),
  33365.         components: [],
  33366.         behaviours: derive$1([Reflecting.config({
  33367.             channel: footerChannel,
  33368.             initialData: initSpec,
  33369.             updateState: updateState,
  33370.             renderComponents: renderComponents
  33371.           })])
  33372.       };
  33373.     };
  33374.     var renderInlineFooter = function (initSpec, backstage) {
  33375.       return renderFooter(initSpec, backstage);
  33376.     };
  33377.     var renderModalFooter = function (initSpec, backstage) {
  33378.       return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
  33379.     };
  33380.  
  33381.     var getCompByName = function (access, name) {
  33382.       var root = access.getRoot();
  33383.       if (root.getSystem().isConnected()) {
  33384.         var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  33385.         return Form.getField(form_1, name).fold(function () {
  33386.           var footer = access.getFooter();
  33387.           var footerState = Reflecting.getState(footer);
  33388.           return footerState.get().bind(function (f) {
  33389.             return f.lookupByName(form_1, name);
  33390.           });
  33391.         }, function (comp) {
  33392.           return Optional.some(comp);
  33393.         });
  33394.       } else {
  33395.         return Optional.none();
  33396.       }
  33397.     };
  33398.     var validateData$1 = function (access, data) {
  33399.       var root = access.getRoot();
  33400.       return Reflecting.getState(root).get().map(function (dialogState) {
  33401.         return getOrDie(asRaw('data', dialogState.dataValidator, data));
  33402.       }).getOr(data);
  33403.     };
  33404.     var getDialogApi = function (access, doRedial, menuItemStates) {
  33405.       var withRoot = function (f) {
  33406.         var root = access.getRoot();
  33407.         if (root.getSystem().isConnected()) {
  33408.           f(root);
  33409.         }
  33410.       };
  33411.       var getData = function () {
  33412.         var root = access.getRoot();
  33413.         var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  33414.         var representedValues = Representing.getValue(valueComp);
  33415.         var menuItemCurrentState = map$1(menuItemStates, function (cell) {
  33416.           return cell.get();
  33417.         });
  33418.         return __assign(__assign({}, representedValues), menuItemCurrentState);
  33419.       };
  33420.       var setData = function (newData) {
  33421.         withRoot(function (_) {
  33422.           var prevData = instanceApi.getData();
  33423.           var mergedData = __assign(__assign({}, prevData), newData);
  33424.           var newInternalData = validateData$1(access, mergedData);
  33425.           var form = access.getFormWrapper();
  33426.           Representing.setValue(form, newInternalData);
  33427.           each(menuItemStates, function (v, k) {
  33428.             if (has$2(mergedData, k)) {
  33429.               v.set(mergedData[k]);
  33430.             }
  33431.           });
  33432.         });
  33433.       };
  33434.       var disable = function (name) {
  33435.         getCompByName(access, name).each(Disabling.disable);
  33436.       };
  33437.       var enable = function (name) {
  33438.         getCompByName(access, name).each(Disabling.enable);
  33439.       };
  33440.       var focus = function (name) {
  33441.         getCompByName(access, name).each(Focusing.focus);
  33442.       };
  33443.       var block = function (message) {
  33444.         if (!isString(message)) {
  33445.           throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  33446.         }
  33447.         withRoot(function (root) {
  33448.           emitWith(root, formBlockEvent, { message: message });
  33449.         });
  33450.       };
  33451.       var unblock = function () {
  33452.         withRoot(function (root) {
  33453.           emit(root, formUnblockEvent);
  33454.         });
  33455.       };
  33456.       var showTab = function (name) {
  33457.         withRoot(function (_) {
  33458.           var body = access.getBody();
  33459.           var bodyState = Reflecting.getState(body);
  33460.           if (bodyState.get().exists(function (b) {
  33461.               return b.isTabPanel();
  33462.             })) {
  33463.             Composing.getCurrent(body).each(function (tabSection) {
  33464.               TabSection.showTab(tabSection, name);
  33465.             });
  33466.           }
  33467.         });
  33468.       };
  33469.       var redial = function (d) {
  33470.         withRoot(function (root) {
  33471.           var dialogInit = doRedial(d);
  33472.           root.getSystem().broadcastOn([dialogChannel], dialogInit);
  33473.           root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  33474.           root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  33475.           root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  33476.           instanceApi.setData(dialogInit.initialData);
  33477.         });
  33478.       };
  33479.       var close = function () {
  33480.         withRoot(function (root) {
  33481.           emit(root, formCloseEvent);
  33482.         });
  33483.       };
  33484.       var instanceApi = {
  33485.         getData: getData,
  33486.         setData: setData,
  33487.         disable: disable,
  33488.         enable: enable,
  33489.         focus: focus,
  33490.         block: block,
  33491.         unblock: unblock,
  33492.         showTab: showTab,
  33493.         redial: redial,
  33494.         close: close
  33495.       };
  33496.       return instanceApi;
  33497.     };
  33498.  
  33499.     var getDialogSizeClasses = function (size) {
  33500.       switch (size) {
  33501.       case 'large':
  33502.         return ['tox-dialog--width-lg'];
  33503.       case 'medium':
  33504.         return ['tox-dialog--width-md'];
  33505.       default:
  33506.         return [];
  33507.       }
  33508.     };
  33509.     var renderDialog = function (dialogInit, extra, backstage) {
  33510.       var header = getHeader(dialogInit.internalDialog.title, backstage);
  33511.       var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  33512.       var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  33513.       var objOfCells = extractCellsToObject(storagedMenuButtons);
  33514.       var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  33515.       var dialogEvents = SilverDialogEvents.initDialog(function () {
  33516.         return instanceApi;
  33517.       }, getEventExtras(function () {
  33518.         return dialog;
  33519.       }, backstage.shared.providers, extra), backstage.shared.getSink);
  33520.       var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
  33521.       var spec = {
  33522.         header: header,
  33523.         body: body,
  33524.         footer: Optional.some(footer),
  33525.         extraClasses: dialogSize,
  33526.         extraBehaviours: [],
  33527.         extraStyles: {}
  33528.       };
  33529.       var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  33530.       var modalAccess = function () {
  33531.         var getForm = function () {
  33532.           var outerForm = ModalDialog.getBody(dialog);
  33533.           return Composing.getCurrent(outerForm).getOr(outerForm);
  33534.         };
  33535.         return {
  33536.           getRoot: constant$1(dialog),
  33537.           getBody: function () {
  33538.             return ModalDialog.getBody(dialog);
  33539.           },
  33540.           getFooter: function () {
  33541.             return ModalDialog.getFooter(dialog);
  33542.           },
  33543.           getFormWrapper: getForm
  33544.         };
  33545.       }();
  33546.       var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  33547.       return {
  33548.         dialog: dialog,
  33549.         instanceApi: instanceApi
  33550.       };
  33551.     };
  33552.  
  33553.     var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  33554.       var _a, _b;
  33555.       var dialogLabelId = generate$6('dialog-label');
  33556.       var dialogContentId = generate$6('dialog-content');
  33557.       var updateState = function (_comp, incoming) {
  33558.         return Optional.some(incoming);
  33559.       };
  33560.       var memHeader = record(renderInlineHeader({
  33561.         title: dialogInit.internalDialog.title,
  33562.         draggable: true
  33563.       }, dialogLabelId, backstage.shared.providers));
  33564.       var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  33565.       var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  33566.       var objOfCells = extractCellsToObject(storagedMenuButtons);
  33567.       var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  33568.       var dialogEvents = SilverDialogEvents.initDialog(function () {
  33569.         return instanceApi;
  33570.       }, {
  33571.         onBlock: function (event) {
  33572.           Blocking.block(dialog, function (_comp, bs) {
  33573.             return getBusySpec(event.message, bs, backstage.shared.providers);
  33574.           });
  33575.         },
  33576.         onUnblock: function () {
  33577.           Blocking.unblock(dialog);
  33578.         },
  33579.         onClose: function () {
  33580.           return extra.closeWindow();
  33581.         }
  33582.       }, backstage.shared.getSink);
  33583.       var dialog = build$1({
  33584.         dom: {
  33585.           tag: 'div',
  33586.           classes: [
  33587.             'tox-dialog',
  33588.             'tox-dialog-inline'
  33589.           ],
  33590.           attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = dialogContentId, _a)
  33591.         },
  33592.         eventOrder: (_b = {}, _b[receive()] = [
  33593.           Reflecting.name(),
  33594.           Receiving.name()
  33595.         ], _b[execute$5()] = ['execute-on-form'], _b[attachedToDom()] = [
  33596.           'reflecting',
  33597.           'execute-on-form'
  33598.         ], _b),
  33599.         behaviours: derive$1([
  33600.           Keying.config({
  33601.             mode: 'cyclic',
  33602.             onEscape: function (c) {
  33603.               emit(c, formCloseEvent);
  33604.               return Optional.some(true);
  33605.             },
  33606.             useTabstopAt: function (elem) {
  33607.               return !isPseudoStop(elem) && (name$2(elem) !== 'button' || get$d(elem, 'disabled') !== 'disabled');
  33608.             }
  33609.           }),
  33610.           Reflecting.config({
  33611.             channel: dialogChannel,
  33612.             updateState: updateState,
  33613.             initialData: dialogInit
  33614.           }),
  33615.           Focusing.config({}),
  33616.           config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  33617.               Keying.focusIn(comp);
  33618.             })])),
  33619.           Blocking.config({
  33620.             getRoot: function () {
  33621.               return Optional.some(dialog);
  33622.             }
  33623.           }),
  33624.           Replacing.config({}),
  33625.           RepresentingConfigs.memory({})
  33626.         ]),
  33627.         components: [
  33628.           memHeader.asSpec(),
  33629.           memBody.asSpec(),
  33630.           memFooter.asSpec()
  33631.         ]
  33632.       });
  33633.       var instanceApi = getDialogApi({
  33634.         getRoot: constant$1(dialog),
  33635.         getFooter: function () {
  33636.           return memFooter.get(dialog);
  33637.         },
  33638.         getBody: function () {
  33639.           return memBody.get(dialog);
  33640.         },
  33641.         getFormWrapper: function () {
  33642.           var body = memBody.get(dialog);
  33643.           return Composing.getCurrent(body).getOr(body);
  33644.         }
  33645.       }, extra.redial, objOfCells);
  33646.       return {
  33647.         dialog: dialog,
  33648.         instanceApi: instanceApi
  33649.       };
  33650.     };
  33651.  
  33652.     var global$1 = tinymce.util.Tools.resolve('tinymce.util.URI');
  33653.  
  33654.     var getUrlDialogApi = function (root) {
  33655.       var withRoot = function (f) {
  33656.         if (root.getSystem().isConnected()) {
  33657.           f(root);
  33658.         }
  33659.       };
  33660.       var block = function (message) {
  33661.         if (!isString(message)) {
  33662.           throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  33663.         }
  33664.         withRoot(function (root) {
  33665.           emitWith(root, formBlockEvent, { message: message });
  33666.         });
  33667.       };
  33668.       var unblock = function () {
  33669.         withRoot(function (root) {
  33670.           emit(root, formUnblockEvent);
  33671.         });
  33672.       };
  33673.       var close = function () {
  33674.         withRoot(function (root) {
  33675.           emit(root, formCloseEvent);
  33676.         });
  33677.       };
  33678.       var sendMessage = function (data) {
  33679.         withRoot(function (root) {
  33680.           root.getSystem().broadcastOn([bodySendMessageChannel], data);
  33681.         });
  33682.       };
  33683.       return {
  33684.         block: block,
  33685.         unblock: unblock,
  33686.         close: close,
  33687.         sendMessage: sendMessage
  33688.       };
  33689.     };
  33690.  
  33691.     var SUPPORTED_MESSAGE_ACTIONS = [
  33692.       'insertContent',
  33693.       'setContent',
  33694.       'execCommand',
  33695.       'close',
  33696.       'block',
  33697.       'unblock'
  33698.     ];
  33699.     var isSupportedMessage = function (data) {
  33700.       return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  33701.     };
  33702.     var isCustomMessage = function (data) {
  33703.       return !isSupportedMessage(data) && isObject(data) && has$2(data, 'mceAction');
  33704.     };
  33705.     var handleMessage = function (editor, api, data) {
  33706.       switch (data.mceAction) {
  33707.       case 'insertContent':
  33708.         editor.insertContent(data.content);
  33709.         break;
  33710.       case 'setContent':
  33711.         editor.setContent(data.content);
  33712.         break;
  33713.       case 'execCommand':
  33714.         var ui = isBoolean(data.ui) ? data.ui : false;
  33715.         editor.execCommand(data.cmd, ui, data.value);
  33716.         break;
  33717.       case 'close':
  33718.         api.close();
  33719.         break;
  33720.       case 'block':
  33721.         api.block(data.message);
  33722.         break;
  33723.       case 'unblock':
  33724.         api.unblock();
  33725.         break;
  33726.       }
  33727.     };
  33728.     var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  33729.       var _a;
  33730.       var header = getHeader(internalDialog.title, backstage);
  33731.       var body = renderIframeBody(internalDialog);
  33732.       var footer = internalDialog.buttons.bind(function (buttons) {
  33733.         if (buttons.length === 0) {
  33734.           return Optional.none();
  33735.         } else {
  33736.           return Optional.some(renderModalFooter({ buttons: buttons }, backstage));
  33737.         }
  33738.       });
  33739.       var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  33740.         return instanceApi;
  33741.       }, getEventExtras(function () {
  33742.         return dialog;
  33743.       }, backstage.shared.providers, extra));
  33744.       var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  33745.         return {};
  33746.       }, function (height) {
  33747.         return {
  33748.           'height': height + 'px',
  33749.           'max-height': height + 'px'
  33750.         };
  33751.       })), internalDialog.width.fold(function () {
  33752.         return {};
  33753.       }, function (width) {
  33754.         return {
  33755.           'width': width + 'px',
  33756.           'max-width': width + 'px'
  33757.         };
  33758.       }));
  33759.       var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  33760.       var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) });
  33761.       var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  33762.       var messageHandlerUnbinder = unbindable();
  33763.       var extraBehaviours = [
  33764.         config('messages', [
  33765.           runOnAttached(function () {
  33766.             var unbind = bind(SugarElement.fromDom(window), 'message', function (e) {
  33767.               if (iframeUri.isSameOrigin(new global$1(e.raw.origin))) {
  33768.                 var data = e.raw.data;
  33769.                 if (isSupportedMessage(data)) {
  33770.                   handleMessage(editor, instanceApi, data);
  33771.                 } else if (isCustomMessage(data)) {
  33772.                   internalDialog.onMessage(instanceApi, data);
  33773.                 }
  33774.               }
  33775.             });
  33776.             messageHandlerUnbinder.set(unbind);
  33777.           }),
  33778.           runOnDetached(messageHandlerUnbinder.clear)
  33779.         ]),
  33780.         Receiving.config({
  33781.           channels: (_a = {}, _a[bodySendMessageChannel] = {
  33782.             onReceive: function (comp, data) {
  33783.               descendant(comp.element, 'iframe').each(function (iframeEle) {
  33784.                 var iframeWin = iframeEle.dom.contentWindow;
  33785.                 iframeWin.postMessage(data, iframeDomain);
  33786.               });
  33787.             }
  33788.           }, _a)
  33789.         })
  33790.       ];
  33791.       var spec = {
  33792.         header: header,
  33793.         body: body,
  33794.         footer: footer,
  33795.         extraClasses: classes,
  33796.         extraBehaviours: extraBehaviours,
  33797.         extraStyles: styles
  33798.       };
  33799.       var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  33800.       var instanceApi = getUrlDialogApi(dialog);
  33801.       return {
  33802.         dialog: dialog,
  33803.         instanceApi: instanceApi
  33804.       };
  33805.     };
  33806.  
  33807.     var setup$2 = function (extras) {
  33808.       var sharedBackstage = extras.backstage.shared;
  33809.       var open = function (message, callback) {
  33810.         var closeDialog = function () {
  33811.           ModalDialog.hide(alertDialog);
  33812.           callback();
  33813.         };
  33814.         var memFooterClose = record(renderFooterButton({
  33815.           name: 'close-alert',
  33816.           text: 'OK',
  33817.           primary: true,
  33818.           align: 'end',
  33819.           disabled: false,
  33820.           icon: Optional.none()
  33821.         }, 'cancel', extras.backstage));
  33822.         var titleSpec = pUntitled();
  33823.         var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  33824.         var alertDialog = build$1(renderDialog$1({
  33825.           lazySink: function () {
  33826.             return sharedBackstage.getSink();
  33827.           },
  33828.           header: hiddenHeader(titleSpec, closeSpec),
  33829.           body: pBodyMessage(message, sharedBackstage.providers),
  33830.           footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  33831.           onEscape: closeDialog,
  33832.           extraClasses: ['tox-alert-dialog'],
  33833.           extraBehaviours: [],
  33834.           extraStyles: {},
  33835.           dialogEvents: [run$1(formCancelEvent, closeDialog)],
  33836.           eventOrder: {}
  33837.         }));
  33838.         ModalDialog.show(alertDialog);
  33839.         var footerCloseButton = memFooterClose.get(alertDialog);
  33840.         Focusing.focus(footerCloseButton);
  33841.       };
  33842.       return { open: open };
  33843.     };
  33844.  
  33845.     var setup$1 = function (extras) {
  33846.       var sharedBackstage = extras.backstage.shared;
  33847.       var open = function (message, callback) {
  33848.         var closeDialog = function (state) {
  33849.           ModalDialog.hide(confirmDialog);
  33850.           callback(state);
  33851.         };
  33852.         var memFooterYes = record(renderFooterButton({
  33853.           name: 'yes',
  33854.           text: 'Yes',
  33855.           primary: true,
  33856.           align: 'end',
  33857.           disabled: false,
  33858.           icon: Optional.none()
  33859.         }, 'submit', extras.backstage));
  33860.         var footerNo = renderFooterButton({
  33861.           name: 'no',
  33862.           text: 'No',
  33863.           primary: false,
  33864.           align: 'end',
  33865.           disabled: false,
  33866.           icon: Optional.none()
  33867.         }, 'cancel', extras.backstage);
  33868.         var titleSpec = pUntitled();
  33869.         var closeSpec = pClose(function () {
  33870.           return closeDialog(false);
  33871.         }, sharedBackstage.providers);
  33872.         var confirmDialog = build$1(renderDialog$1({
  33873.           lazySink: function () {
  33874.             return sharedBackstage.getSink();
  33875.           },
  33876.           header: hiddenHeader(titleSpec, closeSpec),
  33877.           body: pBodyMessage(message, sharedBackstage.providers),
  33878.           footer: Optional.some(pFooter(pFooterGroup([], [
  33879.             footerNo,
  33880.             memFooterYes.asSpec()
  33881.           ]))),
  33882.           onEscape: function () {
  33883.             return closeDialog(false);
  33884.           },
  33885.           extraClasses: ['tox-confirm-dialog'],
  33886.           extraBehaviours: [],
  33887.           extraStyles: {},
  33888.           dialogEvents: [
  33889.             run$1(formCancelEvent, function () {
  33890.               return closeDialog(false);
  33891.             }),
  33892.             run$1(formSubmitEvent, function () {
  33893.               return closeDialog(true);
  33894.             })
  33895.           ],
  33896.           eventOrder: {}
  33897.         }));
  33898.         ModalDialog.show(confirmDialog);
  33899.         var footerYesButton = memFooterYes.get(confirmDialog);
  33900.         Focusing.focus(footerYesButton);
  33901.       };
  33902.       return { open: open };
  33903.     };
  33904.  
  33905.     var validateData = function (data, validator) {
  33906.       return getOrDie(asRaw('data', validator, data));
  33907.     };
  33908.     var isAlertOrConfirmDialog = function (target) {
  33909.       return closest(target, '.tox-alert-dialog') || closest(target, '.tox-confirm-dialog');
  33910.     };
  33911.     var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  33912.       if (isStickyToolbar && isToolbarLocationTop) {
  33913.         return [];
  33914.       } else {
  33915.         return [Docking.config({
  33916.             contextual: {
  33917.               lazyContext: function () {
  33918.                 return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer())));
  33919.               },
  33920.               fadeInClass: 'tox-dialog-dock-fadein',
  33921.               fadeOutClass: 'tox-dialog-dock-fadeout',
  33922.               transitionClass: 'tox-dialog-dock-transition'
  33923.             },
  33924.             modes: ['top']
  33925.           })];
  33926.       }
  33927.     };
  33928.     var setup = function (extras) {
  33929.       var backstage = extras.backstage;
  33930.       var editor = extras.editor;
  33931.       var isStickyToolbar$1 = isStickyToolbar(editor);
  33932.       var alertDialog = setup$2(extras);
  33933.       var confirmDialog = setup$1(extras);
  33934.       var open = function (config, params, closeWindow) {
  33935.         if (params !== undefined && params.inline === 'toolbar') {
  33936.           return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  33937.         } else if (params !== undefined && params.inline === 'cursor') {
  33938.           return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  33939.         } else {
  33940.           return openModalDialog(config, closeWindow);
  33941.         }
  33942.       };
  33943.       var openUrl = function (config, closeWindow) {
  33944.         return openModalUrlDialog(config, closeWindow);
  33945.       };
  33946.       var openModalUrlDialog = function (config, closeWindow) {
  33947.         var factory = function (contents) {
  33948.           var dialog = renderUrlDialog(contents, {
  33949.             closeWindow: function () {
  33950.               ModalDialog.hide(dialog.dialog);
  33951.               closeWindow(dialog.instanceApi);
  33952.             }
  33953.           }, editor, backstage);
  33954.           ModalDialog.show(dialog.dialog);
  33955.           return dialog.instanceApi;
  33956.         };
  33957.         return DialogManager.openUrl(factory, config);
  33958.       };
  33959.       var openModalDialog = function (config, closeWindow) {
  33960.         var factory = function (contents, internalInitialData, dataValidator) {
  33961.           var initialData = internalInitialData;
  33962.           var dialogInit = {
  33963.             dataValidator: dataValidator,
  33964.             initialData: initialData,
  33965.             internalDialog: contents
  33966.           };
  33967.           var dialog = renderDialog(dialogInit, {
  33968.             redial: DialogManager.redial,
  33969.             closeWindow: function () {
  33970.               ModalDialog.hide(dialog.dialog);
  33971.               closeWindow(dialog.instanceApi);
  33972.             }
  33973.           }, backstage);
  33974.           ModalDialog.show(dialog.dialog);
  33975.           dialog.instanceApi.setData(initialData);
  33976.           return dialog.instanceApi;
  33977.         };
  33978.         return DialogManager.open(factory, config);
  33979.       };
  33980.       var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  33981.         var factory = function (contents, internalInitialData, dataValidator) {
  33982.           var initialData = validateData(internalInitialData, dataValidator);
  33983.           var inlineDialog = value$1();
  33984.           var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  33985.           var dialogInit = {
  33986.             dataValidator: dataValidator,
  33987.             initialData: initialData,
  33988.             internalDialog: contents
  33989.           };
  33990.           var refreshDocking = function () {
  33991.             return inlineDialog.on(function (dialog) {
  33992.               InlineView.reposition(dialog);
  33993.               Docking.refresh(dialog);
  33994.             });
  33995.           };
  33996.           var dialogUi = renderInlineDialog(dialogInit, {
  33997.             redial: DialogManager.redial,
  33998.             closeWindow: function () {
  33999.               inlineDialog.on(InlineView.hide);
  34000.               editor.off('ResizeEditor', refreshDocking);
  34001.               inlineDialog.clear();
  34002.               closeWindow(dialogUi.instanceApi);
  34003.             }
  34004.           }, backstage, ariaAttrs);
  34005.           var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  34006.             lazySink: backstage.shared.getSink,
  34007.             dom: {
  34008.               tag: 'div',
  34009.               classes: []
  34010.             },
  34011.             fireDismissalEventInstead: {}
  34012.           }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
  34013.             inlineBehaviours: derive$1(__spreadArray([config('window-manager-inline-events', [run$1(dismissRequested(), function (_comp, _se) {
  34014.                   emit(dialogUi.dialog, formCancelEvent);
  34015.                 })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop), true)),
  34016.             isExtraPart: function (_comp, target) {
  34017.               return isAlertOrConfirmDialog(target);
  34018.             }
  34019.           })));
  34020.           inlineDialog.set(inlineDialogComp);
  34021.           InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor }, Optional.some(body()));
  34022.           if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  34023.             Docking.refresh(inlineDialogComp);
  34024.             editor.on('ResizeEditor', refreshDocking);
  34025.           }
  34026.           dialogUi.instanceApi.setData(initialData);
  34027.           Keying.focusIn(dialogUi.dialog);
  34028.           return dialogUi.instanceApi;
  34029.         };
  34030.         return DialogManager.open(factory, config$1);
  34031.       };
  34032.       var confirm = function (message, callback) {
  34033.         confirmDialog.open(message, function (state) {
  34034.           callback(state);
  34035.         });
  34036.       };
  34037.       var alert = function (message, callback) {
  34038.         alertDialog.open(message, function () {
  34039.           callback();
  34040.         });
  34041.       };
  34042.       var close = function (instanceApi) {
  34043.         instanceApi.close();
  34044.       };
  34045.       return {
  34046.         open: open,
  34047.         openUrl: openUrl,
  34048.         alert: alert,
  34049.         close: close,
  34050.         confirm: confirm
  34051.       };
  34052.     };
  34053.  
  34054.     function Theme () {
  34055.       global$g.add('silver', function (editor) {
  34056.         var _a = setup$3(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  34057.         Autocompleter.register(editor, backstage.shared);
  34058.         var windowMgr = setup({
  34059.           editor: editor,
  34060.           backstage: backstage
  34061.         });
  34062.         return {
  34063.           renderUI: renderUI,
  34064.           getWindowManagerImpl: constant$1(windowMgr),
  34065.           getNotificationManagerImpl: function () {
  34066.             return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  34067.           },
  34068.           ui: getUi()
  34069.         };
  34070.       });
  34071.     }
  34072.  
  34073.     Theme();
  34074.  
  34075. }());
  34076.