UNPKG

tinymce

Version:

Web based JavaScript HTML WYSIWYG editor control.

1,404 lines (1,369 loc) 384 kB
/** * TinyMCE version 7.9.1 (2025-05-29) */ (function () { 'use strict'; var global$1 = tinymce.util.Tools.resolve('tinymce.ModelManager'); /* eslint-disable @typescript-eslint/no-wrapper-object-types */ const hasProto = (v, constructor, predicate) => { var _a; if (predicate(v, constructor.prototype)) { return true; } else { // String-based fallback time return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name; } }; const typeOf = (x) => { const t = typeof x; if (x === null) { return 'null'; } else if (t === 'object' && Array.isArray(x)) { return 'array'; } else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) { return 'string'; } else { return t; } }; const isType$1 = (type) => (value) => typeOf(value) === type; const isSimpleType = (type) => (value) => typeof value === type; const eq$2 = (t) => (a) => t === a; const isString = isType$1('string'); const isObject = isType$1('object'); const isArray = isType$1('array'); const isNull = eq$2(null); const isBoolean = isSimpleType('boolean'); const isUndefined = eq$2(undefined); const isNullable = (a) => a === null || a === undefined; const isNonNullable = (a) => !isNullable(a); const isFunction = isSimpleType('function'); const isNumber = isSimpleType('number'); const noop = () => { }; /** Compose a unary function with an n-ary function */ const compose = (fa, fb) => { return (...args) => { return fa(fb.apply(null, args)); }; }; /** Compose two unary functions. Similar to compose, but avoids using Function.prototype.apply. */ const compose1 = (fbc, fab) => (a) => fbc(fab(a)); const constant = (value) => { return () => { return value; }; }; const identity = (x) => { return x; }; const tripleEquals = (a, b) => { return a === b; }; // eslint-disable-next-line prefer-arrow/prefer-arrow-functions function curry(fn, ...initialArgs) { return (...restArgs) => { const all = initialArgs.concat(restArgs); return fn.apply(null, all); }; } const not = (f) => (t) => !f(t); const die = (msg) => { return () => { throw new Error(msg); }; }; const apply = (f) => { return f(); }; const never = constant(false); const always = constant(true); /** * The `Optional` type represents a value (of any type) that potentially does * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the * value does exist) or a `None` (in which case the value does not exist). This * module defines a whole lot of FP-inspired utility functions for dealing with * `Optional` objects. * * Comparison with null or undefined: * - We don't get fancy null coalescing operators with `Optional` * - We do get fancy helper functions with `Optional` * - `Optional` support nesting, and allow for the type to still be nullable (or * another `Optional`) * - There is no option to turn off strict-optional-checks like there is for * strict-null-checks */ class Optional { // The internal representation has a `tag` and a `value`, but both are // private: able to be console.logged, but not able to be accessed by code constructor(tag, value) { this.tag = tag; this.value = value; } // --- Identities --- /** * Creates a new `Optional<T>` that **does** contain a value. */ static some(value) { return new Optional(true, value); } /** * Create a new `Optional<T>` that **does not** contain a value. `T` can be * any type because we don't actually have a `T`. */ static none() { return Optional.singletonNone; } /** * Perform a transform on an `Optional` type. Regardless of whether this * `Optional` contains a value or not, `fold` will return a value of type `U`. * If this `Optional` does not contain a value, the `U` will be created by * calling `onNone`. If this `Optional` does contain a value, the `U` will be * created by calling `onSome`. * * For the FP enthusiasts in the room, this function: * 1. Could be used to implement all of the functions below * 2. Forms a catamorphism */ fold(onNone, onSome) { if (this.tag) { return onSome(this.value); } else { return onNone(); } } /** * Determine if this `Optional` object contains a value. */ isSome() { return this.tag; } /** * Determine if this `Optional` object **does not** contain a value. */ isNone() { return !this.tag; } // --- Functor (name stolen from Haskell / maths) --- /** * Perform a transform on an `Optional` object, **if** there is a value. If * you provide a function to turn a T into a U, this is the function you use * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain * a value then the output will also contain a value (that value being the * output of `mapper(this.value)`), and if this **does not** contain a value * then neither will the output. */ map(mapper) { if (this.tag) { return Optional.some(mapper(this.value)); } else { return Optional.none(); } } // --- Monad (name stolen from Haskell / maths) --- /** * Perform a transform on an `Optional` object, **if** there is a value. * Unlike `map`, here the transform itself also returns an `Optional`. */ bind(binder) { if (this.tag) { return binder(this.value); } else { return Optional.none(); } } // --- Traversable (name stolen from Haskell / maths) --- /** * For a given predicate, this function finds out if there **exists** a value * inside this `Optional` object that meets the predicate. In practice, this * means that for `Optional`s that do not contain a value it returns false (as * no predicate-meeting value exists). */ exists(predicate) { return this.tag && predicate(this.value); } /** * For a given predicate, this function finds out if **all** the values inside * this `Optional` object meet the predicate. In practice, this means that * for `Optional`s that do not contain a value it returns true (as all 0 * objects do meet the predicate). */ forall(predicate) { return !this.tag || predicate(this.value); } filter(predicate) { if (!this.tag || predicate(this.value)) { return this; } else { return Optional.none(); } } // --- Getters --- /** * Get the value out of the inside of the `Optional` object, using a default * `replacement` value if the provided `Optional` object does not contain a * value. */ getOr(replacement) { return this.tag ? this.value : replacement; } /** * Get the value out of the inside of the `Optional` object, using a default * `replacement` value if the provided `Optional` object does not contain a * value. Unlike `getOr`, in this method the `replacement` object is also * `Optional` - meaning that this method will always return an `Optional`. */ or(replacement) { return this.tag ? this : replacement; } /** * Get the value out of the inside of the `Optional` object, using a default * `replacement` value if the provided `Optional` object does not contain a * value. Unlike `getOr`, in this method the `replacement` value is * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you * pass a function which (if called) will **return** the `value` you want to * use. */ getOrThunk(thunk) { return this.tag ? this.value : thunk(); } /** * Get the value out of the inside of the `Optional` object, using a default * `replacement` value if the provided Optional object does not contain a * value. * * Unlike `or`, in this method the `replacement` value is "thunked" - that is * to say that you don't pass a value to `orThunk`, you pass a function which * (if called) will **return** the `value` you want to use. * * Unlike `getOrThunk`, in this method the `replacement` value is also * `Optional`, meaning that this method will always return an `Optional`. */ orThunk(thunk) { return this.tag ? this : thunk(); } /** * Get the value out of the inside of the `Optional` object, throwing an * exception if the provided `Optional` object does not contain a value. * * WARNING: * You should only be using this function if you know that the `Optional` * object **is not** empty (otherwise you're throwing exceptions in production * code, which is bad). * * In tests this is more acceptable. * * Prefer other methods to this, such as `.each`. */ getOrDie(message) { if (!this.tag) { throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None'); } else { return this.value; } } // --- Interop with null and undefined --- /** * Creates an `Optional` value from a nullable (or undefined-able) input. * Null, or undefined, is converted to `None`, and anything else is converted * to `Some`. */ static from(value) { return isNonNullable(value) ? Optional.some(value) : Optional.none(); } /** * Converts an `Optional` to a nullable type, by getting the value if it * exists, or returning `null` if it does not. */ getOrNull() { return this.tag ? this.value : null; } /** * Converts an `Optional` to an undefined-able type, by getting the value if * it exists, or returning `undefined` if it does not. */ getOrUndefined() { return this.value; } // --- Utilities --- /** * If the `Optional` contains a value, perform an action on that value. * Unlike the rest of the methods on this type, `.each` has side-effects. If * you want to transform an `Optional<T>` **into** something, then this is not * the method for you. If you want to use an `Optional<T>` to **do** * something, then this is the method for you - provided you're okay with not * doing anything in the case where the `Optional` doesn't have a value inside * it. If you're not sure whether your use-case fits into transforming * **into** something or **doing** something, check whether it has a return * value. If it does, you should be performing a transform. */ each(worker) { if (this.tag) { worker(this.value); } } /** * Turn the `Optional` object into an array that contains all of the values * stored inside the `Optional`. In practice, this means the output will have * either 0 or 1 elements. */ toArray() { return this.tag ? [this.value] : []; } /** * Turn the `Optional` object into a string for debugging or printing. Not * recommended for production code, but good for debugging. Also note that * these days an `Optional` object can be logged to the console directly, and * its inner value (if it exists) will be visible. */ toString() { return this.tag ? `some(${this.value})` : 'none()'; } } // Sneaky optimisation: every instance of Optional.none is identical, so just // reuse the same object Optional.singletonNone = new Optional(false); /* eslint-disable @typescript-eslint/unbound-method */ const nativeSlice = Array.prototype.slice; const nativeIndexOf = Array.prototype.indexOf; const nativePush = Array.prototype.push; /* eslint-enable */ const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t); const contains$2 = (xs, x) => rawIndexOf(xs, x) > -1; const exists = (xs, pred) => { for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; if (pred(x, i)) { return true; } } return false; }; const range$1 = (num, f) => { const r = []; for (let i = 0; i < num; i++) { r.push(f(i)); } return r; }; const map$1 = (xs, f) => { // pre-allocating array size when it's guaranteed to be known // http://jsperf.com/push-allocated-vs-dynamic/22 const len = xs.length; const r = new Array(len); for (let i = 0; i < len; i++) { const x = xs[i]; r[i] = f(x, i); } return r; }; // Unwound implementing other functions in terms of each. // The code size is roughly the same, and it should allow for better optimisation. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void { const each$2 = (xs, f) => { for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; f(x, i); } }; const eachr = (xs, f) => { for (let i = xs.length - 1; i >= 0; i--) { const x = xs[i]; f(x, i); } }; const partition = (xs, pred) => { const pass = []; const fail = []; for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; const arr = pred(x, i) ? pass : fail; arr.push(x); } return { pass, fail }; }; const filter$2 = (xs, pred) => { const r = []; for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; if (pred(x, i)) { r.push(x); } } return r; }; const foldr = (xs, f, acc) => { eachr(xs, (x, i) => { acc = f(acc, x, i); }); return acc; }; const foldl = (xs, f, acc) => { each$2(xs, (x, i) => { acc = f(acc, x, i); }); return acc; }; const findUntil = (xs, pred, until) => { for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; if (pred(x, i)) { return Optional.some(x); } else if (until(x, i)) { break; } } return Optional.none(); }; const find$1 = (xs, pred) => { return findUntil(xs, pred, never); }; const findIndex = (xs, pred) => { for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; if (pred(x, i)) { return Optional.some(i); } } return Optional.none(); }; const flatten = (xs) => { // Note, this is possible because push supports multiple arguments: // http://jsperf.com/concat-push/6 // Note that in the past, concat() would silently work (very slowly) for array-like objects. // With this change it will throw an error. const r = []; for (let i = 0, len = xs.length; i < len; ++i) { // Ensure that each value is an array itself if (!isArray(xs[i])) { throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); } nativePush.apply(r, xs[i]); } return r; }; const bind$2 = (xs, f) => flatten(map$1(xs, f)); const forall = (xs, pred) => { for (let i = 0, len = xs.length; i < len; ++i) { const x = xs[i]; if (pred(x, i) !== true) { return false; } } return true; }; const reverse = (xs) => { const r = nativeSlice.call(xs, 0); r.reverse(); return r; }; const mapToObject = (xs, f) => { const r = {}; for (let i = 0, len = xs.length; i < len; i++) { const x = xs[i]; r[String(x)] = f(x, i); } return r; }; const sort$1 = (xs, comparator) => { const copy = nativeSlice.call(xs, 0); copy.sort(comparator); return copy; }; const get$d = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none(); const head = (xs) => get$d(xs, 0); const last$2 = (xs) => get$d(xs, xs.length - 1); const findMap = (arr, f) => { for (let i = 0; i < arr.length; i++) { const r = f(arr[i], i); if (r.isSome()) { return r; } } return Optional.none(); }; // There are many variations of Object iteration that are faster than the 'for-in' style: // http://jsperf.com/object-keys-iteration/107 // // Use the native keys if it is available (IE9+), otherwise fall back to manually filtering const keys = Object.keys; // eslint-disable-next-line @typescript-eslint/unbound-method const hasOwnProperty = Object.hasOwnProperty; const each$1 = (obj, f) => { const props = keys(obj); for (let k = 0, len = props.length; k < len; k++) { const i = props[k]; const x = obj[i]; f(x, i); } }; const map = (obj, f) => { return tupleMap(obj, (x, i) => ({ k: i, v: f(x, i) })); }; const tupleMap = (obj, f) => { const r = {}; each$1(obj, (x, i) => { const tuple = f(x, i); r[tuple.k] = tuple.v; }); return r; }; const objAcc = (r) => (x, i) => { r[i] = x; }; const internalFilter = (obj, pred, onTrue, onFalse) => { each$1(obj, (x, i) => { (pred(x, i) ? onTrue : onFalse)(x, i); }); }; const filter$1 = (obj, pred) => { const t = {}; internalFilter(obj, pred, objAcc(t), noop); return t; }; const mapToArray = (obj, f) => { const r = []; each$1(obj, (value, name) => { r.push(f(value, name)); }); return r; }; const values = (obj) => { return mapToArray(obj, identity); }; const get$c = (obj, key) => { return has$1(obj, key) ? Optional.from(obj[key]) : Optional.none(); }; const has$1 = (obj, key) => hasOwnProperty.call(obj, key); const hasNonNullableKey = (obj, key) => has$1(obj, key) && obj[key] !== undefined && obj[key] !== null; const isEmpty = (r) => { for (const x in r) { if (hasOwnProperty.call(r, x)) { return false; } } return true; }; /* * Generates a church encoded ADT (https://en.wikipedia.org/wiki/Church_encoding) * For syntax and use, look at the test code. */ const generate$1 = (cases) => { // validation 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'); } const constructors = []; // adt is mutated to add the individual cases const adt = {}; each$2(cases, (acase, count) => { const keys$1 = keys(acase); // validation if (keys$1.length !== 1) { throw new Error('one and only one name per case'); } const key = keys$1[0]; const value = acase[key]; // validation 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)) { // this implicitly checks if acase is an object throw new Error('case arguments must be an array'); } constructors.push(key); // // constructor for key // adt[key] = (...args) => { const argLength = args.length; // validation if (argLength !== value.length) { throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength); } const match = (branches) => { const branchKeys = keys(branches); if (constructors.length !== branchKeys.length) { throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(',')); } const allReqd = forall(constructors, (reqKey) => { return contains$2(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); }; // // the fold function for key // return { fold: (...foldArgs) => { // runtime validation if (foldArgs.length !== cases.length) { throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length); } const target = foldArgs[count]; return target.apply(null, args); }, match, // NOTE: Only for debugging. log: (label) => { // eslint-disable-next-line no-console console.log(label, { constructors, constructor: key, params: args }); } }; }; }); return adt; }; const Adt = { generate: generate$1 }; const Cell = (initial) => { let value = initial; const get = () => { return value; }; const set = (v) => { value = v; }; return { get, set }; }; const sort = (arr) => { return arr.slice(0).sort(); }; const reqMessage = (required, keys) => { throw new Error('All required keys (' + sort(required).join(', ') + ') were not specified. Specified keys were: ' + sort(keys).join(', ') + '.'); }; const unsuppMessage = (unsupported) => { throw new Error('Unsupported keys for object: ' + sort(unsupported).join(', ')); }; const validateStrArr = (label, array) => { if (!isArray(array)) { throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.'); } each$2(array, (a) => { if (!isString(a)) { throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.'); } }); }; const invalidTypeMessage = (incorrect, type) => { throw new Error('All values need to be of type: ' + type + '. Keys (' + sort(incorrect).join(', ') + ') were not.'); }; const checkDupes = (everything) => { const sorted = sort(everything); const dupe = find$1(sorted, (s, i) => { return i < sorted.length - 1 && s === sorted[i + 1]; }); dupe.each((d) => { throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].'); }); }; // Ensure that the object has all required fields. They must be functions. const base = (handleUnsupported, required) => { return baseWith(handleUnsupported, required, { validate: isFunction, label: 'function' }); }; // Ensure that the object has all required fields. They must satisy predicates. const baseWith = (handleUnsupported, required, pred) => { if (required.length === 0) { throw new Error('You must specify at least one required field.'); } validateStrArr('required', required); checkDupes(required); return (obj) => { const keys$1 = keys(obj); // Ensure all required keys are present. const allReqd = forall(required, (req) => { return contains$2(keys$1, req); }); if (!allReqd) { reqMessage(required, keys$1); } handleUnsupported(required, keys$1); const invalidKeys = filter$2(required, (key) => { return !pred.validate(obj[key], key); }); if (invalidKeys.length > 0) { invalidTypeMessage(invalidKeys, pred.label); } return obj; }; }; const handleExact = (required, keys) => { const unsupported = filter$2(keys, (key) => { return !contains$2(required, key); }); if (unsupported.length > 0) { unsuppMessage(unsupported); } }; const exactly = (required) => base(handleExact, required); /** * Creates a new `Result<T, E>` that **does** contain a value. */ const value$1 = (value) => { const applyHelper = (fn) => fn(value); const constHelper = constant(value); const outputHelper = () => output; const output = { // Debug info tag: true, inner: value, // Actual Result methods fold: (_onError, onValue) => onValue(value), isValue: always, isError: never, map: (mapper) => Result.value(mapper(value)), mapError: outputHelper, bind: applyHelper, exists: applyHelper, forall: applyHelper, getOr: constHelper, or: outputHelper, getOrThunk: constHelper, orThunk: outputHelper, getOrDie: constHelper, each: (fn) => { // Can't write the function inline because we don't want to return something by mistake fn(value); }, toOptional: () => Optional.some(value), }; return output; }; /** * Creates a new `Result<T, E>` that **does not** contain a value, and therefore * contains an error. */ const error = (error) => { const outputHelper = () => output; const output = { // Debug info tag: false, inner: error, // Actual Result methods fold: (onError, _onValue) => onError(error), isValue: never, isError: always, map: outputHelper, mapError: (mapper) => Result.error(mapper(error)), bind: outputHelper, exists: never, forall: always, getOr: identity, or: identity, getOrThunk: apply, orThunk: apply, getOrDie: die(String(error)), each: noop, toOptional: Optional.none, }; return output; }; /** * Creates a new `Result<T, E>` from an `Optional<T>` and an `E`. If the * `Optional` contains a value, so will the outputted `Result`. If it does not, * the outputted `Result` will contain an error (and that error will be the * error passed in). */ const fromOption = (optional, err) => optional.fold(() => error(err), value$1); const Result = { value: value$1, error, fromOption }; // Use window object as the global if it's available since CSP will block script evals // eslint-disable-next-line @typescript-eslint/no-implied-eval const Global = typeof window !== 'undefined' ? window : Function('return this;')(); // This API is intended to give the capability to return namespaced strings. // For CSS, since dots are not valid class names, the dots are turned into dashes. const css = (namespace) => { const dashNamespace = namespace.replace(/\./g, '-'); const resolve = (str) => { return dashNamespace + '-' + str; }; return { resolve }; }; /** * **Is** the value stored inside this Optional object equal to `rhs`? */ const is$2 = (lhs, rhs, comparator = tripleEquals) => lhs.exists((left) => comparator(left, rhs)); const cat = (arr) => { const r = []; const push = (x) => { r.push(x); }; for (let i = 0; i < arr.length; i++) { arr[i].each(push); } return r; }; const bindFrom = (a, f) => (a !== undefined && a !== null) ? f(a) : Optional.none(); // This can help with type inference, by specifying the type param on the none case, so the caller doesn't have to. const someIf = (b, a) => b ? Optional.some(a) : Optional.none(); /** path :: ([String], JsObj?) -> JsObj */ const path = (parts, scope) => { let o = scope !== undefined && scope !== null ? scope : Global; for (let i = 0; i < parts.length && o !== undefined && o !== null; ++i) { o = o[parts[i]]; } return o; }; /** resolve :: (String, JsObj?) -> JsObj */ const resolve$2 = (p, scope) => { const parts = p.split('.'); return path(parts, scope); }; const singleton = (doRevoke) => { const subject = Cell(Optional.none()); const revoke = () => subject.get().each(doRevoke); const clear = () => { revoke(); subject.set(Optional.none()); }; const isSet = () => subject.get().isSome(); const get = () => subject.get(); const set = (s) => { revoke(); subject.set(Optional.some(s)); }; return { clear, isSet, get, set }; }; const value = () => { const subject = singleton(noop); const on = (f) => subject.get().each(f); return { ...subject, on }; }; const removeFromStart = (str, numChars) => { return str.substring(numChars); }; const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr; const removeLeading = (str, prefix) => { return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str; }; const contains$1 = (str, substr, start = 0, end) => { const idx = str.indexOf(substr, start); if (idx !== -1) { return isUndefined(end) ? true : idx + substr.length <= end; } else { return false; } }; /** Does 'str' start with 'prefix'? * Note: all strings start with the empty string. * More formally, for all strings x, startsWith(x, ""). * This is so that for all strings x and y, startsWith(y + x, y) */ const startsWith = (str, prefix) => { return checkRange(str, prefix, 0); }; /** Does 'str' end with 'suffix'? * Note: all strings end with the empty string. * More formally, for all strings x, endsWith(x, ""). * This is so that for all strings x and y, endsWith(x + y, y) */ const endsWith = (str, suffix) => { return checkRange(str, suffix, str.length - suffix.length); }; const blank = (r) => (s) => s.replace(r, ''); /** removes all leading and trailing spaces */ const trim = blank(/^\s+|\s+$/g); const isNotEmpty = (s) => s.length > 0; const toFloat = (value) => { const num = parseFloat(value); return isNaN(num) ? Optional.none() : Optional.some(num); }; // Run a function fn after rate ms. If another invocation occurs // during the time it is waiting, reschedule the function again // with the new arguments. const last$1 = (fn, rate) => { let timer = null; const cancel = () => { if (!isNull(timer)) { clearTimeout(timer); timer = null; } }; const throttle = (...args) => { cancel(); timer = setTimeout(() => { timer = null; fn.apply(null, args); }, rate); }; return { cancel, throttle }; }; const cached = (f) => { let called = false; let r; return (...args) => { if (!called) { called = true; r = f.apply(null, args); } return r; }; }; const nbsp = '\u00A0'; const validSectionList = ['tfoot', 'thead', 'tbody', 'colgroup']; const isValidSection = (parentName) => contains$2(validSectionList, parentName); const grid = (rows, columns) => ({ rows, columns }); const address = (row, column) => ({ row, column }); const detail = (element, rowspan, colspan) => ({ element, rowspan, colspan }); const detailnew = (element, rowspan, colspan, isNew) => ({ element, rowspan, colspan, isNew }); const extended = (element, rowspan, colspan, row, column, isLocked) => ({ element, rowspan, colspan, row, column, isLocked }); const rowdetail = (element, cells, section) => ({ element, cells, section }); const rowdetailnew = (element, cells, section, isNew) => ({ element, cells, section, isNew }); const elementnew = (element, isNew, isLocked) => ({ element, isNew, isLocked }); const rowcells = (element, cells, section, isNew) => ({ element, cells, section, isNew }); const bounds = (startRow, startCol, finishRow, finishCol) => ({ startRow, startCol, finishRow, finishCol }); const columnext = (element, colspan, column) => ({ element, colspan, column }); const colgroup = (element, columns) => ({ element, columns }); const addCells = (gridRow, index, cells) => { const existingCells = gridRow.cells; const before = existingCells.slice(0, index); const after = existingCells.slice(index); const newCells = before.concat(cells).concat(after); return setCells(gridRow, newCells); }; const addCell = (gridRow, index, cell) => addCells(gridRow, index, [cell]); const mutateCell = (gridRow, index, cell) => { const cells = gridRow.cells; cells[index] = cell; }; const setCells = (gridRow, cells) => rowcells(gridRow.element, cells, gridRow.section, gridRow.isNew); const mapCells = (gridRow, f) => { const cells = gridRow.cells; const r = map$1(cells, f); return rowcells(gridRow.element, r, gridRow.section, gridRow.isNew); }; const getCell = (gridRow, index) => gridRow.cells[index]; const getCellElement = (gridRow, index) => getCell(gridRow, index).element; const cellLength = (gridRow) => gridRow.cells.length; const extractGridDetails = (grid) => { const result = partition(grid, (row) => row.section === 'colgroup'); return { rows: result.fail, cols: result.pass }; }; const clone$2 = (gridRow, cloneRow, cloneCell) => { const newCells = map$1(gridRow.cells, cloneCell); return rowcells(cloneRow(gridRow.element), newCells, gridRow.section, true); }; const fromHtml$1 = (html, scope) => { const doc = scope || document; const div = doc.createElement('div'); div.innerHTML = html; if (!div.hasChildNodes() || div.childNodes.length > 1) { const message = 'HTML does not have a single root node'; // eslint-disable-next-line no-console console.error(message, html); throw new Error(message); } return fromDom$1(div.childNodes[0]); }; const fromTag = (tag, scope) => { const doc = scope || document; const node = doc.createElement(tag); return fromDom$1(node); }; const fromText = (text, scope) => { const doc = scope || document; const node = doc.createTextNode(text); return fromDom$1(node); }; const fromDom$1 = (node) => { // TODO: Consider removing this check, but left atm for safety if (node === null || node === undefined) { throw new Error('Node cannot be null or undefined'); } return { dom: node }; }; const fromPoint$1 = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1); // tslint:disable-next-line:variable-name const SugarElement = { fromHtml: fromHtml$1, fromTag, fromText, fromDom: fromDom$1, fromPoint: fromPoint$1 }; const selectNode = (win, element) => { const rng = win.document.createRange(); rng.selectNode(element.dom); return rng; }; const selectNodeContents = (win, element) => { const rng = win.document.createRange(); selectNodeContentsUsing(rng, element); return rng; }; const selectNodeContentsUsing = (rng, element) => rng.selectNodeContents(element.dom); // NOTE: Mutates the range. const setStart = (rng, situ) => { situ.fold((e) => { rng.setStartBefore(e.dom); }, (e, o) => { rng.setStart(e.dom, o); }, (e) => { rng.setStartAfter(e.dom); }); }; const setFinish = (rng, situ) => { situ.fold((e) => { rng.setEndBefore(e.dom); }, (e, o) => { rng.setEnd(e.dom, o); }, (e) => { rng.setEndAfter(e.dom); }); }; const relativeToNative = (win, startSitu, finishSitu) => { const range = win.document.createRange(); setStart(range, startSitu); setFinish(range, finishSitu); return range; }; const exactToNative = (win, start, soffset, finish, foffset) => { const rng = win.document.createRange(); rng.setStart(start.dom, soffset); rng.setEnd(finish.dom, foffset); return rng; }; const toRect = (rect) => ({ left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, width: rect.width, height: rect.height }); const getFirstRect$1 = (rng) => { const rects = rng.getClientRects(); // ASSUMPTION: The first rectangle is the start of the selection const rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect(); return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none(); }; const adt$6 = Adt.generate([ { ltr: ['start', 'soffset', 'finish', 'foffset'] }, { rtl: ['start', 'soffset', 'finish', 'foffset'] } ]); const fromRange = (win, type, range) => type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset); const getRanges = (win, selection) => selection.match({ domRange: (rng) => { return { ltr: constant(rng), rtl: Optional.none }; }, relative: (startSitu, finishSitu) => { return { ltr: cached(() => relativeToNative(win, startSitu, finishSitu)), rtl: cached(() => Optional.some(relativeToNative(win, finishSitu, startSitu))) }; }, exact: (start, soffset, finish, foffset) => { return { ltr: cached(() => exactToNative(win, start, soffset, finish, foffset)), rtl: cached(() => Optional.some(exactToNative(win, finish, foffset, start, soffset))) }; } }); const doDiagnose = (win, ranges) => { // If we cannot create a ranged selection from start > finish, it could be RTL const rng = ranges.ltr(); if (rng.collapsed) { // Let's check if it's RTL ... if it is, then reversing the direction will not be collapsed const reversed = ranges.rtl().filter((rev) => rev.collapsed === false); return reversed.map((rev) => // We need to use "reversed" here, because the original only has one point (collapsed) adt$6.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset)).getOrThunk(() => fromRange(win, adt$6.ltr, rng)); } else { return fromRange(win, adt$6.ltr, rng); } }; const diagnose = (win, selection) => { const ranges = getRanges(win, selection); return doDiagnose(win, ranges); }; const asLtrRange = (win, selection) => { const diagnosis = diagnose(win, selection); return diagnosis.match({ ltr: (start, soffset, finish, foffset) => { const rng = win.document.createRange(); rng.setStart(start.dom, soffset); rng.setEnd(finish.dom, foffset); return rng; }, rtl: (start, soffset, finish, foffset) => { // NOTE: Reversing start and finish const rng = win.document.createRange(); rng.setStart(finish.dom, foffset); rng.setEnd(start.dom, soffset); return rng; } }); }; adt$6.ltr; adt$6.rtl; const COMMENT = 8; const DOCUMENT = 9; const DOCUMENT_FRAGMENT = 11; const ELEMENT = 1; const TEXT = 3; const is$1 = (element, selector) => { const dom = element.dom; if (dom.nodeType !== ELEMENT) { return false; } else { const 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) { // cast to any as mozMatchesSelector doesn't exist in TS DOM lib return elem.mozMatchesSelector(selector); } else { throw new Error('Browser lacks native selectors'); } // unfortunately we can't throw this on startup :( } }; const bypassSelector = (dom) => // Only elements, documents and shadow roots support querySelector // shadow root element type is DOCUMENT_FRAGMENT dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || // IE fix for complex queries on empty nodes: http://jsfiddle.net/spyder/fv9ptr5L/ dom.childElementCount === 0; const all$1 = (selector, scope) => { const base = scope === undefined ? document : scope.dom; return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), SugarElement.fromDom); }; const one = (selector, scope) => { const base = scope === undefined ? document : scope.dom; return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom); }; const eq$1 = (e1, e2) => e1.dom === e2.dom; // Returns: true if node e1 contains e2, otherwise false. // (returns false if e1===e2: A node does not contain itself). const contains = (e1, e2) => { const d1 = e1.dom; const d2 = e2.dom; return d1 === d2 ? false : d1.contains(d2); }; const is = is$1; const DeviceType = (os, browser, userAgent, mediaMatch) => { const isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; const isiPhone = os.isiOS() && !isiPad; const isMobile = os.isiOS() || os.isAndroid(); const isTouch = isMobile || mediaMatch('(pointer:coarse)'); const isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)'); const isPhone = isiPhone || isMobile && !isTablet; const iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; const 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) }; }; const firstMatch = (regexes, s) => { for (let i = 0; i < regexes.length; i++) { const x = regexes[i]; if (x.test(s)) { return x; } } return undefined; }; const find = (regexes, agent) => { const r = firstMatch(regexes, agent); if (!r) { return { major: 0, minor: 0 }; } const group = (i) => { return Number(agent.replace(r, '$' + i)); }; return nu$2(group(1), group(2)); }; const detect$5 = (versionRegexes, agent) => { const cleanedAgent = String(agent).toLowerCase(); if (versionRegexes.length === 0) { return unknown$2(); } return find(versionRegexes, cleanedAgent); }; const unknown$2 = () => { return nu$2(0, 0); }; const nu$2 = (major, minor) => { return { major, minor }; }; const Version = { nu: nu$2, detect: detect$5, unknown: unknown$2 }; const detectBrowser$1 = (browsers, userAgentData) => { return findMap(userAgentData.brands, (uaBrand) => { const lcBrand = uaBrand.brand.toLowerCase(); return find$1(browsers, (browser) => { var _a; return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase()); }) .map((info) => ({ current: info.name, version: Version.nu(parseInt(uaBrand.version, 10), 0) })); }); }; const detect$4 = (candidates, userAgent) => { const agent = String(userAgent).toLowerCase(); return find$1(candidates, (candidate) => { return candidate.search(agent); }); }; // They (browser and os) are the same at the moment, but they might // not stay that way. const detectBrowser = (browsers, userAgent) => { return detect$4(browsers, userAgent).map((browser) => { const version = Version.detect(browser.versionRegexes, userAgent); return { current: browser.name, version }; }); }; const detectOs = (oses, userAgent) => { return detect$4(oses, userAgent).map((os) => { const version = Version.detect(os.versionRegexes, userAgent); return { current: os.name, version }; }); }; const normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; const checkContains = (target) => { return (uastring) => { return contains$1(uastring, target); }; }; const browsers = [ // This is legacy Edge { name: 'Edge', versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], search: (uastring) => { return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome