/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.1.0 (2019-10-17) */ (function (domGlobals) { 'use strict'; var noop = function () { }; var noarg = function (f) { return function () { return f(); }; }; var compose = function (fa, fb) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return fa(fb.apply(null, args)); }; }; var constant = function (value) { return function () { return value; }; }; var identity = function (x) { return x; }; function curry(fn) { var initialArgs = []; for (var _i = 1; _i < arguments.length; _i++) { initialArgs[_i - 1] = arguments[_i]; } return function () { var restArgs = []; for (var _i = 0; _i < arguments.length; _i++) { restArgs[_i] = arguments[_i]; } var all = initialArgs.concat(restArgs); return fn.apply(null, all); }; } var not = function (f) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return !f.apply(null, args); }; }; var die = function (msg) { return function () { throw new Error(msg); }; }; var never = constant(false); var always = constant(true); var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager'); var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === 'function') for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } var none = function () { return NONE; }; var NONE = function () { var eq = function (o) { return o.isNone(); }; var call = function (thunk) { return thunk(); }; var id = function (n) { return n; }; var me = { fold: function (n, s) { return n(); }, is: never, isSome: never, isNone: always, getOr: id, getOrThunk: call, getOrDie: function (msg) { throw new Error(msg || 'error: getOrDie called on none.'); }, getOrNull: constant(null), getOrUndefined: constant(undefined), or: id, orThunk: call, map: none, each: noop, bind: none, exists: never, forall: always, filter: none, equals: eq, equals_: eq, toArray: function () { return []; }, toString: constant('none()') }; if (Object.freeze) { Object.freeze(me); } return me; }(); var some = function (a) { var constant_a = constant(a); var self = function () { return me; }; var bind = function (f) { return f(a); }; var me = { fold: function (n, s) { return s(a); }, is: function (v) { return a === v; }, isSome: always, isNone: never, getOr: constant_a, getOrThunk: constant_a, getOrDie: constant_a, getOrNull: constant_a, getOrUndefined: constant_a, or: self, orThunk: self, map: function (f) { return some(f(a)); }, each: function (f) { f(a); }, bind: bind, exists: bind, forall: bind, filter: function (f) { return f(a) ? me : NONE; }, toArray: function () { return [a]; }, toString: function () { return 'some(' + a + ')'; }, equals: function (o) { return o.is(a); }, equals_: function (o, elementEq) { return o.fold(never, function (b) { return elementEq(a, b); }); } }; return me; }; var from = function (value) { return value === null || value === undefined ? NONE : some(value); }; var Option = { some: some, none: none, from: from }; var value = function (o) { var is = function (v) { return o === v; }; var or = function (opt) { return value(o); }; var orThunk = function (f) { return value(o); }; var map = function (f) { return value(f(o)); }; var mapError = function (f) { return value(o); }; var each = function (f) { f(o); }; var bind = function (f) { return f(o); }; var fold = function (_, onValue) { return onValue(o); }; var exists = function (f) { return f(o); }; var forall = function (f) { return f(o); }; var toOption = function () { return Option.some(o); }; return { is: is, isValue: always, isError: never, getOr: constant(o), getOrThunk: constant(o), getOrDie: constant(o), or: or, orThunk: orThunk, fold: fold, map: map, mapError: mapError, each: each, bind: bind, exists: exists, forall: forall, toOption: toOption }; }; var error = function (message) { var getOrThunk = function (f) { return f(); }; var getOrDie = function () { return die(String(message))(); }; var or = function (opt) { return opt; }; var orThunk = function (f) { return f(); }; var map = function (f) { return error(message); }; var mapError = function (f) { return error(f(message)); }; var bind = function (f) { return error(message); }; var fold = function (onError, _) { return onError(message); }; return { is: never, isValue: never, isError: always, getOr: identity, getOrThunk: getOrThunk, getOrDie: getOrDie, or: or, orThunk: orThunk, fold: fold, map: map, mapError: mapError, each: noop, bind: bind, exists: never, forall: always, toOption: Option.none }; }; var fromOption = function (opt, err) { return opt.fold(function () { return error(err); }, value); }; var Result = { value: value, error: error, fromOption: fromOption }; var typeOf = function (x) { if (x === null) { return 'null'; } var t = typeof x; if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { return 'array'; } if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { return 'string'; } return t; }; var isType = function (type) { return function (value) { return typeOf(value) === type; }; }; var isString = isType('string'); var isObject = isType('object'); var isArray = isType('array'); var isBoolean = isType('boolean'); var isFunction = isType('function'); var isNumber = isType('number'); var isArrayOf = function (value, pred) { if (isArray(value)) { for (var i = 0, len = value.length; i < len; ++i) { if (pred(value[i]) !== true) { return false; } } return true; } return false; }; var nativeSlice = Array.prototype.slice; var nativeIndexOf = Array.prototype.indexOf; var nativePush = Array.prototype.push; var rawIndexOf = function (ts, t) { return nativeIndexOf.call(ts, t); }; var indexOf = function (xs, x) { var r = rawIndexOf(xs, x); return r === -1 ? Option.none() : Option.some(r); }; var contains = function (xs, x) { return rawIndexOf(xs, x) > -1; }; var exists = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i)) { return true; } } return false; }; var range = function (num, f) { var r = []; for (var i = 0; i < num; i++) { r.push(f(i)); } return r; }; var chunk = function (array, size) { var r = []; for (var i = 0; i < array.length; i += size) { var s = nativeSlice.call(array, i, i + size); r.push(s); } return r; }; var map = function (xs, f) { var len = xs.length; var r = new Array(len); for (var i = 0; i < len; i++) { var x = xs[i]; r[i] = f(x, i); } return r; }; var each = function (xs, f) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; f(x, i); } }; var eachr = function (xs, f) { for (var i = xs.length - 1; i >= 0; i--) { var x = xs[i]; f(x, i); } }; var partition = function (xs, pred) { var pass = []; var fail = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; var arr = pred(x, i) ? pass : fail; arr.push(x); } return { pass: pass, fail: fail }; }; var filter = function (xs, pred) { var r = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i)) { r.push(x); } } return r; }; var foldr = function (xs, f, acc) { eachr(xs, function (x) { acc = f(acc, x); }); return acc; }; var foldl = function (xs, f, acc) { each(xs, function (x) { acc = f(acc, x); }); return acc; }; var find = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i)) { return Option.some(x); } } return Option.none(); }; var findIndex = function (xs, pred) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i)) { return Option.some(i); } } return Option.none(); }; var flatten = function (xs) { var r = []; for (var i = 0, len = xs.length; i < len; ++i) { if (!isArray(xs[i])) { throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); } nativePush.apply(r, xs[i]); } return r; }; var bind = function (xs, f) { var output = map(xs, f); return flatten(output); }; var forall = function (xs, pred) { for (var i = 0, len = xs.length; i < len; ++i) { var x = xs[i]; if (pred(x, i) !== true) { return false; } } return true; }; var reverse = function (xs) { var r = nativeSlice.call(xs, 0); r.reverse(); return r; }; var difference = function (a1, a2) { return filter(a1, function (x) { return !contains(a2, x); }); }; var pure = function (x) { return [x]; }; var sort = function (xs, comparator) { var copy = nativeSlice.call(xs, 0); copy.sort(comparator); return copy; }; var head = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[0]); }; var last = function (xs) { return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]); }; var from$1 = isFunction(Array.from) ? Array.from : function (x) { return nativeSlice.call(x); }; var keys = Object.keys; var hasOwnProperty = Object.hasOwnProperty; var each$1 = function (obj, f) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; f(x, i); } }; var map$1 = function (obj, f) { return tupleMap(obj, function (x, i) { return { k: i, v: f(x, i) }; }); }; var tupleMap = function (obj, f) { var r = {}; each$1(obj, function (x, i) { var tuple = f(x, i); r[tuple.k] = tuple.v; }); return r; }; var mapToArray = function (obj, f) { var r = []; each$1(obj, function (value, name) { r.push(f(value, name)); }); return r; }; var find$1 = function (obj, pred) { var props = keys(obj); for (var k = 0, len = props.length; k < len; k++) { var i = props[k]; var x = obj[i]; if (pred(x, i, obj)) { return Option.some(x); } } return Option.none(); }; var values = function (obj) { return mapToArray(obj, function (v) { return v; }); }; var get = function (obj, key) { return has(obj, key) ? Option.from(obj[key]) : Option.none(); }; var has = function (obj, key) { return hasOwnProperty.call(obj, key); }; var generate = function (cases) { if (!isArray(cases)) { throw new Error('cases must be an array'); } if (cases.length === 0) { throw new Error('there must be at least one case'); } var constructors = []; var adt = {}; each(cases, function (acase, count) { var keys$1 = keys(acase); if (keys$1.length !== 1) { throw new Error('one and only one name per case'); } var key = keys$1[0]; var value = acase[key]; if (adt[key] !== undefined) { throw new Error('duplicate key detected:' + key); } else if (key === 'cata') { throw new Error('cannot have a case named cata (sorry)'); } else if (!isArray(value)) { throw new Error('case arguments must be an array'); } constructors.push(key); adt[key] = function () { var argLength = arguments.length; if (argLength !== value.length) { throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength); } var args = new Array(argLength); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var match = function (branches) { var branchKeys = keys(branches); if (constructors.length !== branchKeys.length) { throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(',')); } var allReqd = forall(constructors, function (reqKey) { return contains(branchKeys, reqKey); }); if (!allReqd) { throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', ')); } return branches[key].apply(null, args); }; return { fold: function () { if (arguments.length !== cases.length) { throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length); } var target = arguments[count]; return target.apply(null, args); }, match: match, log: function (label) { domGlobals.console.log(label, { constructors: constructors, constructor: key, params: args }); } }; }; }); return adt; }; var Adt = { generate: generate }; var hasOwnProperty$1 = Object.prototype.hasOwnProperty; var shallow = function (old, nu) { return nu; }; var deep = function (old, nu) { var bothObjects = isObject(old) && isObject(nu); return bothObjects ? deepMerge(old, nu) : nu; }; var baseMerge = function (merger) { return function () { var objects = new Array(arguments.length); for (var i = 0; i < objects.length; i++) { objects[i] = arguments[i]; } if (objects.length === 0) { throw new Error('Can\'t merge zero objects'); } var ret = {}; for (var j = 0; j < objects.length; j++) { var curObject = objects[j]; for (var key in curObject) { if (hasOwnProperty$1.call(curObject, key)) { ret[key] = merger(ret[key], curObject[key]); } } } return ret; }; }; var deepMerge = baseMerge(deep); var merge = baseMerge(shallow); var cached = function (f) { var called = false; var r; return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (!called) { called = true; r = f.apply(null, args); } return r; }; }; var adt = Adt.generate([ { strict: [] }, { defaultedThunk: ['fallbackThunk'] }, { asOption: [] }, { asDefaultedOptionThunk: ['fallbackThunk'] }, { mergeWithThunk: ['baseThunk'] } ]); var defaulted = function (fallback) { return adt.defaultedThunk(constant(fallback)); }; var mergeWith = function (base) { return adt.mergeWithThunk(constant(base)); }; var strict = adt.strict; var asOption = adt.asOption; var defaultedThunk = adt.defaultedThunk; var mergeWithThunk = adt.mergeWithThunk; var exclude = function (obj, fields) { var r = {}; each$1(obj, function (v, k) { if (!contains(fields, k)) { r[k] = v; } }); return r; }; var readOpt = function (key) { return function (obj) { return has(obj, key) ? Option.from(obj[key]) : Option.none(); }; }; var readOr = function (key, fallback) { return function (obj) { return has(obj, key) ? obj[key] : fallback; }; }; var readOptFrom = function (obj, key) { return readOpt(key)(obj); }; var hasKey = function (obj, key) { return has(obj, key) && obj[key] !== undefined && obj[key] !== null; }; var wrap = function (key, value) { var r = {}; r[key] = value; return r; }; var wrapAll = function (keyvalues) { var r = {}; each(keyvalues, function (kv) { r[kv.key] = kv.value; }); return r; }; var comparison = Adt.generate([ { bothErrors: [ 'error1', 'error2' ] }, { firstError: [ 'error1', 'value2' ] }, { secondError: [ 'value1', 'error2' ] }, { bothValues: [ 'value1', 'value2' ] } ]); var partition$1 = function (results) { var errors = []; var values = []; each(results, function (result) { result.fold(function (err) { errors.push(err); }, function (value) { values.push(value); }); }); return { errors: errors, values: values }; }; var exclude$1 = function (obj, fields) { return exclude(obj, fields); }; var readOpt$1 = function (key) { return readOpt(key); }; var readOr$1 = function (key, fallback) { return readOr(key, fallback); }; var readOptFrom$1 = function (obj, key) { return readOptFrom(obj, key); }; var wrap$1 = function (key, value) { return wrap(key, value); }; var wrapAll$1 = function (keyvalues) { return wrapAll(keyvalues); }; var mergeValues = function (values, base) { return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values))); }; var mergeErrors = function (errors) { return Result.error(flatten(errors)); }; var consolidate = function (objs, base) { var partitions = partition$1(objs); return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base); }; var hasKey$1 = function (obj, key) { return hasKey(obj, key); }; var SimpleResultType; (function (SimpleResultType) { SimpleResultType[SimpleResultType['Error'] = 0] = 'Error'; SimpleResultType[SimpleResultType['Value'] = 1] = 'Value'; }(SimpleResultType || (SimpleResultType = {}))); var fold = function (res, onError, onValue) { return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue); }; var partition$2 = function (results) { var values = []; var errors = []; each(results, function (obj) { fold(obj, function (err) { return errors.push(err); }, function (val) { return values.push(val); }); }); return { values: values, errors: errors }; }; var mapError = function (res, f) { if (res.stype === SimpleResultType.Error) { return { stype: SimpleResultType.Error, serror: f(res.serror) }; } else { return res; } }; var map$2 = function (res, f) { if (res.stype === SimpleResultType.Value) { return { stype: SimpleResultType.Value, svalue: f(res.svalue) }; } else { return res; } }; var bind$1 = function (res, f) { if (res.stype === SimpleResultType.Value) { return f(res.svalue); } else { return res; } }; var bindError = function (res, f) { if (res.stype === SimpleResultType.Error) { return f(res.serror); } else { return res; } }; var svalue = function (v) { return { stype: SimpleResultType.Value, svalue: v }; }; var serror = function (e) { return { stype: SimpleResultType.Error, serror: e }; }; var toResult = function (res) { return fold(res, Result.error, Result.value); }; var fromResult = function (res) { return res.fold(serror, svalue); }; var SimpleResult = { fromResult: fromResult, toResult: toResult, svalue: svalue, partition: partition$2, serror: serror, bind: bind$1, bindError: bindError, map: map$2, mapError: mapError, fold: fold }; var mergeValues$1 = function (values, base) { return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base); }; var mergeErrors$1 = function (errors) { return compose(SimpleResult.serror, flatten)(errors); }; var consolidateObj = function (objects, base) { var partition = SimpleResult.partition(objects); return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base); }; var consolidateArr = function (objects) { var partitions = SimpleResult.partition(objects); return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values); }; var ResultCombine = { consolidateObj: consolidateObj, consolidateArr: consolidateArr }; var typeAdt = Adt.generate([ { setOf: [ 'validator', 'valueType' ] }, { arrOf: ['valueType'] }, { objOf: ['fields'] }, { itemOf: ['validator'] }, { choiceOf: [ 'key', 'branches' ] }, { thunk: ['description'] }, { func: [ 'args', 'outputSchema' ] } ]); var fieldAdt = Adt.generate([ { field: [ 'name', 'presence', 'type' ] }, { state: ['name'] } ]); var formatObj = function (input) { return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2); }; var formatErrors = function (errors) { var es = errors.length > 10 ? errors.slice(0, 10).concat([{ path: [], getErrorInfo: function () { return '... (only showing first ten failures)'; } }]) : errors; return map(es, function (e) { return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo(); }); }; var nu = function (path, getErrorInfo) { return SimpleResult.serror([{ path: path, getErrorInfo: getErrorInfo }]); }; var missingStrict = function (path, key, obj) { return nu(path, function () { return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj); }); }; var missingKey = function (path, key) { return nu(path, function () { return 'Choice schema did not contain choice key: "' + key + '"'; }); }; var missingBranch = function (path, branches, branch) { return nu(path, function () { return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches); }); }; var unsupportedFields = function (path, unsupported) { return nu(path, function () { return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified'; }); }; var custom = function (path, err) { return nu(path, function () { return err; }); }; var adt$1 = Adt.generate([ { field: [ 'key', 'okey', 'presence', 'prop' ] }, { state: [ 'okey', 'instantiator' ] } ]); var strictAccess = function (path, obj, key) { return readOptFrom(obj, key).fold(function () { return missingStrict(path, key, obj); }, SimpleResult.svalue); }; var fallbackAccess = function (obj, key, fallbackThunk) { var v = readOptFrom(obj, key).fold(function () { return fallbackThunk(obj); }, identity); return SimpleResult.svalue(v); }; var optionAccess = function (obj, key) { return SimpleResult.svalue(readOptFrom(obj, key)); }; var optionDefaultedAccess = function (obj, key, fallback) { var opt = readOptFrom(obj, key).map(function (val) { return val === true ? fallback(obj) : val; }); return SimpleResult.svalue(opt); }; var cExtractOne = function (path, obj, field, strength) { return field.fold(function (key, okey, presence, prop) { var bundle = function (av) { var result = prop.extract(path.concat([key]), strength, av); return SimpleResult.map(result, function (res) { return wrap(okey, strength(res)); }); }; var bundleAsOption = function (optValue) { return optValue.fold(function () { var outcome = wrap(okey, strength(Option.none())); return SimpleResult.svalue(outcome); }, function (ov) { var result = prop.extract(path.concat([key]), strength, ov); return SimpleResult.map(result, function (res) { return wrap(okey, strength(Option.some(res))); }); }); }; return function () { return presence.fold(function () { return SimpleResult.bind(strictAccess(path, obj, key), bundle); }, function (fallbackThunk) { return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle); }, function () { return SimpleResult.bind(optionAccess(obj, key), bundleAsOption); }, function (fallbackThunk) { return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption); }, function (baseThunk) { var base = baseThunk(obj); var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) { return deepMerge(base, v); }); return SimpleResult.bind(result, bundle); }); }(); }, function (okey, instantiator) { var state = instantiator(obj); return SimpleResult.svalue(wrap(okey, strength(state))); }); }; var cExtract = function (path, obj, fields, strength) { var results = map(fields, function (field) { return cExtractOne(path, obj, field, strength); }); return ResultCombine.consolidateObj(results, {}); }; var valueThunk = function (getDelegate) { var extract = function (path, strength, val) { return getDelegate().extract(path, strength, val); }; var toString = function () { return getDelegate().toString(); }; var toDsl = function () { return getDelegate().toDsl(); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var value$1 = function (validator) { var extract = function (path, strength, val) { return SimpleResult.bindError(validator(val, strength), function (err) { return custom(path, err); }); }; var toString = function () { return 'val'; }; var toDsl = function () { return typeAdt.itemOf(validator); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var getSetKeys = function (obj) { var keys$1 = keys(obj); return filter(keys$1, function (k) { return hasKey$1(obj, k); }); }; var objOfOnly = function (fields) { var delegate = objOf(fields); var fieldNames = foldr(fields, function (acc, f) { return f.fold(function (key) { return deepMerge(acc, wrap$1(key, true)); }, constant(acc)); }, {}); var extract = function (path, strength, o) { var keys = isBoolean(o) ? [] : getSetKeys(o); var extra = filter(keys, function (k) { return !hasKey$1(fieldNames, k); }); return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra); }; return { extract: extract, toString: delegate.toString, toDsl: delegate.toDsl }; }; var objOf = function (fields) { var extract = function (path, strength, o) { return cExtract(path, o, fields, strength); }; var toString = function () { var fieldStrings = map(fields, function (field) { return field.fold(function (key, okey, presence, prop) { return key + ' -> ' + prop.toString(); }, function (okey, instantiator) { return 'state(' + okey + ')'; }); }); return 'obj{\n' + fieldStrings.join('\n') + '}'; }; var toDsl = function () { return typeAdt.objOf(map(fields, function (f) { return f.fold(function (key, okey, presence, prop) { return fieldAdt.field(key, presence, prop); }, function (okey, instantiator) { return fieldAdt.state(okey); }); })); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var arrOf = function (prop) { var extract = function (path, strength, array) { var results = map(array, function (a, i) { return prop.extract(path.concat(['[' + i + ']']), strength, a); }); return ResultCombine.consolidateArr(results); }; var toString = function () { return 'array(' + prop.toString() + ')'; }; var toDsl = function () { return typeAdt.arrOf(prop); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var setOf = function (validator, prop) { var validateKeys = function (path, keys) { return arrOf(value$1(validator)).extract(path, identity, keys); }; var extract = function (path, strength, o) { var keys$1 = keys(o); var validatedKeys = validateKeys(path, keys$1); return SimpleResult.bind(validatedKeys, function (validKeys) { var schema = map(validKeys, function (vk) { return adt$1.field(vk, vk, strict(), prop); }); return objOf(schema).extract(path, strength, o); }); }; var toString = function () { return 'setOf(' + prop.toString() + ')'; }; var toDsl = function () { return typeAdt.setOf(validator, prop); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var anyValue = constant(value$1(SimpleResult.svalue)); var arrOfObj = compose(arrOf, objOf); var state = adt$1.state; var field = adt$1.field; var chooseFrom = function (path, strength, input, branches, ch) { var fields = readOptFrom$1(branches, ch); return fields.fold(function () { return missingBranch(path, branches, ch); }, function (vp) { return vp.extract(path.concat(['branch: ' + ch]), strength, input); }); }; var choose = function (key, branches) { var extract = function (path, strength, input) { var choice = readOptFrom$1(input, key); return choice.fold(function () { return missingKey(path, key); }, function (chosen) { return chooseFrom(path, strength, input, branches, chosen); }); }; var toString = function () { return 'chooseOn(' + key + '). Possible values: ' + keys(branches); }; var toDsl = function () { return typeAdt.choiceOf(key, branches); }; return { extract: extract, toString: toString, toDsl: toDsl }; }; var _anyValue = value$1(SimpleResult.svalue); var arrOfObj$1 = function (objFields) { return arrOfObj(objFields); }; var arrOfVal = function () { return arrOf(_anyValue); }; var valueThunkOf = valueThunk; var valueOf = function (validator) { return value$1(function (v) { return validator(v).fold(SimpleResult.serror, SimpleResult.svalue); }); }; var setOf$1 = function (validator, prop) { return setOf(function (v) { return SimpleResult.fromResult(validator(v)); }, prop); }; var extract = function (label, prop, strength, obj) { var res = prop.extract([label], strength, obj); return SimpleResult.mapError(res, function (errs) { return { input: obj, errors: errs }; }); }; var asRaw = function (label, prop, obj) { return SimpleResult.toResult(extract(label, prop, identity, obj)); }; var getOrDie = function (extraction) { return extraction.fold(function (errInfo) { throw new Error(formatError(errInfo)); }, identity); }; var asRawOrDie = function (label, prop, obj) { return getOrDie(asRaw(label, prop, obj)); }; var formatError = function (errInfo) { return 'Errors: \n' + formatErrors(errInfo.errors) + '\n\nInput object: ' + formatObj(errInfo.input); }; var chooseProcessor = function (key, branches) { return choose(key, branches); }; var choose$1 = function (key, branches) { return choose(key, map$1(branches, objOf)); }; var anyValue$1 = constant(_anyValue); var typedValue = function (validator, expectedType) { return value$1(function (a) { var actualType = typeof a; return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType); }); }; var number = typedValue(isNumber, 'number'); var string = typedValue(isString, 'string'); var boolean = typedValue(isBoolean, 'boolean'); var functionProcessor = typedValue(isFunction, 'function'); var isPostMessageable = function (val) { var every = function (iter, callbackFn) { var result = iter.next(); while (!result.done) { if (!callbackFn(result.value)) { return false; } result = iter.next(); } return true; }; if (Object(val) !== val) { return true; } switch ({}.toString.call(val).slice(8, -1)) { case 'Boolean': case 'Number': case 'String': case 'Date': case 'RegExp': case 'Blob': case 'FileList': case 'ImageData': case 'ImageBitmap': case 'ArrayBuffer': return true; case 'Array': case 'Object': return Object.keys(val).every(function (prop) { return isPostMessageable(val[prop]); }); case 'Map': return every(val.keys(), isPostMessageable) && every(val.values(), isPostMessageable); case 'Set': return every(val.keys(), isPostMessageable); default: return false; } }; var postMessageable = value$1(function (a) { return isPostMessageable(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected value to be acceptable for sending via postMessage'); }); var validateEnum = function (values) { return valueOf(function (value) { return contains(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".'); }); }; var strict$1 = function (key) { return field(key, key, strict(), anyValue()); }; var strictOf = function (key, schema) { return field(key, key, strict(), schema); }; var strictNumber = function (key) { return strictOf(key, number); }; var strictString = function (key) { return strictOf(key, string); }; var strictStringEnum = function (key, values) { return field(key, key, strict(), validateEnum(values)); }; var strictBoolean = function (key) { return strictOf(key, boolean); }; var strictFunction = function (key) { return strictOf(key, functionProcessor); }; var forbid = function (key, message) { return field(key, key, asOption(), value$1(function (v) { return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message); })); }; var strictObjOf = function (key, objSchema) { return field(key, key, strict(), objOf(objSchema)); }; var strictArrayOfObj = function (key, objFields) { return field(key, key, strict(), arrOfObj(objFields)); }; var strictArrayOf = function (key, schema) { return field(key, key, strict(), arrOf(schema)); }; var option = function (key) { return field(key, key, asOption(), anyValue()); }; var optionOf = function (key, schema) { return field(key, key, asOption(), schema); }; var optionNumber = function (key) { return optionOf(key, number); }; var optionString = function (key) { return optionOf(key, string); }; var optionFunction = function (key) { return optionOf(key, functionProcessor); }; var optionArrayOf = function (key, schema) { return optionOf(key, arrOf(schema)); }; var optionObjOf = function (key, objSchema) { return optionOf(key, objOf(objSchema)); }; var optionObjOfOnly = function (key, objSchema) { return optionOf(key, objOfOnly(objSchema)); }; var defaulted$1 = function (key, fallback) { return field(key, key, defaulted(fallback), anyValue()); }; var defaultedOf = function (key, fallback, schema) { return field(key, key, defaulted(fallback), schema); }; var defaultedNumber = function (key, fallback) { return defaultedOf(key, fallback, number); }; var defaultedString = function (key, fallback) { return defaultedOf(key, fallback, string); }; var defaultedStringEnum = function (key, fallback, values) { return defaultedOf(key, fallback, validateEnum(values)); }; var defaultedBoolean = function (key, fallback) { return defaultedOf(key, fallback, boolean); }; var defaultedFunction = function (key, fallback) { return defaultedOf(key, fallback, functionProcessor); }; var defaultedPostMsg = function (key, fallback) { return defaultedOf(key, fallback, postMessageable); }; var defaultedArrayOf = function (key, fallback, schema) { return defaultedOf(key, fallback, arrOf(schema)); }; var defaultedObjOf = function (key, fallback, objSchema) { return defaultedOf(key, fallback, objOf(objSchema)); }; var state$1 = function (okey, instantiator) { return state(okey, instantiator); }; var Cell = function (initial) { var value = initial; var get = function () { return value; }; var set = function (v) { value = v; }; var clone = function () { return Cell(get()); }; return { get: get, set: set, clone: clone }; }; var fromHtml = function (html, scope) { var doc = scope || domGlobals.document; var div = doc.createElement('div'); div.innerHTML = html; if (!div.hasChildNodes() || div.childNodes.length > 1) { domGlobals.console.error('HTML does not have a single root node', html); throw new Error('HTML must have a single root node'); } return fromDom(div.childNodes[0]); }; var fromTag = function (tag, scope) { var doc = scope || domGlobals.document; var node = doc.createElement(tag); return fromDom(node); }; var fromText = function (text, scope) { var doc = scope || domGlobals.document; var node = doc.createTextNode(text); return fromDom(node); }; var fromDom = function (node) { if (node === null || node === undefined) { throw new Error('Node cannot be null or undefined'); } return { dom: constant(node) }; }; var fromPoint = function (docElm, x, y) { var doc = docElm.dom(); return Option.from(doc.elementFromPoint(x, y)).map(fromDom); }; var Element = { fromHtml: fromHtml, fromTag: fromTag, fromText: fromText, fromDom: fromDom, fromPoint: fromPoint }; var compareDocumentPosition = function (a, b, match) { return (a.compareDocumentPosition(b) & match) !== 0; }; var documentPositionPreceding = function (a, b) { return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_PRECEDING); }; var documentPositionContainedBy = function (a, b) { return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY); }; var Node = { documentPositionPreceding: documentPositionPreceding, documentPositionContainedBy: documentPositionContainedBy }; var firstMatch = function (regexes, s) { for (var i = 0; i < regexes.length; i++) { var x = regexes[i]; if (x.test(s)) { return x; } } return undefined; }; var find$2 = function (regexes, agent) { var r = firstMatch(regexes, agent); if (!r) { return { major: 0, minor: 0 }; } var group = function (i) { return Number(agent.replace(r, '$' + i)); }; return nu$1(group(1), group(2)); }; var detect = function (versionRegexes, agent) { var cleanedAgent = String(agent).toLowerCase(); if (versionRegexes.length === 0) { return unknown(); } return find$2(versionRegexes, cleanedAgent); }; var unknown = function () { return nu$1(0, 0); }; var nu$1 = function (major, minor) { return { major: major, minor: minor }; }; var Version = { nu: nu$1, detect: detect, unknown: unknown }; var edge = 'Edge'; var chrome = 'Chrome'; var ie = 'IE'; var opera = 'Opera'; var firefox = 'Firefox'; var safari = 'Safari'; var isBrowser = function (name, current) { return function () { return current === name; }; }; var unknown$1 = function () { return nu$2({ current: undefined, version: Version.unknown() }); }; var nu$2 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isEdge: isBrowser(edge, current), isChrome: isBrowser(chrome, current), isIE: isBrowser(ie, current), isOpera: isBrowser(opera, current), isFirefox: isBrowser(firefox, current), isSafari: isBrowser(safari, current) }; }; var Browser = { unknown: unknown$1, nu: nu$2, edge: constant(edge), chrome: constant(chrome), ie: constant(ie), opera: constant(opera), firefox: constant(firefox), safari: constant(safari) }; var windows = 'Windows'; var ios = 'iOS'; var android = 'Android'; var linux = 'Linux'; var osx = 'OSX'; var solaris = 'Solaris'; var freebsd = 'FreeBSD'; var isOS = function (name, current) { return function () { return current === name; }; }; var unknown$2 = function () { return nu$3({ current: undefined, version: Version.unknown() }); }; var nu$3 = function (info) { var current = info.current; var version = info.version; return { current: current, version: version, isWindows: isOS(windows, current), isiOS: isOS(ios, current), isAndroid: isOS(android, current), isOSX: isOS(osx, current), isLinux: isOS(linux, current), isSolaris: isOS(solaris, current), isFreeBSD: isOS(freebsd, current) }; }; var OperatingSystem = { unknown: unknown$2, nu: nu$3, windows: constant(windows), ios: constant(ios), android: constant(android), linux: constant(linux), osx: constant(osx), solaris: constant(solaris), freebsd: constant(freebsd) }; var DeviceType = function (os, browser, userAgent, mediaMatch) { var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; var isiPhone = os.isiOS() && !isiPad; var isMobile = os.isiOS() || os.isAndroid(); var isTouch = isMobile || mediaMatch('(pointer:coarse)'); var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)'); var isPhone = isiPhone || isMobile && !isTablet; var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; var isDesktop = !isPhone && !isTablet && !iOSwebview; return { isiPad: constant(isiPad), isiPhone: constant(isiPhone), isTablet: constant(isTablet), isPhone: constant(isPhone), isTouch: constant(isTouch), isAndroid: os.isAndroid, isiOS: os.isiOS, isWebView: constant(iOSwebview), isDesktop: constant(isDesktop) }; }; var detect$1 = function (candidates, userAgent) { var agent = String(userAgent).toLowerCase(); return find(candidates, function (candidate) { return candidate.search(agent); }); }; var detectBrowser = function (browsers, userAgent) { return detect$1(browsers, userAgent).map(function (browser) { var version = Version.detect(browser.versionRegexes, userAgent); return { current: browser.name, version: version }; }); }; var detectOs = function (oses, userAgent) { return detect$1(oses, userAgent).map(function (os) { var version = Version.detect(os.versionRegexes, userAgent); return { current: os.name, version: version }; }); }; var UaString = { detectBrowser: detectBrowser, detectOs: detectOs }; var checkRange = function (str, substr, start) { if (substr === '') { return true; } if (str.length < substr.length) { return false; } var x = str.substr(start, start + substr.length); return x === substr; }; var contains$1 = function (str, substr) { return str.indexOf(substr) !== -1; }; var endsWith = function (str, suffix) { return checkRange(str, suffix, str.length - suffix.length); }; var trim = function (str) { return str.replace(/^\s+|\s+$/g, ''); }; var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; var checkContains = function (target) { return function (uastring) { return contains$1(uastring, target); }; }; var browsers = [ { name: 'Edge', versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], search: function (uastring) { return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit'); } }, { name: 'Chrome', versionRegexes: [ /.*?chrome\/([0-9]+)\.([0-9]+).*/, normalVersionRegex ], search: function (uastring) { return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe'); } }, { name: 'IE', versionRegexes: [ /.*?msie\ ?([0-9]+)\.([0-9]+).*/, /.*?rv:([0-9]+)\.([0-9]+).*/ ], search: function (uastring) { return contains$1(uastring, 'msie') || contains$1(uastring, 'trident'); } }, { name: 'Opera', versionRegexes: [ normalVersionRegex, /.*?opera\/([0-9]+)\.([0-9]+).*/ ], search: checkContains('opera') }, { name: 'Firefox', versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], search: checkContains('firefox') }, { name: 'Safari', versionRegexes: [ normalVersionRegex, /.*?cpu os ([0-9]+)_([0-9]+).*/ ], search: function (uastring) { return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit'); } } ]; var oses = [ { name: 'Windows', search: checkContains('win'), versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'iOS', search: function (uastring) { return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad'); }, versionRegexes: [ /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, /.*cpu os ([0-9]+)_([0-9]+).*/, /.*cpu iphone os ([0-9]+)_([0-9]+).*/ ] }, { name: 'Android', search: checkContains('android'), versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] }, { name: 'OSX', search: checkContains('os x'), versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/] }, { name: 'Linux', search: checkContains('linux'), versionRegexes: [] }, { name: 'Solaris', search: checkContains('sunos'), versionRegexes: [] }, { name: 'FreeBSD', search: checkContains('freebsd'), versionRegexes: [] } ]; var PlatformInfo = { browsers: constant(browsers), oses: constant(oses) }; var detect$2 = function (userAgent, mediaMatch) { var browsers = PlatformInfo.browsers(); var oses = PlatformInfo.oses(); var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu); var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu); var deviceType = DeviceType(os, browser, userAgent, mediaMatch); return { browser: browser, os: os, deviceType: deviceType }; }; var PlatformDetection = { detect: detect$2 }; var mediaMatch = function (query) { return domGlobals.window.matchMedia(query).matches; }; var platform = Cell(PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch)); var detect$3 = function () { return platform.get(); }; var ATTRIBUTE = domGlobals.Node.ATTRIBUTE_NODE; var CDATA_SECTION = domGlobals.Node.CDATA_SECTION_NODE; var COMMENT = domGlobals.Node.COMMENT_NODE; var DOCUMENT = domGlobals.Node.DOCUMENT_NODE; var DOCUMENT_TYPE = domGlobals.Node.DOCUMENT_TYPE_NODE; var DOCUMENT_FRAGMENT = domGlobals.Node.DOCUMENT_FRAGMENT_NODE; var ELEMENT = domGlobals.Node.ELEMENT_NODE; var TEXT = domGlobals.Node.TEXT_NODE; var PROCESSING_INSTRUCTION = domGlobals.Node.PROCESSING_INSTRUCTION_NODE; var ENTITY_REFERENCE = domGlobals.Node.ENTITY_REFERENCE_NODE; var ENTITY = domGlobals.Node.ENTITY_NODE; var NOTATION = domGlobals.Node.NOTATION_NODE; var ELEMENT$1 = ELEMENT; var DOCUMENT$1 = DOCUMENT; var is = function (element, selector) { var dom = element.dom(); if (dom.nodeType !== ELEMENT$1) { return false; } else { var elem = dom; if (elem.matches !== undefined) { return elem.matches(selector); } else if (elem.msMatchesSelector !== undefined) { return elem.msMatchesSelector(selector); } else if (elem.webkitMatchesSelector !== undefined) { return elem.webkitMatchesSelector(selector); } else if (elem.mozMatchesSelector !== undefined) { return elem.mozMatchesSelector(selector); } else { throw new Error('Browser lacks native selectors'); } } }; var bypassSelector = function (dom) { return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0; }; var all = function (selector, scope) { var base = scope === undefined ? domGlobals.document : scope.dom(); return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), Element.fromDom); }; var one = function (selector, scope) { var base = scope === undefined ? domGlobals.document : scope.dom(); return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom); }; var eq = function (e1, e2) { return e1.dom() === e2.dom(); }; var regularContains = function (e1, e2) { var d1 = e1.dom(); var d2 = e2.dom(); return d1 === d2 ? false : d1.contains(d2); }; var ieContains = function (e1, e2) { return Node.documentPositionContainedBy(e1.dom(), e2.dom()); }; var browser = detect$3().browser; var contains$2 = browser.isIE() ? ieContains : regularContains; var isSource = function (component, simulatedEvent) { return eq(component.element(), simulatedEvent.event().target()); }; var nu$4 = function (parts) { if (!hasKey$1(parts, 'can') && !hasKey$1(parts, 'abort') && !hasKey$1(parts, 'run')) { throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!'); } return asRawOrDie('Extracting event.handler', objOfOnly([ defaulted$1('can', constant(true)), defaulted$1('abort', constant(false)), defaulted$1('run', noop) ]), parts); }; var all$1 = function (handlers, f) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return foldl(handlers, function (acc, handler) { return acc && f(handler).apply(undefined, args); }, true); }; }; var any = function (handlers, f) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return foldl(handlers, function (acc, handler) { return acc || f(handler).apply(undefined, args); }, false); }; }; var read = function (handler) { return isFunction(handler) ? { can: constant(true), abort: constant(false), run: handler } : handler; }; var fuse = function (handlers) { var can = all$1(handlers, function (handler) { return handler.can; }); var abort = any(handlers, function (handler) { return handler.abort; }); var run = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } each(handlers, function (handler) { handler.run.apply(undefined, args); }); }; return nu$4({ can: can, abort: abort, run: run }); }; var touchstart = constant('touchstart'); var touchmove = constant('touchmove'); var touchend = constant('touchend'); var mousedown = constant('mousedown'); var mousemove = constant('mousemove'); var mouseout = constant('mouseout'); var mouseup = constant('mouseup'); var mouseover = constant('mouseover'); var focusin = constant('focusin'); var focusout = constant('focusout'); var keydown = constant('keydown'); var keyup = constant('keyup'); var input = constant('input'); var change = constant('change'); var click = constant('click'); var transitionend = constant('transitionend'); var selectstart = constant('selectstart'); var alloy = { tap: constant('alloy.tap') }; var focus = constant('alloy.focus'); var postBlur = constant('alloy.blur.post'); var postPaste = constant('alloy.paste.post'); var receive = constant('alloy.receive'); var execute = constant('alloy.execute'); var focusItem = constant('alloy.focus.item'); var tap = alloy.tap; var tapOrClick = detect$3().deviceType.isTouch() ? alloy.tap : click; var longpress = constant('alloy.longpress'); var sandboxClose = constant('alloy.sandbox.close'); var typeaheadCancel = constant('alloy.typeahead.cancel'); var systemInit = constant('alloy.system.init'); var documentTouchmove = constant('alloy.system.touchmove'); var documentTouchend = constant('alloy.system.touchend'); var windowScroll = constant('alloy.system.scroll'); var windowResize = constant('alloy.system.resize'); var attachedToDom = constant('alloy.system.attached'); var detachedFromDom = constant('alloy.system.detached'); var dismissRequested = constant('alloy.system.dismissRequested'); var repositionRequested = constant('alloy.system.repositionRequested'); var focusShifted = constant('alloy.focusmanager.shifted'); var slotVisibility = constant('alloy.slotcontainer.visibility'); var changeTab = constant('alloy.change.tab'); var dismissTab = constant('alloy.dismiss.tab'); var highlight = constant('alloy.highlight'); var dehighlight = constant('alloy.dehighlight'); var emit = function (component, event) { dispatchWith(component, component.element(), event, {}); }; var emitWith = function (component, event, properties) { dispatchWith(component, component.element(), event, properties); }; var emitExecute = function (component) { emit(component, execute()); }; var dispatch = function (component, target, event) { dispatchWith(component, target, event, {}); }; var dispatchWith = function (component, target, event, properties) { var data = __assign({ target: target }, properties); component.getSystem().triggerEvent(event, target, map$1(data, constant)); }; var dispatchEvent = function (component, target, event, simulatedEvent) { component.getSystem().triggerEvent(event, target, simulatedEvent.event()); }; function ClosestOrAncestor (is, ancestor, scope, a, isRoot) { return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot); } var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')(); var name = function (element) { var r = element.dom().nodeName; return r.toLowerCase(); }; var type = function (element) { return element.dom().nodeType; }; var isType$1 = function (t) { return function (element) { return type(element) === t; }; }; var isElement = isType$1(ELEMENT); var isText = isType$1(TEXT); var inBody = function (element) { var dom = isText(element) ? element.dom().parentNode : element.dom(); return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom); }; var body = cached(function () { return getBody(Element.fromDom(domGlobals.document)); }); var getBody = function (doc) { var b = doc.dom().body; if (b === null || b === undefined) { throw new Error('Body is not available yet'); } return Element.fromDom(b); }; var ancestor = function (scope, predicate, isRoot) { var element = scope.dom(); var stop = isFunction(isRoot) ? isRoot : constant(false); while (element.parentNode) { element = element.parentNode; var el = Element.fromDom(element); if (predicate(el)) { return Option.some(el); } else if (stop(el)) { break; } } return Option.none(); }; var closest = function (scope, predicate, isRoot) { var is = function (s, test) { return test(s); }; return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot); }; var descendant = function (scope, predicate) { var descend = function (node) { for (var i = 0; i < node.childNodes.length; i++) { var child_1 = Element.fromDom(node.childNodes[i]); if (predicate(child_1)) { return Option.some(child_1); } var res = descend(node.childNodes[i]); if (res.isSome()) { return res; } } return Option.none(); }; return descend(scope.dom()); }; var closest$1 = function (target, transform, isRoot) { var delegate = closest(target, function (elem) { return transform(elem).isSome(); }, isRoot); return delegate.bind(transform); }; var derive = function (configs) { return wrapAll$1(configs); }; var abort = function (name, predicate) { return { key: name, value: nu$4({ abort: predicate }) }; }; var can = function (name, predicate) { return { key: name, value: nu$4({ can: predicate }) }; }; var preventDefault = function (name) { return { key: name, value: nu$4({ run: function (component, simulatedEvent) { simulatedEvent.event().prevent(); } }) }; }; var run = function (name, handler) { return { key: name, value: nu$4({ run: handler }) }; }; var runActionExtra = function (name, action, extra) { return { key: name, value: nu$4({ run: function (component) { action.apply(undefined, [component].concat(extra)); } }) }; }; var runOnName = function (name) { return function (handler) { return run(name, handler); }; }; var runOnSourceName = function (name) { return function (handler) { return { key: name, value: nu$4({ run: function (component, simulatedEvent) { if (isSource(component, simulatedEvent)) { handler(component, simulatedEvent); } } }) }; }; }; var redirectToUid = function (name, uid) { return run(name, function (component, simulatedEvent) { component.getSystem().getByUid(uid).each(function (redirectee) { dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent); }); }); }; var redirectToPart = function (name, detail, partName) { var uid = detail.partUids[partName]; return redirectToUid(name, uid); }; var runWithTarget = function (name, f) { return run(name, function (component, simulatedEvent) { var ev = simulatedEvent.event(); var target = component.getSystem().getByDom(ev.target()).fold(function () { var closest = closest$1(ev.target(), function (el) { return component.getSystem().getByDom(el).toOption(); }, constant(false)); return closest.getOr(component); }, function (c) { return c; }); f(component, target, simulatedEvent); }); }; var cutter = function (name) { return run(name, function (component, simulatedEvent) { simulatedEvent.cut(); }); }; var stopper = function (name) { return run(name, function (component, simulatedEvent) { simulatedEvent.stop(); }); }; var runOnSource = function (name, f) { return runOnSourceName(name)(f); }; var runOnAttached = runOnSourceName(attachedToDom()); var runOnDetached = runOnSourceName(detachedFromDom()); var runOnInit = runOnSourceName(systemInit()); var runOnExecute = runOnName(execute()); var Immutable = function () { var fields = []; for (var _i = 0; _i < arguments.length; _i++) { fields[_i] = arguments[_i]; } return function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } if (fields.length !== values.length) { throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments'); } var struct = {}; each(fields, function (name, i) { struct[name] = constant(values[i]); }); return struct; }; }; var sort$1 = function (arr) { return arr.slice(0).sort(); }; var reqMessage = function (required, keys) { throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.'); }; var unsuppMessage = function (unsupported) { throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', ')); }; var validateStrArr = function (label, array) { if (!isArray(array)) { throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.'); } each(array, function (a) { if (!isString(a)) { throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.'); } }); }; var checkDupes = function (everything) { var sorted = sort$1(everything); var dupe = find(sorted, function (s, i) { return i < sorted.length - 1 && s === sorted[i + 1]; }); dupe.each(function (d) { throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].'); }); }; var MixedBag = function (required, optional) { var everything = required.concat(optional); if (everything.length === 0) { throw new Error('You must specify at least one required or optional field.'); } validateStrArr('required', required); validateStrArr('optional', optional); checkDupes(everything); return function (obj) { var keys$1 = keys(obj); var allReqd = forall(required, function (req) { return contains(keys$1, req); }); if (!allReqd) { reqMessage(required, keys$1); } var unsupported = filter(keys$1, function (key) { return !contains(everything, key); }); if (unsupported.length > 0) { unsuppMessage(unsupported); } var r = {}; each(required, function (req) { r[req] = constant(obj[req]); }); each(optional, function (opt) { r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none()); }); return r; }; }; var owner = function (element) { return Element.fromDom(element.dom().ownerDocument); }; var documentElement = function (element) { return Element.fromDom(element.dom().ownerDocument.documentElement); }; var defaultView = function (element) { return Element.fromDom(element.dom().ownerDocument.defaultView); }; var parent = function (element) { return Option.from(element.dom().parentNode).map(Element.fromDom); }; var offsetParent = function (element) { return Option.from(element.dom().offsetParent).map(Element.fromDom); }; var nextSibling = function (element) { return Option.from(element.dom().nextSibling).map(Element.fromDom); }; var children = function (element) { return map(element.dom().childNodes, Element.fromDom); }; var child = function (element, index) { var cs = element.dom().childNodes; return Option.from(cs[index]).map(Element.fromDom); }; var firstChild = function (element) { return child(element, 0); }; var spot = Immutable('element', 'offset'); var fromHtml$1 = function (html, scope) { var doc = scope || domGlobals.document; var div = doc.createElement('div'); div.innerHTML = html; return children(Element.fromDom(div)); }; var before = function (marker, element) { var parent$1 = parent(marker); parent$1.each(function (v) { v.dom().insertBefore(element.dom(), marker.dom()); }); }; var after = function (marker, element) { var sibling = nextSibling(marker); sibling.fold(function () { var parent$1 = parent(marker); parent$1.each(function (v) { append(v, element); }); }, function (v) { before(v, element); }); }; var prepend = function (parent, element) { var firstChild$1 = firstChild(parent); firstChild$1.fold(function () { append(parent, element); }, function (v) { parent.dom().insertBefore(element.dom(), v.dom()); }); }; var append = function (parent, element) { parent.dom().appendChild(element.dom()); }; var appendAt = function (parent, element, index) { child(parent, index).fold(function () { append(parent, element); }, function (v) { before(v, element); }); }; var before$1 = function (marker, elements) { each(elements, function (x) { before(marker, x); }); }; var append$1 = function (parent, elements) { each(elements, function (x) { append(parent, x); }); }; var empty = function (element) { element.dom().textContent = ''; each(children(element), function (rogue) { remove(rogue); }); }; var remove = function (element) { var dom = element.dom(); if (dom.parentNode !== null) { dom.parentNode.removeChild(dom); } }; var unwrap = function (wrapper) { var children$1 = children(wrapper); if (children$1.length > 0) { before$1(wrapper, children$1); } remove(wrapper); }; var get$1 = function (element) { return element.dom().innerHTML; }; var set = function (element, content) { var owner$1 = owner(element); var docDom = owner$1.dom(); var fragment = Element.fromDom(docDom.createDocumentFragment()); var contentElements = fromHtml$1(content, docDom); append$1(fragment, contentElements); empty(element); append(element, fragment); }; var getOuter = function (element) { var container = Element.fromTag('div'); var clone = Element.fromDom(element.dom().cloneNode(true)); append(container, clone); return get$1(container); }; var rawSet = function (dom, key, value) { if (isString(value) || isBoolean(value) || isNumber(value)) { dom.setAttribute(key, value + ''); } else { domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom); throw new Error('Attribute value was not simple'); } }; var set$1 = function (element, key, value) { rawSet(element.dom(), key, value); }; var setAll = function (element, attrs) { var dom = element.dom(); each$1(attrs, function (v, k) { rawSet(dom, k, v); }); }; var get$2 = function (element, key) { var v = element.dom().getAttribute(key); return v === null ? undefined : v; }; var has$1 = function (element, key) { var dom = element.dom(); return dom && dom.hasAttribute ? dom.hasAttribute(key) : false; }; var remove$1 = function (element, key) { element.dom().removeAttribute(key); }; var clone = function (original, isDeep) { return Element.fromDom(original.dom().cloneNode(isDeep)); }; var shallow$1 = function (original) { return clone(original, false); }; var getHtml = function (element) { var clone = shallow$1(element); return getOuter(clone); }; var element = function (elem) { return getHtml(elem); }; var isRecursive = function (component, originator, target) { return eq(originator, component.element()) && !eq(originator, target); }; var events = derive([can(focus(), function (component, simulatedEvent) { var originator = simulatedEvent.event().originator(); var target = simulatedEvent.event().target(); if (isRecursive(component, originator, target)) { domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers'); return false; } else { return true; } })]); var DefaultEvents = /*#__PURE__*/Object.freeze({ events: events }); var unique = 0; var generate$1 = function (prefix) { var date = new Date(); var time = date.getTime(); var random = Math.floor(Math.random() * 1000000000); unique++; return prefix + '_' + random + unique + String(time); }; var prefix = constant('alloy-id-'); var idAttr = constant('data-alloy-id'); var prefix$1 = prefix(); var idAttr$1 = idAttr(); var write = function (label, elem) { var id = generate$1(prefix$1 + label); writeOnly(elem, id); return id; }; var writeOnly = function (elem, uid) { Object.defineProperty(elem.dom(), idAttr$1, { value: uid, writable: true }); }; var read$1 = function (elem) { var id = isElement(elem) ? elem.dom()[idAttr$1] : null; return Option.from(id); }; var generate$2 = function (prefix) { return generate$1(prefix); }; var make = identity; var NoContextApi = function (getComp) { var fail = function (event) { return function () { throw new Error('The component must be in a context to send: ' + event + '\n' + element(getComp().element()) + ' is not in context.'); }; }; return { debugInfo: constant('fake'), triggerEvent: fail('triggerEvent'), triggerFocus: fail('triggerFocus'), triggerEscape: fail('triggerEscape'), build: fail('build'), addToWorld: fail('addToWorld'), removeFromWorld: fail('removeFromWorld'), addToGui: fail('addToGui'), removeFromGui: fail('removeFromGui'), getByUid: fail('getByUid'), getByDom: fail('getByDom'), broadcast: fail('broadcast'), broadcastOn: fail('broadcastOn'), broadcastEvent: fail('broadcastEvent'), isConnected: constant(false) }; }; var singleton = NoContextApi(); var markAsBehaviourApi = function (f, apiName, apiFunction) { var delegate = apiFunction.toString(); var endIndex = delegate.indexOf(')') + 1; var openBracketIndex = delegate.indexOf('('); var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); f.toFunctionAnnotation = function () { return { name: apiName, parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3))) }; }; return f; }; var cleanParameters = function (parameters) { return map(parameters, function (p) { return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p; }); }; var markAsExtraApi = function (f, extraName) { var delegate = f.toString(); var endIndex = delegate.indexOf(')') + 1; var openBracketIndex = delegate.indexOf('('); var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); f.toFunctionAnnotation = function () { return { name: extraName, parameters: cleanParameters(parameters) }; }; return f; }; var markAsSketchApi = function (f, apiFunction) { var delegate = apiFunction.toString(); var endIndex = delegate.indexOf(')') + 1; var openBracketIndex = delegate.indexOf('('); var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); f.toFunctionAnnotation = function () { return { name: 'OVERRIDE', parameters: cleanParameters(parameters.slice(1)) }; }; return f; }; var premadeTag = generate$1('alloy-premade'); var premade = function (comp) { return wrap$1(premadeTag, comp); }; var getPremade = function (spec) { return readOptFrom$1(spec, premadeTag); }; var makeApi = function (f) { return markAsSketchApi(function (component) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } return f.apply(undefined, [component.getApis()].concat([component].concat(rest))); }, f); }; var NoState = { init: function () { return nu$5({ readState: function () { return 'No State required'; } }); } }; var nu$5 = function (spec) { return spec; }; var generateFrom = function (spec, all) { var schema = map(all, function (a) { return optionObjOf(a.name(), [ strict$1('config'), defaulted$1('state', NoState) ]); }); var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) { throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2)); }, function (v) { return v; }); return { list: all, data: map$1(validated, function (optBlobThunk) { var optBlob = optBlobThunk; var output = optBlob.map(function (blob) { return { config: blob.config, state: blob.state.init(blob.config) }; }); return function () { return output; }; }) }; }; var getBehaviours = function (bData) { return bData.list; }; var getData = function (bData) { return bData.data; }; var byInnerKey = function (data, tuple) { var r = {}; each$1(data, function (detail, key) { each$1(detail, function (value, indexKey) { var chain = readOr$1(indexKey, [])(r); r[indexKey] = chain.concat([tuple(key, value)]); }); }); return r; }; var nu$6 = function (s) { return { classes: s.classes !== undefined ? s.classes : [], attributes: s.attributes !== undefined ? s.attributes : {}, styles: s.styles !== undefined ? s.styles : {} }; }; var merge$1 = function (defnA, mod) { return __assign(__assign({}, defnA), { attributes: __assign(__assign({}, defnA.attributes), mod.attributes), styles: __assign(__assign({}, defnA.styles), mod.styles), classes: defnA.classes.concat(mod.classes) }); }; var combine = function (info, baseMod, behaviours, base) { var modsByBehaviour = __assign({}, baseMod); each(behaviours, function (behaviour) { modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base); }); var nameAndMod = function (name, modification) { return { name: name, modification: modification }; }; var byAspect = byInnerKey(modsByBehaviour, nameAndMod); var combineObjects = function (objects) { return foldr(objects, function (b, a) { return __assign(__assign({}, a.modification), b); }, {}); }; var combinedClasses = foldr(byAspect.classes, function (b, a) { return a.modification.concat(b); }, []); var combinedAttributes = combineObjects(byAspect.attributes); var combinedStyles = combineObjects(byAspect.styles); return nu$6({ classes: combinedClasses, attributes: combinedAttributes, styles: combinedStyles }); }; var sortKeys = function (label, keyName, array, order) { var sliced = array.slice(0); try { var sorted = sliced.sort(function (a, b) { var aKey = a[keyName](); var bKey = b[keyName](); var aIndex = order.indexOf(aKey); var bIndex = order.indexOf(bKey); if (aIndex === -1) { throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); } if (bIndex === -1) { throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); } if (aIndex < bIndex) { return -1; } else if (bIndex < aIndex) { return 1; } else { return 0; } }); return Result.value(sorted); } catch (err) { return Result.error([err]); } }; var uncurried = function (handler, purpose) { return { handler: handler, purpose: constant(purpose) }; }; var curried = function (handler, purpose) { return { cHandler: handler, purpose: constant(purpose) }; }; var curryArgs = function (descHandler, extraArgs) { return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose()); }; var getCurried = function (descHandler) { return descHandler.cHandler; }; var behaviourTuple = function (name, handler) { return { name: constant(name), handler: constant(handler) }; }; var nameToHandlers = function (behaviours, info) { var r = {}; each(behaviours, function (behaviour) { r[behaviour.name()] = behaviour.handlers(info); }); return r; }; var groupByEvents = function (info, behaviours, base) { var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info)); return byInnerKey(behaviourEvents, behaviourTuple); }; var combine$1 = function (info, eventOrder, behaviours, base) { var byEventName = groupByEvents(info, behaviours, base); return combineGroups(byEventName, eventOrder); }; var assemble = function (rawHandler) { var handler = read(rawHandler); return function (component, simulatedEvent) { var rest = []; for (var _i = 2; _i < arguments.length; _i++) { rest[_i - 2] = arguments[_i]; } var args = [ component, simulatedEvent ].concat(rest); if (handler.abort.apply(undefined, args)) { simulatedEvent.stop(); } else if (handler.can.apply(undefined, args)) { handler.run.apply(undefined, args); } }; }; var missingOrderError = function (eventName, tuples) { 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(tuples, function (c) { return c.name(); }), null, 2)]); }; var fuse$1 = function (tuples, eventOrder, eventName) { var order = eventOrder[eventName]; if (!order) { return missingOrderError(eventName, tuples); } else { return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) { var handlers = map(sortedTuples, function (tuple) { return tuple.handler(); }); return fuse(handlers); }); } }; var combineGroups = function (byEventName, eventOrder) { var r = mapToArray(byEventName, function (tuples, eventName) { var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName); return combined.map(function (handler) { var assembled = assemble(handler); var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) { return exists(tuples, function (t) { return t.name() === o; }); }).join(' > ') : tuples[0].name(); return wrap$1(eventName, uncurried(assembled, purpose)); }); }); return consolidate(r, {}); }; var toInfo = function (spec) { return asRaw('custom.definition', objOf([ field('dom', 'dom', strict(), objOf([ strict$1('tag'), defaulted$1('styles', {}), defaulted$1('classes', []), defaulted$1('attributes', {}), option('value'), option('innerHtml') ])), strict$1('components'), strict$1('uid'), defaulted$1('events', {}), defaulted$1('apis', {}), field('eventOrder', 'eventOrder', mergeWith({ 'alloy.execute': [ 'disabling', 'alloy.base.behaviour', 'toggling', 'typeaheadevents' ], 'alloy.focus': [ 'alloy.base.behaviour', 'focusing', 'keying' ], 'alloy.system.init': [ 'alloy.base.behaviour', 'disabling', 'toggling', 'representing' ], 'input': [ 'alloy.base.behaviour', 'representing', 'streaming', 'invalidating' ], 'alloy.system.detached': [ 'alloy.base.behaviour', 'representing', 'item-events', 'tooltipping' ], 'mousedown': [ 'focusing', 'alloy.base.behaviour', 'item-type-events' ], 'mouseover': [ 'item-type-events', 'tooltipping' ] }), anyValue$1()), option('domModification') ]), spec); }; var toDefinition = function (detail) { return __assign(__assign({}, detail.dom), { uid: detail.uid, domChildren: map(detail.components, function (comp) { return comp.element(); }) }); }; var toModification = function (detail) { return detail.domModification.fold(function () { return nu$6({}); }, nu$6); }; var toEvents = function (info) { return info.events; }; var read$2 = function (element, attr) { var value = get$2(element, attr); return value === undefined || value === '' ? [] : value.split(' '); }; var add = function (element, attr, id) { var old = read$2(element, attr); var nu = old.concat([id]); set$1(element, attr, nu.join(' ')); return true; }; var remove$2 = function (element, attr, id) { var nu = filter(read$2(element, attr), function (v) { return v !== id; }); if (nu.length > 0) { set$1(element, attr, nu.join(' ')); } else { remove$1(element, attr); } return false; }; var supports = function (element) { return element.dom().classList !== undefined; }; var get$3 = function (element) { return read$2(element, 'class'); }; var add$1 = function (element, clazz) { return add(element, 'class', clazz); }; var remove$3 = function (element, clazz) { return remove$2(element, 'class', clazz); }; var add$2 = function (element, clazz) { if (supports(element)) { element.dom().classList.add(clazz); } else { add$1(element, clazz); } }; var cleanClass = function (element) { var classList = supports(element) ? element.dom().classList : get$3(element); if (classList.length === 0) { remove$1(element, 'class'); } }; var remove$4 = function (element, clazz) { if (supports(element)) { var classList = element.dom().classList; classList.remove(clazz); } else { remove$3(element, clazz); } cleanClass(element); }; var has$2 = function (element, clazz) { return supports(element) && element.dom().classList.contains(clazz); }; var add$3 = function (element, classes) { each(classes, function (x) { add$2(element, x); }); }; var remove$5 = function (element, classes) { each(classes, function (x) { remove$4(element, x); }); }; var isSupported = function (dom) { return dom.style !== undefined && isFunction(dom.style.getPropertyValue); }; var internalSet = function (dom, property, value) { if (!isString(value)) { domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom); throw new Error('CSS value must be a string: ' + value); } if (isSupported(dom)) { dom.style.setProperty(property, value); } }; var internalRemove = function (dom, property) { if (isSupported(dom)) { dom.style.removeProperty(property); } }; var set$2 = function (element, property, value) { var dom = element.dom(); internalSet(dom, property, value); }; var setAll$1 = function (element, css) { var dom = element.dom(); each$1(css, function (v, k) { internalSet(dom, k, v); }); }; var setOptions = function (element, css) { var dom = element.dom(); each$1(css, function (v, k) { v.fold(function () { internalRemove(dom, k); }, function (value) { internalSet(dom, k, value); }); }); }; var get$4 = function (element, property) { var dom = element.dom(); var styles = domGlobals.window.getComputedStyle(dom); var r = styles.getPropertyValue(property); var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r; return v === null ? undefined : v; }; var getUnsafeProperty = function (dom, property) { return isSupported(dom) ? dom.style.getPropertyValue(property) : ''; }; var getRaw = function (element, property) { var dom = element.dom(); var raw = getUnsafeProperty(dom, property); return Option.from(raw).filter(function (r) { return r.length > 0; }); }; var isValidValue = function (tag, property, value) { var element = Element.fromTag(tag); set$2(element, property, value); var style = getRaw(element, property); return style.isSome(); }; var remove$6 = function (element, property) { var dom = element.dom(); internalRemove(dom, property); if (has$1(element, 'style') && trim(get$2(element, 'style')) === '') { remove$1(element, 'style'); } }; var reflow = function (e) { return e.dom().offsetWidth; }; var get$5 = function (element) { return element.dom().value; }; var set$3 = function (element, value) { if (value === undefined) { throw new Error('Value.set was undefined'); } element.dom().value = value; }; var renderToDom = function (definition) { var subject = Element.fromTag(definition.tag); setAll(subject, definition.attributes); add$3(subject, definition.classes); setAll$1(subject, definition.styles); definition.innerHtml.each(function (html) { return set(subject, html); }); var children = definition.domChildren; append$1(subject, children); definition.value.each(function (value) { set$3(subject, value); }); if (!definition.uid) { debugger; } writeOnly(subject, definition.uid); return subject; }; var getBehaviours$1 = function (spec) { var behaviours = readOr$1('behaviours', {})(spec); var keys$1 = filter(keys(behaviours), function (k) { return behaviours[k] !== undefined; }); return map(keys$1, function (k) { return behaviours[k].me; }); }; var generateFrom$1 = function (spec, all) { return generateFrom(spec, all); }; var generate$3 = function (spec) { var all = getBehaviours$1(spec); return generateFrom$1(spec, all); }; var getDomDefinition = function (info, bList, bData) { var definition = toDefinition(info); var infoModification = toModification(info); var baseModification = { 'alloy.base.modification': infoModification }; var modification = bList.length > 0 ? combine(bData, baseModification, bList, definition) : infoModification; return merge$1(definition, modification); }; var getEvents = function (info, bList, bData) { var baseEvents = { 'alloy.base.behaviour': toEvents(info) }; return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie(); }; var build = function (spec) { var getMe = function () { return me; }; var systemApi = Cell(singleton); var info = getOrDie(toInfo(spec)); var bBlob = generate$3(spec); var bList = getBehaviours(bBlob); var bData = getData(bBlob); var modDefinition = getDomDefinition(info, bList, bData); var item = renderToDom(modDefinition); var events = getEvents(info, bList, bData); var subcomponents = Cell(info.components); var connect = function (newApi) { systemApi.set(newApi); }; var disconnect = function () { systemApi.set(NoContextApi(getMe)); }; var syncComponents = function () { var children$1 = children(item); var subs = bind(children$1, function (child) { return systemApi.get().getByDom(child).fold(function () { return []; }, function (c) { return [c]; }); }); subcomponents.set(subs); }; var config = function (behaviour) { var b = bData; var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () { throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2)); }; return f(); }; var hasConfigured = function (behaviour) { return isFunction(bData[behaviour.name()]); }; var getApis = function () { return info.apis; }; var readState = function (behaviourName) { return bData[behaviourName]().map(function (b) { return b.state.readState(); }).getOr('not enabled'); }; var me = { getSystem: systemApi.get, config: config, hasConfigured: hasConfigured, spec: constant(spec), readState: readState, getApis: getApis, connect: connect, disconnect: disconnect, element: constant(item), syncComponents: syncComponents, components: subcomponents.get, events: constant(events) }; return me; }; var buildSubcomponents = function (spec) { var components = readOr$1('components', [])(spec); return map(components, build$1); }; var buildFromSpec = function (userSpec) { var _a = make(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']); var components = buildSubcomponents(spec); var completeSpec = __assign(__assign({}, spec), { events: __assign(__assign({}, DefaultEvents), specEvents), components: components }); return Result.value(build(completeSpec)); }; var text = function (textContent) { var element = Element.fromText(textContent); return external({ element: element }); }; var external = function (spec) { var extSpec = asRawOrDie('external.component', objOfOnly([ strict$1('element'), option('uid') ]), spec); var systemApi = Cell(NoContextApi()); var connect = function (newApi) { systemApi.set(newApi); }; var disconnect = function () { systemApi.set(NoContextApi(function () { return me; })); }; extSpec.uid.each(function (uid) { writeOnly(extSpec.element, uid); }); var me = { getSystem: systemApi.get, config: Option.none, hasConfigured: constant(false), connect: connect, disconnect: disconnect, getApis: function () { return {}; }, element: constant(extSpec.element), spec: constant(spec), readState: constant('No state'), syncComponents: noop, components: constant([]), events: constant({}) }; return premade(me); }; var uids = generate$2; var build$1 = function (spec) { return getPremade(spec).fold(function () { var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec); return buildFromSpec(userSpecWithUid).getOrDie(); }, function (prebuilt) { return prebuilt; }); }; var premade$1 = premade; function Dimension (name, getOffset) { var set = function (element, h) { if (!isNumber(h) && !h.match(/^[0-9]+$/)) { throw new Error(name + '.set accepts only positive integer values. Value was ' + h); } var dom = element.dom(); if (isSupported(dom)) { dom.style[name] = h + 'px'; } }; var get = function (element) { var r = getOffset(element); if (r <= 0 || r === null) { var css = get$4(element, name); return parseFloat(css) || 0; } return r; }; var getOuter = get; var aggregate = function (element, properties) { return foldl(properties, function (acc, property) { var val = get$4(element, property); var value = val === undefined ? 0 : parseInt(val, 10); return isNaN(value) ? acc : acc + value; }, 0); }; var max = function (element, value, properties) { var cumulativeInclusions = aggregate(element, properties); var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0; return absoluteMax; }; return { set: set, get: get, getOuter: getOuter, aggregate: aggregate, max: max }; } var api = Dimension('height', function (element) { var dom = element.dom(); return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight; }); var get$6 = function (element) { return api.get(element); }; var getOuter$1 = function (element) { return api.getOuter(element); }; var setMax = function (element, value) { var inclusions = [ 'margin-top', 'border-top-width', 'padding-top', 'padding-bottom', 'border-bottom-width', 'margin-bottom' ]; var absMax = api.max(element, value, inclusions); set$2(element, 'max-height', absMax + 'px'); }; var r = function (left, top) { var translate = function (x, y) { return r(left + x, top + y); }; return { left: constant(left), top: constant(top), translate: translate }; }; var Position = r; var boxPosition = function (dom) { var box = dom.getBoundingClientRect(); return Position(box.left, box.top); }; var firstDefinedOrZero = function (a, b) { return a !== undefined ? a : b !== undefined ? b : 0; }; var absolute = function (element) { var doc = element.dom().ownerDocument; var body = doc.body; var win = doc.defaultView; var html = doc.documentElement; if (body === element.dom()) { return Position(body.offsetLeft, body.offsetTop); } var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop); var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft); var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop); var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft); return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop); }; var viewport = function (element) { var dom = element.dom(); var doc = dom.ownerDocument; var body = doc.body; if (body === dom) { return Position(body.offsetLeft, body.offsetTop); } if (!inBody(element)) { return Position(0, 0); } return boxPosition(dom); }; var api$1 = Dimension('width', function (element) { return element.dom().offsetWidth; }); var set$4 = function (element, h) { api$1.set(element, h); }; var get$7 = function (element) { return api$1.get(element); }; var getOuter$2 = function (element) { return api$1.getOuter(element); }; var setMax$1 = function (element, value) { var inclusions = [ 'margin-left', 'border-left-width', 'padding-left', 'padding-right', 'border-right-width', 'margin-right' ]; var absMax = api$1.max(element, value, inclusions); set$2(element, 'max-width', absMax + 'px'); }; var isSafari = detect$3().browser.isSafari(); var get$8 = function (_DOC) { var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document; var x = doc.body.scrollLeft || doc.documentElement.scrollLeft; var y = doc.body.scrollTop || doc.documentElement.scrollTop; return Position(x, y); }; var bounds = function (x, y, width, height) { return { x: constant(x), y: constant(y), width: constant(width), height: constant(height), right: constant(x + width), bottom: constant(y + height) }; }; var getBounds = function (_win) { var win = _win === undefined ? domGlobals.window : _win; var visualViewport = win['visualViewport']; if (visualViewport !== undefined) { return bounds(visualViewport.pageLeft, visualViewport.pageTop, visualViewport.width, visualViewport.height); } else { var doc = Element.fromDom(win.document); var html = win.document.documentElement; var scroll = get$8(doc); var width = html.clientWidth; var height = html.clientHeight; return bounds(scroll.left(), scroll.top(), width, height); } }; var walkUp = function (navigation, doc) { var frame = navigation.view(doc); return frame.fold(constant([]), function (f) { var parent = navigation.owner(f); var rest = walkUp(navigation, parent); return [f].concat(rest); }); }; var pathTo = function (element, navigation) { var d = navigation.owner(element); var paths = walkUp(navigation, d); return Option.some(paths); }; var view = function (doc) { var element = doc.dom() === domGlobals.document ? Option.none() : Option.from(doc.dom().defaultView.frameElement); return element.map(Element.fromDom); }; var owner$1 = function (element) { return owner(element); }; var Navigation = /*#__PURE__*/Object.freeze({ view: view, owner: owner$1 }); var find$3 = function (element) { var doc = Element.fromDom(domGlobals.document); var scroll = get$8(doc); var path = pathTo(element, Navigation); return path.fold(curry(absolute, element), function (frames) { var offset = viewport(element); var r = foldr(frames, function (b, a) { var loc = viewport(a); return { left: b.left + loc.left(), top: b.top + loc.top() }; }, { left: 0, top: 0 }); return Position(r.left + offset.left() + scroll.left(), r.top + offset.top() + scroll.top()); }); }; var pointed = Immutable('point', 'width', 'height'); var rect = Immutable('x', 'y', 'width', 'height'); var bounds$1 = function (x, y, width, height) { return { x: constant(x), y: constant(y), width: constant(width), height: constant(height), right: constant(x + width), bottom: constant(y + height) }; }; var box = function (element) { var xy = absolute(element); var w = getOuter$2(element); var h = getOuter$1(element); return bounds$1(xy.left(), xy.top(), w, h); }; var absolute$1 = function (element) { var position = find$3(element); var width = getOuter$2(element); var height = getOuter$1(element); return bounds$1(position.left(), position.top(), width, height); }; var win = function () { return getBounds(domGlobals.window); }; var closest$2 = function (scope, predicate, isRoot) { return closest(scope, predicate, isRoot).isSome(); }; var ancestor$1 = function (scope, selector, isRoot) { return ancestor(scope, function (e) { return is(e, selector); }, isRoot); }; var descendant$1 = function (scope, selector) { return one(selector, scope); }; var closest$3 = function (scope, selector, isRoot) { return ClosestOrAncestor(is, ancestor$1, scope, selector, isRoot); }; var find$4 = function (queryElem) { var dependent = closest(queryElem, function (elem) { if (!isElement(elem)) { return false; } var id = get$2(elem, 'id'); return id !== undefined && id.indexOf('aria-owns') > -1; }); return dependent.bind(function (dep) { var id = get$2(dep, 'id'); var doc = owner(dep); return descendant$1(doc, '[aria-owns="' + id + '"]'); }); }; var manager = function () { var ariaId = generate$1('aria-owns'); var link = function (elem) { set$1(elem, 'aria-owns', ariaId); }; var unlink = function (elem) { remove$1(elem, 'aria-owns'); }; return { id: constant(ariaId), link: link, unlink: unlink }; }; var isAriaPartOf = function (component, queryElem) { return find$4(queryElem).exists(function (owner) { return isPartOf(component, owner); }); }; var isPartOf = function (component, queryElem) { return closest$2(queryElem, function (el) { return eq(el, component.element()); }, constant(false)) || isAriaPartOf(component, queryElem); }; var cat = function (arr) { var r = []; var push = function (x) { r.push(x); }; for (var i = 0; i < arr.length; i++) { arr[i].each(push); } return r; }; var sequence = function (arr) { var r = []; for (var i = 0; i < arr.length; i++) { var x = arr[i]; if (x.isSome()) { r.push(x.getOrDie()); } else { return Option.none(); } } return Option.some(r); }; var findMap = function (arr, f) { for (var i = 0; i < arr.length; i++) { var r = f(arr[i], i); if (r.isSome()) { return r; } } return Option.none(); }; var lift2 = function (oa, ob, f) { return oa.isSome() && ob.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie())) : Option.none(); }; var unknown$3 = 'unknown'; var EventConfiguration; (function (EventConfiguration) { EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP'; EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL'; EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING'; }(EventConfiguration || (EventConfiguration = {}))); var eventConfig = Cell({}); var makeEventLogger = function (eventName, initialTarget) { var sequence = []; var startTime = new Date().getTime(); return { logEventCut: function (name, target, purpose) { sequence.push({ outcome: 'cut', target: target, purpose: purpose }); }, logEventStopped: function (name, target, purpose) { sequence.push({ outcome: 'stopped', target: target, purpose: purpose }); }, logNoParent: function (name, target, purpose) { sequence.push({ outcome: 'no-parent', target: target, purpose: purpose }); }, logEventNoHandlers: function (name, target) { sequence.push({ outcome: 'no-handlers-left', target: target }); }, logEventResponse: function (name, target, purpose) { sequence.push({ outcome: 'response', purpose: purpose, target: target }); }, write: function () { var finishTime = new Date().getTime(); if (contains([ 'mousemove', 'mouseover', 'mouseout', systemInit() ], eventName)) { return; } domGlobals.console.log(eventName, { event: eventName, time: finishTime - startTime, target: initialTarget.dom(), sequence: map(sequence, function (s) { if (!contains([ 'cut', 'stopped', 'response' ], s.outcome)) { return s.outcome; } else { return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')'; } }) }); } }; }; var processEvent = function (eventName, initialTarget, f) { var status = readOptFrom$1(eventConfig.get(), eventName).orThunk(function () { var patterns = keys(eventConfig.get()); return findMap(patterns, function (p) { return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none(); }); }).getOr(EventConfiguration.NORMAL); switch (status) { case EventConfiguration.NORMAL: return f(noLogger()); case EventConfiguration.LOGGING: { var logger = makeEventLogger(eventName, initialTarget); var output = f(logger); logger.write(); return output; } case EventConfiguration.STOP: return true; } }; var path = [ 'alloy/data/Fields', 'alloy/debugging/Debugging' ]; var getTrace = function () { var err = new Error(); if (err.stack !== undefined) { var lines = err.stack.split('\n'); return find(lines, function (line) { return line.indexOf('alloy') > 0 && !exists(path, function (p) { return line.indexOf(p) > -1; }); }).getOr(unknown$3); } else { return unknown$3; } }; var ignoreEvent = { logEventCut: noop, logEventStopped: noop, logNoParent: noop, logEventNoHandlers: noop, logEventResponse: noop, write: noop }; var monitorEvent = function (eventName, initialTarget, f) { return processEvent(eventName, initialTarget, f); }; var noLogger = constant(ignoreEvent); var menuFields = constant([ strict$1('menu'), strict$1('selectedMenu') ]); var itemFields = constant([ strict$1('item'), strict$1('selectedItem') ]); var schema = constant(objOf(itemFields().concat(menuFields()))); var itemSchema = constant(objOf(itemFields())); var _initSize = strictObjOf('initSize', [ strict$1('numColumns'), strict$1('numRows') ]); var itemMarkers = function () { return strictOf('markers', itemSchema()); }; var tieredMenuMarkers = function () { return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields())); }; var markers = function (required) { return strictObjOf('markers', map(required, strict$1)); }; var onPresenceHandler = function (label, fieldName, presence) { var trace = getTrace(); return field(fieldName, fieldName, presence, valueOf(function (f) { return Result.value(function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return f.apply(undefined, args); }); })); }; var onHandler = function (fieldName) { return onPresenceHandler('onHandler', fieldName, defaulted(noop)); }; var onKeyboardHandler = function (fieldName) { return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none)); }; var onStrictHandler = function (fieldName) { return onPresenceHandler('onHandler', fieldName, strict()); }; var onStrictKeyboardHandler = function (fieldName) { return onPresenceHandler('onKeyboardHandler', fieldName, strict()); }; var output = function (name, value) { return state$1(name, constant(value)); }; var snapshot = function (name) { return state$1(name, identity); }; var initSize = constant(_initSize); var nu$7 = Immutable('x', 'y', 'bubble', 'direction', 'label'); var adt$2 = Adt.generate([ { southeast: [] }, { southwest: [] }, { northeast: [] }, { northwest: [] }, { south: [] }, { north: [] }, { east: [] }, { west: [] } ]); var cata = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) { return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west); }; var cataVertical = function (subject, south, middle, north) { return subject.fold(south, south, north, north, south, north, middle, middle); }; var cataHorizontal = function (subject, east, middle, west) { return subject.fold(east, west, east, west, middle, middle, east, west); }; var southeast = adt$2.southeast; var southwest = adt$2.southwest; var northeast = adt$2.northeast; var northwest = adt$2.northwest; var south = adt$2.south; var north = adt$2.north; var east = adt$2.east; var west = adt$2.west; var eastX = function (anchor) { return anchor.x(); }; var middleX = function (anchor, element) { return anchor.x() + anchor.width() / 2 - element.width() / 2; }; var westX = function (anchor, element) { return anchor.x() + anchor.width() - element.width(); }; var northY = function (anchor, element) { return anchor.y() - element.height(); }; var southY = function (anchor) { return anchor.y() + anchor.height(); }; var centreY = function (anchor, element) { return anchor.y() + anchor.height() / 2 - element.height() / 2; }; var eastEdgeX = function (anchor) { return anchor.x() + anchor.width(); }; var westEdgeX = function (anchor, element) { return anchor.x() - element.width(); }; var southeast$1 = function (anchor, element, bubbles) { return nu$7(eastX(anchor), southY(anchor), bubbles.southeast(), southeast(), 'layout-se'); }; var southwest$1 = function (anchor, element, bubbles) { return nu$7(westX(anchor, element), southY(anchor), bubbles.southwest(), southwest(), 'layout-sw'); }; var northeast$1 = function (anchor, element, bubbles) { return nu$7(eastX(anchor), northY(anchor, element), bubbles.northeast(), northeast(), 'layout-ne'); }; var northwest$1 = function (anchor, element, bubbles) { return nu$7(westX(anchor, element), northY(anchor, element), bubbles.northwest(), northwest(), 'layout-nw'); }; var north$1 = function (anchor, element, bubbles) { return nu$7(middleX(anchor, element), northY(anchor, element), bubbles.north(), north(), 'layout-n'); }; var south$1 = function (anchor, element, bubbles) { return nu$7(middleX(anchor, element), southY(anchor), bubbles.south(), south(), 'layout-s'); }; var east$1 = function (anchor, element, bubbles) { return nu$7(eastEdgeX(anchor), centreY(anchor, element), bubbles.east(), east(), 'layout-e'); }; var west$1 = function (anchor, element, bubbles) { return nu$7(westEdgeX(anchor, element), centreY(anchor, element), bubbles.west(), west(), 'layout-w'); }; var all$2 = function () { return [ southeast$1, southwest$1, northeast$1, northwest$1, south$1, north$1, east$1, west$1 ]; }; var allRtl = function () { return [ southwest$1, southeast$1, northwest$1, northeast$1, south$1, north$1, east$1, west$1 ]; }; var belowOrAbove = function () { return [ southeast$1, southwest$1, northeast$1, northwest$1, south$1, north$1 ]; }; var belowOrAboveRtl = function () { return [ southwest$1, southeast$1, northwest$1, northeast$1, south$1, north$1 ]; }; var executeEvent = function (bConfig, bState, executor) { return runOnExecute(function (component) { executor(component, bConfig, bState); }); }; var loadEvent = function (bConfig, bState, f) { return runOnInit(function (component, simulatedEvent) { f(component, bConfig, bState); }); }; var create = function (schema, name, active, apis, extra, state) { var configSchema = objOfOnly(schema); var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]); return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); }; var createModes = function (modes, name, active, apis, extra, state) { var configSchema = modes; var schemaSchema = optionObjOf(name, [optionOf('config', modes)]); return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); }; var wrapApi = function (bName, apiFunction, apiName) { var f = function (component) { var rest = []; for (var _i = 1; _i < arguments.length; _i++) { rest[_i - 1] = arguments[_i]; } var args = [component].concat(rest); return component.config({ name: constant(bName) }).fold(function () { throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName); }, function (info) { var rest = Array.prototype.slice.call(args, 1); return apiFunction.apply(undefined, [ component, info.config, info.state ].concat(rest)); }); }; return markAsBehaviourApi(f, apiName, apiFunction); }; var revokeBehaviour = function (name) { return { key: name, value: undefined }; }; var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) { var getConfig = function (info) { return hasKey$1(info, name) ? info[name]() : Option.none(); }; var wrappedApis = map$1(apis, function (apiF, apiName) { return wrapApi(name, apiF, apiName); }); var wrappedExtra = map$1(extra, function (extraF, extraName) { return markAsExtraApi(extraF, extraName); }); var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), { revoke: curry(revokeBehaviour, name), config: function (spec) { var prepared = asRawOrDie(name + '-config', configSchema, spec); return { key: name, value: { config: prepared, me: me, configAsRaw: cached(function () { return asRawOrDie(name + '-config', configSchema, spec); }), initialConfig: spec, state: state } }; }, schema: function () { return schemaSchema; }, exhibit: function (info, base) { return getConfig(info).bind(function (behaviourInfo) { return readOptFrom$1(active, 'exhibit').map(function (exhibitor) { return exhibitor(base, behaviourInfo.config, behaviourInfo.state); }); }).getOr(nu$6({})); }, name: function () { return name; }, handlers: function (info) { return getConfig(info).map(function (behaviourInfo) { var getEvents = readOr$1('events', function (a, b) { return {}; })(active); return getEvents(behaviourInfo.config, behaviourInfo.state); }).getOr({}); } }); return me; }; var derive$1 = function (capabilities) { return wrapAll$1(capabilities); }; var simpleSchema = objOfOnly([ strict$1('fields'), strict$1('name'), defaulted$1('active', {}), defaulted$1('apis', {}), defaulted$1('state', NoState), defaulted$1('extra', {}) ]); var create$1 = function (data) { var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data); return create(value.fields, value.name, value.active, value.apis, value.extra, value.state); }; var modeSchema = objOfOnly([ strict$1('branchKey'), strict$1('branches'), strict$1('name'), defaulted$1('active', {}), defaulted$1('apis', {}), defaulted$1('state', NoState), defaulted$1('extra', {}) ]); var createModes$1 = function (data) { var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data); return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state); }; var revoke = constant(undefined); var chooseChannels = function (channels, message) { return message.universal() ? channels : filter(channels, function (ch) { return contains(message.channels(), ch); }); }; var events$1 = function (receiveConfig) { return derive([run(receive(), function (component, message) { var channelMap = receiveConfig.channels; var channels = keys(channelMap); var targetChannels = chooseChannels(channels, message); each(targetChannels, function (ch) { var channelInfo = channelMap[ch]; var channelSchema = channelInfo.schema; var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, message.data()); channelInfo.onReceive(component, data); }); })]); }; var ActiveReceiving = /*#__PURE__*/Object.freeze({ events: events$1 }); var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([ onStrictHandler('onReceive'), defaulted$1('schema', anyValue$1()) ])))]; var Receiving = create$1({ fields: ReceivingSchema, name: 'receiving', active: ActiveReceiving }); var exhibit = function (base, posConfig) { return nu$6({ classes: [], styles: posConfig.useFixed() ? {} : { position: 'relative' } }); }; var ActivePosition = /*#__PURE__*/Object.freeze({ exhibit: exhibit }); var focus$1 = function (element) { element.dom().focus(); }; var blur = function (element) { element.dom().blur(); }; var hasFocus = function (element) { var doc = owner(element).dom(); return element.dom() === doc.activeElement; }; var active = function (_doc) { var doc = _doc !== undefined ? _doc.dom() : domGlobals.document; return Option.from(doc.activeElement).map(Element.fromDom); }; var search = function (element) { return active(owner(element)).filter(function (e) { return element.dom().contains(e.dom()); }); }; var preserve = function (f, container) { var ownerDoc = owner(container); var refocus = active(ownerDoc).bind(function (focused) { var hasFocus = function (elem) { return eq(focused, elem); }; return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus); }); var result = f(container); refocus.each(function (oldFocus) { active(ownerDoc).filter(function (newFocus) { return eq(newFocus, oldFocus); }).fold(function () { focus$1(oldFocus); }, noop); }); return result; }; var allAlignments = [ 'valignCentre', 'alignLeft', 'alignRight', 'alignCentre', 'top', 'bottom', 'left', 'right' ]; var nu$8 = function (width, yoffset, classes) { var getClasses = function (prop) { return readOptFrom$1(classes, prop).getOr([]); }; var make = function (xDelta, yDelta, alignmentsOn) { var alignmentsOff = difference(allAlignments, alignmentsOn); return { offset: function () { return Position(xDelta, yDelta); }, classesOn: function () { return bind(alignmentsOn, getClasses); }, classesOff: function () { return bind(alignmentsOff, getClasses); } }; }; return { southeast: function () { return make(-width, yoffset, [ 'top', 'alignLeft' ]); }, southwest: function () { return make(width, yoffset, [ 'top', 'alignRight' ]); }, south: function () { return make(-width / 2, yoffset, [ 'top', 'alignCentre' ]); }, northeast: function () { return make(-width, -yoffset, [ 'bottom', 'alignLeft' ]); }, northwest: function () { return make(width, -yoffset, [ 'bottom', 'alignRight' ]); }, north: function () { return make(-width / 2, -yoffset, [ 'bottom', 'alignCentre' ]); }, east: function () { return make(width, -yoffset / 2, [ 'valignCentre', 'left' ]); }, west: function () { return make(-width, -yoffset / 2, [ 'valignCentre', 'right' ]); }, innerNorthwest: function () { return make(-width, yoffset, [ 'top', 'alignRight' ]); }, innerNortheast: function () { return make(width, yoffset, [ 'top', 'alignLeft' ]); }, innerNorth: function () { return make(-width / 2, yoffset, [ 'top', 'alignCentre' ]); }, innerSouthwest: function () { return make(-width, -yoffset, [ 'bottom', 'alignRight' ]); }, innerSoutheast: function () { return make(width, -yoffset, [ 'bottom', 'alignLeft' ]); }, innerSouth: function () { return make(-width / 2, -yoffset, [ 'bottom', 'alignCentre' ]); }, innerWest: function () { return make(width, -yoffset / 2, [ 'valignCentre', 'right' ]); }, innerEast: function () { return make(-width, -yoffset / 2, [ 'valignCentre', 'left' ]); } }; }; var fallback = function () { return nu$8(0, 0, {}); }; var decision = MixedBag([ 'x', 'y', 'width', 'height', 'maxHeight', 'maxWidth', 'direction', 'classes', 'label', 'candidateYforTest' ], []); var css = Immutable('position', 'left', 'top', 'right', 'bottom'); var adt$3 = Adt.generate([ { none: [] }, { relative: [ 'x', 'y', 'width', 'height' ] }, { fixed: [ 'x', 'y', 'width', 'height' ] } ]); var positionWithDirection = function (posName, decision, x, y, width, height) { var decisionX = decision.x() - x; var decisionY = decision.y() - y; var decisionWidth = decision.width(); var decisionHeight = decision.height(); var decisionRight = width - (decisionX + decisionWidth); var decisionBottom = height - (decisionY + decisionHeight); var left = Option.some(decisionX); var top = Option.some(decisionY); var right = Option.some(decisionRight); var bottom = Option.some(decisionBottom); var none = Option.none(); return cata(decision.direction(), function () { return css(posName, left, top, none, none); }, function () { return css(posName, none, top, right, none); }, function () { return css(posName, left, none, none, bottom); }, function () { return css(posName, none, none, right, bottom); }, function () { return css(posName, left, top, none, none); }, function () { return css(posName, left, none, none, bottom); }, function () { return css(posName, left, top, none, none); }, function () { return css(posName, none, top, right, none); }); }; var reposition = function (origin, decision) { return origin.fold(function () { return css('absolute', Option.some(decision.x()), Option.some(decision.y()), Option.none(), Option.none()); }, function (x, y, width, height) { return positionWithDirection('absolute', decision, x, y, width, height); }, function (x, y, width, height) { return positionWithDirection('fixed', decision, x, y, width, height); }); }; var toBox = function (origin, element) { var rel = curry(find$3, element); var position = origin.fold(rel, rel, function () { var scroll = get$8(); return find$3(element).translate(-scroll.left(), -scroll.top()); }); var width = getOuter$2(element); var height = getOuter$1(element); return bounds$1(position.left(), position.top(), width, height); }; var viewport$1 = function (origin, getBounds) { return getBounds.fold(function () { return origin.fold(win, win, bounds$1); }, function (b) { return origin.fold(b, b, function () { var bounds = b(); var pos = translate(origin, bounds.x(), bounds.y()); return bounds$1(pos.left(), pos.top(), bounds.width(), bounds.height()); }); }); }; var translate = function (origin, x, y) { var pos = Position(x, y); var removeScroll = function () { var outerScroll = get$8(); return pos.translate(-outerScroll.left(), -outerScroll.top()); }; return origin.fold(constant(pos), constant(pos), removeScroll); }; var cata$1 = function (subject, onNone, onRelative, onFixed) { return subject.fold(onNone, onRelative, onFixed); }; var relative = adt$3.relative; var fixed = adt$3.fixed; var nu$9 = function (x) { return x; }; var onDirection = function (isLtr, isRtl) { return function (element) { return getDirection(element) === 'rtl' ? isRtl : isLtr; }; }; var getDirection = function (element) { return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr'; }; var schema$1 = function () { return optionObjOf('layouts', [ strict$1('onLtr'), strict$1('onRtl') ]); }; var get$9 = function (elem, info, defaultLtr, defaultRtl) { var ltr = info.layouts.map(function (ls) { return ls.onLtr(elem); }).getOr(defaultLtr); var rtl = info.layouts.map(function (ls) { return ls.onRtl(elem); }).getOr(defaultRtl); var f = onDirection(ltr, rtl); return f(elem); }; var placement = function (component, anchorInfo, origin) { var hotspot = anchorInfo.hotspot; var anchorBox = toBox(origin, hotspot.element()); var layouts = get$9(component.element(), anchorInfo, belowOrAbove(), belowOrAboveRtl()); return Option.some(nu$9({ anchorBox: anchorBox, bubble: anchorInfo.bubble.getOr(fallback()), overrides: anchorInfo.overrides, layouts: layouts, placer: Option.none() })); }; var HotspotAnchor = [ strict$1('hotspot'), option('bubble'), defaulted$1('overrides', {}), schema$1(), output('placement', placement) ]; var placement$1 = function (component, anchorInfo, origin) { var pos = translate(origin, anchorInfo.x, anchorInfo.y); var anchorBox = bounds$1(pos.left(), pos.top(), anchorInfo.width, anchorInfo.height); var layouts = get$9(component.element(), anchorInfo, all$2(), allRtl()); return Option.some(nu$9({ anchorBox: anchorBox, bubble: anchorInfo.bubble, overrides: anchorInfo.overrides, layouts: layouts, placer: Option.none() })); }; var MakeshiftAnchor = [ strict$1('x'), strict$1('y'), defaulted$1('height', 0), defaulted$1('width', 0), defaulted$1('bubble', fallback()), defaulted$1('overrides', {}), schema$1(), output('placement', placement$1) ]; var zeroWidth = function () { return '\uFEFF'; }; var create$2 = Immutable('start', 'soffset', 'finish', 'foffset'); var SimRange = { create: create$2 }; var adt$4 = Adt.generate([ { before: ['element'] }, { on: [ 'element', 'offset' ] }, { after: ['element'] } ]); var cata$2 = function (subject, onBefore, onOn, onAfter) { return subject.fold(onBefore, onOn, onAfter); }; var getStart = function (situ) { return situ.fold(identity, identity, identity); }; var before$2 = adt$4.before; var on = adt$4.on; var after$1 = adt$4.after; var Situ = { before: before$2, on: on, after: after$1, cata: cata$2, getStart: getStart }; var adt$5 = Adt.generate([ { domRange: ['rng'] }, { relative: [ 'startSitu', 'finishSitu' ] }, { exact: [ 'start', 'soffset', 'finish', 'foffset' ] } ]); var exactFromRange = function (simRange) { return adt$5.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset()); }; var getStart$1 = function (selection) { return selection.match({ domRange: function (rng) { return Element.fromDom(rng.startContainer); }, relative: function (startSitu, finishSitu) { return Situ.getStart(startSitu); }, exact: function (start, soffset, finish, foffset) { return start; } }); }; var domRange = adt$5.domRange; var relative$1 = adt$5.relative; var exact = adt$5.exact; var getWin = function (selection) { var start = getStart$1(selection); return defaultView(start); }; var range$1 = SimRange.create; var Selection = { domRange: domRange, relative: relative$1, exact: exact, exactFromRange: exactFromRange, getWin: getWin, range: range$1 }; var setStart = function (rng, situ) { situ.fold(function (e) { rng.setStartBefore(e.dom()); }, function (e, o) { rng.setStart(e.dom(), o); }, function (e) { rng.setStartAfter(e.dom()); }); }; var setFinish = function (rng, situ) { situ.fold(function (e) { rng.setEndBefore(e.dom()); }, function (e, o) { rng.setEnd(e.dom(), o); }, function (e) { rng.setEndAfter(e.dom()); }); }; var relativeToNative = function (win, startSitu, finishSitu) { var range = win.document.createRange(); setStart(range, startSitu); setFinish(range, finishSitu); return range; }; var exactToNative = function (win, start, soffset, finish, foffset) { var rng = win.document.createRange(); rng.setStart(start.dom(), soffset); rng.setEnd(finish.dom(), foffset); return rng; }; var toRect = function (rect) { return { left: constant(rect.left), top: constant(rect.top), right: constant(rect.right), bottom: constant(rect.bottom), width: constant(rect.width), height: constant(rect.height) }; }; var getFirstRect = function (rng) { var rects = rng.getClientRects(); var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect(); return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none(); }; var adt$6 = Adt.generate([ { ltr: [ 'start', 'soffset', 'finish', 'foffset' ] }, { rtl: [ 'start', 'soffset', 'finish', 'foffset' ] } ]); var fromRange = function (win, type, range) { return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset); }; var getRanges = function (win, selection) { return selection.match({ domRange: function (rng) { return { ltr: constant(rng), rtl: Option.none }; }, relative: function (startSitu, finishSitu) { return { ltr: cached(function () { return relativeToNative(win, startSitu, finishSitu); }), rtl: cached(function () { return Option.some(relativeToNative(win, finishSitu, startSitu)); }) }; }, exact: function (start, soffset, finish, foffset) { return { ltr: cached(function () { return exactToNative(win, start, soffset, finish, foffset); }), rtl: cached(function () { return Option.some(exactToNative(win, finish, foffset, start, soffset)); }) }; } }); }; var doDiagnose = function (win, ranges) { var rng = ranges.ltr(); if (rng.collapsed) { var reversed = ranges.rtl().filter(function (rev) { return rev.collapsed === false; }); return reversed.map(function (rev) { return adt$6.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset); }).getOrThunk(function () { return fromRange(win, adt$6.ltr, rng); }); } else { return fromRange(win, adt$6.ltr, rng); } }; var diagnose = function (win, selection) { var ranges = getRanges(win, selection); return doDiagnose(win, ranges); }; var asLtrRange = function (win, selection) { var diagnosis = diagnose(win, selection); return diagnosis.match({ ltr: function (start, soffset, finish, foffset) { var rng = win.document.createRange(); rng.setStart(start.dom(), soffset); rng.setEnd(finish.dom(), foffset); return rng; }, rtl: function (start, soffset, finish, foffset) { var rng = win.document.createRange(); rng.setStart(finish.dom(), foffset); rng.setEnd(start.dom(), soffset); return rng; } }); }; var searchForPoint = function (rectForOffset, x, y, maxX, length) { if (length === 0) { return 0; } else if (x === maxX) { return length - 1; } var xDelta = maxX; for (var i = 1; i < length; i++) { var rect = rectForOffset(i); var curDeltaX = Math.abs(x - rect.left); if (y <= rect.bottom) { if (y < rect.top || curDeltaX > xDelta) { return i - 1; } else { xDelta = curDeltaX; } } } return 0; }; var inRect = function (rect, x, y) { return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom; }; function NodeValue (is, name) { var get = function (element) { if (!is(element)) { throw new Error('Can only get ' + name + ' value of a ' + name + ' node'); } return getOption(element).getOr(''); }; var getOption = function (element) { return is(element) ? Option.from(element.dom().nodeValue) : Option.none(); }; var set = function (element, value) { if (!is(element)) { throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node'); } element.dom().nodeValue = value; }; return { get: get, getOption: getOption, set: set }; } var api$2 = NodeValue(isText, 'text'); var get$a = function (element) { return api$2.get(element); }; var getOption = function (element) { return api$2.getOption(element); }; var locateOffset = function (doc, textnode, x, y, rect) { var rangeForOffset = function (o) { var r = doc.dom().createRange(); r.setStart(textnode.dom(), o); r.collapse(true); return r; }; var rectForOffset = function (o) { var r = rangeForOffset(o); return r.getBoundingClientRect(); }; var length = get$a(textnode).length; var offset = searchForPoint(rectForOffset, x, y, rect.right, length); return rangeForOffset(offset); }; var locate = function (doc, node, x, y) { var r = doc.dom().createRange(); r.selectNode(node.dom()); var rects = r.getClientRects(); var foundRect = findMap(rects, function (rect) { return inRect(rect, x, y) ? Option.some(rect) : Option.none(); }); return foundRect.map(function (rect) { return locateOffset(doc, node, x, y, rect); }); }; var searchInChildren = function (doc, node, x, y) { var r = doc.dom().createRange(); var nodes = children(node); return findMap(nodes, function (n) { r.selectNode(n.dom()); return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none(); }); }; var locateNode = function (doc, node, x, y) { return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y); }; var locate$1 = function (doc, node, x, y) { var r = doc.dom().createRange(); r.selectNode(node.dom()); var rect = r.getBoundingClientRect(); var boundedX = Math.max(rect.left, Math.min(rect.right, x)); var boundedY = Math.max(rect.top, Math.min(rect.bottom, y)); return locateNode(doc, node, boundedX, boundedY); }; var getEnd = function (element) { return name(element) === 'img' ? 1 : getOption(element).fold(function () { return children(element).length; }, function (v) { return v.length; }); }; var NBSP = '\xA0'; var isTextNodeWithCursorPosition = function (el) { return getOption(el).filter(function (text) { return text.trim().length !== 0 || text.indexOf(NBSP) > -1; }).isSome(); }; var elementsWithCursorPosition = [ 'img', 'br' ]; var isCursorPosition = function (elem) { var hasCursorPosition = isTextNodeWithCursorPosition(elem); return hasCursorPosition || contains(elementsWithCursorPosition, name(elem)); }; var first = function (element) { return descendant(element, isCursorPosition); }; var last$1 = function (element) { return descendantRtl(element, isCursorPosition); }; var descendantRtl = function (scope, predicate) { var descend = function (element) { var children$1 = children(element); for (var i = children$1.length - 1; i >= 0; i--) { var child = children$1[i]; if (predicate(child)) { return Option.some(child); } var res = descend(child); if (res.isSome()) { return res; } } return Option.none(); }; return descend(scope); }; var COLLAPSE_TO_LEFT = true; var COLLAPSE_TO_RIGHT = false; var getCollapseDirection = function (rect, x) { return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT; }; var createCollapsedNode = function (doc, target, collapseDirection) { var r = doc.dom().createRange(); r.selectNode(target.dom()); r.collapse(collapseDirection); return r; }; var locateInElement = function (doc, node, x) { var cursorRange = doc.dom().createRange(); cursorRange.selectNode(node.dom()); var rect = cursorRange.getBoundingClientRect(); var collapseDirection = getCollapseDirection(rect, x); var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1; return f(node).map(function (target) { return createCollapsedNode(doc, target, collapseDirection); }); }; var locateInEmpty = function (doc, node, x) { var rect = node.dom().getBoundingClientRect(); var collapseDirection = getCollapseDirection(rect, x); return Option.some(createCollapsedNode(doc, node, collapseDirection)); }; var search$1 = function (doc, node, x) { var f = children(node).length === 0 ? locateInEmpty : locateInElement; return f(doc, node, x); }; var caretPositionFromPoint = function (doc, x, y) { return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) { if (pos.offsetNode === null) { return Option.none(); } var r = doc.dom().createRange(); r.setStart(pos.offsetNode, pos.offset); r.collapse(); return Option.some(r); }); }; var caretRangeFromPoint = function (doc, x, y) { return Option.from(doc.dom().caretRangeFromPoint(x, y)); }; var searchTextNodes = function (doc, node, x, y) { var r = doc.dom().createRange(); r.selectNode(node.dom()); var rect = r.getBoundingClientRect(); var boundedX = Math.max(rect.left, Math.min(rect.right, x)); var boundedY = Math.max(rect.top, Math.min(rect.bottom, y)); return locate$1(doc, node, boundedX, boundedY); }; var searchFromPoint = function (doc, x, y) { return Element.fromPoint(doc, x, y).bind(function (elem) { var fallback = function () { return search$1(doc, elem, x); }; return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback); }); }; var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint; var descendants = function (scope, selector) { return all(selector, scope); }; var makeRange = function (start, soffset, finish, foffset) { var doc = owner(start); var rng = doc.dom().createRange(); rng.setStart(start.dom(), soffset); rng.setEnd(finish.dom(), foffset); return rng; }; var after$2 = function (start, soffset, finish, foffset) { var r = makeRange(start, soffset, finish, foffset); var same = eq(start, finish) && soffset === foffset; return r.collapsed && !same; }; var readRange = function (selection) { if (selection.rangeCount > 0) { var firstRng = selection.getRangeAt(0); var lastRng = selection.getRangeAt(selection.rangeCount - 1); return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset)); } else { return Option.none(); } }; var doGetExact = function (selection) { var anchor = Element.fromDom(selection.anchorNode); var focus = Element.fromDom(selection.focusNode); return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection); }; var getExact = function (win) { return Option.from(win.getSelection()).filter(function (sel) { return sel.rangeCount > 0; }).bind(doGetExact); }; var getFirstRect$1 = function (win, selection) { var rng = asLtrRange(win, selection); return getFirstRect(rng); }; var point = Immutable('element', 'offset'); var descendOnce = function (element, offset) { var children$1 = children(element); if (children$1.length === 0) { return point(element, offset); } else if (offset < children$1.length) { return point(children$1[offset], 0); } else { var last = children$1[children$1.length - 1]; var len = isText(last) ? get$a(last).length : children(last).length; return point(last, len); } }; var adt$7 = Adt.generate([ { screen: ['point'] }, { absolute: [ 'point', 'scrollLeft', 'scrollTop' ] } ]); var toFixed = function (pos) { return pos.fold(function (point) { return point; }, function (point, scrollLeft, scrollTop) { return point.translate(-scrollLeft, -scrollTop); }); }; var toAbsolute = function (pos) { return pos.fold(function (point) { return point; }, function (point, scrollLeft, scrollTop) { return point; }); }; var sum = function (points) { return foldl(points, function (b, a) { return b.translate(a.left(), a.top()); }, Position(0, 0)); }; var sumAsFixed = function (positions) { var points = map(positions, toFixed); return sum(points); }; var sumAsAbsolute = function (positions) { var points = map(positions, toAbsolute); return sum(points); }; var screen = adt$7.screen; var absolute$2 = adt$7.absolute; var getOffset = function (component, origin, anchorInfo) { var win = defaultView(anchorInfo.root).dom(); var hasSameOwner = function (frame) { var frameOwner = owner(frame); var compOwner = owner(component.element()); return eq(frameOwner, compOwner); }; return Option.from(win.frameElement).map(Element.fromDom).filter(hasSameOwner).map(absolute); }; var getRootPoint = function (component, origin, anchorInfo) { var doc = owner(component.element()); var outerScroll = get$8(doc); var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll); return absolute$2(offset, outerScroll.left(), outerScroll.top()); }; var capRect = function (left, top, width, height) { var newLeft = left, newTop = top, newWidth = width, newHeight = height; if (left < 0) { newLeft = 0; newWidth = width + left; } if (top < 0) { newTop = 0; newHeight = height + top; } var point = screen(Position(newLeft, newTop)); return Option.some(pointed(point, newWidth, newHeight)); }; var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) { return optBox.map(function (box) { var points = [ rootPoint, box.point() ]; var topLeft = cata$1(origin, function () { return sumAsAbsolute(points); }, function () { return sumAsAbsolute(points); }, function () { return sumAsFixed(points); }); var anchorBox = rect(topLeft.left(), topLeft.top(), box.width(), box.height()); var layoutsLtr = function () { return anchorInfo.showAbove ? [ northeast$1, northwest$1, southeast$1, southwest$1, north$1, south$1 ] : [ southeast$1, southwest$1, northeast$1, northwest$1, south$1, south$1 ]; }; var layoutsRtl = function () { return anchorInfo.showAbove ? [ northwest$1, northeast$1, southwest$1, southeast$1, north$1, south$1 ] : [ southwest$1, southeast$1, northwest$1, northeast$1, south$1, north$1 ]; }; var layouts = get$9(elem, anchorInfo, layoutsLtr(), layoutsRtl()); return nu$9({ anchorBox: anchorBox, bubble: anchorInfo.bubble.getOr(fallback()), overrides: anchorInfo.overrides, layouts: layouts, placer: Option.none() }); }); }; var ContentAnchorCommon = { capRect: capRect, calcNewAnchor: calcNewAnchor }; var point$1 = Immutable('element', 'offset'); var descendOnce$1 = function (element, offset) { return isText(element) ? point$1(element, offset) : descendOnce(element, offset); }; var getAnchorSelection = function (win, anchorInfo) { var getSelection = anchorInfo.getSelection.getOrThunk(function () { return function () { return getExact(win); }; }); return getSelection().map(function (sel) { var modStart = descendOnce$1(sel.start(), sel.soffset()); var modFinish = descendOnce$1(sel.finish(), sel.foffset()); return Selection.range(modStart.element(), modStart.offset(), modFinish.element(), modFinish.offset()); }); }; var placement$2 = function (component, anchorInfo, origin) { var win = defaultView(anchorInfo.root).dom(); var rootPoint = getRootPoint(component, origin, anchorInfo); var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) { var optRect = getFirstRect$1(win, Selection.exactFromRange(sel)).orThunk(function () { var x = Element.fromText(zeroWidth()); before(sel.start(), x); return getFirstRect$1(win, Selection.exact(x, 0, x, 1)).map(function (rect) { remove(x); return rect; }); }); return optRect.bind(function (rawRect) { return ContentAnchorCommon.capRect(rawRect.left(), rawRect.top(), rawRect.width(), rawRect.height()); }); }); var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) { return isElement(sel.start()) ? Option.some(sel.start()) : parent(sel.start()); }); var elem = targetElement.getOr(component.element()); return ContentAnchorCommon.calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem); }; var SelectionAnchor = [ option('getSelection'), strict$1('root'), option('bubble'), schema$1(), defaulted$1('overrides', {}), defaulted$1('showAbove', false), output('placement', placement$2) ]; var placement$3 = function (component, anchorInfo, origin) { var rootPoint = getRootPoint(component, origin, anchorInfo); return anchorInfo.node.bind(function (target) { var rect = target.dom().getBoundingClientRect(); var nodeBox = ContentAnchorCommon.capRect(rect.left, rect.top, rect.width, rect.height); var elem = anchorInfo.node.getOr(component.element()); return ContentAnchorCommon.calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem); }); }; var NodeAnchor = [ strict$1('node'), strict$1('root'), option('bubble'), schema$1(), defaulted$1('overrides', {}), defaulted$1('showAbove', false), output('placement', placement$3) ]; var eastX$1 = function (anchor) { return anchor.x() + anchor.width(); }; var westX$1 = function (anchor, element) { return anchor.x() - element.width(); }; var northY$1 = function (anchor, element) { return anchor.y() - element.height() + anchor.height(); }; var southY$1 = function (anchor) { return anchor.y(); }; var southeast$2 = function (anchor, element, bubbles) { return nu$7(eastX$1(anchor), southY$1(anchor), bubbles.southeast(), southeast(), 'link-layout-se'); }; var southwest$2 = function (anchor, element, bubbles) { return nu$7(westX$1(anchor, element), southY$1(anchor), bubbles.southwest(), southwest(), 'link-layout-sw'); }; var northeast$2 = function (anchor, element, bubbles) { return nu$7(eastX$1(anchor), northY$1(anchor, element), bubbles.northeast(), northeast(), 'link-layout-ne'); }; var northwest$2 = function (anchor, element, bubbles) { return nu$7(westX$1(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest(), 'link-layout-nw'); }; var all$3 = function () { return [ southeast$2, southwest$2, northeast$2, northwest$2 ]; }; var allRtl$1 = function () { return [ southwest$2, southeast$2, northwest$2, northeast$2 ]; }; var placement$4 = function (component, submenuInfo, origin) { var anchorBox = toBox(origin, submenuInfo.item.element()); var layouts = get$9(component.element(), submenuInfo, all$3(), allRtl$1()); return Option.some(nu$9({ anchorBox: anchorBox, bubble: fallback(), overrides: submenuInfo.overrides, layouts: layouts, placer: Option.none() })); }; var SubmenuAnchor = [ strict$1('item'), schema$1(), defaulted$1('overrides', {}), output('placement', placement$4) ]; var AnchorSchema = choose$1('anchor', { selection: SelectionAnchor, node: NodeAnchor, hotspot: HotspotAnchor, submenu: SubmenuAnchor, makeshift: MakeshiftAnchor }); var anchor = Immutable('anchorBox', 'origin'); var box$1 = function (anchorBox, origin) { return anchor(anchorBox, origin); }; var cycleBy = function (value, delta, min, max) { var r = value + delta; if (r > max) { return min; } else { return r < min ? max : r; } }; var cap = function (value, min, max) { if (value <= min) { return min; } else { return value >= max ? max : value; } }; var adt$8 = Adt.generate([ { fit: ['reposition'] }, { nofit: [ 'reposition', 'deltaW', 'deltaH' ] } ]); var calcReposition = function (newX, newY, width, height, bounds) { var boundsX = bounds.x(); var boundsY = bounds.y(); var boundsWidth = bounds.width(); var boundsHeight = bounds.height(); var xInBounds = newX >= boundsX; var yInBounds = newY >= boundsY; var originInBounds = xInBounds && yInBounds; var xFit = newX + width <= boundsX + boundsWidth; var yFit = newY + height <= boundsY + boundsHeight; var sizeInBounds = xFit && yFit; var deltaW = Math.abs(Math.min(width, xInBounds ? boundsX + boundsWidth - newX : boundsX - (newX + width))); var deltaH = Math.abs(Math.min(height, yInBounds ? boundsY + boundsHeight - newY : boundsY - (newY + height))); var limitX = cap(newX, bounds.x(), bounds.right()); var limitY = cap(newY, bounds.y(), bounds.bottom()); return { originInBounds: originInBounds, sizeInBounds: sizeInBounds, limitX: limitX, limitY: limitY, deltaW: deltaW, deltaH: deltaH }; }; var attempt = function (candidate, width, height, bounds) { var candidateX = candidate.x(); var candidateY = candidate.y(); var bubbleLeft = candidate.bubble().offset().left(); var bubbleTop = candidate.bubble().offset().top(); var boundsY = bounds.y(); var boundsBottom = bounds.bottom(); var boundsX = bounds.x(); var boundsRight = bounds.right(); var newX = candidateX + bubbleLeft; var newY = candidateY + bubbleTop; var _a = calcReposition(newX, newY, width, height, bounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, limitX = _a.limitX, limitY = _a.limitY, deltaW = _a.deltaW, deltaH = _a.deltaH; var upAvailable = constant(limitY + deltaH - boundsY); var downAvailable = constant(boundsBottom - limitY); var maxHeight = cataVertical(candidate.direction(), downAvailable, downAvailable, upAvailable); var westAvailable = constant(limitX + deltaW - boundsX); var eastAvailable = constant(boundsRight - limitX); var maxWidth = cataHorizontal(candidate.direction(), eastAvailable, eastAvailable, westAvailable); var reposition = decision({ x: limitX, y: limitY, width: deltaW, height: deltaH, maxHeight: maxHeight, maxWidth: maxWidth, direction: candidate.direction(), classes: { on: candidate.bubble().classesOn(), off: candidate.bubble().classesOff() }, label: candidate.label(), candidateYforTest: newY }); return originInBounds && sizeInBounds ? adt$8.fit(reposition) : adt$8.nofit(reposition, deltaW, deltaH); }; var attempts = function (candidates, anchorBox, elementBox, bubbles, bounds) { var panelWidth = elementBox.width(); var panelHeight = elementBox.height(); var attemptBestFit = function (layout, reposition, deltaW, deltaH) { var next = layout(anchorBox, elementBox, bubbles); var attemptLayout = attempt(next, panelWidth, panelHeight, bounds); return attemptLayout.fold(adt$8.fit, function (newReposition, newDeltaW, newDeltaH) { var improved = newDeltaH > deltaH || newDeltaW > deltaW; return improved ? adt$8.nofit(newReposition, newDeltaW, newDeltaH) : adt$8.nofit(reposition, deltaW, deltaH); }); }; var abc = foldl(candidates, function (b, a) { var bestNext = curry(attemptBestFit, a); return b.fold(adt$8.fit, bestNext); }, adt$8.nofit(decision({ x: anchorBox.x(), y: anchorBox.y(), width: elementBox.width(), height: elementBox.height(), maxHeight: elementBox.height(), maxWidth: elementBox.width(), direction: southeast(), classes: { on: [], off: [] }, label: 'none', candidateYforTest: anchorBox.y() }), -1, -1)); return abc.fold(identity, identity); }; var elementSize = function (p) { return { width: constant(getOuter$2(p)), height: constant(getOuter$1(p)) }; }; var layout = function (anchorBox, element, bubbles, options) { remove$6(element, 'max-height'); remove$6(element, 'max-width'); var elementBox = elementSize(element); return attempts(options.preference(), anchorBox, elementBox, bubbles, options.bounds()); }; var setClasses = function (element, decision) { var classInfo = decision.classes(); remove$5(element, classInfo.off); add$3(element, classInfo.on); }; var setHeight = function (element, decision, options) { var maxHeightFunction = options.maxHeightFunction(); maxHeightFunction(element, decision.maxHeight()); }; var setWidth = function (element, decision, options) { var maxWidthFunction = options.maxWidthFunction(); maxWidthFunction(element, decision.maxWidth()); }; var position = function (element, decision, options) { var addPx = function (num) { return num + 'px'; }; var newPosition = reposition(options.origin(), decision); setOptions(element, { position: Option.some(newPosition.position()), left: newPosition.left().map(addPx), top: newPosition.top().map(addPx), right: newPosition.right().map(addPx), bottom: newPosition.bottom().map(addPx) }); }; var setMaxHeight = function (element, maxHeight) { setMax(element, Math.floor(maxHeight)); }; var anchored = constant(function (element, available) { setMaxHeight(element, available); setAll$1(element, { 'overflow-x': 'hidden', 'overflow-y': 'auto' }); }); var expandable = constant(function (element, available) { setMaxHeight(element, available); }); var reparteeOptions = MixedBag([ 'bounds', 'origin', 'preference', 'maxHeightFunction', 'maxWidthFunction' ], []); var defaultOr = function (options, key, dephault) { return options[key] === undefined ? dephault : options[key]; }; var simple = function (anchor, element, bubble, layouts, getBounds, overrideOptions) { var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored()); var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop); var anchorBox = anchor.anchorBox(); var origin = anchor.origin(); var options = reparteeOptions({ bounds: viewport$1(origin, getBounds), origin: origin, preference: layouts, maxHeightFunction: maxHeightFunction, maxWidthFunction: maxWidthFunction }); go(anchorBox, element, bubble, options); }; var go = function (anchorBox, element, bubble, options) { var decision = layout(anchorBox, element, bubble, options); position(element, decision, options); setClasses(element, decision); setHeight(element, decision, options); setWidth(element, decision, options); }; var getFixedOrigin = function () { var html = domGlobals.document.documentElement; return fixed(0, 0, html.clientWidth, html.clientHeight); }; var getRelativeOrigin = function (component) { var position = absolute(component.element()); var bounds = component.element().dom().getBoundingClientRect(); return relative(position.left(), position.top(), bounds.width, bounds.height); }; var place = function (component, origin, anchoring, getBounds, placee) { var anchor = box$1(anchoring.anchorBox, origin); simple(anchor, placee.element(), anchoring.bubble, anchoring.layouts, getBounds, anchoring.overrides); }; var position$1 = function (component, posConfig, posState, anchor, placee) { positionWithin(component, posConfig, posState, anchor, placee, Option.none()); }; var positionWithin = function (component, posConfig, posState, anchor, placee, boxElement) { var boundsBox = boxElement.map(box); return positionWithinBounds(component, posConfig, posState, anchor, placee, boundsBox); }; var positionWithinBounds = function (component, posConfig, posState, anchor, placee, bounds) { var anchorage = asRawOrDie('positioning anchor.info', AnchorSchema, anchor); preserve(function () { set$2(placee.element(), 'position', 'fixed'); var oldVisibility = getRaw(placee.element(), 'visibility'); set$2(placee.element(), 'visibility', 'hidden'); var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component); var placer = anchorage.placement; var getBounds = bounds.map(constant).or(posConfig.getBounds); placer(component, anchorage, origin).each(function (anchoring) { var doPlace = anchoring.placer.getOr(place); doPlace(component, origin, anchoring, getBounds, placee); }); oldVisibility.fold(function () { remove$6(placee.element(), 'visibility'); }, function (vis) { set$2(placee.element(), 'visibility', vis); }); if (getRaw(placee.element(), 'left').isNone() && getRaw(placee.element(), 'top').isNone() && getRaw(placee.element(), 'right').isNone() && getRaw(placee.element(), 'bottom').isNone() && getRaw(placee.element(), 'position').is('fixed')) { remove$6(placee.element(), 'position'); } }, placee.element()); }; var getMode = function (component, pConfig, pState) { return pConfig.useFixed() ? 'fixed' : 'absolute'; }; var PositionApis = /*#__PURE__*/Object.freeze({ position: position$1, positionWithin: positionWithin, positionWithinBounds: positionWithinBounds, getMode: getMode }); var PositionSchema = [ defaulted$1('useFixed', never), option('getBounds') ]; var Positioning = create$1({ fields: PositionSchema, name: 'positioning', active: ActivePosition, apis: PositionApis }); var fireDetaching = function (component) { emit(component, detachedFromDom()); var children = component.components(); each(children, fireDetaching); }; var fireAttaching = function (component) { var children = component.components(); each(children, fireAttaching); emit(component, attachedToDom()); }; var attach = function (parent, child) { append(parent.element(), child.element()); }; var detachChildren = function (component) { each(component.components(), function (childComp) { return remove(childComp.element()); }); empty(component.element()); component.syncComponents(); }; var replaceChildren = function (component, newChildren) { var subs = component.components(); detachChildren(component); var deleted = difference(subs, newChildren); each(deleted, function (comp) { fireDetaching(comp); component.getSystem().removeFromWorld(comp); }); each(newChildren, function (childComp) { if (!childComp.getSystem().isConnected()) { component.getSystem().addToWorld(childComp); attach(component, childComp); if (inBody(component.element())) { fireAttaching(childComp); } } else { attach(component, childComp); } component.syncComponents(); }); }; var attach$1 = function (parent, child) { attachWith(parent, child, append); }; var attachWith = function (parent, child, insertion) { parent.getSystem().addToWorld(child); insertion(parent.element(), child.element()); if (inBody(parent.element())) { fireAttaching(child); } parent.syncComponents(); }; var doDetach = function (component) { fireDetaching(component); remove(component.element()); component.getSystem().removeFromWorld(component); }; var detach = function (component) { var parent$1 = parent(component.element()).bind(function (p) { return component.getSystem().getByDom(p).toOption(); }); doDetach(component); parent$1.each(function (p) { p.syncComponents(); }); }; var detachChildren$1 = function (component) { var subs = component.components(); each(subs, doDetach); empty(component.element()); component.syncComponents(); }; var attachSystem = function (element, guiSystem) { attachSystemWith(element, guiSystem, append); }; var attachSystemAfter = function (element, guiSystem) { attachSystemWith(element, guiSystem, after); }; var attachSystemWith = function (element, guiSystem, inserter) { inserter(element, guiSystem.element()); var children$1 = children(guiSystem.element()); each(children$1, function (child) { guiSystem.getByDom(child).each(fireAttaching); }); }; var detachSystem = function (guiSystem) { var children$1 = children(guiSystem.element()); each(children$1, function (child) { guiSystem.getByDom(child).each(fireDetaching); }); remove(guiSystem.element()); }; var rebuild = function (sandbox, sConfig, sState, data) { sState.get().each(function (data) { detachChildren$1(sandbox); }); var point = sConfig.getAttachPoint(sandbox); attach$1(point, sandbox); var built = sandbox.getSystem().build(data); attach$1(sandbox, built); sState.set(built); return built; }; var open = function (sandbox, sConfig, sState, data) { var newState = rebuild(sandbox, sConfig, sState, data); sConfig.onOpen(sandbox, newState); return newState; }; var setContent = function (sandbox, sConfig, sState, data) { return sState.get().map(function () { return rebuild(sandbox, sConfig, sState, data); }); }; var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) { cloak(sandbox, sConfig); open(sandbox, sConfig, sState, data); transaction(); decloak(sandbox, sConfig); }; var close = function (sandbox, sConfig, sState) { sState.get().each(function (data) { detachChildren$1(sandbox); detach(sandbox); sConfig.onClose(sandbox, data); sState.clear(); }); }; var isOpen = function (sandbox, sConfig, sState) { return sState.isOpen(); }; var isPartOf$1 = function (sandbox, sConfig, sState, queryElem) { return isOpen(sandbox, sConfig, sState) && sState.get().exists(function (data) { return sConfig.isPartOf(sandbox, data, queryElem); }); }; var getState = function (sandbox, sConfig, sState) { return sState.get(); }; var store = function (sandbox, cssKey, attr, newValue) { getRaw(sandbox.element(), cssKey).fold(function () { remove$1(sandbox.element(), attr); }, function (v) { set$1(sandbox.element(), attr, v); }); set$2(sandbox.element(), cssKey, newValue); }; var restore = function (sandbox, cssKey, attr) { if (has$1(sandbox.element(), attr)) { var oldValue = get$2(sandbox.element(), attr); set$2(sandbox.element(), cssKey, oldValue); } else { remove$6(sandbox.element(), cssKey); } }; var cloak = function (sandbox, sConfig, sState) { var sink = sConfig.getAttachPoint(sandbox); set$2(sandbox.element(), 'position', Positioning.getMode(sink)); store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden'); }; var hasPosition = function (element) { return exists([ 'top', 'left', 'right', 'bottom' ], function (pos) { return getRaw(element, pos).isSome(); }); }; var decloak = function (sandbox, sConfig, sState) { if (!hasPosition(sandbox.element())) { remove$6(sandbox.element(), 'position'); } restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr); }; var SandboxApis = /*#__PURE__*/Object.freeze({ cloak: cloak, decloak: decloak, open: open, openWhileCloaked: openWhileCloaked, close: close, isOpen: isOpen, isPartOf: isPartOf$1, getState: getState, setContent: setContent }); var events$2 = function (sandboxConfig, sandboxState) { return derive([run(sandboxClose(), function (sandbox, simulatedEvent) { close(sandbox, sandboxConfig, sandboxState); })]); }; var ActiveSandbox = /*#__PURE__*/Object.freeze({ events: events$2 }); var SandboxSchema = [ onHandler('onOpen'), onHandler('onClose'), strict$1('isPartOf'), strict$1('getAttachPoint'), defaulted$1('cloakVisibilityAttr', 'data-precloak-visibility') ]; var init = function () { var contents = Cell(Option.none()); var readState = constant('not-implemented'); var isOpen = function () { return contents.get().isSome(); }; var set = function (c) { contents.set(Option.some(c)); }; var get = function (c) { return contents.get(); }; var clear = function () { contents.set(Option.none()); }; return nu$5({ readState: readState, isOpen: isOpen, clear: clear, set: set, get: get }); }; var SandboxState = /*#__PURE__*/Object.freeze({ init: init }); var Sandboxing = create$1({ fields: SandboxSchema, name: 'sandboxing', active: ActiveSandbox, apis: SandboxApis, state: SandboxState }); var dismissPopups = constant('dismiss.popups'); var repositionPopups = constant('reposition.popups'); var mouseReleased = constant('mouse.released'); var schema$2 = objOfOnly([ defaulted$1('isExtraPart', constant(false)), optionObjOf('fireEventInstead', [defaulted$1('event', dismissRequested())]) ]); var receivingChannel = function (rawSpec) { var _a; var detail = asRawOrDie('Dismissal', schema$2, rawSpec); return _a = {}, _a[dismissPopups()] = { schema: objOfOnly([strict$1('target')]), onReceive: function (sandbox, data) { if (Sandboxing.isOpen(sandbox)) { var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target); if (!isPart) { detail.fireEventInstead.fold(function () { return Sandboxing.close(sandbox); }, function (fe) { return emit(sandbox, fe.event); }); } } } }, _a; }; var schema$3 = objOfOnly([ defaulted$1('isExtraPart', constant(false)), optionObjOf('fireEventInstead', [defaulted$1('event', repositionRequested())]), strictFunction('doReposition') ]); var receivingChannel$1 = function (rawSpec) { var _a; var detail = asRawOrDie('Reposition', schema$3, rawSpec); return _a = {}, _a[repositionPopups()] = { onReceive: function (sandbox) { if (Sandboxing.isOpen(sandbox)) { detail.fireEventInstead.fold(function () { return detail.doReposition(sandbox); }, function (fe) { return emit(sandbox, fe.event); }); } } }, _a; }; var onLoad = function (component, repConfig, repState) { repConfig.store.manager.onLoad(component, repConfig, repState); }; var onUnload = function (component, repConfig, repState) { repConfig.store.manager.onUnload(component, repConfig, repState); }; var setValue = function (component, repConfig, repState, data) { repConfig.store.manager.setValue(component, repConfig, repState, data); }; var getValue = function (component, repConfig, repState) { return repConfig.store.manager.getValue(component, repConfig, repState); }; var getState$1 = function (component, repConfig, repState) { return repState; }; var RepresentApis = /*#__PURE__*/Object.freeze({ onLoad: onLoad, onUnload: onUnload, setValue: setValue, getValue: getValue, getState: getState$1 }); var events$3 = function (repConfig, repState) { var es = repConfig.resetOnDom ? [ runOnAttached(function (comp, se) { onLoad(comp, repConfig, repState); }), runOnDetached(function (comp, se) { onUnload(comp, repConfig, repState); }) ] : [loadEvent(repConfig, repState, onLoad)]; return derive(es); }; var ActiveRepresenting = /*#__PURE__*/Object.freeze({ events: events$3 }); var memory = function () { var data = Cell(null); var readState = function () { return { mode: 'memory', value: data.get() }; }; var isNotSet = function () { return data.get() === null; }; var clear = function () { data.set(null); }; return nu$5({ set: data.set, get: data.get, isNotSet: isNotSet, clear: clear, readState: readState }); }; var manual = function () { var readState = function () { }; return nu$5({ readState: readState }); }; var dataset = function () { var dataByValue = Cell({}); var dataByText = Cell({}); var readState = function () { return { mode: 'dataset', dataByValue: dataByValue.get(), dataByText: dataByText.get() }; }; var clear = function () { dataByValue.set({}); dataByText.set({}); }; var lookup = function (itemString) { return readOptFrom$1(dataByValue.get(), itemString).orThunk(function () { return readOptFrom$1(dataByText.get(), itemString); }); }; var update = function (items) { var currentDataByValue = dataByValue.get(); var currentDataByText = dataByText.get(); var newDataByValue = {}; var newDataByText = {}; each(items, function (item) { newDataByValue[item.value] = item; readOptFrom$1(item, 'meta').each(function (meta) { readOptFrom$1(meta, 'text').each(function (text) { newDataByText[text] = item; }); }); }); dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue)); dataByText.set(__assign(__assign({}, currentDataByText), newDataByText)); }; return nu$5({ readState: readState, lookup: lookup, update: update, clear: clear }); }; var init$1 = function (spec) { return spec.store.manager.state(spec); }; var RepresentState = /*#__PURE__*/Object.freeze({ memory: memory, dataset: dataset, manual: manual, init: init$1 }); var setValue$1 = function (component, repConfig, repState, data) { var store = repConfig.store; repState.update([data]); store.setValue(component, data); repConfig.onSetValue(component, data); }; var getValue$1 = function (component, repConfig, repState) { var store = repConfig.store; var key = store.getDataKey(component); return repState.lookup(key).fold(function () { return store.getFallbackEntry(key); }, function (data) { return data; }); }; var onLoad$1 = function (component, repConfig, repState) { var store = repConfig.store; store.initialValue.each(function (data) { setValue$1(component, repConfig, repState, data); }); }; var onUnload$1 = function (component, repConfig, repState) { repState.clear(); }; var DatasetStore = [ option('initialValue'), strict$1('getFallbackEntry'), strict$1('getDataKey'), strict$1('setValue'), output('manager', { setValue: setValue$1, getValue: getValue$1, onLoad: onLoad$1, onUnload: onUnload$1, state: dataset }) ]; var getValue$2 = function (component, repConfig, repState) { return repConfig.store.getValue(component); }; var setValue$2 = function (component, repConfig, repState, data) { repConfig.store.setValue(component, data); repConfig.onSetValue(component, data); }; var onLoad$2 = function (component, repConfig, repState) { repConfig.store.initialValue.each(function (data) { repConfig.store.setValue(component, data); }); }; var ManualStore = [ strict$1('getValue'), defaulted$1('setValue', noop), option('initialValue'), output('manager', { setValue: setValue$2, getValue: getValue$2, onLoad: onLoad$2, onUnload: noop, state: NoState.init }) ]; var setValue$3 = function (component, repConfig, repState, data) { repState.set(data); repConfig.onSetValue(component, data); }; var getValue$3 = function (component, repConfig, repState) { return repState.get(); }; var onLoad$3 = function (component, repConfig, repState) { repConfig.store.initialValue.each(function (initVal) { if (repState.isNotSet()) { repState.set(initVal); } }); }; var onUnload$2 = function (component, repConfig, repState) { repState.clear(); }; var MemoryStore = [ option('initialValue'), output('manager', { setValue: setValue$3, getValue: getValue$3, onLoad: onLoad$3, onUnload: onUnload$2, state: memory }) ]; var RepresentSchema = [ defaultedOf('store', { mode: 'memory' }, choose$1('mode', { memory: MemoryStore, manual: ManualStore, dataset: DatasetStore })), onHandler('onSetValue'), defaulted$1('resetOnDom', false) ]; var Representing = create$1({ fields: RepresentSchema, name: 'representing', active: ActiveRepresenting, apis: RepresentApis, extra: { setValueFrom: function (component, source) { var value = Representing.getValue(source); Representing.setValue(component, value); } }, state: RepresentState }); var field$1 = function (name, forbidden) { return defaultedObjOf(name, {}, map(forbidden, function (f) { return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name); }).concat([state$1('dump', identity)])); }; var get$b = function (data) { return data.dump; }; var augment = function (data, original) { return __assign(__assign({}, data.dump), derive$1(original)); }; var SketchBehaviours = { field: field$1, augment: augment, get: get$b }; var _placeholder = 'placeholder'; var adt$9 = Adt.generate([ { single: [ 'required', 'valueThunk' ] }, { multiple: [ 'required', 'valueThunks' ] } ]); var subPlaceholder = function (owner, detail, compSpec, placeholders) { if (owner.exists(function (o) { return o !== compSpec.owner; })) { return adt$9.single(true, constant(compSpec)); } return readOptFrom$1(placeholders, compSpec.name).fold(function () { throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2)); }, function (newSpec) { return newSpec.replace(); }); }; var scan = function (owner, detail, compSpec, placeholders) { if (compSpec.uiType === _placeholder) { return subPlaceholder(owner, detail, compSpec, placeholders); } else { return adt$9.single(false, constant(compSpec)); } }; var substitute = function (owner, detail, compSpec, placeholders) { var base = scan(owner, detail, compSpec, placeholders); return base.fold(function (req, valueThunk) { var value = valueThunk(detail, compSpec.config, compSpec.validated); var childSpecs = readOptFrom$1(value, 'components').getOr([]); var substituted = bind(childSpecs, function (c) { return substitute(owner, detail, c, placeholders); }); return [__assign(__assign({}, value), { components: substituted })]; }, function (req, valuesThunk) { var values = valuesThunk(detail, compSpec.config, compSpec.validated); var preprocessor = compSpec.validated.preprocess.getOr(identity); return preprocessor(values); }); }; var substituteAll = function (owner, detail, components, placeholders) { return bind(components, function (c) { return substitute(owner, detail, c, placeholders); }); }; var oneReplace = function (label, replacements) { var called = false; var used = function () { return called; }; var replace = function () { if (called === true) { throw new Error('Trying to use the same placeholder more than once: ' + label); } called = true; return replacements; }; var required = function () { return replacements.fold(function (req, _) { return req; }, function (req, _) { return req; }); }; return { name: constant(label), required: required, used: used, replace: replace }; }; var substitutePlaces = function (owner, detail, components, placeholders) { var ps = map$1(placeholders, function (ph, name) { return oneReplace(name, ph); }); var outcome = substituteAll(owner, detail, components, ps); each$1(ps, function (p) { if (p.used() === false && p.required()) { throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2)); } }); return outcome; }; var single = adt$9.single; var multiple = adt$9.multiple; var placeholder = constant(_placeholder); var adt$a = Adt.generate([ { required: ['data'] }, { external: ['data'] }, { optional: ['data'] }, { group: ['data'] } ]); var fFactory = defaulted$1('factory', { sketch: identity }); var fSchema = defaulted$1('schema', []); var fName = strict$1('name'); var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) { return ''; }), anyValue$1()); var fGroupSchema = state$1('schema', function () { return [option('preprocess')]; }); var fDefaults = defaulted$1('defaults', constant({})); var fOverrides = defaulted$1('overrides', constant({})); var requiredSpec = objOf([ fFactory, fSchema, fName, fPname, fDefaults, fOverrides ]); var externalSpec = objOf([ fFactory, fSchema, fName, fDefaults, fOverrides ]); var optionalSpec = objOf([ fFactory, fSchema, fName, fPname, fDefaults, fOverrides ]); var groupSpec = objOf([ fFactory, fGroupSchema, fName, strict$1('unit'), fPname, fDefaults, fOverrides ]); var asNamedPart = function (part) { return part.fold(Option.some, Option.none, Option.some, Option.some); }; var name$1 = function (part) { var get = function (data) { return data.name; }; return part.fold(get, get, get, get); }; var asCommon = function (part) { return part.fold(identity, identity, identity, identity); }; var convert = function (adtConstructor, partSchema) { return function (spec) { var data = asRawOrDie('Converting part type', partSchema, spec); return adtConstructor(data); }; }; var required = convert(adt$a.required, requiredSpec); var external$1 = convert(adt$a.external, externalSpec); var optional = convert(adt$a.optional, optionalSpec); var group = convert(adt$a.group, groupSpec); var original = constant('entirety'); var PartType = /*#__PURE__*/Object.freeze({ required: required, external: external$1, optional: optional, group: group, asNamedPart: asNamedPart, name: name$1, asCommon: asCommon, original: original }); var combine$2 = function (detail, data, partSpec, partValidated) { return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated)); }; var subs = function (owner, detail, parts) { var internals = {}; var externals = {}; each(parts, function (part) { part.fold(function (data) { internals[data.pname] = single(true, function (detail, partSpec, partValidated) { return data.factory.sketch(combine$2(detail, data, partSpec, partValidated)); }); }, function (data) { var partSpec = detail.parts[data.name]; externals[data.name] = constant(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec)); }, function (data) { internals[data.pname] = single(false, function (detail, partSpec, partValidated) { return data.factory.sketch(combine$2(detail, data, partSpec, partValidated)); }); }, function (data) { internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) { var units = detail[data.name]; return map(units, function (u) { return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u))); }); }); }); }); return { internals: constant(internals), externals: constant(externals) }; }; var generate$4 = function (owner, parts) { var r = {}; each(parts, function (part) { asNamedPart(part).each(function (np) { var g = doGenerateOne(owner, np.pname); r[np.name] = function (config) { var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config); return __assign(__assign({}, g), { config: config, validated: validated }); }; }); }); return r; }; var doGenerateOne = function (owner, pname) { return { uiType: placeholder(), owner: owner, name: pname }; }; var generateOne = function (owner, pname, config) { return { uiType: placeholder(), owner: owner, name: pname, config: config, validated: {} }; }; var schemas = function (parts) { return bind(parts, function (part) { return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) { return strictObjOf(data.name, data.schema.concat([snapshot(original())])); }).toArray(); }); }; var names = function (parts) { return map(parts, name$1); }; var substitutes = function (owner, detail, parts) { return subs(owner, detail, parts); }; var components = function (owner, detail, internals) { return substitutePlaces(Option.some(owner), detail, detail.components, internals); }; var getPart = function (component, detail, partKey) { var uid = detail.partUids[partKey]; return component.getSystem().getByUid(uid).toOption(); }; var getPartOrDie = function (component, detail, partKey) { return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey); }; var getParts = function (component, detail, partKeys) { var r = {}; var uids = detail.partUids; var system = component.getSystem(); each(partKeys, function (pk) { r[pk] = constant(system.getByUid(uids[pk])); }); return r; }; var getAllParts = function (component, detail) { var system = component.getSystem(); return map$1(detail.partUids, function (pUid, k) { return constant(system.getByUid(pUid)); }); }; var getAllPartNames = function (detail) { return keys(detail.partUids); }; var getPartsOrDie = function (component, detail, partKeys) { var r = {}; var uids = detail.partUids; var system = component.getSystem(); each(partKeys, function (pk) { r[pk] = constant(system.getByUid(uids[pk]).getOrDie()); }); return r; }; var defaultUids = function (baseUid, partTypes) { var partNames = names(partTypes); return wrapAll$1(map(partNames, function (pn) { return { key: pn, value: baseUid + '-' + pn }; })); }; var defaultUidsSchema = function (partTypes) { return field('partUids', 'partUids', mergeWithThunk(function (spec) { return defaultUids(spec.uid, partTypes); }), anyValue$1()); }; var AlloyParts = /*#__PURE__*/Object.freeze({ generate: generate$4, generateOne: generateOne, schemas: schemas, names: names, substitutes: substitutes, components: components, defaultUids: defaultUids, defaultUidsSchema: defaultUidsSchema, getAllParts: getAllParts, getAllPartNames: getAllPartNames, getPart: getPart, getPartOrDie: getPartOrDie, getParts: getParts, getPartsOrDie: getPartsOrDie }); var base = function (partSchemas, partUidsSchemas) { var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : []; return ps.concat([ strict$1('uid'), defaulted$1('dom', {}), defaulted$1('components', []), snapshot('originalSpec'), defaulted$1('debug.sketcher', {}) ]).concat(partUidsSchemas); }; var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) { var baseS = base(partSchemas, partUidsSchemas); return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec); }; var single$1 = function (owner, schema, factory, spec) { var specWithUid = supplyUid(spec); var detail = asRawOrDie$1(owner, schema, specWithUid, [], []); return factory(detail, specWithUid); }; var composite = function (owner, schema, partTypes, factory, spec) { var specWithUid = supplyUid(spec); var partSchemas = schemas(partTypes); var partUidsSchema = defaultUidsSchema(partTypes); var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]); var subs = substitutes(owner, detail, partTypes); var components$1 = components(owner, detail, subs.internals()); return factory(detail, components$1, specWithUid, subs.externals()); }; var supplyUid = function (spec) { return spec.hasOwnProperty('uid') ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') }); }; function isSketchSpec(spec) { return spec.uid !== undefined; } var singleSchema = objOfOnly([ strict$1('name'), strict$1('factory'), strict$1('configFields'), defaulted$1('apis', {}), defaulted$1('extraApis', {}) ]); var compositeSchema = objOfOnly([ strict$1('name'), strict$1('factory'), strict$1('configFields'), strict$1('partFields'), defaulted$1('apis', {}), defaulted$1('extraApis', {}) ]); var single$2 = function (rawConfig) { var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig); var sketch = function (spec) { return single$1(config.name, config.configFields, config.factory, spec); }; var apis = map$1(config.apis, makeApi); var extraApis = map$1(config.extraApis, function (f, k) { return markAsExtraApi(f, k); }); return __assign(__assign({ name: constant(config.name), partFields: constant([]), configFields: constant(config.configFields), sketch: sketch }, apis), extraApis); }; var composite$1 = function (rawConfig) { var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig); var sketch = function (spec) { return composite(config.name, config.configFields, config.partFields, config.factory, spec); }; var parts = generate$4(config.name, config.partFields); var apis = map$1(config.apis, makeApi); var extraApis = map$1(config.extraApis, function (f, k) { return markAsExtraApi(f, k); }); return __assign(__assign({ name: constant(config.name), partFields: constant(config.partFields), configFields: constant(config.configFields), sketch: sketch, parts: constant(parts) }, apis), extraApis); }; var inside = function (target) { return name(target) === 'input' && get$2(target, 'type') !== 'radio' || name(target) === 'textarea'; }; var getCurrent = function (component, composeConfig, composeState) { return composeConfig.find(component); }; var ComposeApis = /*#__PURE__*/Object.freeze({ getCurrent: getCurrent }); var ComposeSchema = [strict$1('find')]; var Composing = create$1({ fields: ComposeSchema, name: 'composing', apis: ComposeApis }); var dehighlightAllExcept = function (component, hConfig, hState, skip) { var highlighted = descendants(component.element(), '.' + hConfig.highlightClass); each(highlighted, function (h) { if (!exists(skip, function (skipComp) { return skipComp.element() === h; })) { remove$4(h, hConfig.highlightClass); component.getSystem().getByDom(h).each(function (target) { hConfig.onDehighlight(component, target); emit(target, dehighlight()); }); } }); }; var dehighlightAll = function (component, hConfig, hState) { return dehighlightAllExcept(component, hConfig, hState, []); }; var dehighlight$1 = function (component, hConfig, hState, target) { if (isHighlighted(component, hConfig, hState, target)) { remove$4(target.element(), hConfig.highlightClass); hConfig.onDehighlight(component, target); emit(target, dehighlight()); } }; var highlight$1 = function (component, hConfig, hState, target) { dehighlightAllExcept(component, hConfig, hState, [target]); if (!isHighlighted(component, hConfig, hState, target)) { add$2(target.element(), hConfig.highlightClass); hConfig.onHighlight(component, target); emit(target, highlight()); } }; var highlightFirst = function (component, hConfig, hState) { getFirst(component, hConfig).each(function (firstComp) { highlight$1(component, hConfig, hState, firstComp); }); }; var highlightLast = function (component, hConfig, hState) { getLast(component, hConfig).each(function (lastComp) { highlight$1(component, hConfig, hState, lastComp); }); }; var highlightAt = function (component, hConfig, hState, index) { getByIndex(component, hConfig, hState, index).fold(function (err) { throw new Error(err); }, function (firstComp) { highlight$1(component, hConfig, hState, firstComp); }); }; var highlightBy = function (component, hConfig, hState, predicate) { var candidates = getCandidates(component, hConfig); var targetComp = find(candidates, predicate); targetComp.each(function (c) { highlight$1(component, hConfig, hState, c); }); }; var isHighlighted = function (component, hConfig, hState, queryTarget) { return has$2(queryTarget.element(), hConfig.highlightClass); }; var getHighlighted = function (component, hConfig, hState) { return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) { return component.getSystem().getByDom(e).toOption(); }); }; var getByIndex = function (component, hConfig, hState, index) { var items = descendants(component.element(), '.' + hConfig.itemClass); return Option.from(items[index]).fold(function () { return Result.error('No element found with index ' + index); }, component.getSystem().getByDom); }; var getFirst = function (component, hConfig, hState) { return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) { return component.getSystem().getByDom(e).toOption(); }); }; var getLast = function (component, hConfig, hState) { var items = descendants(component.element(), '.' + hConfig.itemClass); var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none(); return last.bind(function (c) { return component.getSystem().getByDom(c).toOption(); }); }; var getDelta = function (component, hConfig, hState, delta) { var items = descendants(component.element(), '.' + hConfig.itemClass); var current = findIndex(items, function (item) { return has$2(item, hConfig.highlightClass); }); return current.bind(function (selected) { var dest = cycleBy(selected, delta, 0, items.length - 1); return component.getSystem().getByDom(items[dest]).toOption(); }); }; var getPrevious = function (component, hConfig, hState) { return getDelta(component, hConfig, hState, -1); }; var getNext = function (component, hConfig, hState) { return getDelta(component, hConfig, hState, +1); }; var getCandidates = function (component, hConfig, hState) { var items = descendants(component.element(), '.' + hConfig.itemClass); return cat(map(items, function (i) { return component.getSystem().getByDom(i).toOption(); })); }; var HighlightApis = /*#__PURE__*/Object.freeze({ dehighlightAll: dehighlightAll, dehighlight: dehighlight$1, highlight: highlight$1, highlightFirst: highlightFirst, highlightLast: highlightLast, highlightAt: highlightAt, highlightBy: highlightBy, isHighlighted: isHighlighted, getHighlighted: getHighlighted, getFirst: getFirst, getLast: getLast, getPrevious: getPrevious, getNext: getNext, getCandidates: getCandidates }); var HighlightSchema = [ strict$1('highlightClass'), strict$1('itemClass'), onHandler('onHighlight'), onHandler('onDehighlight') ]; var Highlighting = create$1({ fields: HighlightSchema, name: 'highlighting', apis: HighlightApis }); var BACKSPACE = function () { return [8]; }; var TAB = function () { return [9]; }; var ENTER = function () { return [13]; }; var ESCAPE = function () { return [27]; }; var SPACE = function () { return [32]; }; var LEFT = function () { return [37]; }; var UP = function () { return [38]; }; var RIGHT = function () { return [39]; }; var DOWN = function () { return [40]; }; var cyclePrev = function (values, index, predicate) { var before = reverse(values.slice(0, index)); var after = reverse(values.slice(index + 1)); return find(before.concat(after), predicate); }; var tryPrev = function (values, index, predicate) { var before = reverse(values.slice(0, index)); return find(before, predicate); }; var cycleNext = function (values, index, predicate) { var before = values.slice(0, index); var after = values.slice(index + 1); return find(after.concat(before), predicate); }; var tryNext = function (values, index, predicate) { var after = values.slice(index + 1); return find(after, predicate); }; var inSet = function (keys) { return function (event) { var raw = event.raw(); return contains(keys, raw.which); }; }; var and = function (preds) { return function (event) { return forall(preds, function (pred) { return pred(event); }); }; }; var isShift = function (event) { var raw = event.raw(); return raw.shiftKey === true; }; var isControl = function (event) { var raw = event.raw(); return raw.ctrlKey === true; }; var isNotShift = not(isShift); var rule = function (matches, action) { return { matches: matches, classification: action }; }; var choose$2 = function (transitions, event) { var transition = find(transitions, function (t) { return t.matches(event); }); return transition.map(function (t) { return t.classification; }); }; var reportFocusShifting = function (component, prevFocus, newFocus) { var noChange = prevFocus.exists(function (p) { return newFocus.exists(function (n) { return eq(n, p); }); }); if (!noChange) { emitWith(component, focusShifted(), { prevFocus: prevFocus, newFocus: newFocus }); } }; var dom = function () { var get = function (component) { return search(component.element()); }; var set = function (component, focusee) { var prevFocus = get(component); component.getSystem().triggerFocus(focusee, component.element()); var newFocus = get(component); reportFocusShifting(component, prevFocus, newFocus); }; return { get: get, set: set }; }; var highlights = function () { var get = function (component) { return Highlighting.getHighlighted(component).map(function (item) { return item.element(); }); }; var set = function (component, element) { var prevFocus = get(component); component.getSystem().getByDom(element).fold(noop, function (item) { Highlighting.highlight(component, item); }); var newFocus = get(component); reportFocusShifting(component, prevFocus, newFocus); }; return { get: get, set: set }; }; var FocusInsideModes; (function (FocusInsideModes) { FocusInsideModes['OnFocusMode'] = 'onFocus'; FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace'; FocusInsideModes['OnApiMode'] = 'onApi'; }(FocusInsideModes || (FocusInsideModes = {}))); var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) { var schema = function () { return infoSchema.concat([ defaulted$1('focusManager', dom()), defaultedOf('focusInside', 'onFocus', valueOf(function (val) { return contains([ 'onFocus', 'onEnterOrSpace', 'onApi' ], val) ? Result.value(val) : Result.error('Invalid value for focusInside'); })), output('handler', me), output('state', stateInit), output('sendFocusIn', optFocusIn) ]); }; var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) { var rules = getRules(component, simulatedEvent, keyingConfig, keyingState); return choose$2(rules, simulatedEvent.event()).bind(function (rule) { return rule(component, simulatedEvent, keyingConfig, keyingState); }); }; var toEvents = function (keyingConfig, keyingState) { var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) { return run(focus(), function (component, simulatedEvent) { focusIn(component, keyingConfig, keyingState); simulatedEvent.stop(); }); }); var tryGoInsideComponent = function (component, simulatedEvent) { var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event()); if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) { optFocusIn(keyingConfig).each(function (focusIn) { focusIn(component, keyingConfig, keyingState); simulatedEvent.stop(); }); } }; return derive(onFocusHandler.toArray().concat([ run(keydown(), function (component, simulatedEvent) { processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () { tryGoInsideComponent(component, simulatedEvent); }, function (_) { simulatedEvent.stop(); }); }), run(keyup(), function (component, simulatedEvent) { processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) { simulatedEvent.stop(); }); }) ])); }; var me = { schema: schema, processKey: processKey, toEvents: toEvents }; return me; }; var create$3 = function (cyclicField) { var schema = [ option('onEscape'), option('onEnter'), defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'), defaulted$1('firstTabstop', 0), defaulted$1('useTabstopAt', constant(true)), option('visibilitySelector') ].concat([cyclicField]); var isVisible = function (tabbingConfig, element) { var target = tabbingConfig.visibilitySelector.bind(function (sel) { return closest$3(element, sel); }).getOr(element); return get$6(target) > 0; }; var findInitial = function (component, tabbingConfig) { var tabstops = descendants(component.element(), tabbingConfig.selector); var visibles = filter(tabstops, function (elem) { return isVisible(tabbingConfig, elem); }); return Option.from(visibles[tabbingConfig.firstTabstop]); }; var findCurrent = function (component, tabbingConfig) { return tabbingConfig.focusManager.get(component).bind(function (elem) { return closest$3(elem, tabbingConfig.selector); }); }; var isTabstop = function (tabbingConfig, element) { return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element); }; var focusIn = function (component, tabbingConfig) { findInitial(component, tabbingConfig).each(function (target) { tabbingConfig.focusManager.set(component, target); }); }; var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) { return cycle(tabstops, stopIndex, function (elem) { return isTabstop(tabbingConfig, elem); }).fold(function () { return tabbingConfig.cyclic ? Option.some(true) : Option.none(); }, function (target) { tabbingConfig.focusManager.set(component, target); return Option.some(true); }); }; var go = function (component, simulatedEvent, tabbingConfig, cycle) { var tabstops = descendants(component.element(), tabbingConfig.selector); return findCurrent(component, tabbingConfig).bind(function (tabstop) { var optStopIndex = findIndex(tabstops, curry(eq, tabstop)); return optStopIndex.bind(function (stopIndex) { return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle); }); }); }; var goBackwards = function (component, simulatedEvent, tabbingConfig, tabbingState) { var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev; return go(component, simulatedEvent, tabbingConfig, navigate); }; var goForwards = function (component, simulatedEvent, tabbingConfig, tabbingState) { var navigate = tabbingConfig.cyclic ? cycleNext : tryNext; return go(component, simulatedEvent, tabbingConfig, navigate); }; var execute = function (component, simulatedEvent, tabbingConfig, tabbingState) { return tabbingConfig.onEnter.bind(function (f) { return f(component, simulatedEvent); }); }; var exit = function (component, simulatedEvent, tabbingConfig, tabbingState) { return tabbingConfig.onEscape.bind(function (f) { return f(component, simulatedEvent); }); }; var getKeydownRules = constant([ rule(and([ isShift, inSet(TAB()) ]), goBackwards), rule(inSet(TAB()), goForwards), rule(inSet(ESCAPE()), exit), rule(and([ isNotShift, inSet(ENTER()) ]), execute) ]); var getKeyupRules = constant([]); return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () { return Option.some(focusIn); }); }; var AcyclicType = create$3(state$1('cyclic', constant(false))); var CyclicType = create$3(state$1('cyclic', constant(true))); var doDefaultExecute = function (component, simulatedEvent, focused) { dispatch(component, focused, execute()); return Option.some(true); }; var defaultExecute = function (component, simulatedEvent, focused) { return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused); }; var stopEventForFirefox = function (component, simulatedEvent) { return Option.some(true); }; var schema$4 = [ defaulted$1('execute', defaultExecute), defaulted$1('useSpace', false), defaulted$1('useEnter', true), defaulted$1('useControlEnter', false), defaulted$1('useDown', false) ]; var execute$1 = function (component, simulatedEvent, executeConfig) { return executeConfig.execute(component, simulatedEvent, component.element()); }; var getKeydownRules = function (component, simulatedEvent, executeConfig, executeState) { var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : []; var enterExec = executeConfig.useEnter ? ENTER() : []; var downExec = executeConfig.useDown ? DOWN() : []; var execKeys = spaceExec.concat(enterExec).concat(downExec); return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([ isControl, inSet(ENTER()) ]), execute$1)] : []); }; var getKeyupRules = function (component, simulatedEvent, executeConfig, executeState) { return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : []; }; var ExecutionType = typical(schema$4, NoState.init, getKeydownRules, getKeyupRules, function () { return Option.none(); }); var flatgrid = function (spec) { var dimensions = Cell(Option.none()); var setGridSize = function (numRows, numColumns) { dimensions.set(Option.some({ numRows: constant(numRows), numColumns: constant(numColumns) })); }; var getNumRows = function () { return dimensions.get().map(function (d) { return d.numRows(); }); }; var getNumColumns = function () { return dimensions.get().map(function (d) { return d.numColumns(); }); }; return nu$5({ readState: function () { return dimensions.get().map(function (d) { return { numRows: d.numRows(), numColumns: d.numColumns() }; }).getOr({ numRows: '?', numColumns: '?' }); }, setGridSize: setGridSize, getNumRows: getNumRows, getNumColumns: getNumColumns }); }; var init$2 = function (spec) { return spec.state(spec); }; var KeyingState = /*#__PURE__*/Object.freeze({ flatgrid: flatgrid, init: init$2 }); var useH = function (movement) { return function (component, simulatedEvent, config, state) { var move = movement(component.element()); return use(move, component, simulatedEvent, config, state); }; }; var west$2 = function (moveLeft, moveRight) { var movement = onDirection(moveLeft, moveRight); return useH(movement); }; var east$2 = function (moveLeft, moveRight) { var movement = onDirection(moveRight, moveLeft); return useH(movement); }; var useV = function (move) { return function (component, simulatedEvent, config, state) { return use(move, component, simulatedEvent, config, state); }; }; var use = function (move, component, simulatedEvent, config, state) { var outcome = config.focusManager.get(component).bind(function (focused) { return move(component.element(), focused, config, state); }); return outcome.map(function (newFocus) { config.focusManager.set(component, newFocus); return true; }); }; var north$2 = useV; var south$2 = useV; var move = useV; var isHidden = function (dom) { return dom.offsetWidth <= 0 && dom.offsetHeight <= 0; }; var isVisible = function (element) { var dom = element.dom(); return !isHidden(dom); }; var indexInfo = MixedBag([ 'index', 'candidates' ], []); var locate$2 = function (candidates, predicate) { return findIndex(candidates, predicate).map(function (index) { return indexInfo({ index: index, candidates: candidates }); }); }; var locateVisible = function (container, current, selector) { var predicate = curry(eq, current); var candidates = descendants(container, selector); var visible = filter(candidates, isVisible); return locate$2(visible, predicate); }; var findIndex$1 = function (elements, target) { return findIndex(elements, function (elem) { return eq(target, elem); }); }; var withGrid = function (values, index, numCols, f) { var oldRow = Math.floor(index / numCols); var oldColumn = index % numCols; return f(oldRow, oldColumn).bind(function (address) { var newIndex = address.row() * numCols + address.column(); return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none(); }); }; var cycleHorizontal = function (values, index, numRows, numCols, delta) { return withGrid(values, index, numCols, function (oldRow, oldColumn) { var onLastRow = oldRow === numRows - 1; var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols; var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1); return Option.some({ row: constant(oldRow), column: constant(newColumn) }); }); }; var cycleVertical = function (values, index, numRows, numCols, delta) { return withGrid(values, index, numCols, function (oldRow, oldColumn) { var newRow = cycleBy(oldRow, delta, 0, numRows - 1); var onLastRow = newRow === numRows - 1; var colsInRow = onLastRow ? values.length - newRow * numCols : numCols; var newCol = cap(oldColumn, 0, colsInRow - 1); return Option.some({ row: constant(newRow), column: constant(newCol) }); }); }; var cycleRight = function (values, index, numRows, numCols) { return cycleHorizontal(values, index, numRows, numCols, +1); }; var cycleLeft = function (values, index, numRows, numCols) { return cycleHorizontal(values, index, numRows, numCols, -1); }; var cycleUp = function (values, index, numRows, numCols) { return cycleVertical(values, index, numRows, numCols, -1); }; var cycleDown = function (values, index, numRows, numCols) { return cycleVertical(values, index, numRows, numCols, +1); }; var schema$5 = [ strict$1('selector'), defaulted$1('execute', defaultExecute), onKeyboardHandler('onEscape'), defaulted$1('captureTab', false), initSize() ]; var focusIn = function (component, gridConfig, gridState) { descendant$1(component.element(), gridConfig.selector).each(function (first) { gridConfig.focusManager.set(component, first); }); }; var findCurrent = function (component, gridConfig) { return gridConfig.focusManager.get(component).bind(function (elem) { return closest$3(elem, gridConfig.selector); }); }; var execute$2 = function (component, simulatedEvent, gridConfig, gridState) { return findCurrent(component, gridConfig).bind(function (focused) { return gridConfig.execute(component, simulatedEvent, focused); }); }; var doMove = function (cycle) { return function (element, focused, gridConfig, gridState) { return locateVisible(element, focused, gridConfig.selector).bind(function (identified) { return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns)); }); }; }; var handleTab = function (component, simulatedEvent, gridConfig, gridState) { return gridConfig.captureTab ? Option.some(true) : Option.none(); }; var doEscape = function (component, simulatedEvent, gridConfig, gridState) { return gridConfig.onEscape(component, simulatedEvent); }; var moveLeft = doMove(cycleLeft); var moveRight = doMove(cycleRight); var moveNorth = doMove(cycleUp); var moveSouth = doMove(cycleDown); var getKeydownRules$1 = constant([ rule(inSet(LEFT()), west$2(moveLeft, moveRight)), rule(inSet(RIGHT()), east$2(moveLeft, moveRight)), rule(inSet(UP()), north$2(moveNorth)), rule(inSet(DOWN()), south$2(moveSouth)), rule(and([ isShift, inSet(TAB()) ]), handleTab), rule(and([ isNotShift, inSet(TAB()) ]), handleTab), rule(inSet(ESCAPE()), doEscape), rule(inSet(SPACE().concat(ENTER())), execute$2) ]); var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]); var FlatgridType = typical(schema$5, flatgrid, getKeydownRules$1, getKeyupRules$1, function () { return Option.some(focusIn); }); var horizontal = function (container, selector, current, delta) { var isDisabledButton = function (candidate) { return name(candidate) === 'button' && get$2(candidate, 'disabled') === 'disabled'; }; var tryCycle = function (initial, index, candidates) { var newIndex = cycleBy(index, delta, 0, candidates.length - 1); if (newIndex === initial) { return Option.none(); } else { return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]); } }; return locateVisible(container, current, selector).bind(function (identified) { var index = identified.index(); var candidates = identified.candidates(); return tryCycle(index, index, candidates); }); }; var schema$6 = [ strict$1('selector'), defaulted$1('getInitial', Option.none), defaulted$1('execute', defaultExecute), onKeyboardHandler('onEscape'), defaulted$1('executeOnMove', false), defaulted$1('allowVertical', true) ]; var findCurrent$1 = function (component, flowConfig) { return flowConfig.focusManager.get(component).bind(function (elem) { return closest$3(elem, flowConfig.selector); }); }; var execute$3 = function (component, simulatedEvent, flowConfig) { return findCurrent$1(component, flowConfig).bind(function (focused) { return flowConfig.execute(component, simulatedEvent, focused); }); }; var focusIn$1 = function (component, flowConfig) { flowConfig.getInitial(component).orThunk(function () { return descendant$1(component.element(), flowConfig.selector); }).each(function (first) { flowConfig.focusManager.set(component, first); }); }; var moveLeft$1 = function (element, focused, info) { return horizontal(element, info.selector, focused, -1); }; var moveRight$1 = function (element, focused, info) { return horizontal(element, info.selector, focused, +1); }; var doMove$1 = function (movement) { return function (component, simulatedEvent, flowConfig) { return movement(component, simulatedEvent, flowConfig).bind(function () { return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true); }); }; }; var doEscape$1 = function (component, simulatedEvent, flowConfig, _flowState) { return flowConfig.onEscape(component, simulatedEvent); }; var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) { var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []); var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []); return [ rule(inSet(westMovers), doMove$1(west$2(moveLeft$1, moveRight$1))), rule(inSet(eastMovers), doMove$1(east$2(moveLeft$1, moveRight$1))), rule(inSet(ENTER()), execute$3), rule(inSet(SPACE()), execute$3), rule(inSet(ESCAPE()), doEscape$1) ]; }; var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]); var FlowType = typical(schema$6, NoState.init, getKeydownRules$2, getKeyupRules$2, function () { return Option.some(focusIn$1); }); var outcome = MixedBag([ 'rowIndex', 'columnIndex', 'cell' ], []); var toCell = function (matrix, rowIndex, columnIndex) { return Option.from(matrix[rowIndex]).bind(function (row) { return Option.from(row[columnIndex]).map(function (cell) { return outcome({ rowIndex: rowIndex, columnIndex: columnIndex, cell: cell }); }); }); }; var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) { var row = matrix[rowIndex]; var colsInRow = row.length; var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1); return toCell(matrix, rowIndex, newColIndex); }; var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) { var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1); var colsInNextRow = matrix[nextRowIndex].length; var nextColIndex = cap(colIndex, 0, colsInNextRow - 1); return toCell(matrix, nextRowIndex, nextColIndex); }; var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) { var row = matrix[rowIndex]; var colsInRow = row.length; var newColIndex = cap(startCol + deltaCol, 0, colsInRow - 1); return toCell(matrix, rowIndex, newColIndex); }; var moveVertical = function (matrix, colIndex, startRow, deltaRow) { var nextRowIndex = cap(startRow + deltaRow, 0, matrix.length - 1); var colsInNextRow = matrix[nextRowIndex].length; var nextColIndex = cap(colIndex, 0, colsInNextRow - 1); return toCell(matrix, nextRowIndex, nextColIndex); }; var cycleRight$1 = function (matrix, startRow, startCol) { return cycleHorizontal$1(matrix, startRow, startCol, +1); }; var cycleLeft$1 = function (matrix, startRow, startCol) { return cycleHorizontal$1(matrix, startRow, startCol, -1); }; var cycleUp$1 = function (matrix, startRow, startCol) { return cycleVertical$1(matrix, startCol, startRow, -1); }; var cycleDown$1 = function (matrix, startRow, startCol) { return cycleVertical$1(matrix, startCol, startRow, +1); }; var moveLeft$2 = function (matrix, startRow, startCol) { return moveHorizontal(matrix, startRow, startCol, -1); }; var moveRight$2 = function (matrix, startRow, startCol) { return moveHorizontal(matrix, startRow, startCol, +1); }; var moveUp = function (matrix, startRow, startCol) { return moveVertical(matrix, startCol, startRow, -1); }; var moveDown = function (matrix, startRow, startCol) { return moveVertical(matrix, startCol, startRow, +1); }; var schema$7 = [ strictObjOf('selectors', [ strict$1('row'), strict$1('cell') ]), defaulted$1('cycles', true), defaulted$1('previousSelector', Option.none), defaulted$1('execute', defaultExecute) ]; var focusIn$2 = function (component, matrixConfig) { var focused = matrixConfig.previousSelector(component).orThunk(function () { var selectors = matrixConfig.selectors; return descendant$1(component.element(), selectors.cell); }); focused.each(function (cell) { matrixConfig.focusManager.set(component, cell); }); }; var execute$4 = function (component, simulatedEvent, matrixConfig) { return search(component.element()).bind(function (focused) { return matrixConfig.execute(component, simulatedEvent, focused); }); }; var toMatrix = function (rows, matrixConfig) { return map(rows, function (row) { return descendants(row, matrixConfig.selectors.cell); }); }; var doMove$2 = function (ifCycle, ifMove) { return function (element, focused, matrixConfig) { var move = matrixConfig.cycles ? ifCycle : ifMove; return closest$3(focused, matrixConfig.selectors.row).bind(function (inRow) { var cellsInRow = descendants(inRow, matrixConfig.selectors.cell); return findIndex$1(cellsInRow, focused).bind(function (colIndex) { var allRows = descendants(element, matrixConfig.selectors.row); return findIndex$1(allRows, inRow).bind(function (rowIndex) { var matrix = toMatrix(allRows, matrixConfig); return move(matrix, rowIndex, colIndex).map(function (next) { return next.cell(); }); }); }); }); }; }; var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2); var moveRight$3 = doMove$2(cycleRight$1, moveRight$2); var moveNorth$1 = doMove$2(cycleUp$1, moveUp); var moveSouth$1 = doMove$2(cycleDown$1, moveDown); var getKeydownRules$3 = constant([ rule(inSet(LEFT()), west$2(moveLeft$3, moveRight$3)), rule(inSet(RIGHT()), east$2(moveLeft$3, moveRight$3)), rule(inSet(UP()), north$2(moveNorth$1)), rule(inSet(DOWN()), south$2(moveSouth$1)), rule(inSet(SPACE().concat(ENTER())), execute$4) ]); var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]); var MatrixType = typical(schema$7, NoState.init, getKeydownRules$3, getKeyupRules$3, function () { return Option.some(focusIn$2); }); var schema$8 = [ strict$1('selector'), defaulted$1('execute', defaultExecute), defaulted$1('moveOnTab', false) ]; var execute$5 = function (component, simulatedEvent, menuConfig) { return menuConfig.focusManager.get(component).bind(function (focused) { return menuConfig.execute(component, simulatedEvent, focused); }); }; var focusIn$3 = function (component, menuConfig) { descendant$1(component.element(), menuConfig.selector).each(function (first) { menuConfig.focusManager.set(component, first); }); }; var moveUp$1 = function (element, focused, info) { return horizontal(element, info.selector, focused, -1); }; var moveDown$1 = function (element, focused, info) { return horizontal(element, info.selector, focused, +1); }; var fireShiftTab = function (component, simulatedEvent, menuConfig) { return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig) : Option.none(); }; var fireTab = function (component, simulatedEvent, menuConfig) { return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig) : Option.none(); }; var getKeydownRules$4 = constant([ rule(inSet(UP()), move(moveUp$1)), rule(inSet(DOWN()), move(moveDown$1)), rule(and([ isShift, inSet(TAB()) ]), fireShiftTab), rule(and([ isNotShift, inSet(TAB()) ]), fireTab), rule(inSet(ENTER()), execute$5), rule(inSet(SPACE()), execute$5) ]); var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]); var MenuType = typical(schema$8, NoState.init, getKeydownRules$4, getKeyupRules$4, function () { return Option.some(focusIn$3); }); var schema$9 = [ onKeyboardHandler('onSpace'), onKeyboardHandler('onEnter'), onKeyboardHandler('onShiftEnter'), onKeyboardHandler('onLeft'), onKeyboardHandler('onRight'), onKeyboardHandler('onTab'), onKeyboardHandler('onShiftTab'), onKeyboardHandler('onUp'), onKeyboardHandler('onDown'), onKeyboardHandler('onEscape'), defaulted$1('stopSpaceKeyup', false), option('focusIn') ]; var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) { return [ rule(inSet(SPACE()), specialInfo.onSpace), rule(and([ isNotShift, inSet(ENTER()) ]), specialInfo.onEnter), rule(and([ isShift, inSet(ENTER()) ]), specialInfo.onShiftEnter), rule(and([ isShift, inSet(TAB()) ]), specialInfo.onShiftTab), rule(and([ isNotShift, inSet(TAB()) ]), specialInfo.onTab), rule(inSet(UP()), specialInfo.onUp), rule(inSet(DOWN()), specialInfo.onDown), rule(inSet(LEFT()), specialInfo.onLeft), rule(inSet(RIGHT()), specialInfo.onRight), rule(inSet(SPACE()), specialInfo.onSpace), rule(inSet(ESCAPE()), specialInfo.onEscape) ]; }; var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) { return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : []; }; var SpecialType = typical(schema$9, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) { return specialInfo.focusIn; }); var acyclic = AcyclicType.schema(); var cyclic = CyclicType.schema(); var flow = FlowType.schema(); var flatgrid$1 = FlatgridType.schema(); var matrix = MatrixType.schema(); var execution = ExecutionType.schema(); var menu = MenuType.schema(); var special = SpecialType.schema(); var KeyboardBranches = /*#__PURE__*/Object.freeze({ acyclic: acyclic, cyclic: cyclic, flow: flow, flatgrid: flatgrid$1, matrix: matrix, execution: execution, menu: menu, special: special }); var Keying = createModes$1({ branchKey: 'mode', branches: KeyboardBranches, name: 'keying', active: { events: function (keyingConfig, keyingState) { var handler = keyingConfig.handler; return handler.toEvents(keyingConfig, keyingState); } }, apis: { focusIn: function (component, keyConfig, keyState) { keyConfig.sendFocusIn(keyConfig).fold(function () { component.getSystem().triggerFocus(component.element(), component.element()); }, function (sendFocusIn) { sendFocusIn(component, keyConfig, keyState); }); }, setGridSize: function (component, keyConfig, keyState, numRows, numColumns) { if (!hasKey$1(keyState, 'setGridSize')) { domGlobals.console.error('Layout does not support setGridSize'); } else { keyState.setGridSize(numRows, numColumns); } } }, state: KeyingState }); var set$5 = function (component, replaceConfig, replaceState, data) { preserve(function () { var newChildren = map(data, component.getSystem().build); replaceChildren(component, newChildren); }, component.element()); }; var insert = function (component, replaceConfig, insertion, childSpec) { var child = component.getSystem().build(childSpec); attachWith(component, child, insertion); }; var append$2 = function (component, replaceConfig, replaceState, appendee) { insert(component, replaceConfig, append, appendee); }; var prepend$1 = function (component, replaceConfig, replaceState, prependee) { insert(component, replaceConfig, prepend, prependee); }; var remove$7 = function (component, replaceConfig, replaceState, removee) { var children = contents(component); var foundChild = find(children, function (child) { return eq(removee.element(), child.element()); }); foundChild.each(detach); }; var contents = function (component, replaceConfig) { return component.components(); }; var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) { var children = contents(component); return Option.from(children[replaceeIndex]).map(function (replacee) { remove$7(component, replaceConfig, replaceState, replacee); replacer.each(function (r) { insert(component, replaceConfig, function (p, c) { appendAt(p, c, replaceeIndex); }, r); }); return replacee; }); }; var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) { var children = contents(component); return findIndex(children, replaceePred).bind(function (replaceeIndex) { return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer); }); }; var ReplaceApis = /*#__PURE__*/Object.freeze({ append: append$2, prepend: prepend$1, remove: remove$7, replaceAt: replaceAt, replaceBy: replaceBy, set: set$5, contents: contents }); var Replacing = create$1({ fields: [], name: 'replacing', apis: ReplaceApis }); var events$4 = function (name, eventHandlers) { var events = derive(eventHandlers); return create$1({ fields: [strict$1('enabled')], name: name, active: { events: constant(events) } }); }; var config = function (name, eventHandlers) { var me = events$4(name, eventHandlers); return { key: name, value: { config: {}, me: me, configAsRaw: constant({}), initialConfig: {}, state: NoState } }; }; var focus$2 = function (component, focusConfig) { if (!focusConfig.ignore) { focus$1(component.element()); focusConfig.onFocus(component); } }; var blur$1 = function (component, focusConfig) { if (!focusConfig.ignore) { blur(component.element()); } }; var isFocused = function (component) { return hasFocus(component.element()); }; var FocusApis = /*#__PURE__*/Object.freeze({ focus: focus$2, blur: blur$1, isFocused: isFocused }); var exhibit$1 = function (base, focusConfig) { var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } }; return nu$6(mod); }; var events$5 = function (focusConfig) { return derive([run(focus(), function (component, simulatedEvent) { focus$2(component, focusConfig); simulatedEvent.stop(); })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) { simulatedEvent.event().prevent(); })] : [])); }; var ActiveFocus = /*#__PURE__*/Object.freeze({ exhibit: exhibit$1, events: events$5 }); var FocusSchema = [ onHandler('onFocus'), defaulted$1('stopMousedown', false), defaulted$1('ignore', false) ]; var Focusing = create$1({ fields: FocusSchema, name: 'focusing', active: ActiveFocus, apis: FocusApis }); var updateAriaState = function (component, toggleConfig, toggleState) { var ariaInfo = toggleConfig.aria; ariaInfo.update(component, ariaInfo, toggleState.get()); }; var updateClass = function (component, toggleConfig, toggleState) { toggleConfig.toggleClass.each(function (toggleClass) { if (toggleState.get()) { add$2(component.element(), toggleClass); } else { remove$4(component.element(), toggleClass); } }); }; var toggle = function (component, toggleConfig, toggleState) { set$6(component, toggleConfig, toggleState, !toggleState.get()); }; var on$1 = function (component, toggleConfig, toggleState) { toggleState.set(true); updateClass(component, toggleConfig, toggleState); updateAriaState(component, toggleConfig, toggleState); }; var off = function (component, toggleConfig, toggleState) { toggleState.set(false); updateClass(component, toggleConfig, toggleState); updateAriaState(component, toggleConfig, toggleState); }; var set$6 = function (component, toggleConfig, toggleState, state) { var action = state ? on$1 : off; action(component, toggleConfig, toggleState); }; var isOn = function (component, toggleConfig, toggleState) { return toggleState.get(); }; var onLoad$4 = function (component, toggleConfig, toggleState) { set$6(component, toggleConfig, toggleState, toggleConfig.selected); }; var ToggleApis = /*#__PURE__*/Object.freeze({ onLoad: onLoad$4, toggle: toggle, isOn: isOn, on: on$1, off: off, set: set$6 }); var exhibit$2 = function (base, toggleConfig, toggleState) { return nu$6({}); }; var events$6 = function (toggleConfig, toggleState) { var execute = executeEvent(toggleConfig, toggleState, toggle); var load = loadEvent(toggleConfig, toggleState, onLoad$4); return derive(flatten([ toggleConfig.toggleOnExecute ? [execute] : [], [load] ])); }; var ActiveToggle = /*#__PURE__*/Object.freeze({ exhibit: exhibit$2, events: events$6 }); var SetupBehaviourCellState = function (initialState) { var init = function () { var cell = Cell(initialState); var get = function () { return cell.get(); }; var set = function (newState) { return cell.set(newState); }; var clear = function () { return cell.set(initialState); }; var readState = function () { return cell.get(); }; return { get: get, set: set, clear: clear, readState: readState }; }; return { init: init }; }; var updatePressed = function (component, ariaInfo, status) { set$1(component.element(), 'aria-pressed', status); if (ariaInfo.syncWithExpanded) { updateExpanded(component, ariaInfo, status); } }; var updateSelected = function (component, ariaInfo, status) { set$1(component.element(), 'aria-selected', status); }; var updateChecked = function (component, ariaInfo, status) { set$1(component.element(), 'aria-checked', status); }; var updateExpanded = function (component, ariaInfo, status) { set$1(component.element(), 'aria-expanded', status); }; var ToggleSchema = [ defaulted$1('selected', false), option('toggleClass'), defaulted$1('toggleOnExecute', true), defaultedOf('aria', { mode: 'none' }, choose$1('mode', { pressed: [ defaulted$1('syncWithExpanded', false), output('update', updatePressed) ], checked: [output('update', updateChecked)], expanded: [output('update', updateExpanded)], selected: [output('update', updateSelected)], none: [output('update', noop)] })) ]; var Toggling = create$1({ fields: ToggleSchema, name: 'toggling', active: ActiveToggle, apis: ToggleApis, state: SetupBehaviourCellState(false) }); var hoverEvent = 'alloy.item-hover'; var focusEvent = 'alloy.item-focus'; var onHover = function (item) { if (search(item.element()).isNone() || Focusing.isFocused(item)) { if (!Focusing.isFocused(item)) { Focusing.focus(item); } emitWith(item, hoverEvent, { item: item }); } }; var onFocus = function (item) { emitWith(item, focusEvent, { item: item }); }; var hover = constant(hoverEvent); var focus$3 = constant(focusEvent); var builder = function (detail) { return { dom: detail.dom, 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 } : {}) }), behaviours: SketchBehaviours.augment(detail.itemBehaviours, [ detail.toggling.fold(Toggling.revoke, function (tConfig) { return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig)); }), Focusing.config({ ignore: detail.ignoreFocus, stopMousedown: detail.ignoreFocus, onFocus: function (component) { onFocus(component); } }), Keying.config({ mode: 'execution' }), Representing.config({ store: { mode: 'memory', initialValue: detail.data } }), config('item-type-events', [ run(tapOrClick(), emitExecute), cutter(mousedown()), run(mouseover(), onHover), run(focusItem(), Focusing.focus) ]) ]), components: detail.components, eventOrder: detail.eventOrder }; }; var schema$a = [ strict$1('data'), strict$1('components'), strict$1('dom'), defaulted$1('hasSubmenu', false), option('toggling'), SketchBehaviours.field('itemBehaviours', [ Toggling, Focusing, Keying, Representing ]), defaulted$1('ignoreFocus', false), defaulted$1('domModification', {}), output('builder', builder), defaulted$1('eventOrder', {}) ]; var builder$1 = function (detail) { return { dom: detail.dom, components: detail.components, events: derive([stopper(focusItem())]) }; }; var schema$b = [ strict$1('dom'), strict$1('components'), output('builder', builder$1) ]; var owner$2 = function () { return 'item-widget'; }; var parts = constant([required({ name: 'widget', overrides: function (detail) { return { behaviours: derive$1([Representing.config({ store: { mode: 'manual', getValue: function (component) { return detail.data; }, setValue: function () { } } })]) }; } })]); var builder$2 = function (detail) { var subs = substitutes(owner$2(), detail, parts()); var components$1 = components(owner$2(), detail, subs.internals()); var focusWidget = function (component) { return getPart(component, detail, 'widget').map(function (widget) { Keying.focusIn(widget); return widget; }); }; var onHorizontalArrow = function (component, simulatedEvent) { return inside(simulatedEvent.event().target()) ? Option.none() : function () { if (detail.autofocus) { simulatedEvent.setSource(component.element()); return Option.none(); } else { return Option.none(); } }(); }; return { dom: detail.dom, components: components$1, domModification: detail.domModification, events: derive([ runOnExecute(function (component, simulatedEvent) { focusWidget(component).each(function (widget) { simulatedEvent.stop(); }); }), run(mouseover(), onHover), run(focusItem(), function (component, simulatedEvent) { if (detail.autofocus) { focusWidget(component); } else { Focusing.focus(component); } }) ]), behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [ Representing.config({ store: { mode: 'memory', initialValue: detail.data } }), Focusing.config({ ignore: detail.ignoreFocus, onFocus: function (component) { onFocus(component); } }), Keying.config({ mode: 'special', focusIn: detail.autofocus ? function (component) { focusWidget(component); } : revoke(), onLeft: onHorizontalArrow, onRight: onHorizontalArrow, onEscape: function (component, simulatedEvent) { if (!Focusing.isFocused(component) && !detail.autofocus) { Focusing.focus(component); return Option.some(true); } else if (detail.autofocus) { simulatedEvent.setSource(component.element()); return Option.none(); } else { return Option.none(); } } }) ]) }; }; var schema$c = [ strict$1('uid'), strict$1('data'), strict$1('components'), strict$1('dom'), defaulted$1('autofocus', false), defaulted$1('ignoreFocus', false), SketchBehaviours.field('widgetBehaviours', [ Representing, Focusing, Keying ]), defaulted$1('domModification', {}), defaultUidsSchema(parts()), output('builder', builder$2) ]; var itemSchema$1 = choose$1('type', { widget: schema$c, item: schema$a, separator: schema$b }); var configureGrid = function (detail, movementInfo) { return { mode: 'flatgrid', selector: '.' + detail.markers.item, initSize: { numColumns: movementInfo.initSize.numColumns, numRows: movementInfo.initSize.numRows }, focusManager: detail.focusManager }; }; var configureMatrix = function (detail, movementInfo) { return { mode: 'matrix', selectors: { row: movementInfo.rowSelector, cell: '.' + detail.markers.item }, focusManager: detail.focusManager }; }; var configureMenu = function (detail, movementInfo) { return { mode: 'menu', selector: '.' + detail.markers.item, moveOnTab: movementInfo.moveOnTab, focusManager: detail.focusManager }; }; var parts$1 = constant([group({ factory: { sketch: function (spec) { var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec); return itemInfo.builder(itemInfo); } }, name: 'items', unit: 'item', defaults: function (detail, u) { return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') }); }, overrides: function (detail, u) { return { type: u.type, ignoreFocus: detail.fakeFocus, domModification: { classes: [detail.markers.item] } }; } })]); var schema$d = constant([ strict$1('value'), strict$1('items'), strict$1('dom'), strict$1('components'), defaulted$1('eventOrder', {}), field$1('menuBehaviours', [ Highlighting, Representing, Composing, Keying ]), defaultedOf('movement', { mode: 'menu', moveOnTab: true }, choose$1('mode', { grid: [ initSize(), output('config', configureGrid) ], matrix: [ output('config', configureMatrix), strict$1('rowSelector') ], menu: [ defaulted$1('moveOnTab', true), output('config', configureMenu) ] })), itemMarkers(), defaulted$1('fakeFocus', false), defaulted$1('focusManager', dom()), onHandler('onHighlight') ]); var focus$4 = constant('alloy.menu-focus'); var make$1 = function (detail, components, spec, externals) { return { uid: detail.uid, dom: detail.dom, markers: detail.markers, behaviours: augment(detail.menuBehaviours, [ Highlighting.config({ highlightClass: detail.markers.selectedItem, itemClass: detail.markers.item, onHighlight: detail.onHighlight }), Representing.config({ store: { mode: 'memory', initialValue: detail.value } }), Composing.config({ find: Option.some }), Keying.config(detail.movement.config(detail, detail.movement)) ]), events: derive([ run(focus$3(), function (menu, simulatedEvent) { var event = simulatedEvent.event(); menu.getSystem().getByDom(event.target()).each(function (item) { Highlighting.highlight(menu, item); simulatedEvent.stop(); emitWith(menu, focus$4(), { menu: menu, item: item }); }); }), run(hover(), function (menu, simulatedEvent) { var item = simulatedEvent.event().item(); Highlighting.highlight(menu, item); }) ]), components: components, eventOrder: detail.eventOrder, domModification: { attributes: { role: 'menu' } } }; }; var Menu = composite$1({ name: 'Menu', configFields: schema$d(), partFields: parts$1(), factory: make$1 }); var transpose = function (obj) { return tupleMap(obj, function (v, k) { return { k: v, v: k }; }); }; var trace = function (items, byItem, byMenu, finish) { return readOptFrom$1(byMenu, finish).bind(function (triggerItem) { return readOptFrom$1(items, triggerItem).bind(function (triggerMenu) { var rest = trace(items, byItem, byMenu, triggerMenu); return Option.some([triggerMenu].concat(rest)); }); }).getOr([]); }; var generate$5 = function (menus, expansions) { var items = {}; each$1(menus, function (menuItems, menu) { each(menuItems, function (item) { items[item] = menu; }); }); var byItem = expansions; var byMenu = transpose(expansions); var menuPaths = map$1(byMenu, function (_triggerItem, submenu) { return [submenu].concat(trace(items, byItem, byMenu, submenu)); }); return map$1(items, function (menu) { return readOptFrom$1(menuPaths, menu).getOr([menu]); }); }; var init$3 = function () { var expansions = Cell({}); var menus = Cell({}); var paths = Cell({}); var primary = Cell(Option.none()); var directory = Cell({}); var clear = function () { expansions.set({}); menus.set({}); paths.set({}); primary.set(Option.none()); }; var isClear = function () { return primary.get().isNone(); }; var setMenuBuilt = function (menuName, built) { var _a; menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = { type: 'prepared', menu: built }, _a))); }; var setContents = function (sPrimary, sMenus, sExpansions, dir) { primary.set(Option.some(sPrimary)); expansions.set(sExpansions); menus.set(sMenus); directory.set(dir); var sPaths = generate$5(dir, sExpansions); paths.set(sPaths); }; var getTriggeringItem = function (menuValue) { return find$1(expansions.get(), function (v, k) { return v === menuValue; }); }; var getTriggerData = function (menuValue, getItemByValue, path) { return getPreparedMenu(menuValue).bind(function (menu) { return getTriggeringItem(menuValue).bind(function (triggeringItemValue) { return getItemByValue(triggeringItemValue).map(function (triggeredItem) { return { triggeredMenu: menu, triggeringItem: triggeredItem, triggeringPath: path }; }); }); }); }; var getTriggeringPath = function (itemValue, getItemByValue) { var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) { return getPreparedMenu(menuValue).isSome(); }); return readOptFrom$1(paths.get(), itemValue).bind(function (path) { var revPath = reverse(extraPath.concat(path)); var triggers = bind(revPath, function (menuValue, menuIndex) { return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () { return primary.get().is(menuValue) ? [] : [Option.none()]; }, function (data) { return [Option.some(data)]; }); }); return sequence(triggers); }); }; var expand = function (itemValue) { return readOptFrom$1(expansions.get(), itemValue).map(function (menu) { var current = readOptFrom$1(paths.get(), itemValue).getOr([]); return [menu].concat(current); }); }; var collapse = function (itemValue) { return readOptFrom$1(paths.get(), itemValue).bind(function (path) { return path.length > 1 ? Option.some(path.slice(1)) : Option.none(); }); }; var refresh = function (itemValue) { return readOptFrom$1(paths.get(), itemValue); }; var getPreparedMenu = function (menuValue) { return lookupMenu(menuValue).bind(extractPreparedMenu); }; var lookupMenu = function (menuValue) { return readOptFrom$1(menus.get(), menuValue); }; var lookupItem = function (itemValue) { return readOptFrom$1(expansions.get(), itemValue); }; var otherMenus = function (path) { var menuValues = directory.get(); return difference(keys(menuValues), path); }; var getPrimary = function () { return primary.get().bind(getPreparedMenu); }; var getMenus = function () { return menus.get(); }; return { setMenuBuilt: setMenuBuilt, setContents: setContents, expand: expand, refresh: refresh, collapse: collapse, lookupMenu: lookupMenu, lookupItem: lookupItem, otherMenus: otherMenus, getPrimary: getPrimary, getMenus: getMenus, clear: clear, isClear: isClear, getTriggeringPath: getTriggeringPath }; }; var extractPreparedMenu = function (prep) { return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none(); }; var LayeredState = { init: init$3, extractPreparedMenu: extractPreparedMenu }; var make$2 = function (detail, rawUiSpec) { var submenuParentItems = Cell(Option.none()); var buildMenus = function (container, primaryName, menus) { return map$1(menus, function (spec, name) { var makeSketch = function () { return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), { value: name, items: spec.items, markers: detail.markers, fakeFocus: detail.fakeFocus, onHighlight: detail.onHighlight, focusManager: detail.fakeFocus ? highlights() : dom() })); }; return name === primaryName ? { type: 'prepared', menu: container.getSystem().build(makeSketch()) } : { type: 'notbuilt', nbMenu: makeSketch }; }); }; var layeredState = LayeredState.init(); var setup = function (container) { var componentMap = buildMenus(container, detail.data.primary, detail.data.menus); var directory = toDirectory(); layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory); return layeredState.getPrimary(); }; var getItemValue = function (item) { return Representing.getValue(item).value; }; var getItemByValue = function (container, menus, itemValue) { return findMap(menus, function (menu) { if (!menu.getSystem().isConnected()) { return Option.none(); } var candidates = Highlighting.getCandidates(menu); return find(candidates, function (c) { return getItemValue(c) === itemValue; }); }); }; var toDirectory = function (container) { return map$1(detail.data.menus, function (data, menuName) { return bind(data.items, function (item) { return item.type === 'separator' ? [] : [item.data.value]; }); }); }; var setActiveMenu = function (container, menu) { Highlighting.highlight(container, menu); Highlighting.getHighlighted(menu).orThunk(function () { return Highlighting.getFirst(menu); }).each(function (item) { dispatch(container, item.element(), focusItem()); }); }; var getMenus = function (state, menuValues) { return cat(map(menuValues, function (mv) { return state.lookupMenu(mv).bind(function (prep) { return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none(); }); })); }; var closeOthers = function (container, state, path) { var others = getMenus(state, state.otherMenus(path)); each(others, function (o) { remove$5(o.element(), [detail.markers.backgroundMenu]); if (!detail.stayInDom) { Replacing.remove(container, o); } }); }; var getSubmenuParents = function (container) { return submenuParentItems.get().getOrThunk(function () { var r = {}; var items = descendants(container.element(), '.' + detail.markers.item); var parentItems = filter(items, function (i) { return get$2(i, 'aria-haspopup') === 'true'; }); each(parentItems, function (i) { container.getSystem().getByDom(i).each(function (itemComp) { var key = getItemValue(itemComp); r[key] = itemComp; }); }); submenuParentItems.set(Option.some(r)); return r; }); }; var updateAriaExpansions = function (container, path) { var parentItems = getSubmenuParents(container); each$1(parentItems, function (v, k) { var expanded = contains(path, k); set$1(v.element(), 'aria-expanded', expanded); }); }; var updateMenuPath = function (container, state, path) { return Option.from(path[0]).bind(function (latestMenuName) { return state.lookupMenu(latestMenuName).bind(function (menuPrep) { if (menuPrep.type === 'notbuilt') { return Option.none(); } else { var activeMenu = menuPrep.menu; var rest = getMenus(state, path.slice(1)); each(rest, function (r) { add$2(r.element(), detail.markers.backgroundMenu); }); if (!inBody(activeMenu.element())) { Replacing.append(container, premade$1(activeMenu)); } remove$5(activeMenu.element(), [detail.markers.backgroundMenu]); setActiveMenu(container, activeMenu); closeOthers(container, state, path); return Option.some(activeMenu); } }); }); }; var ExpandHighlightDecision; (function (ExpandHighlightDecision) { ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu'; ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent'; }(ExpandHighlightDecision || (ExpandHighlightDecision = {}))); var buildIfRequired = function (container, menuName, menuPrep) { if (menuPrep.type === 'notbuilt') { var menu = container.getSystem().build(menuPrep.nbMenu()); layeredState.setMenuBuilt(menuName, menu); return menu; } else { return menuPrep.menu; } }; var expandRight = function (container, item, decision) { if (decision === void 0) { decision = ExpandHighlightDecision.HighlightSubmenu; } var value = getItemValue(item); return layeredState.expand(value).bind(function (path) { updateAriaExpansions(container, path); return Option.from(path[0]).bind(function (menuName) { return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) { var activeMenu = buildIfRequired(container, menuName, activeMenuPrep); if (!inBody(activeMenu.element())) { Replacing.append(container, premade$1(activeMenu)); } detail.onOpenSubmenu(container, item, activeMenu, reverse(path)); if (decision === ExpandHighlightDecision.HighlightSubmenu) { Highlighting.highlightFirst(activeMenu); return updateMenuPath(container, layeredState, path); } else { Highlighting.dehighlightAll(activeMenu); return Option.some(item); } }); }); }); }; var collapseLeft = function (container, item) { var value = getItemValue(item); return layeredState.collapse(value).bind(function (path) { updateAriaExpansions(container, path); return updateMenuPath(container, layeredState, path).map(function (activeMenu) { detail.onCollapseMenu(container, item, activeMenu); return activeMenu; }); }); }; var updateView = function (container, item) { var value = getItemValue(item); return layeredState.refresh(value).bind(function (path) { updateAriaExpansions(container, path); return updateMenuPath(container, layeredState, path); }); }; var onRight = function (container, item) { return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu); }; var onLeft = function (container, item) { return inside(item.element()) ? Option.none() : collapseLeft(container, item); }; var onEscape = function (container, item) { return collapseLeft(container, item).orThunk(function () { return detail.onEscape(container, item).map(function () { return container; }); }); }; var keyOnItem = function (f) { return function (container, simulatedEvent) { return closest$3(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) { return container.getSystem().getByDom(target).toOption().bind(function (item) { return f(container, item).map(function () { return true; }); }); }); }; }; var events = derive([ run(focus$4(), function (sandbox, simulatedEvent) { var item = simulatedEvent.event().item(); layeredState.lookupItem(getItemValue(item)).each(function () { var menu = simulatedEvent.event().menu(); Highlighting.highlight(sandbox, menu); var value = getItemValue(simulatedEvent.event().item()); layeredState.refresh(value).each(function (path) { return closeOthers(sandbox, layeredState, path); }); }); }), runOnExecute(function (component, simulatedEvent) { var target = simulatedEvent.event().target(); component.getSystem().getByDom(target).each(function (item) { var itemValue = getItemValue(item); if (itemValue.indexOf('collapse-item') === 0) { collapseLeft(component, item); } expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () { detail.onExecute(component, item); }, function () { }); }); }), runOnAttached(function (container, simulatedEvent) { setup(container).each(function (primary) { Replacing.append(container, premade$1(primary)); detail.onOpenMenu(container, primary); if (detail.highlightImmediately) { setActiveMenu(container, primary); } }); }) ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) { var item = simulatedEvent.event().item(); updateView(sandbox, item); expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent); detail.onHover(sandbox, item); })] : [])); var getActiveItem = function (container) { return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted); }; var collapseMenuApi = function (container) { getActiveItem(container).each(function (currentItem) { collapseLeft(container, currentItem); }); }; var highlightPrimary = function (container) { layeredState.getPrimary().each(function (primary) { setActiveMenu(container, primary); }); }; var extractMenuFromContainer = function (container) { return Option.from(container.components()[0]).filter(function (comp) { return get$2(comp.element(), 'role') === 'menu'; }); }; var repositionMenus = function (container) { var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) { return getActiveItem(container).bind(function (currentItem) { var itemValue = getItemValue(currentItem); var allMenus = values(layeredState.getMenus()); var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu)); return layeredState.getTriggeringPath(itemValue, function (v) { return getItemByValue(container, preparedMenus, v); }); }).map(function (triggeringPath) { return { primary: primary, triggeringPath: triggeringPath }; }); }); maybeActivePrimary.fold(function () { extractMenuFromContainer(container).each(function (primaryMenu) { detail.onRepositionMenu(container, primaryMenu, []); }); }, function (_a) { var primary = _a.primary, triggeringPath = _a.triggeringPath; detail.onRepositionMenu(container, primary, triggeringPath); }); }; var apis = { collapseMenu: collapseMenuApi, highlightPrimary: highlightPrimary, repositionMenus: repositionMenus }; return { uid: detail.uid, dom: detail.dom, markers: detail.markers, behaviours: augment(detail.tmenuBehaviours, [ Keying.config({ mode: 'special', onRight: keyOnItem(onRight), onLeft: keyOnItem(onLeft), onEscape: keyOnItem(onEscape), focusIn: function (container, keyInfo) { layeredState.getPrimary().each(function (primary) { dispatch(container, primary.element(), focusItem()); }); } }), Highlighting.config({ highlightClass: detail.markers.selectedMenu, itemClass: detail.markers.menu }), Composing.config({ find: function (container) { return Highlighting.getHighlighted(container); } }), Replacing.config({}) ]), eventOrder: detail.eventOrder, apis: apis, events: events }; }; var collapseItem = constant('collapse-item'); var tieredData = function (primary, menus, expansions) { return { primary: primary, menus: menus, expansions: expansions }; }; var singleData = function (name, menu) { return { primary: name, menus: wrap$1(name, menu), expansions: {} }; }; var collapseItem$1 = function (text) { return { value: generate$1(collapseItem()), meta: { text: text } }; }; var tieredMenu = single$2({ name: 'TieredMenu', configFields: [ onStrictKeyboardHandler('onExecute'), onStrictKeyboardHandler('onEscape'), onStrictHandler('onOpenMenu'), onStrictHandler('onOpenSubmenu'), onStrictHandler('onRepositionMenu'), onHandler('onCollapseMenu'), defaulted$1('highlightImmediately', true), strictObjOf('data', [ strict$1('primary'), strict$1('menus'), strict$1('expansions') ]), defaulted$1('fakeFocus', false), onHandler('onHighlight'), onHandler('onHover'), tieredMenuMarkers(), strict$1('dom'), defaulted$1('navigateOnHover', true), defaulted$1('stayInDom', false), field$1('tmenuBehaviours', [ Keying, Highlighting, Composing, Replacing ]), defaulted$1('eventOrder', {}) ], apis: { collapseMenu: function (apis, tmenu) { apis.collapseMenu(tmenu); }, highlightPrimary: function (apis, tmenu) { apis.highlightPrimary(tmenu); }, repositionMenus: function (apis, tmenu) { apis.repositionMenus(tmenu); } }, factory: make$2, extraApis: { tieredData: tieredData, singleData: singleData, collapseItem: collapseItem$1 } }); var makeMenu = function (detail, menuSandbox, anchor, menuSpec, getBounds) { var lazySink = function () { return detail.lazySink(menuSandbox); }; var layouts = menuSpec.type === 'horizontal' ? { layouts: { onLtr: function () { return belowOrAbove(); }, onRtl: function () { return belowOrAboveRtl(); } } } : {}; var isFirstTierSubmenu = function (triggeringPaths) { return triggeringPaths.length === 2; }; var getSubmenuLayouts = function (triggeringPaths) { return isFirstTierSubmenu(triggeringPaths) ? layouts : {}; }; return tieredMenu.sketch({ dom: { tag: 'div' }, data: menuSpec.data, markers: menuSpec.menu.markers, onEscape: function () { Sandboxing.close(menuSandbox); detail.onEscape.map(function (handler) { return handler(menuSandbox); }); return Option.some(true); }, onExecute: function () { return Option.some(true); }, onOpenMenu: function (tmenu, menu) { Positioning.positionWithinBounds(lazySink().getOrDie(), anchor, menu, getBounds()); }, onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) { var sink = lazySink().getOrDie(); Positioning.position(sink, __assign({ anchor: 'submenu', item: item }, getSubmenuLayouts(triggeringPaths)), submenu); }, onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) { var sink = lazySink().getOrDie(); Positioning.positionWithinBounds(sink, anchor, primaryMenu, getBounds()); each(submenuTriggers, function (st) { var submenuLayouts = getSubmenuLayouts(st.triggeringPath); Positioning.position(sink, __assign({ anchor: 'submenu', item: st.triggeringItem }, submenuLayouts), st.triggeredMenu); }); } }); }; var factory = function (detail, spec) { var isPartOfRelated = function (sandbox, queryElem) { var related = detail.getRelated(sandbox); return related.exists(function (rel) { return isPartOf(rel, queryElem); }); }; var setContent = function (sandbox, thing) { Sandboxing.setContent(sandbox, thing); }; var showAt = function (sandbox, anchor, thing) { showWithin(sandbox, anchor, thing, Option.none()); }; var showWithin = function (sandbox, anchor, thing, boxElement) { showWithinBounds(sandbox, anchor, thing, function () { return boxElement.map(function (elem) { return box(elem); }); }); }; var showWithinBounds = function (sandbox, anchor, thing, getBounds) { var sink = detail.lazySink(sandbox).getOrDie(); Sandboxing.openWhileCloaked(sandbox, thing, function () { return Positioning.positionWithinBounds(sink, anchor, sandbox, getBounds()); }); Representing.setValue(sandbox, Option.some({ mode: 'position', anchor: anchor, getBounds: getBounds })); }; var showMenuAt = function (sandbox, anchor, menuSpec) { showMenuWithinBounds(sandbox, anchor, menuSpec, function () { return Option.none(); }); }; var showMenuWithinBounds = function (sandbox, anchor, menuSpec, getBounds) { var menu = makeMenu(detail, sandbox, anchor, menuSpec, getBounds); Sandboxing.open(sandbox, menu); Representing.setValue(sandbox, Option.some({ mode: 'menu', menu: menu })); }; var hide = function (sandbox) { Representing.setValue(sandbox, Option.none()); Sandboxing.close(sandbox); }; var getContent = function (sandbox) { return Sandboxing.getState(sandbox); }; var reposition = function (sandbox) { if (Sandboxing.isOpen(sandbox)) { Representing.getValue(sandbox).each(function (state) { switch (state.mode) { case 'menu': Sandboxing.getState(sandbox).each(function (tmenu) { tieredMenu.repositionMenus(tmenu); }); break; case 'position': var sink = detail.lazySink(sandbox).getOrDie(); Positioning.positionWithinBounds(sink, state.anchor, sandbox, state.getBounds()); break; } }); } }; var apis = { setContent: setContent, showAt: showAt, showWithin: showWithin, showWithinBounds: showWithinBounds, showMenuAt: showMenuAt, showMenuWithinBounds: showMenuWithinBounds, hide: hide, getContent: getContent, reposition: reposition, isOpen: Sandboxing.isOpen }; return { uid: detail.uid, dom: detail.dom, behaviours: augment(detail.inlineBehaviours, [ Sandboxing.config({ isPartOf: function (sandbox, data, queryElem) { return isPartOf(data, queryElem) || isPartOfRelated(sandbox, queryElem); }, getAttachPoint: function (sandbox) { return detail.lazySink(sandbox).getOrDie(); }, onOpen: function (sandbox) { detail.onShow(sandbox); }, onClose: function (sandbox) { detail.onHide(sandbox); } }), Representing.config({ store: { mode: 'memory', initialValue: Option.none() } }), Receiving.config({ channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: constant(false) }, detail.fireDismissalEventInstead.map(function (fe) { return { fireEventInstead: { event: fe.event } }; }).getOr({})))), receivingChannel$1(__assign(__assign({ isExtraPart: constant(false) }, detail.fireRepositionEventInstead.map(function (fe) { return { fireEventInstead: { event: fe.event } }; }).getOr({})), { doReposition: reposition }))) }) ]), eventOrder: detail.eventOrder, apis: apis }; }; var InlineView = single$2({ name: 'InlineView', configFields: [ strict$1('lazySink'), onHandler('onShow'), onHandler('onHide'), optionFunction('onEscape'), field$1('inlineBehaviours', [ Sandboxing, Representing, Receiving ]), optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]), optionObjOf('fireRepositionEventInstead', [defaulted$1('event', repositionRequested())]), defaulted$1('getRelated', Option.none), defaulted$1('eventOrder', Option.none) ], factory: factory, apis: { showAt: function (apis, component, anchor, thing) { apis.showAt(component, anchor, thing); }, showWithin: function (apis, component, anchor, thing, boxElement) { apis.showWithin(component, anchor, thing, boxElement); }, showWithinBounds: function (apis, component, anchor, thing, bounds) { apis.showWithinBounds(component, anchor, thing, bounds); }, showMenuAt: function (apis, component, anchor, menuSpec) { apis.showMenuAt(component, anchor, menuSpec); }, showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) { apis.showMenuWithinBounds(component, anchor, menuSpec, bounds); }, hide: function (apis, component) { apis.hide(component); }, isOpen: function (apis, component) { return apis.isOpen(component); }, getContent: function (apis, component) { return apis.getContent(component); }, setContent: function (apis, component, thing) { apis.setContent(component, thing); }, reposition: function (apis, component) { apis.reposition(component); } } }); var westEdgeX$1 = function (anchor) { return anchor.x(); }; var middleX$1 = function (anchor, element) { return anchor.x() + anchor.width() / 2 - element.width() / 2; }; var eastEdgeX$1 = function (anchor, element) { return anchor.x() + anchor.width() - element.width(); }; var northY$2 = function (anchor) { return anchor.y(); }; var southY$2 = function (anchor, element) { return anchor.y() + anchor.height() - element.height(); }; var southeast$3 = function (anchor, element, bubbles) { return nu$7(westEdgeX$1(anchor), southY$2(anchor, element), bubbles.innerSoutheast(), southeast(), 'layout-se'); }; var southwest$3 = function (anchor, element, bubbles) { return nu$7(eastEdgeX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouthwest(), southwest(), 'layout-sw'); }; var northeast$3 = function (anchor, element, bubbles) { return nu$7(westEdgeX$1(anchor), northY$2(anchor), bubbles.innerNortheast(), northeast(), 'layout-ne'); }; var northwest$3 = function (anchor, element, bubbles) { return nu$7(eastEdgeX$1(anchor, element), northY$2(anchor), bubbles.innerNorthwest(), northwest(), 'layout-nw'); }; var north$3 = function (anchor, element, bubbles) { return nu$7(middleX$1(anchor, element), northY$2(anchor), bubbles.innerNorth(), north(), 'layout-n'); }; var south$3 = function (anchor, element, bubbles) { return nu$7(middleX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouth(), south(), 'layout-s'); }; var events$7 = function (optAction) { var executeHandler = function (action) { return run(execute(), function (component, simulatedEvent) { action(component); simulatedEvent.stop(); }); }; var onClick = function (component, simulatedEvent) { simulatedEvent.stop(); emitExecute(component); }; var onMousedown = function (component, simulatedEvent) { simulatedEvent.cut(); }; var pointerEvents = detect$3().deviceType.isTouch() ? [run(tap(), onClick)] : [ run(click(), onClick), run(mousedown(), onMousedown) ]; return derive(flatten([ optAction.map(executeHandler).toArray(), pointerEvents ])); }; var factory$1 = function (detail) { var events = events$7(detail.action); var tag = detail.dom.tag; var lookupAttr = function (attr) { return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) { return readOptFrom$1(attrs, attr); }); }; var getModAttributes = function () { if (tag === 'button') { var type = lookupAttr('type').getOr('button'); var roleAttrs = lookupAttr('role').map(function (role) { return { role: role }; }).getOr({}); return __assign({ type: type }, roleAttrs); } else { var role = lookupAttr('role').getOr('button'); return { role: role }; } }; return { uid: detail.uid, dom: detail.dom, components: detail.components, events: events, behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [ Focusing.config({}), Keying.config({ mode: 'execution', useSpace: true, useEnter: true }) ]), domModification: { attributes: getModAttributes() }, eventOrder: detail.eventOrder }; }; var Button = single$2({ name: 'Button', factory: factory$1, configFields: [ defaulted$1('uid', undefined), strict$1('dom'), defaulted$1('components', []), SketchBehaviours.field('buttonBehaviours', [ Focusing, Keying ]), option('action'), option('role'), defaulted$1('eventOrder', {}) ] }); var record = function (spec) { var uid = isSketchSpec(spec) && hasKey$1(spec, 'uid') ? spec.uid : generate$2('memento'); var get = function (anyInSystem) { return anyInSystem.getSystem().getByUid(uid).getOrDie(); }; var getOpt = function (anyInSystem) { return anyInSystem.getSystem().getByUid(uid).toOption(); }; var asSpec = function () { return __assign(__assign({}, spec), { uid: uid }); }; return { get: get, getOpt: getOpt, asSpec: asSpec }; }; var defaultIcon = function (icons) { return Option.from(icons()['temporary-placeholder']).getOr('!not found!'); }; var get$c = function (name, icons) { return Option.from(icons()[name]).getOrThunk(function () { return defaultIcon(icons); }); }; var getOr = function (name, icons, fallback) { return Option.from(icons()[name]).or(fallback).getOrThunk(function () { return defaultIcon(icons); }); }; var getFirst$1 = function (names, icons) { return findMap(names, function (name) { return Option.from(icons()[name]); }).getOrThunk(function () { return defaultIcon(icons); }); }; var notificationIconMap = { success: 'checkmark', error: 'warning', err: 'error', warning: 'warning', warn: 'warning', info: 'info' }; var factory$2 = function (detail) { var memBannerText = record({ dom: { tag: 'p', innerHtml: detail.translationProvider(detail.text) }, behaviours: derive$1([Replacing.config({})]) }); var renderPercentBar = function (percent) { return { dom: { tag: 'div', classes: ['tox-bar'], attributes: { style: 'width: ' + percent + '%' } } }; }; var renderPercentText = function (percent) { return { dom: { tag: 'div', classes: ['tox-text'], innerHtml: percent + '%' } }; }; var memBannerProgress = record({ dom: { tag: 'div', classes: detail.progress ? [ 'tox-progress-bar', 'tox-progress-indicator' ] : ['tox-progress-bar'] }, components: [ { dom: { tag: 'div', classes: ['tox-bar-container'] }, components: [renderPercentBar(0)] }, renderPercentText(0) ], behaviours: derive$1([Replacing.config({})]) }); var updateProgress = function (comp, percent) { if (comp.getSystem().isConnected()) { memBannerProgress.getOpt(comp).each(function (progress) { Replacing.set(progress, [ { dom: { tag: 'div', classes: ['tox-bar-container'] }, components: [renderPercentBar(percent)] }, renderPercentText(percent) ]); }); } }; var updateText = function (comp, text$1) { if (comp.getSystem().isConnected()) { var banner = memBannerText.get(comp); Replacing.set(banner, [text(text$1)]); } }; var apis = { updateProgress: updateProgress, updateText: updateText }; var iconChoices = flatten([ detail.icon.toArray(), detail.level.toArray(), detail.level.bind(function (level) { return Option.from(notificationIconMap[level]); }).toArray() ]); return { uid: detail.uid, dom: { tag: 'div', attributes: { role: 'alert' }, classes: detail.level.map(function (level) { return [ 'tox-notification', 'tox-notification--in', 'tox-notification--' + level ]; }).getOr([ 'tox-notification', 'tox-notification--in' ]) }, components: [ { dom: { tag: 'div', classes: ['tox-notification__icon'], innerHtml: getFirst$1(iconChoices, detail.iconProvider) } }, { dom: { tag: 'div', classes: ['tox-notification__body'] }, components: [memBannerText.asSpec()], behaviours: derive$1([Replacing.config({})]) } ].concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(Button.sketch({ dom: { tag: 'button', classes: [ 'tox-notification__dismiss', 'tox-button', 'tox-button--naked', 'tox-button--icon' ] }, components: [{ dom: { tag: 'div', classes: ['tox-icon'], innerHtml: get$c('close', detail.iconProvider), attributes: { 'aria-label': detail.translationProvider('Close') } } }], action: function (comp) { detail.onAction(comp); } })), apis: apis }; }; var Notification = single$2({ name: 'Notification', factory: factory$2, configFields: [ option('level'), strict$1('progress'), strict$1('icon'), strict$1('onAction'), strict$1('text'), strict$1('iconProvider'), strict$1('translationProvider') ], apis: { updateProgress: function (apis, comp, percent) { apis.updateProgress(comp, percent); }, updateText: function (apis, comp, text) { apis.updateText(comp, text); } } }); var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay'); function NotificationManagerImpl (editor, extras, uiMothership) { var backstage = extras.backstage; var getLayoutDirection = function (rel) { switch (rel) { case 'bc-bc': return south$3; case 'tc-tc': return north$3; case 'tc-bc': return north$1; case 'bc-tc': default: return south$1; } }; var prePositionNotifications = function (notifications) { each(notifications, function (notification) { return notification.moveTo(0, 0); }); }; var positionNotifications = function (notifications) { if (notifications.length > 0) { head(notifications).each(function (firstItem) { return firstItem.moveRel(null, 'banner'); }); each(notifications, function (notification, index) { if (index > 0) { notification.moveRel(notifications[index - 1].getEl(), 'bc-tc'); } }); } }; var reposition = function (notifications) { prePositionNotifications(notifications); positionNotifications(notifications); }; var open = function (settings, closeCallback) { var close = function () { closeCallback(); InlineView.hide(notificationWrapper); }; var notification = build$1(Notification.sketch({ text: settings.text, level: contains([ 'success', 'error', 'warning', 'warn', 'info' ], settings.type) ? settings.type : undefined, progress: settings.progressBar === true, icon: Option.from(settings.icon), onAction: close, iconProvider: backstage.shared.providers.icons, translationProvider: backstage.shared.providers.translate })); var notificationWrapper = build$1(InlineView.sketch({ dom: { tag: 'div', classes: ['tox-notifications-container'] }, lazySink: extras.backstage.shared.getSink, fireDismissalEventInstead: {} })); uiMothership.add(notificationWrapper); if (settings.timeout > 0) { global$2.setTimeout(function () { close(); }, settings.timeout); } return { close: close, moveTo: function (x, y) { InlineView.showAt(notificationWrapper, { anchor: 'makeshift', x: x, y: y }, premade$1(notification)); }, moveRel: function (element, rel) { if (rel !== 'banner') { var layoutDirection_1 = getLayoutDirection(rel); var nodeAnchor = { anchor: 'node', root: body(), node: Option.some(Element.fromDom(element)), layouts: { onRtl: function () { return [layoutDirection_1]; }, onLtr: function () { return [layoutDirection_1]; } } }; InlineView.showAt(notificationWrapper, nodeAnchor, premade$1(notification)); } else { InlineView.showAt(notificationWrapper, extras.backstage.shared.anchors.banner(), premade$1(notification)); } }, text: function (nuText) { Notification.updateText(notification, nuText); }, settings: settings, getEl: function () { return notification.element().dom(); }, progressBar: { value: function (percent) { Notification.updateProgress(notification, percent); } } }; }; var close = function (notification) { notification.close(); }; var getArgs = function (notification) { return notification.settings; }; return { open: open, close: close, reposition: reposition, getArgs: getArgs }; } var first$1 = function (fn, rate) { var timer = null; var cancel = function () { if (timer !== null) { domGlobals.clearTimeout(timer); timer = null; } }; var throttle = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (timer === null) { timer = domGlobals.setTimeout(function () { fn.apply(null, args); timer = null; }, rate); } }; return { cancel: cancel, throttle: throttle }; }; var last$2 = function (fn, rate) { var timer = null; var cancel = function () { if (timer !== null) { domGlobals.clearTimeout(timer); timer = null; } }; var throttle = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } if (timer !== null) { domGlobals.clearTimeout(timer); } timer = domGlobals.setTimeout(function () { fn.apply(null, args); timer = null; }, rate); }; return { cancel: cancel, throttle: throttle }; }; var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker'); var isText$1 = function (node) { return node.nodeType === domGlobals.Node.TEXT_NODE; }; var isBoundary = function (dom, node) { return dom.isBlock(node) || contains([ 'BR', 'IMG', 'HR', 'INPUT' ], node.nodeName) || dom.getContentEditable(node) === 'false'; }; var outcome$1 = Adt.generate([ { aborted: [] }, { edge: ['element'] }, { success: ['info'] } ]); var phase = Adt.generate([ { abort: [] }, { kontinue: [] }, { finish: ['info'] } ]); var repeat = function (dom, node, offset, process, walker, recent) { var terminate = function () { return recent.fold(outcome$1.aborted, outcome$1.edge); }; var recurse = function () { var next = walker(); if (next) { return repeat(dom, next, Option.none(), process, walker, Option.some(node)); } else { return terminate(); } }; if (isBoundary(dom, node)) { return terminate(); } else if (!isText$1(node)) { return recurse(); } else { var text = node.textContent; return process(phase, node, text, offset).fold(outcome$1.aborted, function () { return recurse(); }, outcome$1.success); } }; var repeatLeft = function (dom, node, offset, process, rootNode) { var walker = new global$3(node, rootNode || dom.getRoot()); return repeat(dom, node, Option.some(offset), process, walker.prev, Option.none()); }; var autocompleteSelector = '[data-mce-autocompleter]'; var create$4 = function (editor, range) { return detect$4(Element.fromDom(editor.selection.getNode())).getOrThunk(function () { var wrapper = Element.fromHtml('', editor.getDoc()); append(wrapper, Element.fromDom(range.extractContents())); range.insertNode(wrapper.dom()); parent(wrapper).each(function (elm) { return elm.dom().normalize(); }); last$1(wrapper).map(function (last) { editor.selection.setCursorLocation(last.dom(), getEnd(last)); }); return wrapper; }); }; var detect$4 = function (elm) { return closest$3(elm, autocompleteSelector); }; var isValidTextRange = function (rng) { return rng.collapsed && rng.startContainer.nodeType === 3; }; var whiteSpace = /[\u00a0 \t\r\n]/; var parse = function (text, index, ch, minChars) { var i; for (i = index - 1; i >= 0; i--) { var char = text.charAt(i); if (whiteSpace.test(char)) { return Option.none(); } if (char === ch) { break; } } if (i === -1 || index - i < minChars) { return Option.none(); } return Option.some(text.substring(i + 1, index)); }; var getText = function (rng, ch) { var text = rng.toString().substring(ch.length); return text.replace(/\u00A0/g, ' ').replace(/\uFEFF/g, ''); }; var findStart = function (dom, initRange, ch, minChars) { if (minChars === void 0) { minChars = 0; } if (!isValidTextRange(initRange)) { return Option.none(); } var findTriggerCh = function (phase, element, text, optOffset) { var index = optOffset.getOr(text.length); return parse(text, index, ch, 1).fold(function () { return text.match(whiteSpace) ? phase.abort() : phase.kontinue(); }, function (newText) { var range = initRange.cloneRange(); range.setStart(element, index - newText.length - 1); range.setEnd(initRange.endContainer, initRange.endOffset); return text.length < minChars ? phase.abort() : phase.finish({ text: getText(range, ch), range: range, triggerChar: ch }); }); }; return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerCh).fold(Option.none, Option.none, Option.some); }; var getContext = function (dom, initRange, ch, minChars) { if (minChars === void 0) { minChars = 0; } return detect$4(Element.fromDom(initRange.startContainer)).fold(function () { return findStart(dom, initRange, ch, minChars); }, function (elm) { var range = dom.createRng(); range.selectNode(elm.dom()); return Option.some({ range: range, text: getText(range, ch), triggerChar: ch }); }); }; var setup = function (api, editor) { editor.on('keypress compositionend', api.onKeypress.throttle); editor.on('remove', api.onKeypress.cancel); var redirectKeyToItem = function (item, e) { emitWith(item, keydown(), { raw: e }); }; editor.on('keydown', function (e) { var getItem = function () { return api.getView().bind(Highlighting.getHighlighted); }; if (e.which === 8) { api.onKeypress.throttle(e); } if (api.isActive()) { if (e.which === 27) { api.cancelIfNecessary(); } if (api.isMenuOpen()) { if (e.which === 13) { getItem().each(emitExecute); e.preventDefault(); } else if (e.which === 40) { getItem().fold(function () { api.getView().each(Highlighting.highlightFirst); }, function (item) { redirectKeyToItem(item, e); }); e.preventDefault(); e.stopImmediatePropagation(); } else if (e.which === 37 || e.which === 38 || e.which === 39) { getItem().each(function (item) { redirectKeyToItem(item, e); e.preventDefault(); e.stopImmediatePropagation(); }); } } else { if (e.which === 13 || e.which === 38 || e.which === 40) { api.cancelIfNecessary(); } } } }); editor.on('NodeChange', function (e) { if (api.isActive() && !api.isProcessingAction() && detect$4(Element.fromDom(e.element)).isNone()) { api.cancelIfNecessary(); } }); }; var AutocompleterEditorEvents = { setup: setup }; var global$4 = tinymce.util.Tools.resolve('tinymce.util.Promise'); var point$2 = function (element, offset) { return { element: element, offset: offset }; }; var isText$2 = function (node) { return node.nodeType === domGlobals.Node.TEXT_NODE; }; var isElement$1 = function (node) { return node.nodeType === domGlobals.Node.ELEMENT_NODE; }; var toLast = function (node) { if (isText$2(node)) { return point$2(node, node.data.length); } else { var children = node.childNodes; return children.length > 0 ? toLast(children[children.length - 1]) : point$2(node, children.length); } }; var toLeaf = function (node, offset) { var children = node.childNodes; if (children.length > 0 && offset < children.length) { return toLeaf(children[offset], 0); } else if (children.length > 0 && isElement$1(node) && children.length === offset) { return toLast(children[children.length - 1]); } else { return point$2(node, offset); } }; var isStartOfWord = function (dom) { var process = function (phase, element, text, optOffset) { var index = optOffset.getOr(text.length); return index === 0 ? phase.kontinue() : phase.finish(/\s/.test(text.charAt(index - 1))); }; return function (rng) { var leaf = toLeaf(rng.startContainer, rng.startOffset); return repeatLeft(dom, leaf.element, leaf.offset, process).fold(constant(true), constant(true), identity); }; }; var getTriggerContext = function (dom, initRange, database) { return findMap(database.triggerChars, function (ch) { return getContext(dom, initRange, ch); }); }; var lookup = function (editor, getDatabase) { var database = getDatabase(); var rng = editor.selection.getRng(); return getTriggerContext(editor.dom, rng, database).bind(function (context) { return lookupWithContext(editor, getDatabase, context); }); }; var lookupWithContext = function (editor, getDatabase, context, fetchOptions) { if (fetchOptions === void 0) { fetchOptions = {}; } var database = getDatabase(); var rng = editor.selection.getRng(); var startText = rng.startContainer.nodeValue; var autocompleters = filter(database.lookupByChar(context.triggerChar), function (autocompleter) { return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () { return isStartOfWord(editor.dom); })(context.range, startText, context.text); }); if (autocompleters.length === 0) { return Option.none(); } var lookupData = global$4.all(map(autocompleters, function (ac) { var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions); return fetchResult.then(function (results) { return { matchText: context.text, items: results, columns: ac.columns, onAction: ac.onAction }; }); })); return Option.some({ lookupData: lookupData, context: context }); }; var separatorMenuItemSchema = objOf([ strictString('type'), optionString('text') ]); var createSeparatorMenuItem = function (spec) { return asRaw('separatormenuitem', separatorMenuItemSchema, spec); }; var autocompleterItemSchema = objOf([ state$1('type', function () { return 'autocompleteitem'; }), state$1('active', function () { return false; }), state$1('disabled', function () { return false; }), defaulted$1('meta', {}), strictString('value'), optionString('text'), optionString('icon') ]); var autocompleterSchema = objOf([ strictString('type'), strictString('ch'), defaultedNumber('minChars', 1), defaulted$1('columns', 1), defaultedNumber('maxResults', 10), optionFunction('matches'), strictFunction('fetch'), strictFunction('onAction') ]); var createSeparatorItem = function (spec) { return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec); }; var createAutocompleterItem = function (spec) { return asRaw('Autocompleter.Item', autocompleterItemSchema, spec); }; var createAutocompleter = function (spec) { return asRaw('Autocompleter', autocompleterSchema, spec); }; var stringArray = function (a) { var all = {}; each(a, function (key) { all[key] = {}; }); return keys(all); }; var register = function (editor) { var popups = editor.ui.registry.getAll().popups; var dataset = map$1(popups, function (popup) { return createAutocompleter(popup).fold(function (err) { throw new Error(formatError(err)); }, function (x) { return x; }); }); var triggerChars = stringArray(mapToArray(dataset, function (v) { return v.ch; })); var datasetValues = values(dataset); var lookupByChar = function (ch) { return filter(datasetValues, function (dv) { return dv.ch === ch; }); }; return { dataset: dataset, triggerChars: triggerChars, lookupByChar: lookupByChar }; }; var commonMenuItemFields = [ defaultedBoolean('disabled', false), optionString('text'), optionString('shortcut'), field('value', 'value', defaultedThunk(function () { return generate$1('menuitem-value'); }), anyValue$1()), defaulted$1('meta', {}) ]; var menuItemSchema = objOf([ strictString('type'), defaultedFunction('onSetup', function () { return noop; }), defaultedFunction('onAction', noop), optionString('icon') ].concat(commonMenuItemFields)); var createMenuItem = function (spec) { return asRaw('menuitem', menuItemSchema, spec); }; var nestedMenuItemSchema = objOf([ strictString('type'), strictFunction('getSubmenuItems'), defaultedFunction('onSetup', function () { return noop; }), optionString('icon') ].concat(commonMenuItemFields)); var createNestedMenuItem = function (spec) { return asRaw('nestedmenuitem', nestedMenuItemSchema, spec); }; var toggleMenuItemSchema = objOf([ strictString('type'), defaultedBoolean('active', false), defaultedFunction('onSetup', function () { return noop; }), strictFunction('onAction') ].concat(commonMenuItemFields)); var createToggleMenuItem = function (spec) { return asRaw('togglemenuitem', toggleMenuItemSchema, spec); }; var choiceMenuItemSchema = objOf([ strictString('type'), defaultedBoolean('active', false), optionString('icon') ].concat(commonMenuItemFields)); var createChoiceMenuItem = function (spec) { return asRaw('choicemenuitem', choiceMenuItemSchema, spec); }; var fancyTypes = [ 'inserttable', 'colorswatch' ]; var fancyMenuItemSchema = objOf([ strictString('type'), strictStringEnum('fancytype', fancyTypes), defaultedFunction('onAction', noop) ]); var createFancyMenuItem = function (spec) { return asRaw('fancymenuitem', fancyMenuItemSchema, spec); }; var detectSize = function (comp, margin, selectorClass) { var descendants$1 = descendants(comp.element(), '.' + selectorClass); if (descendants$1.length > 0) { var columnLength = findIndex(descendants$1, function (c) { var thisTop = c.dom().getBoundingClientRect().top; var cTop = descendants$1[0].dom().getBoundingClientRect().top; return Math.abs(thisTop - cTop) > margin; }).getOr(descendants$1.length); return Option.some({ numColumns: columnLength, numRows: Math.ceil(descendants$1.length / columnLength) }); } else { return Option.none(); } }; var namedEvents = function (name, handlers) { return derive$1([config(name, handlers)]); }; var unnamedEvents = function (handlers) { return namedEvents(generate$1('unnamed-events'), handlers); }; var SimpleBehaviours = { namedEvents: namedEvents, unnamedEvents: unnamedEvents }; var TooltippingSchema = [ strict$1('lazySink'), strict$1('tooltipDom'), defaulted$1('exclusive', true), defaulted$1('tooltipComponents', []), defaulted$1('delay', 300), defaultedStringEnum('mode', 'normal', [ 'normal', 'follow-highlight' ]), defaulted$1('anchor', function (comp) { return { anchor: 'hotspot', hotspot: comp, layouts: { onLtr: constant([ south$1, north$1, southeast$1, northeast$1, southwest$1, northwest$1 ]), onRtl: constant([ south$1, north$1, southeast$1, northeast$1, southwest$1, northwest$1 ]) } }; }), onHandler('onHide'), onHandler('onShow') ]; var init$4 = function () { var timer = Cell(Option.none()); var popup = Cell(Option.none()); var getTooltip = function () { return popup.get(); }; var setTooltip = function (s) { popup.set(Option.some(s)); }; var clearTooltip = function () { popup.set(Option.none()); }; var clearTimer = function () { timer.get().each(function (t) { domGlobals.clearTimeout(t); }); }; var resetTimer = function (f, delay) { clearTimer(); timer.set(Option.some(domGlobals.setTimeout(function () { f(); }, delay))); }; var isShowing = function () { return popup.get().isSome(); }; var readState = constant('not-implemented'); return nu$5({ getTooltip: getTooltip, isShowing: isShowing, setTooltip: setTooltip, clearTooltip: clearTooltip, clearTimer: clearTimer, resetTimer: resetTimer, readState: readState }); }; var TooltippingState = /*#__PURE__*/Object.freeze({ init: init$4 }); var ExclusivityChannel = generate$1('tooltip.exclusive'); var ShowTooltipEvent = generate$1('tooltip.show'); var HideTooltipEvent = generate$1('tooltip.hide'); var hideAllExclusive = function (component, tConfig, tState) { component.getSystem().broadcastOn([ExclusivityChannel], {}); }; var setComponents = function (component, tConfig, tState, specs) { tState.getTooltip().each(function (tooltip) { if (tooltip.getSystem().isConnected()) { Replacing.set(tooltip, specs); } }); }; var TooltippingApis = /*#__PURE__*/Object.freeze({ hideAllExclusive: hideAllExclusive, setComponents: setComponents }); var events$8 = function (tooltipConfig, state) { var hide = function (comp) { state.getTooltip().each(function (p) { detach(p); tooltipConfig.onHide(comp, p); state.clearTooltip(); }); state.clearTimer(); }; var show = function (comp) { if (!state.isShowing()) { hideAllExclusive(comp); var sink = tooltipConfig.lazySink(comp).getOrDie(); var popup = comp.getSystem().build({ dom: tooltipConfig.tooltipDom, components: tooltipConfig.tooltipComponents, events: derive(tooltipConfig.mode === 'normal' ? [ run(mouseover(), function (_) { emit(comp, ShowTooltipEvent); }), run(mouseout(), function (_) { emit(comp, HideTooltipEvent); }) ] : []), behaviours: derive$1([Replacing.config({})]) }); state.setTooltip(popup); attach$1(sink, popup); tooltipConfig.onShow(comp, popup); Positioning.position(sink, tooltipConfig.anchor(comp), popup); } }; return derive(flatten([ [ run(ShowTooltipEvent, function (comp) { state.resetTimer(function () { show(comp); }, tooltipConfig.delay); }), run(HideTooltipEvent, function (comp) { state.resetTimer(function () { hide(comp); }, tooltipConfig.delay); }), run(receive(), function (comp, message) { var receivingData = message; if (contains(receivingData.channels(), ExclusivityChannel)) { hide(comp); } }), runOnDetached(function (comp) { hide(comp); }) ], tooltipConfig.mode === 'normal' ? [ run(focusin(), function (comp) { emit(comp, ShowTooltipEvent); }), run(postBlur(), function (comp) { emit(comp, HideTooltipEvent); }), run(mouseover(), function (comp) { emit(comp, ShowTooltipEvent); }), run(mouseout(), function (comp) { emit(comp, HideTooltipEvent); }) ] : [ run(highlight(), function (comp, se) { emit(comp, ShowTooltipEvent); }), run(dehighlight(), function (comp) { emit(comp, HideTooltipEvent); }) ] ])); }; var ActiveTooltipping = /*#__PURE__*/Object.freeze({ events: events$8 }); var Tooltipping = create$1({ fields: TooltippingSchema, name: 'tooltipping', active: ActiveTooltipping, state: TooltippingState, apis: TooltippingApis }); var getAttrs = function (elem) { var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : []; return foldl(attributes, function (b, attr) { var _a; if (attr.name === 'class') { return b; } else { return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a)); } }, {}); }; var getClasses = function (elem) { return Array.prototype.slice.call(elem.dom().classList, 0); }; var fromHtml$2 = function (html) { var elem = Element.fromHtml(html); var children$1 = children(elem); var attrs = getAttrs(elem); var classes = getClasses(elem); var contents = children$1.length === 0 ? {} : { innerHtml: get$1(elem) }; return __assign({ tag: name(elem), classes: classes, attributes: attrs }, contents); }; var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n'); var navClass = 'tox-menu-nav__js'; var selectableClass = 'tox-collection__item'; var colorClass = 'tox-swatch'; var presetClasses = { normal: navClass, color: colorClass }; var tickedClass = 'tox-collection__item--enabled'; var groupHeadingClass = 'tox-collection__group-heading'; var iconClass = 'tox-collection__item-icon'; var textClass = 'tox-collection__item-label'; var accessoryClass = 'tox-collection__item-accessory'; var caretClass = 'tox-collection__item-caret'; var checkmarkClass = 'tox-collection__item-checkmark'; var activeClass = 'tox-collection__item--active'; var iconClassRtl = 'tox-collection__item-icon-rtl'; var classForPreset = function (presets) { return readOptFrom$1(presetClasses, presets).getOr(navClass); }; var global$6 = tinymce.util.Tools.resolve('tinymce.Env'); var convertText = function (source) { var mac = { alt: '⌥', ctrl: '⌃', shift: '⇧', meta: '⌘', access: '⌃⌥' }; var other = { meta: 'Ctrl', access: 'Shift+Alt' }; var replace = global$6.mac ? mac : other; var shortcut = source.split('+'); var updated = map(shortcut, function (segment) { var search = segment.toLowerCase().trim(); return has(replace, search) ? replace[search] : segment; }); return global$6.mac ? updated.join('') : updated.join('+'); }; var ConvertShortcut = { convertText: convertText }; var renderIcon = function (iconHtml) { return { dom: { tag: 'div', classes: [iconClass], innerHtml: iconHtml } }; }; var renderText = function (text$1) { return { dom: { tag: 'div', classes: [textClass] }, components: [text(global$5.translate(text$1))] }; }; var renderHtml = function (html) { return { dom: { tag: 'div', classes: [textClass], innerHtml: html } }; }; var renderStyledText = function (style, text$1) { return { dom: { tag: 'div', classes: [textClass] }, components: [{ dom: { tag: style.tag, attributes: { style: style.styleAttr } }, components: [text(global$5.translate(text$1))] }] }; }; var renderShortcut = function (shortcut) { return { dom: { tag: 'div', classes: [accessoryClass], innerHtml: ConvertShortcut.convertText(shortcut) } }; }; var renderCheckmark = function (icons) { return { dom: { tag: 'div', classes: [ iconClass, checkmarkClass ], innerHtml: get$c('checkmark', icons) } }; }; var renderSubmenuCaret = function (icons) { return { dom: { tag: 'div', classes: [caretClass], innerHtml: get$c('chevron-right', icons) } }; }; var renderDownwardsCaret = function (icons) { return { dom: { tag: 'div', classes: [caretClass], innerHtml: get$c('chevron-down', icons) } }; }; var renderColorStructure = function (itemText, itemValue, iconSvg, providerBackstage) { var colorPickerCommand = 'custom'; var removeColorCommand = 'remove'; var getDom = function () { var common = colorClass; var icon = iconSvg.getOr(''); var title = itemText.map(function (text) { return ' title="' + providerBackstage.translate(text) + '"'; }).getOr(''); if (itemValue === colorPickerCommand) { return fromHtml$2(''); } else if (itemValue === removeColorCommand) { return fromHtml$2('
' + icon + '
'); } else { return fromHtml$2('
'); } }; return { dom: getDom(), optComponents: [] }; }; var renderNormalItemStructure = function (info, icon, renderIcons, textRender, rtlClass) { var leftIcon = renderIcons ? info.checkMark.orThunk(function () { return icon.or(Option.some('')).map(renderIcon); }) : Option.none(); var domTitle = info.ariaLabel.map(function (label) { return { attributes: { title: global$5.translate(label) } }; }).getOr({}); var dom = merge({ tag: 'div', classes: [ navClass, selectableClass ].concat(rtlClass ? [iconClassRtl] : []) }, domTitle); var content = info.htmlContent.fold(function () { return info.textContent.map(textRender); }, function (html) { return Option.some(renderHtml(html)); }); var menuItem = { dom: dom, optComponents: [ leftIcon, content, info.shortcutContent.map(renderShortcut), info.caret ] }; return menuItem; }; var rtlIcon = [ 'list-num-default', 'list-num-lower-alpha', 'list-num-lower-greek', 'list-num-lower-roman', 'list-num-upper-alpha', 'list-num-upper-roman' ]; var rtlTransform = [ 'list-bull-circle', 'list-bull-default', 'list-bull-square' ]; var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) { if (fallbackIcon === void 0) { fallbackIcon = Option.none(); } var getIconName = function (iconName) { return iconName.map(function (name) { return global$5.isRtl() && contains(rtlIcon, name) ? name + '-rtl' : name; }); }; var needRtlClass = global$5.isRtl() && info.iconContent.exists(function (name) { return contains(rtlTransform, name); }); var icon = getIconName(info.iconContent).map(function (iconName) { return getOr(iconName, providersBackstage.icons, fallbackIcon); }); var textRender = Option.from(info.meta).fold(function () { return renderText; }, function (meta) { return has(meta, 'style') ? curry(renderStyledText, meta.style) : renderText; }); if (info.presets === 'color') { return renderColorStructure(info.ariaLabel, info.value, icon, providersBackstage); } else { return renderNormalItemStructure(info, icon, renderIcons, textRender, needRtlClass); } }; var nativeDisabled = [ 'input', 'button', 'textarea', 'select' ]; var onLoad$5 = function (component, disableConfig, disableState) { if (disableConfig.disabled) { disable(component, disableConfig); } }; var hasNative = function (component, config) { return config.useNative === true && contains(nativeDisabled, name(component.element())); }; var nativeIsDisabled = function (component) { return has$1(component.element(), 'disabled'); }; var nativeDisable = function (component) { set$1(component.element(), 'disabled', 'disabled'); }; var nativeEnable = function (component) { remove$1(component.element(), 'disabled'); }; var ariaIsDisabled = function (component) { return get$2(component.element(), 'aria-disabled') === 'true'; }; var ariaDisable = function (component) { set$1(component.element(), 'aria-disabled', 'true'); }; var ariaEnable = function (component) { set$1(component.element(), 'aria-disabled', 'false'); }; var disable = function (component, disableConfig, disableState) { disableConfig.disableClass.each(function (disableClass) { add$2(component.element(), disableClass); }); var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable; f(component); disableConfig.onDisabled(component); }; var enable = function (component, disableConfig, disableState) { disableConfig.disableClass.each(function (disableClass) { remove$4(component.element(), disableClass); }); var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable; f(component); disableConfig.onEnabled(component); }; var isDisabled = function (component, disableConfig) { return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component); }; var set$7 = function (component, disableConfig, disableState, disabled) { var f = disabled ? disable : enable; f(component, disableConfig, disableState); }; var DisableApis = /*#__PURE__*/Object.freeze({ enable: enable, disable: disable, isDisabled: isDisabled, onLoad: onLoad$5, set: set$7 }); var exhibit$3 = function (base, disableConfig, disableState) { return nu$6({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] }); }; var events$9 = function (disableConfig, disableState) { return derive([ abort(execute(), function (component, simulatedEvent) { return isDisabled(component, disableConfig); }), loadEvent(disableConfig, disableState, onLoad$5) ]); }; var ActiveDisable = /*#__PURE__*/Object.freeze({ exhibit: exhibit$3, events: events$9 }); var DisableSchema = [ defaulted$1('disabled', false), defaulted$1('useNative', true), option('disableClass'), onHandler('onDisabled'), onHandler('onEnabled') ]; var Disabling = create$1({ fields: DisableSchema, name: 'disabling', active: ActiveDisable, apis: DisableApis }); var item = function (disabled) { return Disabling.config({ disabled: disabled, disableClass: 'tox-collection__item--state-disabled' }); }; var button = function (disabled) { return Disabling.config({ disabled: disabled }); }; var splitButton = function (disabled) { return Disabling.config({ disabled: disabled, disableClass: 'tox-tbtn--disabled' }); }; var toolbarButton = function (disabled) { return Disabling.config({ disabled: disabled, disableClass: 'tox-tbtn--disabled', useNative: false }); }; var DisablingConfigs = { item: item, button: button, splitButton: splitButton, toolbarButton: toolbarButton }; var runWithApi = function (info, comp) { var api = info.getApi(comp); return function (f) { f(api); }; }; var onControlAttached = function (info, editorOffCell) { return runOnAttached(function (comp) { var run = runWithApi(info, comp); run(function (api) { var onDestroy = info.onSetup(api); if (onDestroy !== null && onDestroy !== undefined) { editorOffCell.set(onDestroy); } }); }); }; var onControlDetached = function (getApi, editorOffCell) { return runOnDetached(function (comp) { return runWithApi(getApi, comp)(editorOffCell.get()); }); }; var ItemResponse; (function (ItemResponse) { ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE'; ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX'; }(ItemResponse || (ItemResponse = {}))); var ItemResponse$1 = ItemResponse; var onMenuItemExecute = function (info, itemResponse) { return runOnExecute(function (comp, simulatedEvent) { runWithApi(info, comp)(info.onAction); if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) { emit(comp, sandboxClose()); simulatedEvent.stop(); } }); }; var menuItemEventOrder = { 'alloy.execute': [ 'disabling', 'alloy.base.behaviour', 'toggling', 'item-events' ] }; var componentRenderPipeline = function (xs) { return bind(xs, function (o) { return o.toArray(); }); }; var renderCommonItem = function (spec, structure, itemResponse) { var editorOffCell = Cell(noop); return { type: 'item', dom: structure.dom, components: componentRenderPipeline(structure.optComponents), data: spec.data, eventOrder: menuItemEventOrder, hasSubmenu: spec.triggersSubmenu, itemBehaviours: derive$1([ config('item-events', [ onMenuItemExecute(spec, itemResponse), onControlAttached(spec, editorOffCell), onControlDetached(spec, editorOffCell) ]), DisablingConfigs.item(spec.disabled), Replacing.config({}) ].concat(spec.itemBehaviours)) }; }; var buildData = function (source) { return { value: source.value, meta: merge({ text: source.text.getOr('') }, source.meta) }; }; var global$7 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var tooltipBehaviour = function (meta, sharedBackstage) { return get(meta, 'tooltipWorker').map(function (tooltipWorker) { return [Tooltipping.config({ lazySink: sharedBackstage.getSink, tooltipDom: { tag: 'div', classes: ['tox-tooltip-worker-container'] }, tooltipComponents: [], anchor: function (comp) { return { anchor: 'submenu', item: comp, overrides: { maxHeightFunction: expandable } }; }, mode: 'follow-highlight', onShow: function (component, _tooltip) { tooltipWorker(function (elm) { Tooltipping.setComponents(component, [external({ element: Element.fromDom(elm) })]); }); } })]; }).getOr([]); }; var escapeRegExp = function (text) { return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }; var encodeText = function (text) { return global$7.DOM.encode(text); }; var replaceText = function (text, matchText) { var translated = global$5.translate(text); var encoded = encodeText(translated); if (matchText.length > 0) { var escapedMatchRegex = new RegExp(escapeRegExp(matchText), 'gi'); return encoded.replace(escapedMatchRegex, function (match) { return '' + match + ''; }); } else { return encoded; } }; var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) { if (renderIcons === void 0) { renderIcons = true; } var structure = renderItemStructure({ presets: presets, textContent: Option.none(), htmlContent: useText ? spec.text.map(function (text) { return replaceText(text, matchText); }) : Option.none(), ariaLabel: spec.text, iconContent: spec.icon, shortcutContent: Option.none(), checkMark: Option.none(), caret: Option.none(), value: spec.value }, sharedBackstage.providers, renderIcons, spec.icon); return renderCommonItem({ data: buildData(spec), disabled: spec.disabled, getApi: function () { return {}; }, onAction: function (_api) { return onItemValueHandler(spec.value, spec.meta); }, onSetup: function () { return function () { }; }, triggersSubmenu: false, itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage) }, structure, itemResponse); }; var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage) { var getApi = function (component) { return { setActive: function (state) { Toggling.set(component, state); }, isActive: function () { return Toggling.isOn(component); }, isDisabled: function () { return Disabling.isDisabled(component); }, setDisabled: function (state) { return Disabling.set(component, state); } }; }; var structure = renderItemStructure({ presets: presets, textContent: useText ? spec.text : Option.none(), htmlContent: Option.none(), ariaLabel: spec.text, iconContent: spec.icon, shortcutContent: useText ? spec.shortcut : Option.none(), checkMark: useText ? Option.some(renderCheckmark(providersBackstage.icons)) : Option.none(), caret: Option.none(), value: spec.value }, providersBackstage, true); return deepMerge(renderCommonItem({ data: buildData(spec), disabled: spec.disabled, getApi: getApi, onAction: function (_api) { return onItemValueHandler(spec.value); }, onSetup: function (api) { api.setActive(isSelected); return function () { }; }, triggersSubmenu: false, itemBehaviours: [] }, structure, itemResponse), { toggling: { toggleClass: tickedClass, toggleOnExecute: false, selected: spec.active } }); }; var parts$2 = constant(generate$4(owner$2(), parts())); var cellOverEvent = generate$1('cell-over'); var cellExecuteEvent = generate$1('cell-execute'); var makeCell = function (row, col, labelId) { var _a; var emitCellOver = function (c) { return emitWith(c, cellOverEvent, { row: row, col: col }); }; var emitExecute = function (c) { return emitWith(c, cellExecuteEvent, { row: row, col: col }); }; return build$1({ dom: { tag: 'div', attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a) }, behaviours: derive$1([ config('insert-table-picker-cell', [ run(mouseover(), Focusing.focus), run(execute(), emitExecute), run(tapOrClick(), emitExecute) ]), Toggling.config({ toggleClass: 'tox-insert-table-picker__selected', toggleOnExecute: false }), Focusing.config({ onFocus: emitCellOver }) ]) }); }; var makeCells = function (labelId, numRows, numCols) { var cells = []; for (var i = 0; i < numRows; i++) { var row = []; for (var j = 0; j < numCols; j++) { row.push(makeCell(i, j, labelId)); } cells.push(row); } return cells; }; var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) { for (var i = 0; i < numRows; i++) { for (var j = 0; j < numColumns; j++) { Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn); } } }; var makeComponents = function (cells) { return bind(cells, function (cellRow) { return map(cellRow, premade$1); }); }; var makeLabelText = function (row, col) { return text(col + 1 + 'x' + (row + 1)); }; function renderInsertTableMenuItem(spec) { var numRows = 10; var numColumns = 10; var sizeLabelId = generate$1('size-label'); var cells = makeCells(sizeLabelId, numRows, numColumns); var memLabel = record({ dom: { tag: 'span', classes: ['tox-insert-table-picker__label'], attributes: { id: sizeLabelId } }, components: [text('0x0')], behaviours: derive$1([Replacing.config({})]) }); return { type: 'widget', data: { value: generate$1('widget-id') }, dom: { tag: 'div', classes: ['tox-fancymenuitem'] }, autofocus: true, components: [parts$2().widget({ dom: { tag: 'div', classes: ['tox-insert-table-picker'] }, components: makeComponents(cells).concat(memLabel.asSpec()), behaviours: derive$1([ config('insert-table-picker', [ runWithTarget(cellOverEvent, function (c, t, e) { var row = e.event().row(); var col = e.event().col(); selectCells(cells, row, col, numRows, numColumns); Replacing.set(memLabel.get(c), [makeLabelText(row, col)]); }), runWithTarget(cellExecuteEvent, function (c, _, e) { spec.onAction({ numRows: e.event().row() + 1, numColumns: e.event().col() + 1 }); emit(c, sandboxClose()); }) ]), Keying.config({ initSize: { numRows: numRows, numColumns: numColumns }, mode: 'flatgrid', selector: '[role="button"]' }) ]) })] }; } var hexColour = function (hexString) { return { value: constant(hexString) }; }; var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; var isHexString = function (hex) { return shorthandRegex.test(hex) || longformRegex.test(hex); }; var getLongForm = function (hex) { var hexString = hex.value().replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; }); return { value: constant(hexString) }; }; var extractValues = function (hex) { var longForm = getLongForm(hex); var splitForm = longformRegex.exec(longForm.value()); return splitForm === null ? [ 'FFFFFF', 'FF', 'FF', 'FF' ] : splitForm; }; var toHex = function (component) { var hex = component.toString(16); return hex.length === 1 ? '0' + hex : hex; }; var fromRgba = function (rgbaColour) { var value = toHex(rgbaColour.red()) + toHex(rgbaColour.green()) + toHex(rgbaColour.blue()); return hexColour(value); }; var min = Math.min; var max = Math.max; var round = Math.round; var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/; var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/; var rgbaColour = function (red, green, blue, alpha) { return { red: constant(red), green: constant(green), blue: constant(blue), alpha: constant(alpha) }; }; var isRgbaComponent = function (value) { var num = parseInt(value, 10); return num.toString() === value && num >= 0 && num <= 255; }; var fromHsv = function (hsv) { var r; var g; var b; var hue = (hsv.hue() || 0) % 360; var saturation = hsv.saturation() / 100; var brightness = hsv.value() / 100; saturation = max(0, min(saturation, 1)); brightness = max(0, min(brightness, 1)); if (saturation === 0) { r = g = b = round(255 * brightness); return rgbaColour(r, g, b, 1); } var side = hue / 60; var chroma = brightness * saturation; var x = chroma * (1 - Math.abs(side % 2 - 1)); var match = brightness - chroma; switch (Math.floor(side)) { case 0: r = chroma; g = x; b = 0; break; case 1: r = x; g = chroma; b = 0; break; case 2: r = 0; g = chroma; b = x; break; case 3: r = 0; g = x; b = chroma; break; case 4: r = x; g = 0; b = chroma; break; case 5: r = chroma; g = 0; b = x; break; default: r = g = b = 0; } r = round(255 * (r + match)); g = round(255 * (g + match)); b = round(255 * (b + match)); return rgbaColour(r, g, b, 1); }; var fromHex = function (hexColour) { var result = extractValues(hexColour); var red = parseInt(result[1], 16); var green = parseInt(result[2], 16); var blue = parseInt(result[3], 16); return rgbaColour(red, green, blue, 1); }; var fromStringValues = function (red, green, blue, alpha) { var r = parseInt(red, 10); var g = parseInt(green, 10); var b = parseInt(blue, 10); var a = parseFloat(alpha); return rgbaColour(r, g, b, a); }; var fromString = function (rgbaString) { if (rgbaString === 'transparent') { return Option.some(rgbaColour(0, 0, 0, 0)); } var rgbMatch = rgbRegex.exec(rgbaString); if (rgbMatch !== null) { return Option.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1')); } var rgbaMatch = rgbaRegex.exec(rgbaString); if (rgbaMatch !== null) { return Option.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4])); } return Option.none(); }; var toString = function (rgba) { return 'rgba(' + rgba.red() + ',' + rgba.green() + ',' + rgba.blue() + ',' + rgba.alpha() + ')'; }; var redColour = constant(rgbaColour(255, 0, 0, 1)); var global$8 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage'); var storageName = 'tinymce-custom-colors'; function ColorCache (max) { if (max === void 0) { max = 10; } var storageString = global$8.getItem(storageName); var localstorage = isString(storageString) ? JSON.parse(storageString) : []; var prune = function (list) { var diff = max - list.length; return diff < 0 ? list.slice(0, max) : list; }; var cache = prune(localstorage); var add = function (key) { indexOf(cache, key).each(remove); cache.unshift(key); if (cache.length > max) { cache.pop(); } global$8.setItem(storageName, JSON.stringify(cache)); }; var remove = function (idx) { cache.splice(idx, 1); }; var state = function () { return cache.slice(0); }; return { add: add, state: state }; } var choiceItem = 'choiceitem'; var defaultColors = [ { type: choiceItem, text: 'Light Green', value: '#BFEDD2' }, { type: choiceItem, text: 'Light Yellow', value: '#FBEEB8' }, { type: choiceItem, text: 'Light Red', value: '#F8CAC6' }, { type: choiceItem, text: 'Light Purple', value: '#ECCAFA' }, { type: choiceItem, text: 'Light Blue', value: '#C2E0F4' }, { type: choiceItem, text: 'Green', value: '#2DC26B' }, { type: choiceItem, text: 'Yellow', value: '#F1C40F' }, { type: choiceItem, text: 'Red', value: '#E03E2D' }, { type: choiceItem, text: 'Purple', value: '#B96AD9' }, { type: choiceItem, text: 'Blue', value: '#3598DB' }, { type: choiceItem, text: 'Dark Turquoise', value: '#169179' }, { type: choiceItem, text: 'Orange', value: '#E67E23' }, { type: choiceItem, text: 'Dark Red', value: '#BA372A' }, { type: choiceItem, text: 'Dark Purple', value: '#843FA1' }, { type: choiceItem, text: 'Dark Blue', value: '#236FA1' }, { type: choiceItem, text: 'Light Gray', value: '#ECF0F1' }, { type: choiceItem, text: 'Medium Gray', value: '#CED4D9' }, { type: choiceItem, text: 'Gray', value: '#95A5A6' }, { type: choiceItem, text: 'Dark Gray', value: '#7E8C8D' }, { type: choiceItem, text: 'Navy Blue', value: '#34495E' }, { type: choiceItem, text: 'Black', value: '#000000' }, { type: choiceItem, text: 'White', value: '#ffffff' } ]; var colorCache = ColorCache(10); var mapColors = function (colorMap) { var colors = []; var canvas = domGlobals.document.createElement('canvas'); canvas.height = 1; canvas.width = 1; var ctx = canvas.getContext('2d'); var byteAsHex = function (colorByte, alphaByte) { var bg = 255; var alpha = alphaByte / 255; var colorByteWithWhiteBg = Math.round(colorByte * alpha + bg * (1 - alpha)); return ('0' + colorByteWithWhiteBg.toString(16)).slice(-2).toUpperCase(); }; var asHexColor = function (color) { if (/^[0-9A-Fa-f]{6}$/.test(color)) { return '#' + color.toUpperCase(); } ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#FFFFFF'; ctx.fillStyle = color; ctx.fillRect(0, 0, 1, 1); var rgba = ctx.getImageData(0, 0, 1, 1).data; var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3]; return '#' + byteAsHex(r, a) + byteAsHex(g, a) + byteAsHex(b, a); }; for (var i = 0; i < colorMap.length; i += 2) { colors.push({ text: colorMap[i + 1], value: asHexColor(colorMap[i]), type: 'choiceitem' }); } return colors; }; var getColorCols = function (editor, defaultCols) { return editor.getParam('color_cols', defaultCols, 'number'); }; var hasCustomColors = function (editor) { return editor.getParam('custom_colors') !== false; }; var getColorMap = function (editor) { return editor.getParam('color_map'); }; var getColors = function (editor) { var unmapped = getColorMap(editor); return unmapped !== undefined ? mapColors(unmapped) : defaultColors; }; var getCurrentColors = function () { return map(colorCache.state(), function (color) { return { type: choiceItem, text: color, value: color }; }); }; var addColor = function (color) { colorCache.add(color); }; var Settings = { mapColors: mapColors, getColorCols: getColorCols, hasCustomColors: hasCustomColors, getColorMap: getColorMap, getColors: getColors, getCurrentColors: getCurrentColors, addColor: addColor }; var fireSkinLoaded = function (editor) { return editor.fire('SkinLoaded'); }; var fireResizeEditor = function (editor) { return editor.fire('ResizeEditor'); }; var fireBeforeRenderUI = function (editor) { return editor.fire('BeforeRenderUI'); }; var fireResizeContent = function (editor, e) { return editor.fire('ResizeContent', e); }; var fireScrollContent = function (editor, e) { return editor.fire('ScrollContent', e); }; var fireTextColorChange = function (editor, data) { return editor.fire('TextColorChange', data); }; var Events = { fireSkinLoaded: fireSkinLoaded, fireResizeEditor: fireResizeEditor, fireScrollContent: fireScrollContent, fireBeforeRenderUI: fireBeforeRenderUI, fireResizeContent: fireResizeContent, fireTextColorChange: fireTextColorChange }; var getCurrentColor = function (editor, format) { var color; editor.dom.getParents(editor.selection.getStart(), function (elm) { var value; if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) { color = color ? color : value; } }); return color; }; var applyFormat = function (editor, format, value) { editor.undoManager.transact(function () { editor.focus(); editor.formatter.apply(format, { value: value }); editor.nodeChanged(); }); }; var removeFormat = function (editor, format) { editor.undoManager.transact(function () { editor.focus(); editor.formatter.remove(format, { value: null }, null, true); editor.nodeChanged(); }); }; var registerCommands = function (editor) { editor.addCommand('mceApplyTextcolor', function (format, value) { applyFormat(editor, format, value); }); editor.addCommand('mceRemoveTextcolor', function (format) { removeFormat(editor, format); }); }; var calcCols = function (colors) { return Math.max(5, Math.ceil(Math.sqrt(colors))); }; var getColorCols$1 = function (editor) { var colors = Settings.getColors(editor); var defaultCols = calcCols(colors.length); return Settings.getColorCols(editor, defaultCols); }; var getAdditionalColors = function (hasCustom) { var type = 'choiceitem'; var remove = { type: type, text: 'Remove color', icon: 'color-swatch-remove-color', value: 'remove' }; var custom = { type: type, text: 'Custom color', icon: 'color-picker', value: 'custom' }; return hasCustom ? [ remove, custom ] : [remove]; }; var applyColor = function (editor, format, value, onChoice) { if (value === 'custom') { var dialog = colorPickerDialog(editor); dialog(function (colorOpt) { colorOpt.each(function (color) { Settings.addColor(color); editor.execCommand('mceApplyTextcolor', format, color); onChoice(color); }); }, '#000000'); } else if (value === 'remove') { onChoice(''); editor.execCommand('mceRemoveTextcolor', format); } else { onChoice(value); editor.execCommand('mceApplyTextcolor', format, value); } }; var getMenuColors = function (colors, hasCustom) { return colors.concat(Settings.getCurrentColors().concat(getAdditionalColors(hasCustom))); }; var getFetch = function (colors, hasCustom) { return function (callback) { callback(getMenuColors(colors, hasCustom)); }; }; var setIconColor = function (splitButtonApi, name, newColor) { var setIconFillAndStroke = function (pathId, color) { splitButtonApi.setIconFill(pathId, color); splitButtonApi.setIconStroke(pathId, color); }; var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color'; setIconFillAndStroke(id, newColor); }; var registerTextColorButton = function (editor, name, format, tooltip, lastColor) { editor.ui.registry.addSplitButton(name, { tooltip: tooltip, presets: 'color', icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color', select: function (value) { var optCurrentRgb = Option.from(getCurrentColor(editor, format)); return optCurrentRgb.bind(function (currentRgb) { return fromString(currentRgb).map(function (rgba) { var currentHex = fromRgba(rgba).value(); return contains$1(value.toLowerCase(), currentHex); }); }).getOr(false); }, columns: getColorCols$1(editor), fetch: getFetch(Settings.getColors(editor), Settings.hasCustomColors(editor)), onAction: function (splitButtonApi) { if (lastColor.get() !== null) { applyColor(editor, format, lastColor.get(), function () { }); } }, onItemAction: function (splitButtonApi, value) { applyColor(editor, format, value, function (newColor) { lastColor.set(newColor); Events.fireTextColorChange(editor, { name: name, color: newColor }); }); }, onSetup: function (splitButtonApi) { if (lastColor.get() !== null) { setIconColor(splitButtonApi, name, lastColor.get()); } var handler = function (e) { if (e.name === name) { setIconColor(splitButtonApi, e.name, e.color); } }; editor.on('TextColorChange', handler); return function () { editor.off('TextColorChange', handler); }; } }); }; var registerTextColorMenuItem = function (editor, name, format, text) { editor.ui.registry.addNestedMenuItem(name, { text: text, icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color', getSubmenuItems: function () { return [{ type: 'fancymenuitem', fancytype: 'colorswatch', onAction: function (data) { applyColor(editor, format, data.value, noop); } }]; } }); }; var colorPickerDialog = function (editor) { return function (callback, value) { var getOnSubmit = function (callback) { return function (api) { var data = api.getData(); callback(Option.from(data.colorpicker)); api.close(); }; }; var onAction = function (api, details) { if (details.name === 'hex-valid') { if (details.value) { api.enable('ok'); } else { api.disable('ok'); } } }; var initialData = { colorpicker: value }; var submit = getOnSubmit(callback); editor.windowManager.open({ title: 'Color Picker', size: 'normal', body: { type: 'panel', items: [{ type: 'colorpicker', name: 'colorpicker', label: 'Color' }] }, buttons: [ { type: 'cancel', name: 'cancel', text: 'Cancel' }, { type: 'submit', name: 'save', text: 'Save', primary: true } ], initialData: initialData, onAction: onAction, onSubmit: submit, onClose: function () { }, onCancel: function () { callback(Option.none()); } }); }; }; var register$1 = function (editor) { registerCommands(editor); var lastForeColor = Cell(null); var lastBackColor = Cell(null); registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor); registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor); registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color'); registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color'); }; var ColorSwatch = { register: register$1, getColors: getMenuColors, getFetch: getFetch, colorPickerDialog: colorPickerDialog, getCurrentColor: getCurrentColor, getColorCols: getColorCols$1, calcCols: calcCols }; var chunk$1 = function (rowDom, numColumns) { return function (items) { var chunks = chunk(items, numColumns); return map(chunks, function (c) { return { dom: rowDom, components: c }; }); }; }; var forSwatch = function (columns) { return { dom: { tag: 'div', classes: [ 'tox-menu', 'tox-swatches-menu' ] }, components: [{ dom: { tag: 'div', classes: ['tox-swatches'] }, components: [Menu.parts().items({ preprocess: columns !== 'auto' ? chunk$1({ tag: 'div', classes: ['tox-swatches__row'] }, columns) : identity })] }] }; }; var forToolbar = function (columns) { return { dom: { tag: 'div', classes: [ 'tox-menu', 'tox-collection', 'tox-collection--toolbar', 'tox-collection--toolbar-lg' ] }, components: [Menu.parts().items({ preprocess: chunk$1({ tag: 'div', classes: ['tox-collection__group'] }, columns) })] }; }; var preprocessCollection = function (items, isSeparator) { var allSplits = []; var currentSplit = []; each(items, function (item, i) { if (isSeparator(item, i)) { if (currentSplit.length > 0) { allSplits.push(currentSplit); } currentSplit = []; if (has(item.dom, 'innerHtml')) { currentSplit.push(item); } } else { currentSplit.push(item); } }); if (currentSplit.length > 0) { allSplits.push(currentSplit); } return map(allSplits, function (s) { return { dom: { tag: 'div', classes: ['tox-collection__group'] }, components: s }; }); }; var forCollection = function (columns, initItems, _hasIcons) { return { dom: { tag: 'div', classes: [ 'tox-menu', 'tox-collection' ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid']) }, components: [Menu.parts().items({ preprocess: function (items) { if (columns !== 'auto' && columns > 1) { return chunk$1({ tag: 'div', classes: ['tox-collection__group'] }, columns)(items); } else { return preprocessCollection(items, function (_item, i) { return initItems[i].type === 'separator'; }); } } })] }; }; var forHorizontalCollection = function (initItems, _hasIcons) { return { dom: { tag: 'div', classes: [ 'tox-collection', 'tox-collection--horizontal' ] }, components: [Menu.parts().items({ preprocess: function (items) { return preprocessCollection(items, function (_item, i) { return initItems[i].type === 'separator'; }); } })] }; }; var forMenu = function (presets) { if (presets === 'color') { return 'tox-swatches'; } else { return 'tox-menu'; } }; var classes = function (presets) { return { backgroundMenu: 'tox-background-menu', selectedMenu: 'tox-selected-menu', selectedItem: 'tox-collection__item--active', hasIcons: 'tox-menu--has-icons', menu: forMenu(presets), tieredMenu: 'tox-tiered-menu' }; }; var markers$1 = function (presets) { var menuClasses = classes(presets); return { backgroundMenu: menuClasses.backgroundMenu, selectedMenu: menuClasses.selectedMenu, menu: menuClasses.menu, selectedItem: menuClasses.selectedItem, item: classForPreset(presets) }; }; var dom$1 = function (hasIcons, columns, presets) { var menuClasses = classes(presets); return { tag: 'div', classes: flatten([ [ menuClasses.menu, 'tox-menu-' + columns + '-column' ], hasIcons ? [menuClasses.hasIcons] : [] ]) }; }; var components$1 = [Menu.parts().items({})]; var part = function (hasIcons, columns, presets) { var menuClasses = classes(presets); var d = { tag: 'div', classes: flatten([[menuClasses.tieredMenu]]) }; return { dom: d, markers: markers$1(presets) }; }; var hasIcon = function (item) { return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem'; }; var menuHasIcons = function (xs) { return exists(xs, hasIcon); }; var handleError = function (error) { domGlobals.console.error(formatError(error)); domGlobals.console.log(error); return Option.none(); }; var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) { var structure = forHorizontalCollection(items); return { value: value, dom: structure.dom, components: structure.components, items: items }; }; var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) { if (presets === 'color') { var structure = forSwatch(columns); return { value: value, dom: structure.dom, components: structure.components, items: items }; } if (presets === 'normal' && columns === 'auto') { var structure = forCollection(columns, items); return { value: value, dom: structure.dom, components: structure.components, items: items }; } if (presets === 'normal' && columns === 1) { var structure = forCollection(1, items); return { value: value, dom: structure.dom, components: structure.components, items: items }; } if (presets === 'normal') { var structure = forCollection(columns, items); return { value: value, dom: structure.dom, components: structure.components, items: items }; } if (presets === 'listpreview' && columns !== 'auto') { var structure = forToolbar(columns); return { value: value, dom: structure.dom, components: structure.components, items: items }; } return { value: value, dom: dom$1(hasIcons, columns, presets), components: components$1, items: items }; }; var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) { var hasIcons = menuHasIcons(items); var presetItemTypes = presets !== 'color' ? 'normal' : 'color'; var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage); return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets); }; var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) { return cat(map(items, function (item) { if (item.type === 'choiceitem') { return createChoiceMenuItem(item).fold(handleError, function (d) { return Option.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage)); }); } else { return Option.none(); } })); }; var deriveMenuMovement = function (columns, presets) { var menuMarkers = markers$1(presets); if (columns === 1) { return { mode: 'menu', moveOnTab: true }; } else if (columns === 'auto') { return { mode: 'grid', selector: '.' + menuMarkers.item, initSize: { numColumns: 1, numRows: 1 } }; } else { var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group'; return { mode: 'matrix', rowSelector: '.' + rowClass }; } }; var deriveCollectionMovement = function (columns, presets) { if (columns === 1) { return { mode: 'menu', moveOnTab: false, selector: '.tox-collection__item' }; } else if (columns === 'auto') { return { mode: 'flatgrid', selector: '.' + 'tox-collection__item', initSize: { numColumns: 1, numRows: 1 } }; } else { return { mode: 'matrix', selectors: { row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group', cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass } }; } }; function renderColorSwatchItem(spec, backstage) { var items = ColorSwatch.getColors(backstage.colorinput.getColors(), backstage.colorinput.hasCustomColors()); var columns = backstage.colorinput.getColorCols(); var presets = 'color'; var menuSpec = createPartialChoiceMenu(generate$1('menu-value'), items, function (value) { spec.onAction({ value: value }); }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () { return false; }, backstage.shared.providers); var widgetSpec = deepMerge(__assign(__assign({}, menuSpec), { markers: markers$1(presets), movement: deriveMenuMovement(columns, presets) })); return { type: 'widget', data: { value: generate$1('widget-id') }, dom: { tag: 'div', classes: ['tox-fancymenuitem'] }, autofocus: true, components: [parts$2().widget(Menu.sketch(widgetSpec))] }; } var fancyMenuItems = { inserttable: renderInsertTableMenuItem, colorswatch: renderColorSwatchItem }; var valueOpt = function (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) ? Option.some(obj[key]) : Option.none(); }; var renderFancyMenuItem = function (spec, backstage) { return valueOpt(fancyMenuItems, spec.fancytype).map(function (render) { return render(spec, backstage); }); }; var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) { if (renderIcons === void 0) { renderIcons = true; } var getApi = function (component) { return { isDisabled: function () { return Disabling.isDisabled(component); }, setDisabled: function (state) { return Disabling.set(component, state); } }; }; var structure = renderItemStructure({ presets: 'normal', iconContent: spec.icon, textContent: spec.text, htmlContent: Option.none(), ariaLabel: spec.text, caret: Option.none(), checkMark: Option.none(), shortcutContent: spec.shortcut }, providersBackstage, renderIcons); return renderCommonItem({ data: buildData(spec), getApi: getApi, disabled: spec.disabled, onAction: spec.onAction, onSetup: spec.onSetup, triggersSubmenu: false, itemBehaviours: [] }, structure, itemResponse); }; var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) { if (renderIcons === void 0) { renderIcons = true; } if (downwardsCaret === void 0) { downwardsCaret = false; } var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons); var getApi = function (component) { return { isDisabled: function () { return Disabling.isDisabled(component); }, setDisabled: function (state) { return Disabling.set(component, state); } }; }; var structure = renderItemStructure({ presets: 'normal', iconContent: spec.icon, textContent: spec.text, htmlContent: Option.none(), ariaLabel: spec.text, caret: Option.some(caret), checkMark: Option.none(), shortcutContent: spec.shortcut }, providersBackstage, renderIcons); return renderCommonItem({ data: buildData(spec), getApi: getApi, disabled: spec.disabled, onAction: noop, onSetup: spec.onSetup, triggersSubmenu: true, itemBehaviours: [] }, structure, itemResponse); }; var renderSeparatorItem = function (spec) { var innerHtml = spec.text.fold(function () { return {}; }, function (text) { return { innerHtml: text }; }); return { type: 'separator', dom: __assign({ tag: 'div', classes: [ selectableClass, groupHeadingClass ] }, innerHtml), components: [] }; }; var renderToggleMenuItem = function (spec, itemResponse, providersBackstage) { var getApi = function (component) { return { setActive: function (state) { Toggling.set(component, state); }, isActive: function () { return Toggling.isOn(component); }, isDisabled: function () { return Disabling.isDisabled(component); }, setDisabled: function (state) { return Disabling.set(component, state); } }; }; var structure = renderItemStructure({ iconContent: Option.none(), textContent: spec.text, htmlContent: Option.none(), ariaLabel: spec.text, checkMark: Option.some(renderCheckmark(providersBackstage.icons)), caret: Option.none(), shortcutContent: spec.shortcut, presets: 'normal', meta: spec.meta }, providersBackstage, true); return deepMerge(renderCommonItem({ data: buildData(spec), disabled: spec.disabled, getApi: getApi, onAction: spec.onAction, onSetup: spec.onSetup, triggersSubmenu: false, itemBehaviours: [] }, structure, itemResponse), { toggling: { toggleClass: tickedClass, toggleOnExecute: false, selected: spec.active } }); }; var autocomplete = renderAutocompleteItem; var separator = renderSeparatorItem; var normal = renderNormalItem; var nested = renderNestedItem; var toggle$1 = renderToggleMenuItem; var fancy = renderFancyMenuItem; var FocusMode; (function (FocusMode) { FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus'; FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus'; }(FocusMode || (FocusMode = {}))); var hasIcon$1 = function (item) { return item.icon !== undefined || item.type === 'togglemenuitem' || item.type === 'choicemenuitem'; }; var menuHasIcons$1 = function (xs) { return exists(xs, hasIcon$1); }; var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) { var providersBackstage = backstage.shared.providers; var parseForHorizontalMenu = function (menuitem) { return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), { shortcut: Option.none(), icon: menuitem.text.isSome() ? Option.none() : menuitem.icon }); }; switch (item.type) { case 'menuitem': return createMenuItem(item).fold(handleError, function (d) { return Option.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons)); }); case 'nestedmenuitem': return createNestedMenuItem(item).fold(handleError, function (d) { return Option.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu)); }); case 'togglemenuitem': return createToggleMenuItem(item).fold(handleError, function (d) { return Option.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage)); }); case 'separator': return createSeparatorMenuItem(item).fold(handleError, function (d) { return Option.some(separator(d)); }); case 'fancymenuitem': return createFancyMenuItem(item).fold(handleError, function (d) { return fancy(parseForHorizontalMenu(d), backstage); }); default: { domGlobals.console.error('Unknown item in general menu', item); return Option.none(); } } }; var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage) { var renderText = columns === 1; var renderIcons = !renderText || menuHasIcons$1(items); return cat(map(items, function (item) { if (item.type === 'separator') { return createSeparatorItem(item).fold(handleError, function (d) { return Option.some(separator(d)); }); } else { return createAutocompleterItem(item).fold(handleError, function (d) { return Option.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons)); }); } })); }; var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) { var hasIcons = menuHasIcons$1(items); var alloyItems = cat(map(items, function (item) { var itemHasIcon = function (i) { return isHorizontalMenu ? !i.hasOwnProperty('text') : hasIcons; }; var createItem = function (i) { return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu); }; if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) { return createItem(merge(item, { disabled: true })); } else { return createItem(item); } })); var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems; return createPartial(value, hasIcons, alloyItems, 1, 'normal'); }; var createTieredDataFrom = function (partialMenu) { return tieredMenu.singleData(partialMenu.value, partialMenu); }; var createMenuFrom = function (partialMenu, columns, focusMode, presets) { var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom(); var movement = deriveMenuMovement(columns, presets); var menuMarkers = markers$1(presets); return { dom: partialMenu.dom, components: partialMenu.components, items: partialMenu.items, value: partialMenu.value, markers: { selectedItem: menuMarkers.selectedItem, item: menuMarkers.item }, movement: movement, fakeFocus: focusMode === FocusMode.ContentFocus, focusManager: focusManager, menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, se) { detectSize(comp, 4, menuMarkers.item).each(function (_a) { var numColumns = _a.numColumns, numRows = _a.numRows; Keying.setGridSize(comp, numRows, numColumns); }); })]) }; }; var register$2 = function (editor, sharedBackstage) { var activeAutocompleter = Cell(Option.none()); var processingAction = Cell(false); var autocompleter = build$1(InlineView.sketch({ dom: { tag: 'div', classes: ['tox-autocompleter'] }, components: [], fireDismissalEventInstead: {}, inlineBehaviours: derive$1([config('dismissAutocompleter', [run(dismissRequested(), function () { return cancelIfNecessary(); })])]), lazySink: sharedBackstage.getSink })); var isMenuOpen = function () { return InlineView.isOpen(autocompleter); }; var isActive = function () { return activeAutocompleter.get().isSome(); }; var hideIfNecessary = function () { if (isActive()) { InlineView.hide(autocompleter); } }; var cancelIfNecessary = function () { if (isActive()) { var lastElement = activeAutocompleter.get().map(function (ac) { return ac.element; }); detect$4(lastElement.getOr(Element.fromDom(editor.selection.getNode()))).each(unwrap); hideIfNecessary(); activeAutocompleter.set(Option.none()); processingAction.set(false); } }; var getAutocompleters = cached(function () { return register(editor); }); var getCombinedItems = function (triggerChar, matches) { var columns = findMap(matches, function (m) { return Option.from(m.columns); }).getOr(1); return bind(matches, function (match) { var choices = match.items; return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) { var nr = editor.selection.getRng(); getContext(editor.dom, nr, triggerChar).fold(function () { return domGlobals.console.error('Lost context. Cursor probably moved'); }, function (_a) { var range = _a.range; var autocompleterApi = { hide: function () { cancelIfNecessary(); }, reload: function (fetchOptions) { hideIfNecessary(); load(fetchOptions); } }; processingAction.set(true); match.onAction(autocompleterApi, range, itemValue, itemMeta); processingAction.set(false); }); }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage); }); }; var commenceIfNecessary = function (context) { if (!isActive()) { var wrapper = create$4(editor, context.range); activeAutocompleter.set(Option.some({ triggerChar: context.triggerChar, element: wrapper, matchLength: context.text.length })); processingAction.set(false); } }; var display = function (ac, context, lookupData, items) { ac.matchLength = context.text.length; var columns = findMap(lookupData, function (ld) { return Option.from(ld.columns); }).getOr(1); InlineView.showAt(autocompleter, { anchor: 'node', root: Element.fromDom(editor.getBody()), node: Option.from(ac.element) }, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal'))); InlineView.getContent(autocompleter).each(Highlighting.highlightFirst); }; var doLookup = function (fetchOptions) { return activeAutocompleter.get().map(function (ac) { return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) { return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions); }); }).getOrThunk(function () { return lookup(editor, getAutocompleters); }); }; var load = function (fetchOptions) { doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) { commenceIfNecessary(lookupInfo.context); lookupInfo.lookupData.then(function (lookupData) { activeAutocompleter.get().map(function (ac) { var context = lookupInfo.context; if (ac.triggerChar === context.triggerChar) { var combinedItems = getCombinedItems(context.triggerChar, lookupData); if (combinedItems.length > 0) { display(ac, context, lookupData, combinedItems); } else if (context.text.length - ac.matchLength >= 10) { cancelIfNecessary(); } else { hideIfNecessary(); } } }); }); }); }; var onKeypress = last$2(function (e) { if (e.which === 27) { return; } load(); }, 50); var autocompleterUiApi = { onKeypress: onKeypress, cancelIfNecessary: cancelIfNecessary, isMenuOpen: isMenuOpen, isActive: isActive, isProcessingAction: processingAction.get, getView: function () { return InlineView.getContent(autocompleter); } }; AutocompleterEditorEvents.setup(autocompleterUiApi, editor); }; var Autocompleter = { register: register$2 }; var mkEvent = function (target, x, y, stop, prevent, kill, raw) { return { target: constant(target), x: constant(x), y: constant(y), stop: stop, prevent: prevent, kill: kill, raw: constant(raw) }; }; var fromRawEvent = function (rawEvent) { var target = Element.fromDom(rawEvent.target); var stop = function () { rawEvent.stopPropagation(); }; var prevent = function () { rawEvent.preventDefault(); }; var kill = compose(prevent, stop); return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent); }; var handle = function (filter, handler) { return function (rawEvent) { if (!filter(rawEvent)) { return; } handler(fromRawEvent(rawEvent)); }; }; var binder = function (element, event, filter, handler, useCapture) { var wrapped = handle(filter, handler); element.dom().addEventListener(event, wrapped, useCapture); return { unbind: curry(unbind, element, event, wrapped, useCapture) }; }; var bind$2 = function (element, event, filter, handler) { return binder(element, event, filter, handler, false); }; var capture = function (element, event, filter, handler) { return binder(element, event, filter, handler, true); }; var unbind = function (element, event, handler, useCapture) { element.dom().removeEventListener(event, handler, useCapture); }; var filter$1 = constant(true); var bind$3 = function (element, event, handler) { return bind$2(element, event, filter$1, handler); }; var capture$1 = function (element, event, handler) { return capture(element, event, filter$1, handler); }; var fromRawEvent$1 = fromRawEvent; var closest$4 = function (scope, selector, isRoot) { return closest$3(scope, selector, isRoot).isSome(); }; function DelayedFunction (fun, delay) { var ref = null; var schedule = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } ref = domGlobals.setTimeout(function () { fun.apply(null, args); ref = null; }, delay); }; var cancel = function () { if (ref !== null) { domGlobals.clearTimeout(ref); ref = null; } }; return { cancel: cancel, schedule: schedule }; } var SIGNIFICANT_MOVE = 5; var LONGPRESS_DELAY = 400; var getTouch = function (event) { var raw = event.raw(); if (raw.touches === undefined || raw.touches.length !== 1) { return Option.none(); } return Option.some(raw.touches[0]); }; var isFarEnough = function (touch, data) { var distX = Math.abs(touch.clientX - data.x()); var distY = Math.abs(touch.clientY - data.y()); return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE; }; var monitor = function (settings) { var startData = Cell(Option.none()); var longpressFired = Cell(false); var longpress$1 = DelayedFunction(function (event) { settings.triggerEvent(longpress(), event); longpressFired.set(true); }, LONGPRESS_DELAY); var handleTouchstart = function (event) { getTouch(event).each(function (touch) { longpress$1.cancel(); var data = { x: constant(touch.clientX), y: constant(touch.clientY), target: event.target }; longpress$1.schedule(event); longpressFired.set(false); startData.set(Option.some(data)); }); return Option.none(); }; var handleTouchmove = function (event) { longpress$1.cancel(); getTouch(event).each(function (touch) { startData.get().each(function (data) { if (isFarEnough(touch, data)) { startData.set(Option.none()); } }); }); return Option.none(); }; var handleTouchend = function (event) { longpress$1.cancel(); var isSame = function (data) { return eq(data.target(), event.target()); }; return startData.get().filter(isSame).map(function (data) { if (longpressFired.get()) { event.prevent(); return false; } else { return settings.triggerEvent(tap(), event); } }); }; var handlers = wrapAll$1([ { key: touchstart(), value: handleTouchstart }, { key: touchmove(), value: handleTouchmove }, { key: touchend(), value: handleTouchend } ]); var fireIfReady = function (event, type) { return readOptFrom$1(handlers, type).bind(function (handler) { return handler(event); }); }; return { fireIfReady: fireIfReady }; }; var isDangerous = function (event) { var keyEv = event.raw(); return keyEv.which === BACKSPACE()[0] && !contains([ 'input', 'textarea' ], name(event.target())) && !closest$4(event.target(), '[contenteditable="true"]'); }; var isFirefox = detect$3().browser.isFirefox(); var settingsSchema = objOfOnly([ strictFunction('triggerEvent'), defaulted$1('stopBackspace', true) ]); var bindFocus = function (container, handler) { if (isFirefox) { return capture$1(container, 'focus', handler); } else { return bind$3(container, 'focusin', handler); } }; var bindBlur = function (container, handler) { if (isFirefox) { return capture$1(container, 'blur', handler); } else { return bind$3(container, 'focusout', handler); } }; var setup$1 = function (container, rawSettings) { var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings); var pointerEvents = detect$3().deviceType.isTouch() ? [ 'touchstart', 'touchmove', 'touchend', 'gesturestart' ] : [ 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout', 'click' ]; var tapEvent = monitor(settings); var simpleEvents = map(pointerEvents.concat([ 'selectstart', 'input', 'contextmenu', 'change', 'transitionend', 'drag', 'dragstart', 'dragend', 'dragenter', 'dragleave', 'dragover', 'drop', 'keyup' ]), function (type) { return bind$3(container, type, function (event) { tapEvent.fireIfReady(event, type).each(function (tapStopped) { if (tapStopped) { event.kill(); } }); var stopped = settings.triggerEvent(type, event); if (stopped) { event.kill(); } }); }); var pasteTimeout = Cell(Option.none()); var onPaste = bind$3(container, 'paste', function (event) { tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) { if (tapStopped) { event.kill(); } }); var stopped = settings.triggerEvent('paste', event); if (stopped) { event.kill(); } pasteTimeout.set(Option.some(domGlobals.setTimeout(function () { settings.triggerEvent(postPaste(), event); }, 0))); }); var onKeydown = bind$3(container, 'keydown', function (event) { var stopped = settings.triggerEvent('keydown', event); if (stopped) { event.kill(); } else if (settings.stopBackspace === true && isDangerous(event)) { event.prevent(); } }); var onFocusIn = bindFocus(container, function (event) { var stopped = settings.triggerEvent('focusin', event); if (stopped) { event.kill(); } }); var focusoutTimeout = Cell(Option.none()); var onFocusOut = bindBlur(container, function (event) { var stopped = settings.triggerEvent('focusout', event); if (stopped) { event.kill(); } focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () { settings.triggerEvent(postBlur(), event); }, 0))); }); var unbind = function () { each(simpleEvents, function (e) { e.unbind(); }); onKeydown.unbind(); onFocusIn.unbind(); onFocusOut.unbind(); onPaste.unbind(); pasteTimeout.get().each(domGlobals.clearTimeout); focusoutTimeout.get().each(domGlobals.clearTimeout); }; return { unbind: unbind }; }; var derive$2 = function (rawEvent, rawTarget) { var source = readOptFrom$1(rawEvent, 'target').map(function (getTarget) { return getTarget(); }).getOr(rawTarget); return Cell(source); }; var fromSource = function (event, source) { var stopper = Cell(false); var cutter = Cell(false); var stop = function () { stopper.set(true); }; var cut = function () { cutter.set(true); }; return { stop: stop, cut: cut, isStopped: stopper.get, isCut: cutter.get, event: constant(event), setSource: source.set, getSource: source.get }; }; var fromExternal = function (event) { var stopper = Cell(false); var stop = function () { stopper.set(true); }; return { stop: stop, cut: noop, isStopped: stopper.get, isCut: constant(false), event: constant(event), setSource: die('Cannot set source of a broadcasted event'), getSource: die('Cannot get source of a broadcasted event') }; }; var adt$b = Adt.generate([ { stopped: [] }, { resume: ['element'] }, { complete: [] } ]); var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) { var handler = lookup(eventType, target); var simulatedEvent = fromSource(rawEvent, source); return handler.fold(function () { logger.logEventNoHandlers(eventType, target); return adt$b.complete(); }, function (handlerInfo) { var descHandler = handlerInfo.descHandler(); var eventHandler = getCurried(descHandler); eventHandler(simulatedEvent); if (simulatedEvent.isStopped()) { logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose()); return adt$b.stopped(); } else if (simulatedEvent.isCut()) { logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose()); return adt$b.complete(); } else { return parent(handlerInfo.element()).fold(function () { logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose()); return adt$b.complete(); }, function (parent) { logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose()); return adt$b.resume(parent); }); } }); }; var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) { return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () { return true; }, function (parent) { return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger); }, function () { return false; }); }; var triggerHandler = function (lookup, eventType, rawEvent, target, logger) { var source = derive$2(rawEvent, target); return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger); }; var broadcast = function (listeners, rawEvent, logger) { var simulatedEvent = fromExternal(rawEvent); each(listeners, function (listener) { var descHandler = listener.descHandler(); var handler = getCurried(descHandler); handler(simulatedEvent); }); return simulatedEvent.isStopped(); }; var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) { var rawTarget = rawEvent.target(); return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger); }; var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) { var source = derive$2(rawEvent, rawTarget); return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger); }; var eventHandler = Immutable('element', 'descHandler'); var broadcastHandler = function (id, handler) { return { id: constant(id), descHandler: constant(handler) }; }; function EventRegistry () { var registry = {}; var registerId = function (extraArgs, id, events) { each$1(events, function (v, k) { var handlers = registry[k] !== undefined ? registry[k] : {}; handlers[id] = curryArgs(v, extraArgs); registry[k] = handlers; }); }; var findHandler = function (handlers, elem) { return read$1(elem).fold(function () { return Option.none(); }, function (id) { var reader = readOpt$1(id); return handlers.bind(reader).map(function (descHandler) { return eventHandler(elem, descHandler); }); }); }; var filterByType = function (type) { return readOptFrom$1(registry, type).map(function (handlers) { return mapToArray(handlers, function (f, id) { return broadcastHandler(id, f); }); }).getOr([]); }; var find = function (isAboveRoot, type, target) { var readType = readOpt$1(type); var handlers = readType(registry); return closest$1(target, function (elem) { return findHandler(handlers, elem); }, isAboveRoot); }; var unregisterId = function (id) { each$1(registry, function (handlersById, eventName) { if (handlersById.hasOwnProperty(id)) { delete handlersById[id]; } }); }; return { registerId: registerId, unregisterId: unregisterId, filterByType: filterByType, find: find }; } function Registry () { var events = EventRegistry(); var components = {}; var readOrTag = function (component) { var elem = component.element(); return read$1(elem).fold(function () { return write('uid-', component.element()); }, function (uid) { return uid; }); }; var failOnDuplicate = function (component, tagId) { var conflict = components[tagId]; if (conflict === component) { unregister(component); } else { 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'); } }; var register = function (component) { var tagId = readOrTag(component); if (hasKey$1(components, tagId)) { failOnDuplicate(component, tagId); } var extraArgs = [component]; events.registerId(extraArgs, tagId, component.events()); components[tagId] = component; }; var unregister = function (component) { read$1(component.element()).each(function (tagId) { delete components[tagId]; events.unregisterId(tagId); }); }; var filter = function (type) { return events.filterByType(type); }; var find = function (isAboveRoot, type, target) { return events.find(isAboveRoot, type, target); }; var getById = function (id) { return readOpt$1(id)(components); }; return { find: find, filter: filter, register: register, unregister: unregister, getById: getById }; } var factory$3 = function (detail) { var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']); return { uid: detail.uid, dom: __assign({ tag: 'div', attributes: __assign({ role: 'presentation' }, attributes) }, domWithoutAttributes), components: detail.components, behaviours: get$b(detail.containerBehaviours), events: detail.events, domModification: detail.domModification, eventOrder: detail.eventOrder }; }; var Container = single$2({ name: 'Container', factory: factory$3, configFields: [ defaulted$1('components', []), field$1('containerBehaviours', []), defaulted$1('events', {}), defaulted$1('domModification', {}), defaulted$1('eventOrder', {}) ] }); var takeover = function (root) { var isAboveRoot = function (el) { return parent(root.element()).fold(function () { return true; }, function (parent) { return eq(el, parent); }); }; var registry = Registry(); var lookup = function (eventName, target) { return registry.find(isAboveRoot, eventName, target); }; var domEvents = setup$1(root.element(), { triggerEvent: function (eventName, event) { return monitorEvent(eventName, event.target(), function (logger) { return triggerUntilStopped(lookup, eventName, event, logger); }); } }); var systemApi = { debugInfo: constant('real'), triggerEvent: function (eventName, target, data) { monitorEvent(eventName, target, function (logger) { triggerOnUntilStopped(lookup, eventName, data, target, logger); }); }, triggerFocus: function (target, originator) { read$1(target).fold(function () { focus$1(target); }, function (_alloyId) { monitorEvent(focus(), target, function (logger) { triggerHandler(lookup, focus(), { originator: constant(originator), kill: noop, prevent: noop, target: constant(target) }, target, logger); }); }); }, triggerEscape: function (comp, simulatedEvent) { systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event()); }, getByUid: function (uid) { return getByUid(uid); }, getByDom: function (elem) { return getByDom(elem); }, build: build$1, addToGui: function (c) { add(c); }, removeFromGui: function (c) { remove$1(c); }, addToWorld: function (c) { addToWorld(c); }, removeFromWorld: function (c) { removeFromWorld(c); }, broadcast: function (message) { broadcast$1(message); }, broadcastOn: function (channels, message) { broadcastOn(channels, message); }, broadcastEvent: function (eventName, event) { broadcastEvent(eventName, event); }, isConnected: constant(true) }; var addToWorld = function (component) { component.connect(systemApi); if (!isText(component.element())) { registry.register(component); each(component.components(), addToWorld); systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) }); } }; var removeFromWorld = function (component) { if (!isText(component.element())) { each(component.components(), removeFromWorld); registry.unregister(component); } component.disconnect(); }; var add = function (component) { attach$1(root, component); }; var remove$1 = function (component) { detach(component); }; var destroy = function () { domEvents.unbind(); remove(root.element()); }; var broadcastData = function (data) { var receivers = registry.filter(receive()); each(receivers, function (receiver) { var descHandler = receiver.descHandler(); var handler = getCurried(descHandler); handler(data); }); }; var broadcast$1 = function (message) { broadcastData({ universal: constant(true), data: constant(message) }); }; var broadcastOn = function (channels, message) { broadcastData({ universal: constant(false), channels: constant(channels), data: constant(message) }); }; var broadcastEvent = function (eventName, event) { var listeners = registry.filter(eventName); return broadcast(listeners, event); }; var getByUid = function (uid) { return registry.getById(uid).fold(function () { return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.')); }, Result.value); }; var getByDom = function (elem) { var uid = read$1(elem).getOr('not found'); return getByUid(uid); }; addToWorld(root); return { root: constant(root), element: root.element, destroy: destroy, add: add, remove: remove$1, getByUid: getByUid, getByDom: getByDom, addToWorld: addToWorld, removeFromWorld: removeFromWorld, broadcast: broadcast$1, broadcastOn: broadcastOn, broadcastEvent: broadcastEvent }; }; var global$9 = tinymce.util.Tools.resolve('tinymce.EditorManager'); var getSkinUrl = function (editor) { var settings = editor.settings; var skin = settings.skin; var skinUrl = settings.skin_url; if (skin !== false) { var skinName = skin ? skin : 'oxide'; if (skinUrl) { skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); } else { skinUrl = global$9.baseURL + '/skins/ui/' + skinName; } } return skinUrl; }; var isReadOnly = function (editor) { return editor.getParam('readonly', false, 'boolean'); }; var isSkinDisabled = function (editor) { return editor.getParam('skin') === false; }; var getHeightSetting = function (editor) { return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200)); }; var getMinWidthSetting = function (editor) { return Option.from(editor.settings.min_width).filter(isNumber); }; var getMinHeightSetting = function (editor) { return Option.from(editor.settings.min_height).filter(isNumber); }; var getMaxWidthSetting = function (editor) { return Option.from(editor.getParam('max_width')).filter(isNumber); }; var getMaxHeightSetting = function (editor) { return Option.from(editor.getParam('max_height')).filter(isNumber); }; var getUserStyleFormats = function (editor) { return Option.from(editor.getParam('style_formats')).filter(isArray); }; var isMergeStyleFormats = function (editor) { return editor.getParam('style_formats_merge', false, 'boolean'); }; var getRemovedMenuItems = function (editor) { return editor.getParam('removed_menuitems', ''); }; var isMenubarEnabled = function (editor) { return editor.getParam('menubar', true, 'boolean') !== false; }; var isToolbarEnabled = function (editor) { var toolbar = editor.getParam('toolbar', true); var isToolbarTrue = toolbar === true; var isToolbarString = isString(toolbar); var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0; return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue); }; var getMultipleToolbarsSetting = function (editor) { var keys$1 = keys(editor.settings); var toolbarKeys = filter(keys$1, function (key) { return /^toolbar([1-9])$/.test(key); }); var toolbars = map(toolbarKeys, function (key) { return editor.getParam(key, false, 'string'); }); var toolbarArray = filter(toolbars, function (toolbar) { return typeof toolbar === 'string'; }); return toolbarArray.length > 0 ? Option.some(toolbarArray) : Option.none(); }; var isMultipleToolbars = function (editor) { return getMultipleToolbarsSetting(editor).fold(function () { var toolbar = editor.getParam('toolbar', [], 'string[]'); return toolbar.length > 0; }, function () { return true; }); }; var ToolbarDrawer; (function (ToolbarDrawer) { ToolbarDrawer['default'] = ''; ToolbarDrawer['floating'] = 'floating'; ToolbarDrawer['sliding'] = 'sliding'; }(ToolbarDrawer || (ToolbarDrawer = {}))); var getToolbarDrawer = function (editor) { return editor.getParam('toolbar_drawer', '', 'string'); }; var fixedContainerSelector = function (editor) { return editor.getParam('fixed_toolbar_container', '', 'string'); }; var fixedContainerElement = function (editor) { var selector = fixedContainerSelector(editor); return selector.length > 0 && editor.inline ? descendant$1(body(), selector) : Option.none(); }; var useFixedContainer = function (editor) { return editor.inline && fixedContainerElement(editor).isSome(); }; var getUiContainer = function (editor) { var fixedContainer = fixedContainerElement(editor); return fixedContainer.getOr(body()); }; var isDistractionFree = function (editor) { return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor); }; var isStickyToolbar = function (editor) { var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean'); return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor); }; var isDraggableModal = function (editor) { return editor.getParam('draggable_modal', false, 'boolean'); }; var formChangeEvent = generate$1('form-component-change'); var formCloseEvent = generate$1('form-close'); var formCancelEvent = generate$1('form-cancel'); var formActionEvent = generate$1('form-action'); var formSubmitEvent = generate$1('form-submit'); var formBlockEvent = generate$1('form-block'); var formUnblockEvent = generate$1('form-unblock'); var formTabChangeEvent = generate$1('form-tabchange'); var formResizeEvent = generate$1('form-resize'); var renderAlertBanner = function (spec, providersBackstage) { return Container.sketch({ dom: { tag: 'div', attributes: { role: 'alert' }, classes: [ 'tox-notification', 'tox-notification--in', 'tox-notification--' + spec.level ] }, components: [ { dom: { tag: 'div', classes: ['tox-notification__icon'] }, components: [Button.sketch({ dom: { tag: 'button', classes: [ 'tox-button', 'tox-button--naked', 'tox-button--icon' ], innerHtml: get$c(spec.icon, providersBackstage.icons), attributes: { title: providersBackstage.translate(spec.iconTooltip) } }, action: function (comp) { emitWith(comp, formActionEvent, { name: 'alert-banner', value: spec.url }); } })] }, { dom: { tag: 'div', classes: ['tox-notification__body'], innerHtml: providersBackstage.translate(spec.text) } } ] }); }; var renderBar = function (spec, backstage) { return { dom: { tag: 'div', classes: [ 'tox-bar', 'tox-form__controls-h-stack' ] }, components: map(spec.items, backstage.interpreter) }; }; var schema$e = constant([ defaulted$1('prefix', 'form-field'), field$1('fieldBehaviours', [ Composing, Representing ]) ]); var parts$3 = constant([ optional({ schema: [strict$1('dom')], name: 'label' }), optional({ factory: { sketch: function (spec) { return { uid: spec.uid, dom: { tag: 'span', styles: { display: 'none' }, attributes: { 'aria-hidden': 'true' }, innerHtml: spec.text } }; } }, schema: [strict$1('text')], name: 'aria-descriptor' }), required({ factory: { sketch: function (spec) { var excludeFactory = exclude$1(spec, ['factory']); return spec.factory.sketch(excludeFactory); } }, schema: [strict$1('factory')], name: 'field' }) ]); var factory$4 = function (detail, components, spec, externals) { var behaviours = augment(detail.fieldBehaviours, [ Composing.config({ find: function (container) { return getPart(container, detail, 'field'); } }), Representing.config({ store: { mode: 'manual', getValue: function (field) { return Composing.getCurrent(field).bind(Representing.getValue); }, setValue: function (field, value) { Composing.getCurrent(field).each(function (current) { Representing.setValue(current, value); }); } } }) ]); var events = derive([runOnAttached(function (component, simulatedEvent) { var ps = getParts(component, detail, [ 'label', 'field', 'aria-descriptor' ]); ps.field().each(function (field) { var id = generate$1(detail.prefix); ps.label().each(function (label) { set$1(label.element(), 'for', id); set$1(field.element(), 'id', id); }); ps['aria-descriptor']().each(function (descriptor) { var descriptorId = generate$1(detail.prefix); set$1(descriptor.element(), 'id', descriptorId); set$1(field.element(), 'aria-describedby', descriptorId); }); }); })]); var apis = { getField: function (container) { return getPart(container, detail, 'field'); }, getLabel: function (container) { return getPart(container, detail, 'label'); } }; return { uid: detail.uid, dom: detail.dom, components: components, behaviours: behaviours, events: events, apis: apis }; }; var FormField = composite$1({ name: 'FormField', configFields: schema$e(), partFields: parts$3(), factory: factory$4, apis: { getField: function (apis, comp) { return apis.getField(comp); }, getLabel: function (apis, comp) { return apis.getLabel(comp); } } }); var schema$f = constant([ option('data'), defaulted$1('inputAttributes', {}), defaulted$1('inputStyles', {}), defaulted$1('tag', 'input'), defaulted$1('inputClasses', []), onHandler('onSetValue'), defaulted$1('styles', {}), defaulted$1('eventOrder', {}), field$1('inputBehaviours', [ Representing, Focusing ]), defaulted$1('selectOnFocus', true) ]); var focusBehaviours = function (detail) { return derive$1([Focusing.config({ onFocus: detail.selectOnFocus === false ? noop : function (component) { var input = component.element(); var value = get$5(input); input.dom().setSelectionRange(0, value.length); } })]); }; var behaviours = function (detail) { return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({ store: { mode: 'manual', initialValue: detail.data.getOr(undefined), getValue: function (input) { return get$5(input.element()); }, setValue: function (input, data) { var current = get$5(input.element()); if (current !== data) { set$3(input.element(), data); } } }, onSetValue: detail.onSetValue })])); }; var dom$2 = function (detail) { return { tag: detail.tag, attributes: __assign({ type: 'text' }, detail.inputAttributes), styles: detail.inputStyles, classes: detail.inputClasses }; }; var factory$5 = function (detail, spec) { return { uid: detail.uid, dom: dom$2(detail), components: [], behaviours: behaviours(detail), eventOrder: detail.eventOrder }; }; var Input = single$2({ name: 'Input', configFields: schema$f(), factory: factory$5 }); var exports$1 = {}, module = { exports: exports$1 }; (function (define, exports, module, require) { (function (f) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = f(); } else if (typeof define === 'function' && define.amd) { define([], f); } else { var g; if (typeof window !== 'undefined') { g = window; } else if (typeof global !== 'undefined') { g = global; } else if (typeof self !== 'undefined') { g = self; } else { g = this; } g.EphoxContactWrapper = f(); } }(function () { return function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = 'function' == typeof require && require; if (!f && c) return c(i, !0); if (u) return u(i, !0); var a = new Error('Cannot find module \'' + i + '\''); throw a.code = 'MODULE_NOT_FOUND', a; } var p = n[i] = { exports: {} }; e[i][0].call(p.exports, function (r) { var n = e[i][1][r]; return o(n || r); }, p, p.exports, r, e, n, t); } return n[i].exports; } for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++) o(t[i]); return o; } return r; }()({ 1: [ function (require, module, exports) { var process = module.exports = {}; var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } }()); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { return setTimeout(fun, 0); } if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { return cachedSetTimeout(fun, 0); } catch (e) { try { return cachedSetTimeout.call(null, fun, 0); } catch (e) { return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { return clearTimeout(marker); } if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { return cachedClearTimeout(marker); } catch (e) { try { return cachedClearTimeout.call(null, marker); } catch (e) { return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; process.versions = {}; function noop() { } process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return []; }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; }, {} ], 2: [ function (require, module, exports) { (function (setImmediate) { (function (root) { var setTimeoutFunc = setTimeout; function noop() { } function bind(fn, thisArg) { return function () { fn.apply(thisArg, arguments); }; } function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); this._state = 0; this._handled = false; this._value = undefined; this._deferreds = []; doResolve(fn, this); } function handle(self, deferred) { while (self._state === 3) { self = self._value; } if (self._state === 0) { self._deferreds.push(deferred); return; } self._handled = true; Promise._immediateFn(function () { var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (self._state === 1 ? resolve : reject)(deferred.promise, self._value); return; } var ret; try { ret = cb(self._value); } catch (e) { reject(deferred.promise, e); return; } resolve(deferred.promise, ret); }); } function resolve(self, newValue) { try { if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.'); if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (newValue instanceof Promise) { self._state = 3; self._value = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(bind(then, newValue), self); return; } } self._state = 1; self._value = newValue; finale(self); } catch (e) { reject(self, e); } } function reject(self, newValue) { self._state = 2; self._value = newValue; finale(self); } function finale(self) { if (self._state === 2 && self._deferreds.length === 0) { Promise._immediateFn(function () { if (!self._handled) { Promise._unhandledRejectionFn(self._value); } }); } for (var i = 0, len = self._deferreds.length; i < len; i++) { handle(self, self._deferreds[i]); } self._deferreds = null; } function Handler(onFulfilled, onRejected, promise) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } function doResolve(fn, self) { var done = false; try { fn(function (value) { if (done) return; done = true; resolve(self, value); }, function (reason) { if (done) return; done = true; reject(self, reason); }); } catch (ex) { if (done) return; done = true; reject(self, ex); } } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { var prom = new this.constructor(noop); handle(this, new Handler(onFulfilled, onRejected, prom)); return prom; }; Promise.all = function (arr) { var args = Array.prototype.slice.call(arr); return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call(val, function (val) { res(i, val); }, reject); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise) { return value; } return new Promise(function (resolve) { resolve(value); }); }; Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); }; Promise.race = function (values) { return new Promise(function (resolve, reject) { for (var i = 0, len = values.length; i < len; i++) { values[i].then(resolve, reject); } }); }; Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) { setImmediate(fn); } : function (fn) { setTimeoutFunc(fn, 0); }; Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); } }; Promise._setImmediateFn = function _setImmediateFn(fn) { Promise._immediateFn = fn; }; Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) { Promise._unhandledRejectionFn = fn; }; if (typeof module !== 'undefined' && module.exports) { module.exports = Promise; } else if (!root.Promise) { root.Promise = Promise; } }(this)); }.call(this, require('timers').setImmediate)); }, { 'timers': 3 } ], 3: [ function (require, module, exports) { (function (setImmediate, clearImmediate) { var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; exports.setTimeout = function () { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function () { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function (timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function () { }; Timeout.prototype.close = function () { this._clearFn.call(window, this._id); }; exports.enroll = function (item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function (item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function (item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { if (args) { fn.apply(null, args); } else { fn.call(null); } exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) { delete immediateIds[id]; }; }.call(this, require('timers').setImmediate, require('timers').clearImmediate)); }, { 'process/browser.js': 1, 'timers': 3 } ], 4: [ function (require, module, exports) { var promisePolyfill = require('promise-polyfill'); var Global = function () { if (typeof window !== 'undefined') { return window; } else { return Function('return this;')(); } }(); module.exports = { boltExport: Global.Promise || promisePolyfill }; }, { 'promise-polyfill': 2 } ] }, {}, [4])(4); })); }(undefined, exports$1, module, undefined)); var Promise = module.exports.boltExport; var nu$a = function (baseFn) { var data = Option.none(); var callbacks = []; var map = function (f) { return nu$a(function (nCallback) { get(function (data) { nCallback(f(data)); }); }); }; var get = function (nCallback) { if (isReady()) { call(nCallback); } else { callbacks.push(nCallback); } }; var set = function (x) { data = Option.some(x); run(callbacks); callbacks = []; }; var isReady = function () { return data.isSome(); }; var run = function (cbs) { each(cbs, call); }; var call = function (cb) { data.each(function (x) { domGlobals.setTimeout(function () { cb(x); }, 0); }); }; baseFn(set); return { get: get, map: map, isReady: isReady }; }; var pure$1 = function (a) { return nu$a(function (callback) { callback(a); }); }; var LazyValue = { nu: nu$a, pure: pure$1 }; var errorReporter = function (err) { domGlobals.setTimeout(function () { throw err; }, 0); }; var make$3 = function (run) { var get = function (callback) { run().then(callback, errorReporter); }; var map = function (fab) { return make$3(function () { return run().then(fab); }); }; var bind = function (aFutureB) { return make$3(function () { return run().then(function (v) { return aFutureB(v).toPromise(); }); }); }; var anonBind = function (futureB) { return make$3(function () { return run().then(function () { return futureB.toPromise(); }); }); }; var toLazy = function () { return LazyValue.nu(get); }; var toCached = function () { var cache = null; return make$3(function () { if (cache === null) { cache = run(); } return cache; }); }; var toPromise = run; return { map: map, bind: bind, anonBind: anonBind, toLazy: toLazy, toCached: toCached, toPromise: toPromise, get: get }; }; var nu$b = function (baseFn) { return make$3(function () { return new Promise(baseFn); }); }; var pure$2 = function (a) { return make$3(function () { return Promise.resolve(a); }); }; var Future = { nu: nu$b, pure: pure$2 }; var ariaElements = [ 'input', 'textarea' ]; var isAriaElement = function (elem) { var name$1 = name(elem); return contains(ariaElements, name$1); }; var markValid = function (component, invalidConfig) { var elem = invalidConfig.getRoot(component).getOr(component.element()); remove$4(elem, invalidConfig.invalidClass); invalidConfig.notify.each(function (notifyInfo) { if (isAriaElement(component.element())) { set$1(component.element(), 'aria-invalid', false); } notifyInfo.getContainer(component).each(function (container) { set(container, notifyInfo.validHtml); }); notifyInfo.onValid(component); }); }; var markInvalid = function (component, invalidConfig, invalidState, text) { var elem = invalidConfig.getRoot(component).getOr(component.element()); add$2(elem, invalidConfig.invalidClass); invalidConfig.notify.each(function (notifyInfo) { if (isAriaElement(component.element())) { set$1(component.element(), 'aria-invalid', true); } notifyInfo.getContainer(component).each(function (container) { set(container, text); }); notifyInfo.onInvalid(component, text); }); }; var query = function (component, invalidConfig, invalidState) { return invalidConfig.validator.fold(function () { return Future.pure(Result.value(true)); }, function (validatorInfo) { return validatorInfo.validate(component); }); }; var run$1 = function (component, invalidConfig, invalidState) { invalidConfig.notify.each(function (notifyInfo) { notifyInfo.onValidate(component); }); return query(component, invalidConfig).map(function (valid) { if (component.getSystem().isConnected()) { return valid.fold(function (err) { markInvalid(component, invalidConfig, invalidState, err); return Result.error(err); }, function (v) { markValid(component, invalidConfig); return Result.value(v); }); } else { return Result.error('No longer in system'); } }); }; var isInvalid = function (component, invalidConfig) { var elem = invalidConfig.getRoot(component).getOr(component.element()); return has$2(elem, invalidConfig.invalidClass); }; var InvalidateApis = /*#__PURE__*/Object.freeze({ markValid: markValid, markInvalid: markInvalid, query: query, run: run$1, isInvalid: isInvalid }); var events$a = function (invalidConfig, invalidState) { return invalidConfig.validator.map(function (validatorInfo) { return derive([run(validatorInfo.onEvent, function (component) { run$1(component, invalidConfig, invalidState).get(identity); })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) { run$1(component, invalidConfig, invalidState).get(noop); })] : [])); }).getOr({}); }; var ActiveInvalidate = /*#__PURE__*/Object.freeze({ events: events$a }); var InvalidateSchema = [ strict$1('invalidClass'), defaulted$1('getRoot', Option.none), optionObjOf('notify', [ defaulted$1('aria', 'alert'), defaulted$1('getContainer', Option.none), defaulted$1('validHtml', ''), onHandler('onValid'), onHandler('onInvalid'), onHandler('onValidate') ]), optionObjOf('validator', [ strict$1('validate'), defaulted$1('onEvent', 'input'), defaulted$1('validateOnLoad', true) ]) ]; var Invalidating = create$1({ fields: InvalidateSchema, name: 'invalidating', active: ActiveInvalidate, apis: InvalidateApis, extra: { validation: function (validator) { return function (component) { var v = Representing.getValue(component); return Future.pure(validator(v)); }; } } }); var exhibit$4 = function (base, tabConfig) { return nu$6({ attributes: wrapAll$1([{ key: tabConfig.tabAttr, value: 'true' }]) }); }; var ActiveTabstopping = /*#__PURE__*/Object.freeze({ exhibit: exhibit$4 }); var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')]; var Tabstopping = create$1({ fields: TabstopSchema, name: 'tabstopping', active: ActiveTabstopping }); var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) { var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours); return FormField.sketch(spec); }; var renderFormField = function (pLabel, pField) { return renderFormFieldWith(pLabel, pField, [], []); }; var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) { return { dom: renderFormFieldDomWith(extraClasses), components: pLabel.toArray().concat([pField]), fieldBehaviours: derive$1(extraBehaviours) }; }; var renderFormFieldDom = function () { return renderFormFieldDomWith([]); }; var renderFormFieldDomWith = function (extraClasses) { return { tag: 'div', classes: ['tox-form__group'].concat(extraClasses) }; }; var renderLabel = function (label, providersBackstage) { return FormField.parts().label({ dom: { tag: 'label', classes: ['tox-label'], innerHtml: providersBackstage.translate(label) } }); }; var getCoupled = function (component, coupleConfig, coupleState, name) { return coupleState.getOrCreate(component, coupleConfig, name); }; var CouplingApis = /*#__PURE__*/Object.freeze({ getCoupled: getCoupled }); var CouplingSchema = [strictOf('others', setOf$1(Result.value, anyValue$1()))]; var init$5 = function (spec) { var coupled = {}; var getOrCreate = function (component, coupleConfig, name) { var available = keys(coupleConfig.others); if (!available) { throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2)); } else { return readOptFrom$1(coupled, name).getOrThunk(function () { var builder = readOptFrom$1(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name); var spec = builder(component); var built = component.getSystem().build(spec); coupled[name] = built; return built; }); } }; var readState = constant({}); return nu$5({ readState: readState, getOrCreate: getOrCreate }); }; var CouplingState = /*#__PURE__*/Object.freeze({ init: init$5 }); var Coupling = create$1({ fields: CouplingSchema, name: 'coupling', apis: CouplingApis, state: CouplingState }); var suffix = constant('sink'); var partType = constant(optional({ name: suffix(), overrides: constant({ dom: { tag: 'div' }, behaviours: derive$1([Positioning.config({ useFixed: always })]), events: derive([ cutter(keydown()), cutter(mousedown()), cutter(click()) ]) }) })); var HighlightOnOpen; (function (HighlightOnOpen) { HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst'; HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone'; }(HighlightOnOpen || (HighlightOnOpen = {}))); var getAnchor = function (detail, component) { var hotspot = detail.getHotspot(component).getOr(component); var anchor = 'hotspot'; var overrides = detail.getAnchorOverrides(); return detail.layouts.fold(function () { return { anchor: anchor, hotspot: hotspot, overrides: overrides }; }, function (layouts) { return { anchor: anchor, hotspot: hotspot, overrides: overrides, layouts: layouts }; }); }; var fetch = function (detail, mapFetch, component) { var fetcher = detail.fetch; return fetcher(component).map(mapFetch); }; var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) { var futureData = fetch(detail, mapFetch, component); var getLazySink = getSink(component, detail); return futureData.map(function (tdata) { return tdata.bind(function (data) { return Option.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), { uid: generate$2(''), data: data, highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst, onOpenMenu: function (tmenu, menu) { var sink = getLazySink().getOrDie(); Positioning.position(sink, anchor, menu); Sandboxing.decloak(sandbox); }, onOpenSubmenu: function (tmenu, item, submenu) { var sink = getLazySink().getOrDie(); Positioning.position(sink, { anchor: 'submenu', item: item }, submenu); Sandboxing.decloak(sandbox); }, onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) { var sink = getLazySink().getOrDie(); Positioning.position(sink, anchor, primaryMenu); each(submenuTriggers, function (st) { Positioning.position(sink, { anchor: 'submenu', item: st.triggeringItem }, st.triggeredMenu); }); }, onEscape: function () { Focusing.focus(component); Sandboxing.close(sandbox); return Option.some(true); } }))); }); }); }; var open$1 = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) { var anchor = getAnchor(detail, hotspot); var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen); return processed.map(function (tdata) { tdata.fold(function () { if (Sandboxing.isOpen(sandbox)) { Sandboxing.close(sandbox); } }, function (data) { Sandboxing.cloak(sandbox); Sandboxing.open(sandbox, data); onOpenSync(sandbox); }); return sandbox; }); }; var close$1 = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) { Sandboxing.close(sandbox); return Future.pure(sandbox); }; var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) { var sandbox = Coupling.getCoupled(hotspot, 'sandbox'); var showing = Sandboxing.isOpen(sandbox); var action = showing ? close$1 : open$1; return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen); }; var matchWidth = function (hotspot, container, useMinWidth) { var menu = Composing.getCurrent(container).getOr(container); var buttonWidth = get$7(hotspot.element()); if (useMinWidth) { set$2(menu.element(), 'min-width', buttonWidth + 'px'); } else { set$4(menu.element(), buttonWidth); } }; var getSink = function (anyInSystem, sinkDetail) { return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) { return function () { return Result.value(internalSink); }; }).getOrThunk(function () { return sinkDetail.lazySink.fold(function () { return function () { return Result.error(new Error('No internal sink is specified, nor could an external sink be found')); }; }, function (lazySinkFn) { return function () { return lazySinkFn(anyInSystem); }; }); }); }; var doRepositionMenus = function (sandbox) { Sandboxing.getState(sandbox).each(function (tmenu) { tieredMenu.repositionMenus(tmenu); }); }; var makeSandbox = function (detail, hotspot, extras) { var ariaOwner = manager(); var onOpen = function (component, menu) { var anchor = getAnchor(detail, hotspot); ariaOwner.link(hotspot.element()); if (detail.matchWidth) { matchWidth(anchor.hotspot, menu, detail.useMinWidth); } detail.onOpen(anchor, component, menu); if (extras !== undefined && extras.onOpen !== undefined) { extras.onOpen(component, menu); } }; var onClose = function (component, menu) { ariaOwner.unlink(hotspot.element()); if (extras !== undefined && extras.onClose !== undefined) { extras.onClose(component, menu); } }; var lazySink = getSink(hotspot, detail); return { dom: { tag: 'div', classes: detail.sandboxClasses, attributes: { id: ariaOwner.id(), role: 'listbox' } }, behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [ Representing.config({ store: { mode: 'memory', initialValue: hotspot } }), Sandboxing.config({ onOpen: onOpen, onClose: onClose, isPartOf: function (container, data, queryElem) { return isPartOf(data, queryElem) || isPartOf(hotspot, queryElem); }, getAttachPoint: function () { return lazySink().getOrDie(); } }), Composing.config({ find: function (sandbox) { return Sandboxing.getState(sandbox).bind(function (menu) { return Composing.getCurrent(menu); }); } }), Receiving.config({ channels: __assign(__assign({}, receivingChannel({ isExtraPart: constant(false) })), receivingChannel$1({ isExtraPart: constant(false), doReposition: doRepositionMenus })) }) ]) }; }; var repositionMenus = function (comp) { var sandbox = Coupling.getCoupled(comp, 'sandbox'); doRepositionMenus(sandbox); }; var sandboxFields = function () { return [ defaulted$1('sandboxClasses', []), SketchBehaviours.field('sandboxBehaviours', [ Composing, Receiving, Sandboxing, Representing ]) ]; }; var schema$g = constant([ strict$1('dom'), strict$1('fetch'), onHandler('onOpen'), onKeyboardHandler('onExecute'), defaulted$1('getHotspot', Option.some), defaulted$1('getAnchorOverrides', constant({})), defaulted$1('layouts', Option.none()), field$1('dropdownBehaviours', [ Toggling, Coupling, Keying, Focusing ]), strict$1('toggleClass'), defaulted$1('eventOrder', {}), option('lazySink'), defaulted$1('matchWidth', false), defaulted$1('useMinWidth', false), option('role') ].concat(sandboxFields())); var parts$4 = constant([ external$1({ schema: [tieredMenuMarkers()], name: 'menu', defaults: function (detail) { return { onExecute: detail.onExecute }; } }), partType() ]); var factory$6 = function (detail, components, _spec, externals) { var _a; var lookupAttr = function (attr) { return readOptFrom$1(detail.dom, 'attributes').bind(function (attrs) { return readOptFrom$1(attrs, attr); }); }; var switchToMenu = function (sandbox) { Sandboxing.getState(sandbox).each(function (tmenu) { tieredMenu.highlightPrimary(tmenu); }); }; var action = function (component) { var onOpenSync = switchToMenu; togglePopup(detail, function (x) { return x; }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); }; var apis = { expand: function (comp) { if (!Toggling.isOn(comp)) { togglePopup(detail, function (x) { return x; }, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop); } }, open: function (comp) { if (!Toggling.isOn(comp)) { togglePopup(detail, function (x) { return x; }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop); } }, isOpen: Toggling.isOn, close: function (comp) { if (Toggling.isOn(comp)) { togglePopup(detail, function (x) { return x; }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop); } }, repositionMenus: function (comp) { if (Toggling.isOn(comp)) { repositionMenus(comp); } } }; var triggerExecute = function (comp, se) { emitExecute(comp); return Option.some(true); }; return { uid: detail.uid, dom: detail.dom, components: components, behaviours: augment(detail.dropdownBehaviours, [ Toggling.config({ toggleClass: detail.toggleClass, aria: { mode: 'expanded' } }), Coupling.config({ others: { sandbox: function (hotspot) { return makeSandbox(detail, hotspot, { onOpen: function () { Toggling.on(hotspot); }, onClose: function () { Toggling.off(hotspot); } }); } } }), Keying.config({ mode: 'special', onSpace: triggerExecute, onEnter: triggerExecute, onDown: function (comp, se) { if (Dropdown.isOpen(comp)) { var sandbox = Coupling.getCoupled(comp, 'sandbox'); switchToMenu(sandbox); } else { Dropdown.open(comp); } return Option.some(true); }, onEscape: function (comp, se) { if (Dropdown.isOpen(comp)) { Dropdown.close(comp); return Option.some(true); } else { return Option.none(); } } }), Focusing.config({}) ]), events: events$7(Option.some(action)), eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [ 'disabling', 'toggling', 'alloy.base.behaviour' ], _a)), apis: apis, domModification: { attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () { return {}; }, function (role) { return { role: role }; })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {}) } }; }; var Dropdown = composite$1({ name: 'Dropdown', configFields: schema$g(), partFields: parts$4(), factory: factory$6, apis: { open: function (apis, comp) { return apis.open(comp); }, expand: function (apis, comp) { return apis.expand(comp); }, close: function (apis, comp) { return apis.close(comp); }, isOpen: function (apis, comp) { return apis.isOpen(comp); }, repositionMenus: function (apis, comp) { return apis.repositionMenus(comp); } } }); var exhibit$5 = function (base, unselectConfig) { return nu$6({ styles: { '-webkit-user-select': 'none', 'user-select': 'none', '-ms-user-select': 'none', '-moz-user-select': '-moz-none' }, attributes: { unselectable: 'on' } }); }; var events$b = function (unselectConfig) { return derive([abort(selectstart(), constant(true))]); }; var ActiveUnselecting = /*#__PURE__*/Object.freeze({ events: events$b, exhibit: exhibit$5 }); var Unselecting = create$1({ fields: [], name: 'unselecting', active: ActiveUnselecting }); var renderPanelButton = function (spec, sharedBackstage) { return Dropdown.sketch({ dom: spec.dom, components: spec.components, toggleClass: 'mce-active', dropdownBehaviours: derive$1([ Unselecting.config({}), Tabstopping.config({}) ]), layouts: spec.layouts, sandboxClasses: ['tox-dialog__popups'], lazySink: sharedBackstage.getSink, fetch: function (comp) { return Future.nu(function (callback) { return spec.fetch(callback); }).map(function (items) { return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) { spec.onItemAction(comp, value); }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () { return false; }, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) }))); }); }, parts: { menu: part(false, 1, spec.presets) } }); }; var colorInputChangeEvent = generate$1('color-input-change'); var colorSwatchChangeEvent = generate$1('color-swatch-change'); var colorPickerCancelEvent = generate$1('color-picker-cancel'); var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) { var pField = FormField.parts().field({ factory: Input, inputClasses: ['tox-textfield'], onSetValue: function (c) { return Invalidating.run(c).get(function () { }); }, inputBehaviours: derive$1([ Tabstopping.config({}), Invalidating.config({ invalidClass: 'tox-textbox-field-invalid', getRoot: function (comp) { return parent(comp.element()); }, notify: { onValid: function (comp) { var val = Representing.getValue(comp); emitWith(comp, colorInputChangeEvent, { color: val }); } }, validator: { validateOnLoad: false, validate: function (input) { var inputValue = Representing.getValue(input); if (inputValue.length === 0) { return Future.pure(Result.value(true)); } else { var span = Element.fromTag('span'); set$2(span, 'background-color', inputValue); var res = getRaw(span, 'background-color').fold(function () { return Result.error('blah'); }, function (_) { return Result.value(inputValue); }); return Future.pure(res); } } } }) ]), selectOnFocus: false }); var pLabel = spec.label.map(function (label) { return renderLabel(label, sharedBackstage.providers); }); var emitSwatchChange = function (colorBit, value) { emitWith(colorBit, colorSwatchChangeEvent, { value: value }); }; var onItemAction = function (comp, value) { memColorButton.getOpt(comp).each(function (colorBit) { if (value === 'custom') { colorInputBackstage.colorPicker(function (valueOpt) { valueOpt.fold(function () { return emit(colorBit, colorPickerCancelEvent); }, function (value) { emitSwatchChange(colorBit, value); Settings.addColor(value); }); }, '#ffffff'); } else if (value === 'remove') { emitSwatchChange(colorBit, ''); } else { emitSwatchChange(colorBit, value); } }); }; var memColorButton = record(renderPanelButton({ dom: { tag: 'span', attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') } }, layouts: Option.some({ onRtl: function () { return [southeast$1]; }, onLtr: function () { return [southwest$1]; } }), components: [], fetch: ColorSwatch.getFetch(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()), columns: colorInputBackstage.getColorCols(), presets: 'color', onItemAction: onItemAction }, sharedBackstage)); return FormField.sketch({ dom: { tag: 'div', classes: ['tox-form__group'] }, components: pLabel.toArray().concat([{ dom: { tag: 'div', classes: ['tox-color-input'] }, components: [ pField, memColorButton.asSpec() ] }]), fieldBehaviours: derive$1([config('form-field-events', [ run(colorInputChangeEvent, function (comp, se) { memColorButton.getOpt(comp).each(function (colorButton) { set$2(colorButton.element(), 'background-color', se.event().color()); }); emitWith(comp, formChangeEvent, { name: spec.name }); }), run(colorSwatchChangeEvent, function (comp, se) { FormField.getField(comp).each(function (field) { Representing.setValue(field, se.event().value()); Composing.getCurrent(comp).each(Focusing.focus); }); }), run(colorPickerCancelEvent, function (comp, se) { FormField.getField(comp).each(function (field) { Composing.getCurrent(comp).each(Focusing.focus); }); }) ])]) }); }; var hsvColour = function (hue, saturation, value) { return { hue: constant(hue), saturation: constant(saturation), value: constant(value) }; }; var fromRgb = function (rgbaColour) { var h = 0; var s = 0; var v = 0; var r = rgbaColour.red() / 255; var g = rgbaColour.green() / 255; var b = rgbaColour.blue() / 255; var minRGB = Math.min(r, Math.min(g, b)); var maxRGB = Math.max(r, Math.max(g, b)); if (minRGB === maxRGB) { v = minRGB; return hsvColour(0, 0, v * 100); } var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r; h = r === minRGB ? 3 : b === minRGB ? 1 : 5; h = 60 * (h - d / (maxRGB - minRGB)); s = (maxRGB - minRGB) / maxRGB; v = maxRGB; return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100)); }; var calcHex = function (value) { var hue = (100 - value) / 100 * 360; var hsv = hsvColour(hue, 100, 100); var rgb = fromHsv(hsv); return fromRgba(rgb); }; var fieldsUpdate = constant(generate$1('rgb-hex-update')); var sliderUpdate = constant(generate$1('slider-update')); var paletteUpdate = constant(generate$1('palette-update')); var platform$1 = detect$3(); var isTouch = platform$1.deviceType.isTouch(); var labelPart = optional({ schema: [strict$1('dom')], name: 'label' }); var edgePart = function (name) { return optional({ name: '' + name + '-edge', overrides: function (detail) { var action = detail.model.manager.edgeActions[name]; return action.fold(function () { return {}; }, function (a) { var touchEvents = derive([runActionExtra(touchstart(), a, [detail])]); var mouseEvents = derive([ runActionExtra(mousedown(), a, [detail]), runActionExtra(mousemove(), function (l, det) { if (det.mouseIsDown.get()) { a(l, det); } }, [detail]) ]); return { events: isTouch ? touchEvents : mouseEvents }; }); } }); }; var tlEdgePart = edgePart('top-left'); var tedgePart = edgePart('top'); var trEdgePart = edgePart('top-right'); var redgePart = edgePart('right'); var brEdgePart = edgePart('bottom-right'); var bedgePart = edgePart('bottom'); var blEdgePart = edgePart('bottom-left'); var ledgePart = edgePart('left'); var thumbPart = required({ name: 'thumb', defaults: constant({ dom: { styles: { position: 'absolute' } } }), overrides: function (detail) { return { events: derive([ redirectToPart(touchstart(), detail, 'spectrum'), redirectToPart(touchmove(), detail, 'spectrum'), redirectToPart(touchend(), detail, 'spectrum'), redirectToPart(mousedown(), detail, 'spectrum'), redirectToPart(mousemove(), detail, 'spectrum'), redirectToPart(mouseup(), detail, 'spectrum') ]) }; } }); var spectrumPart = required({ schema: [state$1('mouseIsDown', function () { return Cell(false); })], name: 'spectrum', overrides: function (detail) { var modelDetail = detail.model; var model = modelDetail.manager; var setValueFrom = function (component, simulatedEvent) { return model.getValueFromEvent(simulatedEvent).map(function (value) { return model.setValueFrom(component, detail, value); }); }; var touchEvents = derive([ run(touchstart(), setValueFrom), run(touchmove(), setValueFrom) ]); var mouseEvents = derive([ run(mousedown(), setValueFrom), run(mousemove(), function (spectrum, se) { if (detail.mouseIsDown.get()) { setValueFrom(spectrum, se); } }) ]); return { behaviours: derive$1(isTouch ? [] : [ Keying.config({ mode: 'special', onLeft: function (spectrum) { return model.onLeft(spectrum, detail); }, onRight: function (spectrum) { return model.onRight(spectrum, detail); }, onUp: function (spectrum) { return model.onUp(spectrum, detail); }, onDown: function (spectrum) { return model.onDown(spectrum, detail); } }), Focusing.config({}) ]), events: isTouch ? touchEvents : mouseEvents }; } }); var SliderParts = [ labelPart, ledgePart, redgePart, tedgePart, bedgePart, tlEdgePart, trEdgePart, blEdgePart, brEdgePart, thumbPart, spectrumPart ]; var isTouch$1 = detect$3().deviceType.isTouch(); var _sliderChangeEvent = 'slider.change.value'; var sliderChangeEvent = constant(_sliderChangeEvent); var getEventSource = function (simulatedEvent) { var evt = simulatedEvent.event().raw(); if (isTouch$1) { var touchEvent = evt; return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) { return Position(t.clientX, t.clientY); }) : Option.none(); } else { var mouseEvent = evt; return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) { return Position(me.clientX, me.clientY); }) : Option.none(); } }; var t = 'top', r$1 = 'right', b = 'bottom', l = 'left'; var minX = function (detail) { return detail.model.minX; }; var minY = function (detail) { return detail.model.minY; }; var min1X = function (detail) { return detail.model.minX - 1; }; var min1Y = function (detail) { return detail.model.minY - 1; }; var maxX = function (detail) { return detail.model.maxX; }; var maxY = function (detail) { return detail.model.maxY; }; var max1X = function (detail) { return detail.model.maxX + 1; }; var max1Y = function (detail) { return detail.model.maxY + 1; }; var range$2 = function (detail, max, min) { return max(detail) - min(detail); }; var xRange = function (detail) { return range$2(detail, maxX, minX); }; var yRange = function (detail) { return range$2(detail, maxY, minY); }; var halfX = function (detail) { return xRange(detail) / 2; }; var halfY = function (detail) { return yRange(detail) / 2; }; var step = function (detail) { return detail.stepSize; }; var snap = function (detail) { return detail.snapToGrid; }; var snapStart = function (detail) { return detail.snapStart; }; var rounded = function (detail) { return detail.rounded; }; var hasEdge = function (detail, edgeName) { return detail[edgeName + '-edge'] !== undefined; }; var hasLEdge = function (detail) { return hasEdge(detail, l); }; var hasREdge = function (detail) { return hasEdge(detail, r$1); }; var hasTEdge = function (detail) { return hasEdge(detail, t); }; var hasBEdge = function (detail) { return hasEdge(detail, b); }; var currentValue = function (detail) { return detail.model.value.get(); }; var xValue = function (x) { return { x: constant(x) }; }; var yValue = function (y) { return { y: constant(y) }; }; var xyValue = function (x, y) { return { x: constant(x), y: constant(y) }; }; var fireSliderChange = function (component, value) { emitWith(component, sliderChangeEvent(), { value: value }); }; var setToTLEdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail))); }; var setToTEdge = function (edge, detail) { fireSliderChange(edge, yValue(min1Y(detail))); }; var setToTEdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail))); }; var setToTREdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail))); }; var setToREdge = function (edge, detail) { fireSliderChange(edge, xValue(max1X(detail))); }; var setToREdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(max1X(detail), halfY(detail))); }; var setToBREdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail))); }; var setToBEdge = function (edge, detail) { fireSliderChange(edge, yValue(max1Y(detail))); }; var setToBEdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail))); }; var setToBLEdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail))); }; var setToLEdge = function (edge, detail) { fireSliderChange(edge, xValue(min1X(detail))); }; var setToLEdgeXY = function (edge, detail) { fireSliderChange(edge, xyValue(min1X(detail), halfY(detail))); }; var reduceBy = function (value, min, max, step) { if (value < min) { return value; } else if (value > max) { return max; } else if (value === min) { return min - 1; } else { return Math.max(min, value - step); } }; var increaseBy = function (value, min, max, step) { if (value > max) { return value; } else if (value < min) { return min; } else if (value === max) { return max + 1; } else { return Math.min(max, value + step); } }; var capValue = function (value, min, max) { return Math.max(min, Math.min(max, value)); }; var snapValueOf = function (value, min, max, step, snapStart) { return snapStart.fold(function () { var initValue = value - min; var extraValue = Math.round(initValue / step) * step; return capValue(min + extraValue, min - 1, max + 1); }, function (start) { var remainder = (value - start) % step; var adjustment = Math.round(remainder / step); var rawSteps = Math.floor((value - start) / step); var maxSteps = Math.floor((max - start) / step); var numSteps = Math.min(maxSteps, rawSteps + adjustment); var r = start + numSteps * step; return Math.max(start, r); }); }; var findOffsetOf = function (value, min, max) { return Math.min(max, Math.max(value, min)) - min; }; var findValueOf = function (args) { 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; var capMin = hasMinEdge ? min - 1 : min; var capMax = hasMaxEdge ? max + 1 : max; if (value < minBound) { return capMin; } else if (value > maxBound) { return capMax; } else { var offset = findOffsetOf(value, minBound, maxBound); var newValue = capValue(offset / screenRange * range + min, capMin, capMax); if (snap && newValue >= min && newValue <= max) { return snapValueOf(newValue, min, max, step, snapStart); } else if (rounded) { return Math.round(newValue); } else { return newValue; } } }; var findOffsetOfValue = function (args) { 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; if (value < min) { return hasMinEdge ? 0 : centerMinEdge; } else if (value > max) { return hasMaxEdge ? maxBound : centerMaxEdge; } else { return (value - min) / range * maxOffset; } }; var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height'; var getBounds$1 = function (component) { return component.element().dom().getBoundingClientRect(); }; var getBoundsProperty = function (bounds, property) { return bounds[property]; }; var getMinXBounds = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, left); }; var getMaxXBounds = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, right); }; var getMinYBounds = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, top); }; var getMaxYBounds = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, bottom); }; var getXScreenRange = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, width); }; var getYScreenRange = function (component) { var bounds = getBounds$1(component); return getBoundsProperty(bounds, height); }; var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) { return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge; }; var getXCenterOffSetOf = function (component, spectrum) { var componentBounds = getBounds$1(component); var spectrumBounds = getBounds$1(spectrum); var componentMinEdge = getBoundsProperty(componentBounds, left); var componentMaxEdge = getBoundsProperty(componentBounds, right); var spectrumMinEdge = getBoundsProperty(spectrumBounds, left); return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); }; var getYCenterOffSetOf = function (component, spectrum) { var componentBounds = getBounds$1(component); var spectrumBounds = getBounds$1(spectrum); var componentMinEdge = getBoundsProperty(componentBounds, top); var componentMaxEdge = getBoundsProperty(componentBounds, bottom); var spectrumMinEdge = getBoundsProperty(spectrumBounds, top); return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); }; var fireSliderChange$1 = function (spectrum, value) { emitWith(spectrum, sliderChangeEvent(), { value: value }); }; var sliderValue = function (x) { return { x: constant(x) }; }; var findValueOfOffset = function (spectrum, detail, left) { var args = { min: minX(detail), max: maxX(detail), range: xRange(detail), value: left, step: step(detail), snap: snap(detail), snapStart: snapStart(detail), rounded: rounded(detail), hasMinEdge: hasLEdge(detail), hasMaxEdge: hasREdge(detail), minBound: getMinXBounds(spectrum), maxBound: getMaxXBounds(spectrum), screenRange: getXScreenRange(spectrum) }; return findValueOf(args); }; var setValueFrom = function (spectrum, detail, value) { var xValue = findValueOfOffset(spectrum, detail, value); var sliderVal = sliderValue(xValue); fireSliderChange$1(spectrum, sliderVal); return xValue; }; var setToMin = function (spectrum, detail) { var min = minX(detail); fireSliderChange$1(spectrum, sliderValue(min)); }; var setToMax = function (spectrum, detail) { var max = maxX(detail); fireSliderChange$1(spectrum, sliderValue(max)); }; var moveBy = function (direction, spectrum, detail) { var f = direction > 0 ? increaseBy : reduceBy; var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail)); fireSliderChange$1(spectrum, sliderValue(xValue)); return Option.some(xValue); }; var handleMovement = function (direction) { return function (spectrum, detail) { return moveBy(direction, spectrum, detail).map(function () { return true; }); }; }; var getValueFromEvent = function (simulatedEvent) { var pos = getEventSource(simulatedEvent); return pos.map(function (p) { return p.left(); }); }; var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) { var minOffset = 0; var maxOffset = getXScreenRange(spectrum); var centerMinEdge = minEdge.bind(function (edge) { return Option.some(getXCenterOffSetOf(edge, spectrum)); }).getOr(minOffset); var centerMaxEdge = maxEdge.bind(function (edge) { return Option.some(getXCenterOffSetOf(edge, spectrum)); }).getOr(maxOffset); var args = { min: minX(detail), max: maxX(detail), range: xRange(detail), value: value, hasMinEdge: hasLEdge(detail), hasMaxEdge: hasREdge(detail), minBound: getMinXBounds(spectrum), minOffset: minOffset, maxBound: getMaxXBounds(spectrum), maxOffset: maxOffset, centerMinEdge: centerMinEdge, centerMaxEdge: centerMaxEdge }; return findOffsetOfValue(args); }; var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) { var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge); return getMinXBounds(spectrum) - getMinXBounds(slider) + offset; }; var setPositionFromValue = function (slider, thumb, detail, edges) { var value = currentValue(detail); var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); var thumbRadius = get$7(thumb.element()) / 2; set$2(thumb.element(), 'left', pos - thumbRadius + 'px'); }; var onLeft = handleMovement(-1); var onRight = handleMovement(1); var onUp = Option.none; var onDown = Option.none; var edgeActions = { 'top-left': Option.none(), 'top': Option.none(), 'top-right': Option.none(), 'right': Option.some(setToREdge), 'bottom-right': Option.none(), 'bottom': Option.none(), 'bottom-left': Option.none(), 'left': Option.some(setToLEdge) }; var HorizontalModel = /*#__PURE__*/Object.freeze({ setValueFrom: setValueFrom, setToMin: setToMin, setToMax: setToMax, findValueOfOffset: findValueOfOffset, getValueFromEvent: getValueFromEvent, findPositionOfValue: findPositionOfValue, setPositionFromValue: setPositionFromValue, onLeft: onLeft, onRight: onRight, onUp: onUp, onDown: onDown, edgeActions: edgeActions }); var fireSliderChange$2 = function (spectrum, value) { emitWith(spectrum, sliderChangeEvent(), { value: value }); }; var sliderValue$1 = function (y) { return { y: constant(y) }; }; var findValueOfOffset$1 = function (spectrum, detail, top) { var args = { min: minY(detail), max: maxY(detail), range: yRange(detail), value: top, step: step(detail), snap: snap(detail), snapStart: snapStart(detail), rounded: rounded(detail), hasMinEdge: hasTEdge(detail), hasMaxEdge: hasBEdge(detail), minBound: getMinYBounds(spectrum), maxBound: getMaxYBounds(spectrum), screenRange: getYScreenRange(spectrum) }; return findValueOf(args); }; var setValueFrom$1 = function (spectrum, detail, value) { var yValue = findValueOfOffset$1(spectrum, detail, value); var sliderVal = sliderValue$1(yValue); fireSliderChange$2(spectrum, sliderVal); return yValue; }; var setToMin$1 = function (spectrum, detail) { var min = minY(detail); fireSliderChange$2(spectrum, sliderValue$1(min)); }; var setToMax$1 = function (spectrum, detail) { var max = maxY(detail); fireSliderChange$2(spectrum, sliderValue$1(max)); }; var moveBy$1 = function (direction, spectrum, detail) { var f = direction > 0 ? increaseBy : reduceBy; var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail)); fireSliderChange$2(spectrum, sliderValue$1(yValue)); return Option.some(yValue); }; var handleMovement$1 = function (direction) { return function (spectrum, detail) { return moveBy$1(direction, spectrum, detail).map(function () { return true; }); }; }; var getValueFromEvent$1 = function (simulatedEvent) { var pos = getEventSource(simulatedEvent); return pos.map(function (p) { return p.top(); }); }; var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) { var minOffset = 0; var maxOffset = getYScreenRange(spectrum); var centerMinEdge = minEdge.bind(function (edge) { return Option.some(getYCenterOffSetOf(edge, spectrum)); }).getOr(minOffset); var centerMaxEdge = maxEdge.bind(function (edge) { return Option.some(getYCenterOffSetOf(edge, spectrum)); }).getOr(maxOffset); var args = { min: minY(detail), max: maxY(detail), range: yRange(detail), value: value, hasMinEdge: hasTEdge(detail), hasMaxEdge: hasBEdge(detail), minBound: getMinYBounds(spectrum), minOffset: minOffset, maxBound: getMaxYBounds(spectrum), maxOffset: maxOffset, centerMinEdge: centerMinEdge, centerMaxEdge: centerMaxEdge }; return findOffsetOfValue(args); }; var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) { var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge); return getMinYBounds(spectrum) - getMinYBounds(slider) + offset; }; var setPositionFromValue$1 = function (slider, thumb, detail, edges) { var value = currentValue(detail); var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); var thumbRadius = get$6(thumb.element()) / 2; set$2(thumb.element(), 'top', pos - thumbRadius + 'px'); }; var onLeft$1 = Option.none; var onRight$1 = Option.none; var onUp$1 = handleMovement$1(-1); var onDown$1 = handleMovement$1(1); var edgeActions$1 = { 'top-left': Option.none(), 'top': Option.some(setToTEdge), 'top-right': Option.none(), 'right': Option.none(), 'bottom-right': Option.none(), 'bottom': Option.some(setToBEdge), 'bottom-left': Option.none(), 'left': Option.none() }; var VerticalModel = /*#__PURE__*/Object.freeze({ setValueFrom: setValueFrom$1, setToMin: setToMin$1, setToMax: setToMax$1, findValueOfOffset: findValueOfOffset$1, getValueFromEvent: getValueFromEvent$1, findPositionOfValue: findPositionOfValue$1, setPositionFromValue: setPositionFromValue$1, onLeft: onLeft$1, onRight: onRight$1, onUp: onUp$1, onDown: onDown$1, edgeActions: edgeActions$1 }); var fireSliderChange$3 = function (spectrum, value) { emitWith(spectrum, sliderChangeEvent(), { value: value }); }; var sliderValue$2 = function (x, y) { return { x: constant(x), y: constant(y) }; }; var setValueFrom$2 = function (spectrum, detail, value) { var xValue = findValueOfOffset(spectrum, detail, value.left()); var yValue = findValueOfOffset$1(spectrum, detail, value.top()); var val = sliderValue$2(xValue, yValue); fireSliderChange$3(spectrum, val); return val; }; var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) { var f = direction > 0 ? increaseBy : reduceBy; var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail)); var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail)); fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue)); return Option.some(xValue); }; var handleMovement$2 = function (direction, isVerticalMovement) { return function (spectrum, detail) { return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () { return true; }); }; }; var setToMin$2 = function (spectrum, detail) { var mX = minX(detail); var mY = minY(detail); fireSliderChange$3(spectrum, sliderValue$2(mX, mY)); }; var setToMax$2 = function (spectrum, detail) { var mX = maxX(detail); var mY = maxY(detail); fireSliderChange$3(spectrum, sliderValue$2(mX, mY)); }; var getValueFromEvent$2 = function (simulatedEvent) { return getEventSource(simulatedEvent); }; var setPositionFromValue$2 = function (slider, thumb, detail, edges) { var value = currentValue(detail); var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); var thumbXRadius = get$7(thumb.element()) / 2; var thumbYRadius = get$6(thumb.element()) / 2; set$2(thumb.element(), 'left', xPos - thumbXRadius + 'px'); set$2(thumb.element(), 'top', yPos - thumbYRadius + 'px'); }; var onLeft$2 = handleMovement$2(-1, false); var onRight$2 = handleMovement$2(1, false); var onUp$2 = handleMovement$2(-1, true); var onDown$2 = handleMovement$2(1, true); var edgeActions$2 = { 'top-left': Option.some(setToTLEdgeXY), 'top': Option.some(setToTEdgeXY), 'top-right': Option.some(setToTREdgeXY), 'right': Option.some(setToREdgeXY), 'bottom-right': Option.some(setToBREdgeXY), 'bottom': Option.some(setToBEdgeXY), 'bottom-left': Option.some(setToBLEdgeXY), 'left': Option.some(setToLEdgeXY) }; var TwoDModel = /*#__PURE__*/Object.freeze({ setValueFrom: setValueFrom$2, setToMin: setToMin$2, setToMax: setToMax$2, getValueFromEvent: getValueFromEvent$2, setPositionFromValue: setPositionFromValue$2, onLeft: onLeft$2, onRight: onRight$2, onUp: onUp$2, onDown: onDown$2, edgeActions: edgeActions$2 }); var isTouch$2 = detect$3().deviceType.isTouch(); var SliderSchema = [ defaulted$1('stepSize', 1), defaulted$1('onChange', noop), defaulted$1('onChoose', noop), defaulted$1('onInit', noop), defaulted$1('onDragStart', noop), defaulted$1('onDragEnd', noop), defaulted$1('snapToGrid', false), defaulted$1('rounded', true), option('snapStart'), strictOf('model', choose$1('mode', { x: [ defaulted$1('minX', 0), defaulted$1('maxX', 100), state$1('value', function (spec) { return Cell(spec.mode.minX); }), strict$1('getInitialValue'), output('manager', HorizontalModel) ], y: [ defaulted$1('minY', 0), defaulted$1('maxY', 100), state$1('value', function (spec) { return Cell(spec.mode.minY); }), strict$1('getInitialValue'), output('manager', VerticalModel) ], xy: [ defaulted$1('minX', 0), defaulted$1('maxX', 100), defaulted$1('minY', 0), defaulted$1('maxY', 100), state$1('value', function (spec) { return Cell({ x: constant(spec.mode.minX), y: constant(spec.mode.minY) }); }), strict$1('getInitialValue'), output('manager', TwoDModel) ] })), field$1('sliderBehaviours', [ Keying, Representing ]) ].concat(!isTouch$2 ? [state$1('mouseIsDown', function () { return Cell(false); })] : []); var isTouch$3 = detect$3().deviceType.isTouch(); var sketch = function (detail, components, _spec, _externals) { var getThumb = function (component) { return getPartOrDie(component, detail, 'thumb'); }; var getSpectrum = function (component) { return getPartOrDie(component, detail, 'spectrum'); }; var getLeftEdge = function (component) { return getPart(component, detail, 'left-edge'); }; var getRightEdge = function (component) { return getPart(component, detail, 'right-edge'); }; var getTopEdge = function (component) { return getPart(component, detail, 'top-edge'); }; var getBottomEdge = function (component) { return getPart(component, detail, 'bottom-edge'); }; var modelDetail = detail.model; var model = modelDetail.manager; var refresh = function (slider, thumb) { model.setPositionFromValue(slider, thumb, detail, { getLeftEdge: getLeftEdge, getRightEdge: getRightEdge, getTopEdge: getTopEdge, getBottomEdge: getBottomEdge, getSpectrum: getSpectrum }); }; var changeValue = function (slider, newValue) { modelDetail.value.set(newValue); var thumb = getThumb(slider); refresh(slider, thumb); detail.onChange(slider, thumb, newValue); return Option.some(true); }; var resetToMin = function (slider) { model.setToMin(slider, detail); }; var resetToMax = function (slider) { model.setToMax(slider, detail); }; var touchEvents = [ run(touchstart(), function (slider, _simulatedEvent) { detail.onDragStart(slider, getThumb(slider)); }), run(touchend(), function (slider, _simulatedEvent) { detail.onDragEnd(slider, getThumb(slider)); }) ]; var mouseEvents = [ run(mousedown(), function (slider, simulatedEvent) { simulatedEvent.stop(); detail.onDragStart(slider, getThumb(slider)); detail.mouseIsDown.set(true); }), run(mouseup(), function (slider, _simulatedEvent) { detail.onDragEnd(slider, getThumb(slider)); }) ]; var uiEventsArr = isTouch$3 ? touchEvents : mouseEvents; return { uid: detail.uid, dom: detail.dom, components: components, behaviours: augment(detail.sliderBehaviours, flatten([ !isTouch$3 ? [Keying.config({ mode: 'special', focusIn: function (slider) { return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true)); } })] : [], [ Representing.config({ store: { mode: 'manual', getValue: function (_) { return modelDetail.value.get(); } } }), Receiving.config({ channels: { 'mouse.released': { onReceive: function (slider, se) { var fireOnChoose = function () { getPart(slider, detail, 'thumb').each(function (thumb) { var value = modelDetail.value.get(); detail.onChoose(slider, thumb, value); }); }; if (isTouch$3) { fireOnChoose(); } else { var wasDown = detail.mouseIsDown.get(); detail.mouseIsDown.set(false); if (wasDown) { fireOnChoose(); } } } } } }) ] ])), events: derive([ run(sliderChangeEvent(), function (slider, simulatedEvent) { changeValue(slider, simulatedEvent.event().value()); }), runOnAttached(function (slider, simulatedEvent) { var getInitial = modelDetail.getInitialValue(); modelDetail.value.set(getInitial); var thumb = getThumb(slider); refresh(slider, thumb); var spectrum = getSpectrum(slider); detail.onInit(slider, thumb, spectrum, modelDetail.value.get()); }) ].concat(uiEventsArr)), apis: { resetToMin: resetToMin, resetToMax: resetToMax, changeValue: changeValue, refresh: refresh }, domModification: { styles: { position: 'relative' } } }; }; var Slider = composite$1({ name: 'Slider', configFields: SliderSchema, partFields: SliderParts, factory: sketch, apis: { resetToMin: function (apis, slider) { apis.resetToMin(slider); }, resetToMax: function (apis, slider) { apis.resetToMax(slider); }, refresh: function (apis, slider) { apis.refresh(slider); } } }); var sliderFactory = function (translate, getClass) { var spectrum = Slider.parts().spectrum({ dom: { tag: 'div', classes: [getClass('hue-slider-spectrum')], attributes: { role: 'presentation' } } }); var thumb = Slider.parts().thumb({ dom: { tag: 'div', classes: [getClass('hue-slider-thumb')], attributes: { role: 'presentation' } } }); return Slider.sketch({ dom: { tag: 'div', classes: [getClass('hue-slider')], attributes: { role: 'presentation' } }, rounded: false, model: { mode: 'y', getInitialValue: constant({ y: constant(0) }) }, components: [ spectrum, thumb ], sliderBehaviours: derive$1([Focusing.config({})]), onChange: function (slider, _thumb, value) { emitWith(slider, sliderUpdate(), { value: value }); } }); }; var HueSlider = { sliderFactory: sliderFactory }; var owner$3 = 'form'; var schema$h = [field$1('formBehaviours', [Representing])]; var getPartName = function (name) { return ''; }; var sketch$1 = function (fSpec) { var parts = function () { var record = []; var field = function (name, config) { record.push(name); return generateOne(owner$3, getPartName(name), config); }; return { field: field, record: function () { return record; } }; }(); var spec = fSpec(parts); var partNames = parts.record(); var fieldParts = map(partNames, function (n) { return required({ name: n, pname: getPartName(n) }); }); return composite(owner$3, schema$h, fieldParts, make$4, spec); }; var toResult$1 = function (o, e) { return o.fold(function () { return Result.error(e); }, Result.value); }; var make$4 = function (detail, components, spec) { return { uid: detail.uid, dom: detail.dom, components: components, behaviours: augment(detail.formBehaviours, [Representing.config({ store: { mode: 'manual', getValue: function (form) { var resPs = getAllParts(form, detail); return map$1(resPs, function (resPThunk, pName) { return resPThunk().bind(function (v) { var opt = Composing.getCurrent(v); return toResult$1(opt, 'missing current'); }).map(Representing.getValue); }); }, setValue: function (form, values) { each$1(values, function (newValue, key) { getPart(form, detail, key).each(function (wrapper) { Composing.getCurrent(wrapper).each(function (field) { Representing.setValue(field, newValue); }); }); }); } } })]), apis: { getField: function (form, key) { return getPart(form, detail, key).bind(Composing.getCurrent); } } }; }; var Form = { getField: makeApi(function (apis, component, key) { return apis.getField(component, key); }), sketch: sketch$1 }; var validInput = generate$1('valid-input'); var invalidInput = generate$1('invalid-input'); var validatingInput = generate$1('validating-input'); var translatePrefix = 'colorcustom.rgb.'; var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) { var invalidation = function (label, isValid) { return Invalidating.config({ invalidClass: getClass('invalid'), notify: { onValidate: function (comp) { emitWith(comp, validatingInput, { type: label }); }, onValid: function (comp) { emitWith(comp, validInput, { type: label, value: Representing.getValue(comp) }); }, onInvalid: function (comp) { emitWith(comp, invalidInput, { type: label, value: Representing.getValue(comp) }); } }, validator: { validate: function (comp) { var value = Representing.getValue(comp); var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid')); return Future.pure(res); }, validateOnLoad: false } }); }; var renderTextField = function (isValid, name, label, description, data) { var helptext = translate(translatePrefix + 'range'); var pLabel = FormField.parts().label({ dom: { tag: 'label', innerHtml: label, attributes: { 'aria-label': description } } }); var pField = FormField.parts().field({ data: data, factory: Input, inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}), inputClasses: [getClass('textfield')], inputBehaviours: derive$1([ invalidation(name, isValid), Tabstopping.config({}) ]), onSetValue: function (input) { if (Invalidating.isInvalid(input)) { var run = Invalidating.run(input); run.get(noop); } } }); var comps = [ pLabel, pField ]; var concats = name !== 'hex' ? [FormField.parts()['aria-descriptor']({ text: helptext })] : []; var components = comps.concat(concats); return { dom: { tag: 'div', attributes: { role: 'presentation' } }, components: components }; }; var copyRgbToHex = function (form, rgba) { var hex = fromRgba(rgba); Form.getField(form, 'hex').each(function (hexField) { if (!Focusing.isFocused(hexField)) { Representing.setValue(form, { hex: hex.value() }); } }); return hex; }; var copyRgbToForm = function (form, rgb) { var red = rgb.red(); var green = rgb.green(); var blue = rgb.blue(); Representing.setValue(form, { red: red, green: green, blue: blue }); }; var memPreview = record({ dom: { tag: 'div', classes: [getClass('rgba-preview')], styles: { 'background-color': 'white' }, attributes: { role: 'presentation' } } }); var updatePreview = function (anyInSystem, hex) { memPreview.getOpt(anyInSystem).each(function (preview) { set$2(preview.element(), 'background-color', '#' + hex.value()); }); }; var factory = function () { var state = { red: constant(Cell(Option.some(255))), green: constant(Cell(Option.some(255))), blue: constant(Cell(Option.some(255))), hex: constant(Cell(Option.some('ffffff'))) }; var copyHexToRgb = function (form, hex) { var rgb = fromHex(hex); copyRgbToForm(form, rgb); setValueRgb(rgb); }; var get = function (prop) { return state[prop]().get(); }; var set = function (prop, value) { state[prop]().set(value); }; var getValueRgb = function () { return get('red').bind(function (red) { return get('green').bind(function (green) { return get('blue').map(function (blue) { return rgbaColour(red, green, blue, 1); }); }); }); }; var setValueRgb = function (rgb) { var red = rgb.red(); var green = rgb.green(); var blue = rgb.blue(); set('red', Option.some(red)); set('green', Option.some(green)); set('blue', Option.some(blue)); }; var onInvalidInput = function (form, simulatedEvent) { var data = simulatedEvent.event(); if (data.type() !== 'hex') { set(data.type(), Option.none()); } else { onInvalidHexx(form); } }; var onValidHex = function (form, value) { onValidHexx(form); var hex = hexColour(value); set('hex', Option.some(value)); var rgb = fromHex(hex); copyRgbToForm(form, rgb); setValueRgb(rgb); emitWith(form, fieldsUpdate(), { hex: hex }); updatePreview(form, hex); }; var onValidRgb = function (form, prop, value) { var val = parseInt(value, 10); set(prop, Option.some(val)); getValueRgb().each(function (rgb) { var hex = copyRgbToHex(form, rgb); updatePreview(form, hex); }); }; var isHexInputEvent = function (data) { return data.type() === 'hex'; }; var onValidInput = function (form, simulatedEvent) { var data = simulatedEvent.event(); if (isHexInputEvent(data)) { onValidHex(form, data.value()); } else { onValidRgb(form, data.type(), data.value()); } }; var formPartStrings = function (key) { return { label: translate(translatePrefix + key + '.label'), description: translate(translatePrefix + key + '.description') }; }; var redStrings = formPartStrings('red'); var greenStrings = formPartStrings('green'); var blueStrings = formPartStrings('blue'); var hexStrings = formPartStrings('hex'); return deepMerge(Form.sketch(function (parts) { return { dom: { tag: 'form', classes: [getClass('rgb-form')], attributes: { 'aria-label': translate('aria.color.picker') } }, components: [ parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))), parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))), parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))), parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))), memPreview.asSpec() ], formBehaviours: derive$1([ Invalidating.config({ invalidClass: getClass('form-invalid') }), config('rgb-form-events', [ run(validInput, onValidInput), run(invalidInput, onInvalidInput), run(validatingInput, onInvalidInput) ]) ]) }; }), { apis: { updateHex: function (form, hex) { Representing.setValue(form, { hex: hex.value() }); copyHexToRgb(form, hex); updatePreview(form, hex); } } }); }; var rgbFormSketcher = single$2({ factory: factory, name: 'RgbForm', configFields: [], apis: { updateHex: function (apis, form, hex) { apis.updateHex(form, hex); } }, extraApis: {} }); return rgbFormSketcher; }; var RgbForm = { rgbFormFactory: rgbFormFactory }; var paletteFactory = function (_translate, getClass) { var spectrumPart = Slider.parts().spectrum({ dom: { tag: 'canvas', attributes: { role: 'presentation' }, classes: [getClass('sv-palette-spectrum')] } }); var thumbPart = Slider.parts().thumb({ dom: { tag: 'div', attributes: { role: 'presentation' }, classes: [getClass('sv-palette-thumb')], innerHtml: '' } }); var setColour = function (canvas, rgba) { var width = canvas.width, height = canvas.height; var ctx = canvas.getContext('2d'); if (ctx === null) { return; } ctx.fillStyle = rgba; ctx.fillRect(0, 0, width, height); var grdWhite = ctx.createLinearGradient(0, 0, width, 0); grdWhite.addColorStop(0, 'rgba(255,255,255,1)'); grdWhite.addColorStop(1, 'rgba(255,255,255,0)'); ctx.fillStyle = grdWhite; ctx.fillRect(0, 0, width, height); var grdBlack = ctx.createLinearGradient(0, 0, 0, height); grdBlack.addColorStop(0, 'rgba(0,0,0,0)'); grdBlack.addColorStop(1, 'rgba(0,0,0,1)'); ctx.fillStyle = grdBlack; ctx.fillRect(0, 0, width, height); }; var setSliderColour = function (slider, rgba) { var canvas = slider.components()[0].element().dom(); setColour(canvas, toString(rgba)); }; var factory = function (_detail) { var getInitialValue = constant({ x: constant(0), y: constant(0) }); var onChange = function (slider, _thumb, value) { emitWith(slider, paletteUpdate(), { value: value }); }; var onInit = function (_slider, _thumb, spectrum, _value) { setColour(spectrum.element().dom(), toString(redColour())); }; var sliderBehaviours = derive$1([ Composing.config({ find: Option.some }), Focusing.config({}) ]); return Slider.sketch({ dom: { tag: 'div', attributes: { role: 'presentation' }, classes: [getClass('sv-palette')] }, model: { mode: 'xy', getInitialValue: getInitialValue }, rounded: false, components: [ spectrumPart, thumbPart ], onChange: onChange, onInit: onInit, sliderBehaviours: sliderBehaviours }); }; var saturationBrightnessPaletteSketcher = single$2({ factory: factory, name: 'SaturationBrightnessPalette', configFields: [], apis: { setRgba: function (_apis, slider, rgba) { setSliderColour(slider, rgba); } }, extraApis: {} }); return saturationBrightnessPaletteSketcher; }; var SaturationBrightnessPalette = { paletteFactory: paletteFactory }; var makeFactory = function (translate, getClass) { var factory = function (detail) { var rgbForm = RgbForm.rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex); var sbPalette = SaturationBrightnessPalette.paletteFactory(translate, getClass); var state = { paletteRgba: constant(Cell(redColour())) }; var memPalette = record(sbPalette.sketch({})); var memRgb = record(rgbForm.sketch({})); var updatePalette = function (anyInSystem, hex) { memPalette.getOpt(anyInSystem).each(function (palette) { var rgba = fromHex(hex); state.paletteRgba().set(rgba); sbPalette.setRgba(palette, rgba); }); }; var updateFields = function (anyInSystem, hex) { memRgb.getOpt(anyInSystem).each(function (form) { rgbForm.updateHex(form, hex); }); }; var runUpdates = function (anyInSystem, hex, updates) { each(updates, function (update) { update(anyInSystem, hex); }); }; var paletteUpdates = function () { var updates = [updateFields]; return function (form, simulatedEvent) { var value = simulatedEvent.event().value(); var oldRgb = state.paletteRgba().get(); var hsvColour$1 = fromRgb(oldRgb); var newHsvColour = hsvColour(hsvColour$1.hue(), value.x(), 100 - value.y()); var rgb = fromHsv(newHsvColour); var nuHex = fromRgba(rgb); runUpdates(form, nuHex, updates); }; }; var sliderUpdates = function () { var updates = [ updatePalette, updateFields ]; return function (form, simulatedEvent) { var value = simulatedEvent.event().value(); var hex = calcHex(value.y()); runUpdates(form, hex, updates); }; }; return { uid: detail.uid, dom: detail.dom, components: [ memPalette.asSpec(), HueSlider.sliderFactory(translate, getClass), memRgb.asSpec() ], behaviours: derive$1([ config('colour-picker-events', [ run(paletteUpdate(), paletteUpdates()), run(sliderUpdate(), sliderUpdates()) ]), Composing.config({ find: function (comp) { return memRgb.getOpt(comp); } }), Keying.config({ mode: 'acyclic' }) ]) }; }; var colourPickerSketcher = single$2({ name: 'ColourPicker', configFields: [ strict$1('dom'), defaulted$1('onValidHex', noop), defaulted$1('onInvalidHex', noop) ], factory: factory }); return colourPickerSketcher; }; var ColourPicker = { makeFactory: makeFactory }; var self$1 = function () { return Composing.config({ find: Option.some }); }; var memento = function (mem) { return Composing.config({ find: mem.getOpt }); }; var childAt = function (index) { return Composing.config({ find: function (comp) { return child(comp.element(), index).bind(function (element) { return comp.getSystem().getByDom(element).toOption(); }); } }); }; var ComposingConfigs = { self: self$1, memento: memento, childAt: childAt }; var english = { 'colorcustom.rgb.red.label': 'R', 'colorcustom.rgb.red.description': 'Red component', 'colorcustom.rgb.green.label': 'G', 'colorcustom.rgb.green.description': 'Green component', 'colorcustom.rgb.blue.label': 'B', 'colorcustom.rgb.blue.description': 'Blue component', 'colorcustom.rgb.hex.label': '#', 'colorcustom.rgb.hex.description': 'Hex color code', 'colorcustom.rgb.range': 'Range 0 to 255', 'colorcustom.sb.saturation': 'Saturation', 'colorcustom.sb.brightness': 'Brightness', 'colorcustom.sb.picker': 'Saturation and Brightness Picker', 'colorcustom.sb.palette': 'Saturation and Brightness Palette', 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes', 'colorcustom.hue.hue': 'Hue', 'colorcustom.hue.slider': 'Hue Slider', 'colorcustom.hue.palette': 'Hue Palette', 'colorcustom.hue.instructions': 'Use arrow keys to select a hue', 'aria.color.picker': 'Color Picker', 'aria.input.invalid': 'Invalid input' }; var getEnglishText = function (key) { return english[key]; }; var translate$1 = function (key) { return getEnglishText(key); }; var renderColorPicker = function (spec) { var getClass = function (key) { return 'tox-' + key; }; var colourPickerFactory = ColourPicker.makeFactory(translate$1, getClass); var onValidHex = function (form) { emitWith(form, formActionEvent, { name: 'hex-valid', value: true }); }; var onInvalidHex = function (form) { emitWith(form, formActionEvent, { name: 'hex-valid', value: false }); }; var memPicker = record(colourPickerFactory.sketch({ dom: { tag: 'div', classes: [getClass('color-picker-container')], attributes: { role: 'presentation' } }, onValidHex: onValidHex, onInvalidHex: onInvalidHex })); return { dom: { tag: 'div' }, components: [memPicker.asSpec()], behaviours: derive$1([ Representing.config({ store: { mode: 'manual', getValue: function (comp) { var picker = memPicker.get(comp); var optRgbForm = Composing.getCurrent(picker); var optHex = optRgbForm.bind(function (rgbForm) { var formValues = Representing.getValue(rgbForm); return formValues.hex; }); return optHex.map(function (hex) { return '#' + hex; }).getOr(''); }, setValue: function (comp, newValue) { var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/; var m = pattern.exec(newValue); var picker = memPicker.get(comp); var optRgbForm = Composing.getCurrent(picker); optRgbForm.fold(function () { domGlobals.console.log('Can not find form'); }, function (rgbForm) { Representing.setValue(rgbForm, { hex: Option.from(m[1]).getOr('') }); Form.getField(rgbForm, 'hex').each(function (hexField) { emit(hexField, input()); }); }); } } }), ComposingConfigs.self() ]) }; }; var global$a = tinymce.util.Tools.resolve('tinymce.Resource'); var isOldCustomEditor = function (spec) { return Object.prototype.hasOwnProperty.call(spec, 'init'); }; var renderCustomEditor = function (spec) { var editorApi = Cell(Option.none()); var memReplaced = record({ dom: { tag: spec.tag } }); var initialValue = Cell(Option.none()); return { dom: { tag: 'div', classes: ['tox-custom-editor'] }, behaviours: derive$1([ config('editor-foo-events', [runOnAttached(function (component) { memReplaced.getOpt(component).each(function (ta) { (isOldCustomEditor(spec) ? spec.init(ta.element().dom()) : global$a.load(spec.scriptId, spec.scriptUrl).then(function (init) { return init(ta.element().dom(), spec.settings); })).then(function (ea) { initialValue.get().each(function (cvalue) { ea.setValue(cvalue); }); initialValue.set(Option.none()); editorApi.set(Option.some(ea)); }); }); })]), Representing.config({ store: { mode: 'manual', getValue: function () { return editorApi.get().fold(function () { return initialValue.get().getOr(''); }, function (ed) { return ed.getValue(); }); }, setValue: function (component, value) { editorApi.get().fold(function () { initialValue.set(Option.some(value)); }, function (ed) { return ed.setValue(value); }); } } }), ComposingConfigs.self() ]), components: [memReplaced.asSpec()] }; }; var processors = objOf([ defaulted$1('preprocess', identity), defaulted$1('postprocess', identity) ]); var memento$1 = function (mem, rawProcessors) { var ps = asRawOrDie('RepresentingConfigs.memento processors', processors, rawProcessors); return Representing.config({ store: { mode: 'manual', getValue: function (comp) { var other = mem.get(comp); var rawValue = Representing.getValue(other); return ps.postprocess(rawValue); }, setValue: function (comp, rawValue) { var newValue = ps.preprocess(rawValue); var other = mem.get(comp); Representing.setValue(other, newValue); } } }); }; var withComp = function (optInitialValue, getter, setter) { return Representing.config(deepMerge({ store: { mode: 'manual', getValue: getter, setValue: setter } }, optInitialValue.map(function (initialValue) { return { store: { initialValue: initialValue } }; }).getOr({}))); }; var withElement = function (initialValue, getter, setter) { return withComp(initialValue, function (c) { return getter(c.element()); }, function (c, v) { return setter(c.element(), v); }); }; var domValue = function (optInitialValue) { return withElement(optInitialValue, get$5, set$3); }; var domHtml = function (optInitialValue) { return withElement(optInitialValue, get$1, set); }; var memory$1 = function (initialValue) { return Representing.config({ store: { mode: 'memory', initialValue: initialValue } }); }; var RepresentingConfigs = { memento: memento$1, withElement: withElement, withComp: withComp, domValue: domValue, domHtml: domHtml, memory: memory$1 }; var extensionsAccepted = '.jpg,.jpeg,.png,.gif'; var filterByExtension = function (files) { var re = new RegExp('(' + extensionsAccepted.split(/\s*,\s*/).join('|') + ')$', 'i'); return filter(from$1(files), function (file) { return re.test(file.name); }); }; var renderDropZone = function (spec, providersBackstage) { var stopper = function (_, se) { se.stop(); }; var sequence = function (actions) { return function (comp, se) { each(actions, function (a) { a(comp, se); }); }; }; var onDrop = function (comp, se) { if (!Disabling.isDisabled(comp)) { var transferEvent = se.event().raw(); handleFiles(comp, transferEvent.dataTransfer.files); } }; var onSelect = function (component, simulatedEvent) { var files = simulatedEvent.event().raw().target.files; handleFiles(component, files); }; var handleFiles = function (component, files) { Representing.setValue(component, filterByExtension(files)); emitWith(component, formChangeEvent, { name: spec.name }); }; var memInput = record({ dom: { tag: 'input', attributes: { type: 'file', accept: 'image/*' }, styles: { display: 'none' } }, behaviours: derive$1([config('input-file-events', [cutter(tapOrClick())])]) }); var renderField = function (s) { return { uid: s.uid, dom: { tag: 'div', classes: ['tox-dropzone-container'] }, behaviours: derive$1([ RepresentingConfigs.memory([]), ComposingConfigs.self(), Disabling.config({}), Toggling.config({ toggleClass: 'dragenter', toggleOnExecute: false }), config('dropzone-events', [ run('dragenter', sequence([ stopper, Toggling.toggle ])), run('dragleave', sequence([ stopper, Toggling.toggle ])), run('dragover', stopper), run('drop', sequence([ stopper, onDrop ])), run(change(), onSelect) ]) ]), components: [{ dom: { tag: 'div', classes: ['tox-dropzone'], styles: {} }, components: [ { dom: { tag: 'p', innerHtml: providersBackstage.translate('Drop an image here') } }, Button.sketch({ dom: { tag: 'button', innerHtml: providersBackstage.translate('Browse for an image'), styles: { position: 'relative' }, classes: [ 'tox-button', 'tox-button--secondary' ] }, components: [memInput.asSpec()], action: function (comp) { var inputComp = memInput.get(comp); inputComp.element().dom().click(); }, buttonBehaviours: derive$1([Tabstopping.config({})]) }) ] }] }; }; var pLabel = spec.label.map(function (label) { return renderLabel(label, providersBackstage); }); var pField = FormField.parts().field({ factory: { sketch: renderField } }); return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []); }; var renderGrid = function (spec, backstage) { return { dom: { tag: 'div', classes: [ 'tox-form__grid', 'tox-form__grid--' + spec.columns + 'col' ] }, components: map(spec.items, backstage.interpreter) }; }; var beforeObject = generate$1('alloy-fake-before-tabstop'); var afterObject = generate$1('alloy-fake-after-tabstop'); var craftWithClasses = function (classes) { return { dom: { tag: 'div', styles: { width: '1px', height: '1px', outline: 'none' }, attributes: { tabindex: '0' }, classes: classes }, behaviours: derive$1([ Focusing.config({ ignore: true }), Tabstopping.config({}) ]) }; }; var craft = function (spec) { return { dom: { tag: 'div', classes: ['tox-navobj'] }, components: [ craftWithClasses([beforeObject]), spec, craftWithClasses([afterObject]) ], behaviours: derive$1([ComposingConfigs.childAt(1)]) }; }; var triggerTab = function (placeholder, shiftKey) { emitWith(placeholder, keydown(), { raw: { which: 9, shiftKey: shiftKey } }); }; var onFocus$1 = function (container, targetComp) { var target = targetComp.element(); if (has$2(target, beforeObject)) { triggerTab(container, true); } else if (has$2(target, afterObject)) { triggerTab(container, false); } }; var isPseudoStop = function (element) { return closest$4(element, [ '.' + beforeObject, '.' + afterObject ].join(','), constant(false)); }; var NavigableObject = { isPseudoStop: isPseudoStop, onFocus: onFocus$1, craft: craft }; var platformNeedsSandboxing = !(detect$3().browser.isIE() || detect$3().browser.isEdge()); var getDynamicSource = function (isSandbox) { var cachedValue = Cell(''); return { getValue: function (frameComponent) { return cachedValue.get(); }, setValue: function (frameComponent, html) { if (!isSandbox) { set$1(frameComponent.element(), 'src', 'javascript:\'\''); var doc = frameComponent.element().dom().contentWindow.document; doc.open(); doc.write(html); doc.close(); } else { set$1(frameComponent.element(), 'srcdoc', html); } cachedValue.set(html); } }; }; var renderIFrame = function (spec, providersBackstage) { var isSandbox = platformNeedsSandboxing && spec.sandboxed; var attributes = __assign(__assign({}, spec.label.map(function (title) { return { title: title }; }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {}); var sourcing = getDynamicSource(isSandbox); var pLabel = spec.label.map(function (label) { return renderLabel(label, providersBackstage); }); var factory = function (newSpec) { return NavigableObject.craft({ uid: newSpec.uid, dom: { tag: 'iframe', attributes: attributes }, behaviours: derive$1([ Tabstopping.config({}), Focusing.config({}), RepresentingConfigs.withComp(Option.none(), sourcing.getValue, sourcing.setValue) ]) }); }; var pField = FormField.parts().field({ factory: { sketch: factory } }); return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []); }; function create$5(width, height) { return resize(domGlobals.document.createElement('canvas'), width, height); } function clone$1(canvas) { var tCanvas = create$5(canvas.width, canvas.height); var ctx = get2dContext(tCanvas); ctx.drawImage(canvas, 0, 0); return tCanvas; } function get2dContext(canvas) { return canvas.getContext('2d'); } function resize(canvas, width, height) { canvas.width = width; canvas.height = height; return canvas; } function getWidth(image) { return image.naturalWidth || image.width; } function getHeight(image) { return image.naturalHeight || image.height; } var promise = function () { var Promise = function (fn) { if (typeof this !== 'object') { throw new TypeError('Promises must be constructed via new'); } if (typeof fn !== 'function') { throw new TypeError('not a function'); } this._state = null; this._value = null; this._deferreds = []; doResolve(fn, bind(resolve, this), bind(reject, this)); }; var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) { domGlobals.setTimeout(fn, 1); }; function bind(fn, thisArg) { return function () { return fn.apply(thisArg, arguments); }; } var isArray = Array.isArray || function (value) { return Object.prototype.toString.call(value) === '[object Array]'; }; function handle(deferred) { var me = this; if (this._state === null) { this._deferreds.push(deferred); return; } asap(function () { var cb = me._state ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (me._state ? deferred.resolve : deferred.reject)(me._value); return; } var ret; try { ret = cb(me._value); } catch (e) { deferred.reject(e); return; } deferred.resolve(ret); }); } function resolve(newValue) { try { if (newValue === this) { throw new TypeError('A promise cannot be resolved with itself.'); } if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then; if (typeof then === 'function') { doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this)); return; } } this._state = true; this._value = newValue; finale.call(this); } catch (e) { reject.call(this, e); } } function reject(newValue) { this._state = false; this._value = newValue; finale.call(this); } function finale() { for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) { var deferred = _a[_i]; handle.call(this, deferred); } this._deferreds = []; } function Handler(onFulfilled, onRejected, resolve, reject) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.resolve = resolve; this.reject = reject; } function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) { return; } done = true; onFulfilled(value); }, function (reason) { if (done) { return; } done = true; onRejected(reason); }); } catch (ex) { if (done) { return; } done = true; onRejected(ex); } } Promise.prototype.catch = function (onRejected) { return this.then(null, onRejected); }; Promise.prototype.then = function (onFulfilled, onRejected) { var me = this; return new Promise(function (resolve, reject) { handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject)); }); }; Promise.all = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values); return new Promise(function (resolve, reject) { if (args.length === 0) { return resolve([]); } var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call(val, function (val) { res(i, val); }, reject); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise.resolve = function (value) { if (value && typeof value === 'object' && value.constructor === Promise) { return value; } return new Promise(function (resolve) { resolve(value); }); }; Promise.reject = function (reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.race = function (values) { return new Promise(function (resolve, reject) { for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { var value = values_1[_i]; value.then(resolve, reject); } }); }; return Promise; }; var Promise$1 = window.Promise ? window.Promise : promise(); function blobToImage(blob) { return new Promise$1(function (resolve, reject) { var blobUrl = domGlobals.URL.createObjectURL(blob); var image = new domGlobals.Image(); var removeListeners = function () { image.removeEventListener('load', loaded); image.removeEventListener('error', error); }; function loaded() { removeListeners(); resolve(image); } function error() { removeListeners(); reject('Unable to load data of type ' + blob.type + ': ' + blobUrl); } image.addEventListener('load', loaded); image.addEventListener('error', error); image.src = blobUrl; if (image.complete) { loaded(); } }); } function dataUriToBlobSync(uri) { var data = uri.split(','); var matches = /data:([^;]+)/.exec(data[0]); if (!matches) { return Option.none(); } var mimetype = matches[1]; var base64 = data[1]; var sliceSize = 1024; var byteCharacters = domGlobals.atob(base64); var bytesLength = byteCharacters.length; var slicesCount = Math.ceil(bytesLength / sliceSize); var byteArrays = new Array(slicesCount); for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { var begin = sliceIndex * sliceSize; var end = Math.min(begin + sliceSize, bytesLength); var bytes = new Array(end - begin); for (var offset = begin, i = 0; offset < end; ++i, ++offset) { bytes[i] = byteCharacters[offset].charCodeAt(0); } byteArrays[sliceIndex] = new Uint8Array(bytes); } return Option.some(new domGlobals.Blob(byteArrays, { type: mimetype })); } function dataUriToBlob(uri) { return new Promise$1(function (resolve, reject) { dataUriToBlobSync(uri).fold(function () { reject('uri is not base64: ' + uri); }, resolve); }); } function canvasToBlob(canvas, type, quality) { type = type || 'image/png'; if (domGlobals.HTMLCanvasElement.prototype.toBlob) { return new Promise$1(function (resolve, reject) { canvas.toBlob(function (blob) { if (blob) { resolve(blob); } else { reject(); } }, type, quality); }); } else { return dataUriToBlob(canvas.toDataURL(type, quality)); } } function canvasToDataURL(canvas, type, quality) { type = type || 'image/png'; return canvas.toDataURL(type, quality); } function blobToCanvas(blob) { return blobToImage(blob).then(function (image) { revokeImageUrl(image); var canvas = create$5(getWidth(image), getHeight(image)); var context = get2dContext(canvas); context.drawImage(image, 0, 0); return canvas; }); } function blobToDataUri(blob) { return new Promise$1(function (resolve) { var reader = new domGlobals.FileReader(); reader.onloadend = function () { resolve(reader.result); }; reader.readAsDataURL(blob); }); } function revokeImageUrl(image) { domGlobals.URL.revokeObjectURL(image.src); } function create$6(getCanvas, blob, uri) { var initialType = blob.type; var getType = constant(initialType); function toBlob() { return Promise$1.resolve(blob); } function toDataURL() { return uri; } function toBase64() { return uri.split(',')[1]; } function toAdjustedBlob(type, quality) { return getCanvas.then(function (canvas) { return canvasToBlob(canvas, type, quality); }); } function toAdjustedDataURL(type, quality) { return getCanvas.then(function (canvas) { return canvasToDataURL(canvas, type, quality); }); } function toAdjustedBase64(type, quality) { return toAdjustedDataURL(type, quality).then(function (dataurl) { return dataurl.split(',')[1]; }); } function toCanvas() { return getCanvas.then(clone$1); } return { getType: getType, toBlob: toBlob, toDataURL: toDataURL, toBase64: toBase64, toAdjustedBlob: toAdjustedBlob, toAdjustedDataURL: toAdjustedDataURL, toAdjustedBase64: toAdjustedBase64, toCanvas: toCanvas }; } function fromBlob(blob) { return blobToDataUri(blob).then(function (uri) { return create$6(blobToCanvas(blob), blob, uri); }); } function fromCanvas(canvas, type) { return canvasToBlob(canvas, type).then(function (blob) { return create$6(Promise$1.resolve(canvas), blob, canvas.toDataURL()); }); } var blobToImageResult = function (blob) { return fromBlob(blob); }; function clamp(value, min, max) { var parsedValue = typeof value === 'string' ? parseFloat(value) : value; if (parsedValue > max) { parsedValue = max; } else if (parsedValue < min) { parsedValue = min; } return parsedValue; } function identity$1() { return [ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]; } var DELTA_INDEX = [ 0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11, 0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.2, 0.21, 0.22, 0.24, 0.25, 0.27, 0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.42, 0.44, 0.46, 0.48, 0.5, 0.53, 0.56, 0.59, 0.62, 0.65, 0.68, 0.71, 0.74, 0.77, 0.8, 0.83, 0.86, 0.89, 0.92, 0.95, 0.98, 1, 1.06, 1.12, 1.18, 1.24, 1.3, 1.36, 1.42, 1.48, 1.54, 1.6, 1.66, 1.72, 1.78, 1.84, 1.9, 1.96, 2, 2.12, 2.25, 2.37, 2.5, 2.62, 2.75, 2.87, 3, 3.2, 3.4, 3.6, 3.8, 4, 4.3, 4.7, 4.9, 5, 5.5, 6, 6.5, 6.8, 7, 7.3, 7.5, 7.8, 8, 8.4, 8.7, 9, 9.4, 9.6, 9.8, 10 ]; function multiply(matrix1, matrix2) { var col = []; var out = new Array(25); var val; for (var i = 0; i < 5; i++) { for (var j = 0; j < 5; j++) { col[j] = matrix2[j + i * 5]; } for (var j = 0; j < 5; j++) { val = 0; for (var k = 0; k < 5; k++) { val += matrix1[j + k * 5] * col[k]; } out[j + i * 5] = val; } } return out; } function adjustContrast(matrix, value) { var x; value = clamp(value, -1, 1); value *= 100; if (value < 0) { x = 127 + value / 100 * 127; } else { x = value % 1; if (x === 0) { x = DELTA_INDEX[value]; } else { x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x; } x = x * 127 + 127; } return multiply(matrix, [ x / 127, 0, 0, 0, 0.5 * (127 - x), 0, x / 127, 0, 0, 0.5 * (127 - x), 0, 0, x / 127, 0, 0.5 * (127 - x), 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]); } function adjustBrightness(matrix, value) { value = clamp(255 * value, -255, 255); return multiply(matrix, [ 1, 0, 0, 0, value, 0, 1, 0, 0, value, 0, 0, 1, 0, value, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]); } function adjustColors(matrix, adjustR, adjustG, adjustB) { adjustR = clamp(adjustR, 0, 2); adjustG = clamp(adjustG, 0, 2); adjustB = clamp(adjustB, 0, 2); return multiply(matrix, [ adjustR, 0, 0, 0, 0, 0, adjustG, 0, 0, 0, 0, 0, adjustB, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]); } function colorFilter(ir, matrix) { return ir.toCanvas().then(function (canvas) { return applyColorFilter(canvas, ir.getType(), matrix); }); } function applyColorFilter(canvas, type, matrix) { var context = get2dContext(canvas); function applyMatrix(pixelsData, m) { var r, g, b, a; 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]; for (var i = 0; i < data.length; i += 4) { r = data[i]; g = data[i + 1]; b = data[i + 2]; a = data[i + 3]; data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4; data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9; data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14; data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19; } return pixelsData; } var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix); context.putImageData(pixels, 0, 0); return fromCanvas(canvas, type); } function convoluteFilter(ir, matrix) { return ir.toCanvas().then(function (canvas) { return applyConvoluteFilter(canvas, ir.getType(), matrix); }); } function applyConvoluteFilter(canvas, type, matrix) { var context = get2dContext(canvas); function applyMatrix(pIn, pOut, aMatrix) { function clamp(value, min, max) { if (value > max) { value = max; } else if (value < min) { value = min; } return value; } var side = Math.round(Math.sqrt(aMatrix.length)); var halfSide = Math.floor(side / 2); var rgba = pIn.data; var drgba = pOut.data; var w = pIn.width; var h = pIn.height; for (var y = 0; y < h; y++) { for (var x = 0; x < w; x++) { var r = 0; var g = 0; var b = 0; for (var cy = 0; cy < side; cy++) { for (var cx = 0; cx < side; cx++) { var scx = clamp(x + cx - halfSide, 0, w - 1); var scy = clamp(y + cy - halfSide, 0, h - 1); var innerOffset = (scy * w + scx) * 4; var wt = aMatrix[cy * side + cx]; r += rgba[innerOffset] * wt; g += rgba[innerOffset + 1] * wt; b += rgba[innerOffset + 2] * wt; } } var offset = (y * w + x) * 4; drgba[offset] = clamp(r, 0, 255); drgba[offset + 1] = clamp(g, 0, 255); drgba[offset + 2] = clamp(b, 0, 255); } } return pOut; } var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height); var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height); pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix); context.putImageData(pixelsOut, 0, 0); return fromCanvas(canvas, type); } function functionColorFilter(colorFn) { var filterImpl = function (canvas, type, value) { var context = get2dContext(canvas); var lookup = new Array(256); function applyLookup(pixelsData, lookupData) { var data = pixelsData.data; for (var i = 0; i < data.length; i += 4) { data[i] = lookupData[data[i]]; data[i + 1] = lookupData[data[i + 1]]; data[i + 2] = lookupData[data[i + 2]]; } return pixelsData; } for (var i = 0; i < lookup.length; i++) { lookup[i] = colorFn(i, value); } var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup); context.putImageData(pixels, 0, 0); return fromCanvas(canvas, type); }; return function (ir, value) { return ir.toCanvas().then(function (canvas) { return filterImpl(canvas, ir.getType(), value); }); }; } function complexAdjustableColorFilter(matrixAdjustFn) { return function (ir, adjust) { return colorFilter(ir, matrixAdjustFn(identity$1(), adjust)); }; } function basicColorFilter(matrix) { return function (ir) { return colorFilter(ir, matrix); }; } function basicConvolutionFilter(kernel) { return function (ir) { return convoluteFilter(ir, kernel); }; } var invert = basicColorFilter([ -1, 0, 0, 0, 255, 0, -1, 0, 0, 255, 0, 0, -1, 0, 255, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1 ]); var brightness = complexAdjustableColorFilter(adjustBrightness); var contrast = complexAdjustableColorFilter(adjustContrast); var colorize = function (ir, adjustR, adjustG, adjustB) { return colorFilter(ir, adjustColors(identity$1(), adjustR, adjustG, adjustB)); }; var sharpen = basicConvolutionFilter([ 0, -1, 0, -1, 5, -1, 0, -1, 0 ]); var gamma = functionColorFilter(function (color, value) { return Math.pow(color / 255, 1 - value) * 255; }); function scale(image, dW, dH) { var sW = getWidth(image); var sH = getHeight(image); var wRatio = dW / sW; var hRatio = dH / sH; var scaleCapped = false; if (wRatio < 0.5 || wRatio > 2) { wRatio = wRatio < 0.5 ? 0.5 : 2; scaleCapped = true; } if (hRatio < 0.5 || hRatio > 2) { hRatio = hRatio < 0.5 ? 0.5 : 2; scaleCapped = true; } var scaled = _scale(image, wRatio, hRatio); return !scaleCapped ? scaled : scaled.then(function (tCanvas) { return scale(tCanvas, dW, dH); }); } function _scale(image, wRatio, hRatio) { return new Promise$1(function (resolve) { var sW = getWidth(image); var sH = getHeight(image); var dW = Math.floor(sW * wRatio); var dH = Math.floor(sH * hRatio); var canvas = create$5(dW, dH); var context = get2dContext(canvas); context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH); resolve(canvas); }); } function rotate(ir, angle) { return ir.toCanvas().then(function (canvas) { return applyRotate(canvas, ir.getType(), angle); }); } function applyRotate(image, type, angle) { var canvas = create$5(image.width, image.height); var context = get2dContext(canvas); var translateX = 0; var translateY = 0; angle = angle < 0 ? 360 + angle : angle; if (angle === 90 || angle === 270) { resize(canvas, canvas.height, canvas.width); } if (angle === 90 || angle === 180) { translateX = canvas.width; } if (angle === 270 || angle === 180) { translateY = canvas.height; } context.translate(translateX, translateY); context.rotate(angle * Math.PI / 180); context.drawImage(image, 0, 0); return fromCanvas(canvas, type); } function flip(ir, axis) { return ir.toCanvas().then(function (canvas) { return applyFlip(canvas, ir.getType(), axis); }); } function applyFlip(image, type, axis) { var canvas = create$5(image.width, image.height); var context = get2dContext(canvas); if (axis === 'v') { context.scale(1, -1); context.drawImage(image, 0, -canvas.height); } else { context.scale(-1, 1); context.drawImage(image, -canvas.width, 0); } return fromCanvas(canvas, type); } function crop(ir, x, y, w, h) { return ir.toCanvas().then(function (canvas) { return applyCrop(canvas, ir.getType(), x, y, w, h); }); } function applyCrop(image, type, x, y, w, h) { var canvas = create$5(w, h); var context = get2dContext(canvas); context.drawImage(image, -x, -y); return fromCanvas(canvas, type); } function resize$1(ir, w, h) { return ir.toCanvas().then(function (canvas) { return scale(canvas, w, h).then(function (newCanvas) { return fromCanvas(newCanvas, ir.getType()); }); }); } var invert$1 = function (ir) { return invert(ir); }; var sharpen$1 = function (ir) { return sharpen(ir); }; var gamma$1 = function (ir, value) { return gamma(ir, value); }; var colorize$1 = function (ir, adjustR, adjustG, adjustB) { return colorize(ir, adjustR, adjustG, adjustB); }; var brightness$1 = function (ir, adjust) { return brightness(ir, adjust); }; var contrast$1 = function (ir, adjust) { return contrast(ir, adjust); }; var flip$1 = function (ir, axis) { return flip(ir, axis); }; var crop$1 = function (ir, x, y, w, h) { return crop(ir, x, y, w, h); }; var resize$2 = function (ir, w, h) { return resize$1(ir, w, h); }; var rotate$1 = function (ir, angle) { return rotate(ir, angle); }; var renderIcon$1 = function (iconHtml, behaviours) { return __assign({ dom: { tag: 'span', innerHtml: iconHtml, classes: [ 'tox-icon', 'tox-tbtn__icon-wrap' ] } }, behaviours); }; var renderIconFromPack = function (iconName, iconsProvider) { return renderIcon$1(get$c(iconName, iconsProvider), {}); }; var renderReplacableIconFromPack = function (iconName, iconsProvider) { return renderIcon$1(get$c(iconName, iconsProvider), { behaviours: derive$1([Replacing.config({})]) }); }; var renderLabel$1 = function (text, prefix, providersBackstage) { return { dom: { tag: 'span', innerHtml: providersBackstage.translate(text), classes: [prefix + '__select-label'] }, behaviours: derive$1([Replacing.config({})]) }; }; var internalToolbarButtonExecute = generate$1('toolbar.button.execute'); var onToolbarButtonExecute = function (info) { return runOnExecute(function (comp, simulatedEvent) { runWithApi(info, comp)(function (itemApi) { emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi }); info.onAction(itemApi); }); }); }; var toolbarButtonEventOrder = { 'alloy.execute': [ 'disabling', 'alloy.base.behaviour', 'toggling', 'toolbar-button-events' ] }; var updateMenuText = generate$1('update-menu-text'); var updateMenuIcon = generate$1('update-menu-icon'); var renderCommonDropdown = function (spec, prefix, sharedBackstage) { var editorOffCell = Cell(noop); var optMemDisplayText = spec.text.map(function (text) { return record(renderLabel$1(text, prefix, sharedBackstage.providers)); }); var optMemDisplayIcon = spec.icon.map(function (iconName) { return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons)); }); var onLeftOrRightInMenu = function (comp, se) { var dropdown = Representing.getValue(comp); Focusing.focus(dropdown); emitWith(dropdown, 'keydown', { raw: se.event().raw() }); Dropdown.close(dropdown); return Option.some(true); }; var role = spec.role.fold(function () { return {}; }, function (role) { return { role: role }; }); var tooltipAttributes = spec.tooltip.fold(function () { return {}; }, function (tooltip) { var translatedTooltip = sharedBackstage.providers.translate(tooltip); return { 'title': translatedTooltip, 'aria-label': translatedTooltip }; }); var memDropdown = record(Dropdown.sketch(__assign(__assign({}, role), { dom: { tag: 'button', classes: [ prefix, prefix + '--select' ].concat(map(spec.classes, function (c) { return prefix + '--' + c; })), attributes: __assign({}, tooltipAttributes) }, components: componentRenderPipeline([ optMemDisplayIcon.map(function (mem) { return mem.asSpec(); }), optMemDisplayText.map(function (mem) { return mem.asSpec(); }), Option.some({ dom: { tag: 'div', classes: [prefix + '__select-chevron'], innerHtml: get$c('chevron-down', sharedBackstage.providers.icons) } }) ]), matchWidth: true, useMinWidth: true, dropdownBehaviours: derive$1(__spreadArrays(spec.dropdownBehaviours, [ DisablingConfigs.button(spec.disabled), Unselecting.config({}), Replacing.config({}), config('dropdown-events', [ onControlAttached(spec, editorOffCell), onControlDetached(spec, editorOffCell) ]), config('menubutton-update-display-text', [ run(updateMenuText, function (comp, se) { optMemDisplayText.bind(function (mem) { return mem.getOpt(comp); }).each(function (displayText) { Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event().text()))]); }); }), run(updateMenuIcon, function (comp, se) { optMemDisplayIcon.bind(function (mem) { return mem.getOpt(comp); }).each(function (displayIcon) { Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event().icon(), sharedBackstage.providers.icons)]); }); }) ]) ])), eventOrder: deepMerge(toolbarButtonEventOrder, { mousedown: [ 'focusing', 'alloy.base.behaviour', 'item-type-events', 'normal-dropdown-events' ] }), sandboxBehaviours: derive$1([Keying.config({ mode: 'special', onLeft: onLeftOrRightInMenu, onRight: onLeftOrRightInMenu })]), lazySink: sharedBackstage.getSink, toggleClass: prefix + '--active', parts: { menu: part(false, spec.columns, spec.presets) }, fetch: function () { return Future.nu(spec.fetch); } }))); return memDropdown.asSpec(); }; var isMenuItemReference = function (item) { return isString(item); }; var isSeparator = function (item) { return item.type === 'separator'; }; var isExpandingMenuItem = function (item) { return has(item, 'getSubmenuItems'); }; var separator$1 = { type: 'separator' }; var unwrapReferences = function (items, menuItems) { var realItems = foldl(items, function (acc, item) { if (isMenuItemReference(item)) { if (item === '') { return acc; } else if (item === '|') { return acc.length > 0 && !isSeparator(acc[acc.length - 1]) ? acc.concat([separator$1]) : acc; } else if (has(menuItems, item.toLowerCase())) { return acc.concat([menuItems[item.toLowerCase()]]); } else { return acc; } } else { return acc.concat([item]); } }, []); if (realItems.length > 0 && isSeparator(realItems[realItems.length - 1])) { realItems.pop(); } return realItems; }; var getFromExpandingItem = function (item, menuItems) { var submenuItems = item.getSubmenuItems(); var rest = expand(submenuItems, menuItems); var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items)); var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value)); return { item: item, menus: newMenus, expansions: newExpansions }; }; var getFromItem = function (item, menuItems) { return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : { item: item, menus: {}, expansions: {} }; }; var generateValueIfRequired = function (item) { if (isSeparator(item)) { return item; } else { var itemValue = readOptFrom$1(item, 'value').getOrThunk(function () { return generate$1('generated-menu-item'); }); return deepMerge({ value: itemValue }, item); } }; var expand = function (items, menuItems) { var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems); return foldr(realItems, function (acc, item) { var itemWithValue = generateValueIfRequired(item); var newData = getFromItem(itemWithValue, menuItems); return { menus: deepMerge(acc.menus, newData.menus), items: [newData.item].concat(acc.items), expansions: deepMerge(acc.expansions, newData.expansions) }; }, { menus: {}, expansions: {}, items: [] }); }; var build$2 = function (items, itemResponse, backstage, isHorizontalMenu) { var primary = generate$1('primary-menu'); var data = expand(items, backstage.shared.providers.menuItems()); if (data.items.length === 0) { return Option.none(); } var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu); var submenus = map$1(data.menus, function (menuItems, menuName) { return createPartialMenu(menuName, menuItems, itemResponse, backstage, false); }); var menus = deepMerge(submenus, wrap$1(primary, mainMenu)); return Option.from(tieredMenu.tieredData(primary, menus, data.expansions)); }; var getMenuButtonApi = function (component) { return { isDisabled: function () { return Disabling.isDisabled(component); }, setDisabled: function (state) { return Disabling.set(component, state); }, setActive: function (state) { var elm = component.element(); if (state) { add$2(elm, 'tox-tbtn--enabled'); set$1(elm, 'aria-pressed', true); } else { remove$4(elm, 'tox-tbtn--enabled'); remove$1(elm, 'aria-pressed'); } }, isActive: function () { return has$2(component.element(), 'tox-tbtn--enabled'); } }; }; var renderMenuButton = function (spec, prefix, backstage, role) { return renderCommonDropdown({ text: spec.text, icon: spec.icon, tooltip: spec.tooltip, role: role, fetch: function (callback) { spec.fetch(function (items) { callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false)); }); }, onSetup: spec.onSetup, getApi: getMenuButtonApi, columns: 1, presets: 'normal', classes: [], dropdownBehaviours: [Tabstopping.config({})] }, prefix, backstage.shared); }; var getFetch$1 = function (items, getButton, backstage) { var getMenuItemAction = function (item) { return function (api) { backstage.shared.getSink().each(function (sink) { getButton().getOpt(sink).each(function (orig) { focus$1(orig.element()); emitWith(orig, formActionEvent, { name: item.name, value: item.storage.get() }); }); }); var newValue = !api.isActive(); api.setActive(newValue); item.storage.set(newValue); }; }; var getMenuItemSetup = function (item) { return function (api) { api.setActive(item.storage.get()); }; }; return function (success) { success(map(items, function (item) { var text = item.text.fold(function () { return {}; }, function (text) { return { text: text }; }); return __assign(__assign({ type: item.type }, text), { onAction: getMenuItemAction(item), onSetup: getMenuItemSetup(item) }); })); }; }; var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components) { if (extraBehaviours === void 0) { extraBehaviours = []; } var action = actionOpt.fold(function () { return {}; }, function (action) { return { action: action }; }); var common = __assign({ buttonBehaviours: derive$1([ DisablingConfigs.button(spec.disabled), Tabstopping.config({}), config('button press', [ preventDefault('click'), preventDefault('mousedown') ]) ].concat(extraBehaviours)), eventOrder: { click: [ 'button press', 'alloy.base.behaviour' ], mousedown: [ 'button press', 'alloy.base.behaviour' ] } }, action); var domFinal = deepMerge(common, { dom: dom }); return deepMerge(domFinal, { components: components }); }; var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) { if (extraBehaviours === void 0) { extraBehaviours = []; } var tooltipAttributes = spec.tooltip.map(function (tooltip) { return { 'aria-label': providersBackstage.translate(tooltip), 'title': providersBackstage.translate(tooltip) }; }).getOr({}); var dom = { tag: 'button', classes: ['tox-tbtn'], attributes: tooltipAttributes }; var icon = spec.icon.map(function (iconName) { return renderIconFromPack(iconName, providersBackstage.icons); }); var components = componentRenderPipeline([icon]); return renderCommonSpec(spec, action, extraBehaviours, dom, components); }; var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) { if (extraBehaviours === void 0) { extraBehaviours = []; } var iconButtonSpec = renderIconButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours); return Button.sketch(iconButtonSpec); }; var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) { if (extraBehaviours === void 0) { extraBehaviours = []; } if (extraClasses === void 0) { extraClasses = []; } var translatedText = providersBackstage.translate(spec.text); var icon = spec.icon ? spec.icon.map(function (iconName) { return renderIconFromPack(iconName, providersBackstage.icons); }) : Option.none(); var components = icon.isSome() ? componentRenderPipeline([icon]) : []; var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText }; var classes = __spreadArrays(!spec.primary && !spec.borderless ? [ 'tox-button', 'tox-button--secondary' ] : ['tox-button'], icon.isSome() ? ['tox-button--icon'] : [], spec.borderless ? ['tox-button--naked'] : [], extraClasses); var dom = __assign(__assign({ tag: 'button', classes: classes }, innerHtml), { attributes: { title: translatedText } }); return renderCommonSpec(spec, action, extraBehaviours, dom, components); }; var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) { if (extraBehaviours === void 0) { extraBehaviours = []; } if (extraClasses === void 0) { extraClasses = []; } var buttonSpec = renderButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours, extraClasses); return Button.sketch(buttonSpec); }; var getAction = function (name, buttonType) { return function (comp) { if (buttonType === 'custom') { emitWith(comp, formActionEvent, { name: name, value: {} }); } else if (buttonType === 'submit') { emit(comp, formSubmitEvent); } else if (buttonType === 'cancel') { emit(comp, formCancelEvent); } else { domGlobals.console.error('Unknown button type: ', buttonType); } }; }; var isMenuFooterButtonSpec = function (spec, buttonType) { return buttonType === 'menu'; }; var isNormalFooterButtonSpec = function (spec, buttonType) { return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit'; }; var renderFooterButton = function (spec, buttonType, backstage) { if (isMenuFooterButtonSpec(spec, buttonType)) { var getButton = function () { return memButton_1; }; var menuButtonSpec = spec; var fixedSpec = __assign(__assign({}, spec), { fetch: getFetch$1(menuButtonSpec.items, getButton, backstage) }); var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Option.none())); return memButton_1.asSpec(); } else if (isNormalFooterButtonSpec(spec, buttonType)) { var action = getAction(spec.name, buttonType); var buttonSpec = __assign(__assign({}, spec), { borderless: false }); return renderButton(buttonSpec, action, backstage.shared.providers, []); } else { domGlobals.console.error('Unknown footer button type: ', buttonType); } }; var renderDialogButton = function (spec, providersBackstage) { var action = getAction(spec.name, 'custom'); return renderFormField(Option.none(), FormField.parts().field(__assign({ factory: Button }, renderButtonSpec(spec, Option.some(action), providersBackstage, [ RepresentingConfigs.memory(''), ComposingConfigs.self() ])))); }; var schema$i = constant([ defaulted$1('field1Name', 'field1'), defaulted$1('field2Name', 'field2'), onStrictHandler('onLockedChange'), markers(['lockClass']), defaulted$1('locked', false), SketchBehaviours.field('coupledFieldBehaviours', [ Composing, Representing ]) ]); var getField = function (comp, detail, partName) { return getPart(comp, detail, partName).bind(Composing.getCurrent); }; var coupledPart = function (selfName, otherName) { return required({ factory: FormField, name: selfName, overrides: function (detail) { return { fieldBehaviours: derive$1([config('coupled-input-behaviour', [run(input(), function (me) { getField(me, detail, otherName).each(function (other) { getPart(me, detail, 'lock').each(function (lock) { if (Toggling.isOn(lock)) { detail.onLockedChange(me, other, lock); } }); }); })])]) }; } }); }; var parts$5 = constant([ coupledPart('field1', 'field2'), coupledPart('field2', 'field1'), required({ factory: Button, schema: [strict$1('dom')], name: 'lock', overrides: function (detail) { return { buttonBehaviours: derive$1([Toggling.config({ selected: detail.locked, toggleClass: detail.markers.lockClass, aria: { mode: 'pressed' } })]) }; } }) ]); var factory$7 = function (detail, components, spec, externals) { return { uid: detail.uid, dom: detail.dom, components: components, behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [ Composing.config({ find: Option.some }), Representing.config({ store: { mode: 'manual', getValue: function (comp) { var _a; var parts = getPartsOrDie(comp, detail, [ 'field1', 'field2' ]); return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a; }, setValue: function (comp, value) { var parts = getPartsOrDie(comp, detail, [ 'field1', 'field2' ]); if (hasKey$1(value, detail.field1Name)) { Representing.setValue(parts.field1(), value[detail.field1Name]); } if (hasKey$1(value, detail.field2Name)) { Representing.setValue(parts.field2(), value[detail.field2Name]); } } } }) ]), apis: { getField1: function (component) { return getPart(component, detail, 'field1'); }, getField2: function (component) { return getPart(component, detail, 'field2'); }, getLock: function (component) { return getPart(component, detail, 'lock'); } } }; }; var FormCoupledInputs = composite$1({ name: 'FormCoupledInputs', configFields: schema$i(), partFields: parts$5(), factory: factory$7, apis: { getField1: function (apis, component) { return apis.getField1(component); }, getField2: function (apis, component) { return apis.getField2(component); }, getLock: function (apis, component) { return apis.getLock(component); } } }); var formatSize = function (size) { var unitDec = { '': 0, 'px': 0, 'pt': 1, 'mm': 1, 'pc': 2, 'ex': 2, 'em': 2, 'ch': 2, 'rem': 2, 'cm': 3, 'in': 4, '%': 4 }; var maxDecimal = function (unit) { return unit in unitDec ? unitDec[unit] : 1; }; var numText = size.value.toFixed(maxDecimal(size.unit)); if (numText.indexOf('.') !== -1) { numText = numText.replace(/\.?0*$/, ''); } return numText + size.unit; }; var parseSize = function (sizeText) { var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/; var match = numPattern.exec(sizeText); if (match !== null) { var value = parseFloat(match[1]); var unit = match[2]; return Result.value({ value: value, unit: unit }); } else { return Result.error(sizeText); } }; var convertUnit = function (size, unit) { var inInch = { '': 96, 'px': 96, 'pt': 72, 'cm': 2.54, 'pc': 12, 'mm': 25.4, 'in': 1 }; var supported = function (u) { return Object.prototype.hasOwnProperty.call(inInch, u); }; if (size.unit === unit) { return Option.some(size.value); } else if (supported(size.unit) && supported(unit)) { if (inInch[size.unit] === inInch[unit]) { return Option.some(size.value); } else { return Option.some(size.value / inInch[size.unit] * inInch[unit]); } } else { return Option.none(); } }; var noSizeConversion = function (input) { return Option.none(); }; var ratioSizeConversion = function (scale, unit) { return function (size) { return convertUnit(size, unit).map(function (value) { return { value: value * scale, unit: unit }; }); }; }; var makeRatioConverter = function (currentFieldText, otherFieldText) { var cValue = parseSize(currentFieldText).toOption(); var oValue = parseSize(otherFieldText).toOption(); return lift2(cValue, oValue, function (cSize, oSize) { return convertUnit(cSize, oSize.unit).map(function (val) { return oSize.value / val; }).map(function (r) { return ratioSizeConversion(r, oSize.unit); }).getOr(noSizeConversion); }).getOr(noSizeConversion); }; var renderSizeInput = function (spec, providersBackstage) { var converter = noSizeConversion; var ratioEvent = generate$1('ratio-event'); var pLock = FormCoupledInputs.parts().lock({ dom: { tag: 'button', classes: [ 'tox-lock', 'tox-button', 'tox-button--naked', 'tox-button--icon' ], attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) } }, components: [ { dom: { tag: 'span', classes: [ 'tox-icon', 'tox-lock-icon__lock' ], innerHtml: get$c('lock', providersBackstage.icons) } }, { dom: { tag: 'span', classes: [ 'tox-icon', 'tox-lock-icon__unlock' ], innerHtml: get$c('unlock', providersBackstage.icons) } } ], buttonBehaviours: derive$1([ DisablingConfigs.button(spec.disabled), Tabstopping.config({}) ]) }); var formGroup = function (components) { return { dom: { tag: 'div', classes: ['tox-form__group'] }, components: components }; }; var getFieldPart = function (isField1) { return FormField.parts().field({ factory: Input, inputClasses: ['tox-textfield'], inputBehaviours: derive$1([ Disabling.config({ disabled: spec.disabled }), Tabstopping.config({}), config('size-input-events', [ run(focusin(), function (component, simulatedEvent) { emitWith(component, ratioEvent, { isField1: isField1 }); }), run(change(), function (component, simulatedEvent) { emitWith(component, formChangeEvent, { name: spec.name }); }) ]) ]), selectOnFocus: false }); }; var getLabel = function (label) { return { dom: { tag: 'label', classes: ['tox-label'], innerHtml: providersBackstage.translate(label) } }; }; var widthField = FormCoupledInputs.parts().field1(formGroup([ FormField.parts().label(getLabel('Width')), getFieldPart(true) ])); var heightField = FormCoupledInputs.parts().field2(formGroup([ FormField.parts().label(getLabel('Height')), getFieldPart(false) ])); return FormCoupledInputs.sketch({ dom: { tag: 'div', classes: ['tox-form__group'] }, components: [{ dom: { tag: 'div', classes: ['tox-form__controls-h-stack'] }, components: [ widthField, heightField, formGroup([ getLabel(' '), pLock ]) ] }], field1Name: 'width', field2Name: 'height', locked: true, markers: { lockClass: 'tox-locked' }, onLockedChange: function (current, other, lock) { parseSize(Representing.getValue(current)).each(function (size) { converter(size).each(function (newSize) { Representing.setValue(other, formatSize(newSize)); }); }); }, coupledFieldBehaviours: derive$1([ Disabling.config({ disabled: spec.disabled, onDisabled: function (comp) { FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable); FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable); FormCoupledInputs.getLock(comp).each(Disabling.disable); }, onEnabled: function (comp) { FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable); FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable); FormCoupledInputs.getLock(comp).each(Disabling.enable); } }), config('size-input-events2', [run(ratioEvent, function (component, simulatedEvent) { var isField1 = simulatedEvent.event().isField1(); var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component); var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component); var value1 = optCurrent.map(Representing.getValue).getOr(''); var value2 = optOther.map(Representing.getValue).getOr(''); converter = makeRatioConverter(value1, value2); })]) ]) }); }; var undo = constant(generate$1('undo')); var redo = constant(generate$1('redo')); var zoom = constant(generate$1('zoom')); var back = constant(generate$1('back')); var apply = constant(generate$1('apply')); var swap = constant(generate$1('swap')); var transform = constant(generate$1('transform')); var tempTransform = constant(generate$1('temp-transform')); var transformApply = constant(generate$1('transform-apply')); var internal = { undo: undo, redo: redo, zoom: zoom, back: back, apply: apply, swap: swap, transform: transform, tempTransform: tempTransform, transformApply: transformApply }; var saveState = constant('save-state'); var disable$1 = constant('disable'); var enable$1 = constant('enable'); var external$2 = { formActionEvent: formActionEvent, saveState: saveState, disable: disable$1, enable: enable$1 }; var renderEditPanel = function (imagePanel, providersBackstage) { var createButton = function (text, action, disabled, primary) { return record(renderButton({ name: text, text: text, disabled: disabled, primary: primary, icon: Option.none(), borderless: false }, action, providersBackstage)); }; var createIconButton = function (icon, tooltip, action, disabled) { return record(renderIconButton({ name: icon, icon: Option.some(icon), tooltip: Option.some(tooltip), disabled: disabled, primary: false, borderless: false }, action, providersBackstage)); }; var disableAllComponents = function (comps, eventcomp) { comps.map(function (mem) { var component = mem.get(eventcomp); if (component.hasConfigured(Disabling)) { Disabling.disable(component); } }); }; var enableAllComponents = function (comps, eventcomp) { comps.map(function (mem) { var component = mem.get(eventcomp); if (component.hasConfigured(Disabling)) { Disabling.enable(component); } }); }; var panelDom = { tag: 'div', classes: [ 'tox-image-tools__toolbar', 'tox-image-tools-edit-panel' ] }; var noop$1 = noop; var emit$1 = function (comp, event, data) { emitWith(comp, event, data); }; var emitDisable = function (component) { return emit(component, external$2.disable()); }; var emitEnable = function (component) { return emit(component, external$2.enable()); }; var emitTransform = function (comp, transform) { emitDisable(comp); emit$1(comp, internal.transform(), { transform: transform }); emitEnable(comp); }; var emitTempTransform = function (comp, transform) { emitDisable(comp); emit$1(comp, internal.tempTransform(), { transform: transform }); emitEnable(comp); }; var getBackSwap = function (anyInSystem) { return function () { memContainer.getOpt(anyInSystem).each(function (container) { Replacing.set(container, [ButtonPanel]); }); }; }; var emitTransformApply = function (comp, transform) { emitDisable(comp); emit$1(comp, internal.transformApply(), { transform: transform, swap: getBackSwap(comp) }); emitEnable(comp); }; var createBackButton = function () { return createButton('Back', function (button) { return emit$1(button, internal.back(), { swap: getBackSwap(button) }); }, false, false); }; var createSpacer = function () { return record({ dom: { tag: 'div', classes: ['tox-spacer'] }, behaviours: derive$1([Disabling.config({})]) }); }; var createApplyButton = function () { return createButton('Apply', function (button) { return emit$1(button, internal.apply(), { swap: getBackSwap(button) }); }, true, true); }; var makeCropTransform = function () { return function (ir) { var rect = imagePanel.getRect(); return crop$1(ir, rect.x, rect.y, rect.w, rect.h); }; }; var cropPanelComponents = [ createBackButton(), createSpacer(), createButton('Apply', function (button) { var transform = makeCropTransform(); emitTransformApply(button, transform); imagePanel.hideCrop(); }, false, true) ]; var CropPanel = Container.sketch({ dom: panelDom, components: cropPanelComponents.map(function (mem) { return mem.asSpec(); }), containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [ run(external$2.disable(), function (comp, se) { disableAllComponents(cropPanelComponents, comp); }), run(external$2.enable(), function (comp, se) { enableAllComponents(cropPanelComponents, comp); }) ])]) }); var memSize = record(renderSizeInput({ name: 'size', label: Option.none(), constrain: true, disabled: false }, providersBackstage)); var makeResizeTransform = function (width, height) { return function (ir) { return resize$2(ir, width, height); }; }; var resizePanelComponents = [ createBackButton(), createSpacer(), memSize, createSpacer(), createButton('Apply', function (button) { memSize.getOpt(button).each(function (sizeInput) { var value = Representing.getValue(sizeInput); var width = parseInt(value.width, 10); var height = parseInt(value.height, 10); var transform = makeResizeTransform(width, height); emitTransformApply(button, transform); }); }, false, true) ]; var ResizePanel = Container.sketch({ dom: panelDom, components: resizePanelComponents.map(function (mem) { return mem.asSpec(); }), containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [ run(external$2.disable(), function (comp, se) { disableAllComponents(resizePanelComponents, comp); }), run(external$2.enable(), function (comp, se) { enableAllComponents(resizePanelComponents, comp); }) ])]) }); var makeValueTransform = function (transform, value) { return function (ir) { return transform(ir, value); }; }; var horizontalFlip = makeValueTransform(flip$1, 'h'); var verticalFlip = makeValueTransform(flip$1, 'v'); var counterclockwiseRotate = makeValueTransform(rotate$1, -90); var clockwiseRotate = makeValueTransform(rotate$1, 90); var flipRotateOnAction = function (comp, operation) { emitTempTransform(comp, operation); }; var flipRotateComponents = [ createBackButton(), createSpacer(), createIconButton('flip-horizontally', 'Flip horizontally', function (button) { flipRotateOnAction(button, horizontalFlip); }, false), createIconButton('flip-vertically', 'Flip vertically', function (button) { flipRotateOnAction(button, verticalFlip); }, false), createIconButton('rotate-left', 'Rotate counterclockwise', function (button) { flipRotateOnAction(button, counterclockwiseRotate); }, false), createIconButton('rotate-right', 'Rotate clockwise', function (button) { flipRotateOnAction(button, clockwiseRotate); }, false), createSpacer(), createApplyButton() ]; var FlipRotatePanel = Container.sketch({ dom: panelDom, components: flipRotateComponents.map(function (mem) { return mem.asSpec(); }), containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [ run(external$2.disable(), function (comp, se) { disableAllComponents(flipRotateComponents, comp); }), run(external$2.enable(), function (comp, se) { enableAllComponents(flipRotateComponents, comp); }) ])]) }); var makeSlider = function (label, onChoose, min, value, max) { var labelPart = Slider.parts().label({ dom: { tag: 'label', classes: ['tox-label'], innerHtml: providersBackstage.translate(label) } }); var spectrum = Slider.parts().spectrum({ dom: { tag: 'div', classes: ['tox-slider__rail'], attributes: { role: 'presentation' } } }); var thumb = Slider.parts().thumb({ dom: { tag: 'div', classes: ['tox-slider__handle'], attributes: { role: 'presentation' } } }); return record(Slider.sketch({ dom: { tag: 'div', classes: ['tox-slider'], attributes: { role: 'presentation' } }, model: { mode: 'x', minX: min, maxX: max, getInitialValue: constant({ x: constant(value) }) }, components: [ labelPart, spectrum, thumb ], sliderBehaviours: derive$1([Focusing.config({})]), onChoose: onChoose })); }; var makeVariableSlider = function (label, transform, min, value, max) { var onChoose = function (slider, thumb, value) { var valTransform = makeValueTransform(transform, value.x() / 100); emitTransform(slider, valTransform); }; return makeSlider(label, onChoose, min, value, max); }; var variableFilterPanelComponents = function (label, transform, min, value, max) { return [ createBackButton(), makeVariableSlider(label, transform, min, value, max), createApplyButton() ]; }; var createVariableFilterPanel = function (label, transform, min, value, max) { var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max); return Container.sketch({ dom: panelDom, components: filterPanelComponents.map(function (mem) { return mem.asSpec(); }), containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [ run(external$2.disable(), function (comp, se) { disableAllComponents(filterPanelComponents, comp); }), run(external$2.enable(), function (comp, se) { enableAllComponents(filterPanelComponents, comp); }) ])]) }); }; var filterPanelComponents = [ createBackButton(), createSpacer(), createApplyButton() ]; var FilterPanel = Container.sketch({ dom: panelDom, components: filterPanelComponents.map(function (mem) { return mem.asSpec(); }) }); var BrightnessPanel = createVariableFilterPanel('Brightness', brightness$1, -100, 0, 100); var ContrastPanel = createVariableFilterPanel('Contrast', contrast$1, -100, 0, 100); var GammaPanel = createVariableFilterPanel('Gamma', gamma$1, -100, 0, 100); var makeColorTransform = function (red, green, blue) { return function (ir) { return colorize$1(ir, red, green, blue); }; }; var makeColorSlider = function (label) { var onChoose = function (slider, thumb, value) { var redOpt = memRed.getOpt(slider); var blueOpt = memBlue.getOpt(slider); var greenOpt = memGreen.getOpt(slider); redOpt.each(function (red) { blueOpt.each(function (blue) { greenOpt.each(function (green) { var r = Representing.getValue(red).x() / 100; var g = Representing.getValue(green).x() / 100; var b = Representing.getValue(blue).x() / 100; var transform = makeColorTransform(r, g, b); emitTransform(slider, transform); }); }); }); }; return makeSlider(label, onChoose, 0, 100, 200); }; var memRed = makeColorSlider('R'); var memGreen = makeColorSlider('G'); var memBlue = makeColorSlider('B'); var colorizePanelComponents = [ createBackButton(), memRed, memGreen, memBlue, createApplyButton() ]; var ColorizePanel = Container.sketch({ dom: panelDom, components: colorizePanelComponents.map(function (mem) { return mem.asSpec(); }) }); var getTransformPanelEvent = function (panel, transform, update) { return function (button) { var swap = function () { memContainer.getOpt(button).each(function (container) { Replacing.set(container, [panel]); update(container); }); }; emit$1(button, internal.swap(), { transform: transform, swap: swap }); }; }; var cropPanelUpdate = function (_anyInSystem) { imagePanel.showCrop(); }; var resizePanelUpdate = function (anyInSystem) { memSize.getOpt(anyInSystem).each(function (sizeInput) { var measurements = imagePanel.getMeasurements(); var width = measurements.width; var height = measurements.height; Representing.setValue(sizeInput, { width: width, height: height }); }); }; var sharpenTransform = Option.some(sharpen$1); var invertTransform = Option.some(invert$1); var buttonPanelComponents = [ createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Option.none(), cropPanelUpdate), false), createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Option.none(), resizePanelUpdate), false), createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Option.none(), noop$1), false), createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Option.none(), noop$1), false), createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false), createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Option.none(), noop$1), false), createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Option.none(), noop$1), false), createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Option.none(), noop$1), false), createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false) ]; var ButtonPanel = Container.sketch({ dom: panelDom, components: buttonPanelComponents.map(function (mem) { return mem.asSpec(); }) }); var container = Container.sketch({ dom: { tag: 'div' }, components: [ButtonPanel], containerBehaviours: derive$1([Replacing.config({})]) }); var memContainer = record(container); var getApplyButton = function (anyInSystem) { return memContainer.getOpt(anyInSystem).map(function (container) { var panel = container.components()[0]; return panel.components()[panel.components().length - 1]; }); }; return { memContainer: memContainer, getApplyButton: getApplyButton }; }; var global$b = tinymce.util.Tools.resolve('tinymce.dom.DomQuery'); var global$c = tinymce.util.Tools.resolve('tinymce.geom.Rect'); var global$d = tinymce.util.Tools.resolve('tinymce.util.Observable'); var global$e = tinymce.util.Tools.resolve('tinymce.util.Tools'); var global$f = tinymce.util.Tools.resolve('tinymce.util.VK'); function getDocumentSize(doc) { var documentElement, body, scrollWidth, clientWidth; var offsetWidth, scrollHeight, clientHeight, offsetHeight; var max = Math.max; documentElement = doc.documentElement; body = doc.body; scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); clientWidth = max(documentElement.clientWidth, body.clientWidth); offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); clientHeight = max(documentElement.clientHeight, body.clientHeight); offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); return { width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, height: scrollHeight < offsetHeight ? clientHeight : scrollHeight }; } function updateWithTouchData(e) { var keys, i; if (e.changedTouches) { keys = 'screenX screenY pageX pageY clientX clientY'.split(' '); for (i = 0; i < keys.length; i++) { e[keys[i]] = e.changedTouches[0][keys[i]]; } } } function DragHelper (id, settings) { var $eventOverlay; var doc = settings.document || domGlobals.document; var downButton; var start, stop, drag, startX, startY; settings = settings || {}; var handleElement = doc.getElementById(settings.handle || id); start = function (e) { var docSize = getDocumentSize(doc); var handleElm, cursor; updateWithTouchData(e); e.preventDefault(); downButton = e.button; handleElm = handleElement; startX = e.screenX; startY = e.screenY; if (domGlobals.window.getComputedStyle) { cursor = domGlobals.window.getComputedStyle(handleElm, null).getPropertyValue('cursor'); } else { cursor = handleElm.runtimeStyle.cursor; } $eventOverlay = global$b('
').css({ position: 'absolute', top: 0, left: 0, width: docSize.width, height: docSize.height, zIndex: 2147483647, opacity: 0.0001, cursor: cursor }).appendTo(doc.body); global$b(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop); settings.start(e); }; drag = function (e) { updateWithTouchData(e); if (e.button !== downButton) { return stop(e); } e.deltaX = e.screenX - startX; e.deltaY = e.screenY - startY; e.preventDefault(); settings.drag(e); }; stop = function (e) { updateWithTouchData(e); global$b(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop); $eventOverlay.remove(); if (settings.stop) { settings.stop(e); } }; this.destroy = function () { global$b(handleElement).off(); }; global$b(handleElement).on('mousedown touchstart', start); } var count = 0; var create$7 = function (currentRect, viewPortRect, clampRect, containerElm, action) { var instance; var dragHelpers; var blockers; var prefix = 'tox-'; var id = prefix + 'crid-' + count++; var handles = [ { name: 'move', xMul: 0, yMul: 0, deltaX: 1, deltaY: 1, deltaW: 0, deltaH: 0, label: 'Crop Mask' }, { name: 'nw', xMul: 0, yMul: 0, deltaX: 1, deltaY: 1, deltaW: -1, deltaH: -1, label: 'Top Left Crop Handle' }, { name: 'ne', xMul: 1, yMul: 0, deltaX: 0, deltaY: 1, deltaW: 1, deltaH: -1, label: 'Top Right Crop Handle' }, { name: 'sw', xMul: 0, yMul: 1, deltaX: 1, deltaY: 0, deltaW: -1, deltaH: 1, label: 'Bottom Left Crop Handle' }, { name: 'se', xMul: 1, yMul: 1, deltaX: 0, deltaY: 0, deltaW: 1, deltaH: 1, label: 'Bottom Right Crop Handle' } ]; blockers = [ 'top', 'right', 'bottom', 'left' ]; var getAbsoluteRect = function (outerRect, relativeRect) { return { x: relativeRect.x + outerRect.x, y: relativeRect.y + outerRect.y, w: relativeRect.w, h: relativeRect.h }; }; var getRelativeRect = function (outerRect, innerRect) { return { x: innerRect.x - outerRect.x, y: innerRect.y - outerRect.y, w: innerRect.w, h: innerRect.h }; }; var getInnerRect = function () { return getRelativeRect(clampRect, currentRect); }; function moveRect(handle, startRect, deltaX, deltaY) { var x, y, w, h, rect; x = startRect.x; y = startRect.y; w = startRect.w; h = startRect.h; x += deltaX * handle.deltaX; y += deltaY * handle.deltaY; w += deltaX * handle.deltaW; h += deltaY * handle.deltaH; if (w < 20) { w = 20; } if (h < 20) { h = 20; } rect = currentRect = global$c.clamp({ x: x, y: y, w: w, h: h }, clampRect, handle.name === 'move'); rect = getRelativeRect(clampRect, rect); instance.fire('updateRect', { rect: rect }); setInnerRect(rect); } function render() { function createDragHelper(handle) { var startRect; return new DragHelper(id, { document: containerElm.ownerDocument, handle: id + '-' + handle.name, start: function () { startRect = currentRect; }, drag: function (e) { moveRect(handle, startRect, e.deltaX, e.deltaY); } }); } global$b('
').appendTo(containerElm); global$e.each(blockers, function (blocker) { global$b('#' + id, containerElm).append('