tinymce
Version:
Web based JavaScript HTML WYSIWYG editor control.
1,316 lines (1,269 loc) • 163 kB
JavaScript
/**
* TinyMCE version 7.9.0 (2025-05-15)
*/
(function () {
'use strict';
var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
/* 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$1 = (t) => (a) => t === a;
const isString = isType$1('string');
const isArray = isType$1('array');
const isBoolean = isSimpleType('boolean');
const isUndefined = eq$1(undefined);
const isNullable = (a) => a === null || a === undefined;
const isNonNullable = (a) => !isNullable(a);
const isFunction = isSimpleType('function');
const isNumber = isSimpleType('number');
const noop = () => { };
/** 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 call = (f) => {
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 = (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 = (num, f) => {
const r = [];
for (let i = 0; i < num; i++) {
r.push(f(i));
}
return r;
};
const map = (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$1 = (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$1 = (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$1(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 = (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$1 = (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 = (xs, f) => flatten$1(map(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 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 get$4 = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
const head = (xs) => get$4(xs, 0);
const last = (xs) => get$4(xs, xs.length - 1);
isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
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 = (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 objAcc = (r) => (x, i) => {
r[i] = x;
};
const internalFilter = (obj, pred, onTrue, onFalse) => {
each(obj, (x, i) => {
(pred(x, i) ? onTrue : onFalse)(x, i);
});
};
const filter = (obj, pred) => {
const t = {};
internalFilter(obj, pred, objAcc(t), noop);
return t;
};
const mapToArray = (obj, f) => {
const r = [];
each(obj, (value, name) => {
r.push(f(value, name));
});
return r;
};
const values = (obj) => {
return mapToArray(obj, identity);
};
const size = (obj) => {
return keys(obj).length;
};
const get$3 = (obj, key) => {
return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
};
const has = (obj, key) => hasOwnProperty.call(obj, key);
const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
const isEmpty$1 = (r) => {
for (const x in r) {
if (hasOwnProperty.call(r, x)) {
return false;
}
}
return true;
};
const Cell = (initial) => {
let value = initial;
const get = () => {
return value;
};
const set = (v) => {
value = v;
};
return {
get,
set
};
};
/**
* **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;
};
/*
Notes on the lift functions:
- We used to have a generic liftN, but we were concerned about its type-safety, and the below variants were faster in microbenchmarks.
- The getOrDie calls are partial functions, but are checked beforehand. This is faster and more convenient (but less safe) than folds.
- && is used instead of a loop for simplicity and performance.
*/
const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
const flatten = (oot) => oot.bind(identity);
// 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();
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 unbindable = () => singleton((s) => s.unbind());
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;
};
/** 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);
};
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 isEmpty = (s) => !isNotEmpty(s);
const toInt = (value, radix = 10) => {
const num = parseInt(value, radix);
return isNaN(num) ? Optional.none() : Optional.some(num);
};
const toFloat = (value) => {
const num = parseFloat(value);
return isNaN(num) ? Optional.none() : Optional.some(num);
};
const cached = (f) => {
let called = false;
let r;
return (...args) => {
if (!called) {
called = true;
r = f.apply(null, args);
}
return r;
};
};
const fromHtml = (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 = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom$1);
// tslint:disable-next-line:variable-name
const SugarElement = {
fromHtml,
fromTag,
fromText,
fromDom: fromDom$1,
fromPoint
};
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(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 = (e1, e2) => e1.dom === e2.dom;
const is = is$1;
const name = (element) => {
const r = element.dom.nodeName;
return r.toLowerCase();
};
const type = (element) => element.dom.nodeType;
const isType = (t) => (element) => type(element) === t;
const isComment = (element) => type(element) === COMMENT || name(element) === '#comment';
const isElement = isType(ELEMENT);
const isText = isType(TEXT);
const isDocument = isType(DOCUMENT);
const isDocumentFragment = isType(DOCUMENT_FRAGMENT);
const isTag = (tag) => (e) => isElement(e) && name(e) === tag;
/**
* The document associated with the current element
* NOTE: this will throw if the owner is null.
*/
const owner = (element) => SugarElement.fromDom(element.dom.ownerDocument);
/**
* If the element is a document, return it. Otherwise, return its ownerDocument.
* @param dos
*/
const documentOrOwner = (dos) => isDocument(dos) ? dos : owner(dos);
const parent = (element) => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
const parents = (element, isRoot) => {
const stop = isFunction(isRoot) ? isRoot : never;
// This is used a *lot* so it needs to be performant, not recursive
let dom = element.dom;
const ret = [];
while (dom.parentNode !== null && dom.parentNode !== undefined) {
const rawParent = dom.parentNode;
const p = SugarElement.fromDom(rawParent);
ret.push(p);
if (stop(p) === true) {
break;
}
else {
dom = rawParent;
}
}
return ret;
};
const prevSibling = (element) => Optional.from(element.dom.previousSibling).map(SugarElement.fromDom);
const nextSibling = (element) => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
const children$3 = (element) => map(element.dom.childNodes, SugarElement.fromDom);
const child$3 = (element, index) => {
const cs = element.dom.childNodes;
return Optional.from(cs[index]).map(SugarElement.fromDom);
};
const firstChild = (element) => child$3(element, 0);
/**
* Is the element a ShadowRoot?
*
* Note: this is insufficient to test if any element is a shadow root, but it is sufficient to differentiate between
* a Document and a ShadowRoot.
*/
const isShadowRoot = (dos) => isDocumentFragment(dos) && isNonNullable(dos.dom.host);
const getRootNode = (e) => SugarElement.fromDom(e.dom.getRootNode());
/** If this element is in a ShadowRoot, return it. */
const getShadowRoot = (e) => {
const r = getRootNode(e);
return isShadowRoot(r) ? Optional.some(r) : Optional.none();
};
/** Return the host of a ShadowRoot.
*
* This function will throw if Shadow DOM is unsupported in the browser, or if the host is null.
* If you actually have a ShadowRoot, this shouldn't happen.
*/
const getShadowHost = (e) => SugarElement.fromDom(e.dom.host);
const before = (marker, element) => {
const parent$1 = parent(marker);
parent$1.each((v) => {
v.dom.insertBefore(element.dom, marker.dom);
});
};
const after$1 = (marker, element) => {
const sibling = nextSibling(marker);
sibling.fold(() => {
const parent$1 = parent(marker);
parent$1.each((v) => {
append$1(v, element);
});
}, (v) => {
before(v, element);
});
};
const prepend = (parent, element) => {
const firstChild$1 = firstChild(parent);
firstChild$1.fold(() => {
append$1(parent, element);
}, (v) => {
parent.dom.insertBefore(element.dom, v.dom);
});
};
const append$1 = (parent, element) => {
parent.dom.appendChild(element.dom);
};
const wrap = (element, wrapper) => {
before(element, wrapper);
append$1(wrapper, element);
};
const after = (marker, elements) => {
each$1(elements, (x, i) => {
const e = i === 0 ? marker : elements[i - 1];
after$1(e, x);
});
};
const append = (parent, elements) => {
each$1(elements, (x) => {
append$1(parent, x);
});
};
const rawSet = (dom, key, value) => {
/*
* JQuery coerced everything to a string, and silently did nothing on text node/null/undefined.
*
* We fail on those invalid cases, only allowing numbers and booleans.
*/
if (isString(value) || isBoolean(value) || isNumber(value)) {
dom.setAttribute(key, value + '');
}
else {
// eslint-disable-next-line no-console
console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
throw new Error('Attribute value was not simple');
}
};
const set$2 = (element, key, value) => {
rawSet(element.dom, key, value);
};
const setAll = (element, attrs) => {
const dom = element.dom;
each(attrs, (v, k) => {
rawSet(dom, k, v);
});
};
const get$2 = (element, key) => {
const v = element.dom.getAttribute(key);
// undefined is the more appropriate value for JS, and this matches JQuery
return v === null ? undefined : v;
};
const getOpt = (element, key) => Optional.from(get$2(element, key));
const remove$2 = (element, key) => {
element.dom.removeAttribute(key);
};
const clone = (element) => foldl(element.dom.attributes, (acc, attr) => {
acc[attr.name] = attr.value;
return acc;
}, {});
const remove$1 = (element) => {
const dom = element.dom;
if (dom.parentNode !== null) {
dom.parentNode.removeChild(dom);
}
};
const unwrap = (wrapper) => {
const children = children$3(wrapper);
if (children.length > 0) {
after(wrapper, children);
}
remove$1(wrapper);
};
const fromDom = (nodes) => map(nodes, SugarElement.fromDom);
// some elements, such as mathml, don't have style attributes
// others, such as angular elements, have style attributes that aren't a CSSStyleDeclaration
const isSupported = (dom) =>
// eslint-disable-next-line @typescript-eslint/unbound-method
dom.style !== undefined && isFunction(dom.style.getPropertyValue);
// Node.contains() is very, very, very good performance
// http://jsperf.com/closest-vs-contains/5
const inBody = (element) => {
// Technically this is only required on IE, where contains() returns false for text nodes.
// But it's cheap enough to run everywhere and Sugar doesn't have platform detection (yet).
const dom = isText(element) ? element.dom.parentNode : element.dom;
// use ownerDocument.body to ensure this works inside iframes.
// Normally contains is bad because an element "contains" itself, but here we want that.
if (dom === undefined || dom === null || dom.ownerDocument === null) {
return false;
}
const doc = dom.ownerDocument;
return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
};
const internalSet = (dom, property, value) => {
// This is going to hurt. Apologies.
// JQuery coerces numbers to pixels for certain property names, and other times lets numbers through.
// we're going to be explicit; strings only.
if (!isString(value)) {
// eslint-disable-next-line no-console
console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
throw new Error('CSS value must be a string: ' + value);
}
// removed: support for dom().style[property] where prop is camel case instead of normal property name
if (isSupported(dom)) {
dom.style.setProperty(property, value);
}
};
const internalRemove = (dom, property) => {
/*
* IE9 and above - MDN doesn't have details, but here's a couple of random internet claims
*
* http://help.dottoro.com/ljopsjck.php
* http://stackoverflow.com/a/7901886/7546
*/
if (isSupported(dom)) {
dom.style.removeProperty(property);
}
};
const set$1 = (element, property, value) => {
const dom = element.dom;
internalSet(dom, property, value);
};
/*
* NOTE: For certain properties, this returns the "used value" which is subtly different to the "computed value" (despite calling getComputedStyle).
* Blame CSS 2.0.
*
* https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
*/
const get$1 = (element, property) => {
const dom = element.dom;
/*
* IE9 and above per
* https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle
*
* Not in numerosity, because it doesn't memoize and looking this up dynamically in performance critical code would be horrendous.
*
* JQuery has some magic here for IE popups, but we don't really need that.
* It also uses element.ownerDocument.defaultView to handle iframes but that hasn't been required since FF 3.6.
*/
const styles = window.getComputedStyle(dom);
const r = styles.getPropertyValue(property);
// jquery-ism: If r is an empty string, check that the element is not in a document. If it isn't, return the raw value.
// Turns out we do this a lot.
return (r === '' && !inBody(element)) ? getUnsafeProperty(dom, property) : r;
};
// removed: support for dom().style[property] where prop is camel case instead of normal property name
// empty string is what the browsers (IE11 and Chrome) return when the propertyValue doesn't exists.
const getUnsafeProperty = (dom, property) => isSupported(dom) ? dom.style.getPropertyValue(property) : '';
/*
* Gets the raw value from the style attribute. Useful for retrieving "used values" from the DOM:
* https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
*
* Returns NONE if the property isn't set, or the value is an empty string.
*/
const getRaw$1 = (element, property) => {
const dom = element.dom;
const raw = getUnsafeProperty(dom, property);
return Optional.from(raw).filter((r) => r.length > 0);
};
const remove = (element, property) => {
const dom = element.dom;
internalRemove(dom, property);
if (is$2(getOpt(element, 'style').map(trim), '')) {
// No more styles left, remove the style attribute as well
remove$2(element, 'style');
}
};
const Dimension = (name, getOffset) => {
const set = (element, h) => {
if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
}
const dom = element.dom;
if (isSupported(dom)) {
dom.style[name] = h + 'px';
}
};
/*
* jQuery supports querying width and height on the document and window objects.
*
* TBIO doesn't do this, so the code is removed to save space, but left here just in case.
*/
/*
var getDocumentWidth = (element) => {
var dom = element.dom;
if (Node.isDocument(element)) {
var body = dom.body;
var doc = dom.documentElement;
return Math.max(
body.scrollHeight,
doc.scrollHeight,
body.offsetHeight,
doc.offsetHeight,
doc.clientHeight
);
}
};
var getWindowWidth = (element) => {
var dom = element.dom;
if (dom.window === dom) {
// There is no offsetHeight on a window, so use the clientHeight of the document
return dom.document.documentElement.clientHeight;
}
};
*/
const get = (element) => {
const r = getOffset(element);
// zero or null means non-standard or disconnected, fall back to CSS
if (r <= 0 || r === null) {
const css = get$1(element, name);
// ugh this feels dirty, but it saves cycles
return parseFloat(css) || 0;
}
return r;
};
// in jQuery, getOuter replicates (or uses) box-sizing: border-box calculations
// although these calculations only seem relevant for quirks mode, and edge cases TBIO doesn't rely on
const getOuter = get;
const aggregate = (element, properties) => foldl(properties, (acc, property) => {
const val = get$1(element, property);
const value = val === undefined ? 0 : parseInt(val, 10);
return isNaN(value) ? acc : acc + value;
}, 0);
const max = (element, value, properties) => {
const cumulativeInclusions = aggregate(element, properties);
// if max-height is 100px and your cumulativeInclusions is 150px, there is no way max-height can be 100px, so we return 0.
const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
return absoluteMax;
};
return {
set,
get,
getOuter,
aggregate,
max
};
};
const toNumber = (px, fallback) => toFloat(px).getOr(fallback);
const getProp = (element, name, fallback) => toNumber(get$1(element, name), fallback);
const calcContentBoxSize = (element, size, upper, lower) => {
const paddingUpper = getProp(element, `padding-${upper}`, 0);
const paddingLower = getProp(element, `padding-${lower}`, 0);
const borderUpper = getProp(element, `border-${upper}-width`, 0);
const borderLower = getProp(element, `border-${lower}-width`, 0);
return size - paddingUpper - paddingLower - borderUpper - borderLower;
};
const getCalculatedWidth = (element, boxSizing) => {
const dom = element.dom;
const width = dom.getBoundingClientRect().width || dom.offsetWidth;
return boxSizing === 'border-box' ? width : calcContentBoxSize(element, width, 'left', 'right');
};
const getInnerWidth = (element) => getCalculatedWidth(element, 'content-box');
Dimension('width', (element) =>
// IMO passing this function is better than using dom['offset' + 'width']
element.dom.offsetWidth);
Dimension('width', (element) => {
const dom = element.dom;
return inBody(element) ? dom.getBoundingClientRect().width : dom.offsetWidth;
});
const getInner = getInnerWidth;
const NodeValue = (is, name) => {
const get = (element) => {
if (!is(element)) {
throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
}
return getOption(element).getOr('');
};
const getOption = (element) => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
const set = (element, value) => {
if (!is(element)) {
throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
}
element.dom.nodeValue = value;
};
return {
get,
getOption,
set
};
};
const api = NodeValue(isText, 'text');
const get = (element) => api.get(element);
const set = (element, value) => api.set(element, value);
var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
if (is(scope, a)) {
return Optional.some(scope);
}
else if (isFunction(isRoot) && isRoot(scope)) {
return Optional.none();
}
else {
return ancestor(scope, a, isRoot);
}
};
const ancestor$1 = (scope, predicate, isRoot) => {
let element = scope.dom;
const stop = isFunction(isRoot) ? isRoot : never;
while (element.parentNode) {
element = element.parentNode;
const el = SugarElement.fromDom(element);
if (predicate(el)) {
return Optional.some(el);
}
else if (stop(el)) {
break;
}
}
return Optional.none();
};
const closest$2 = (scope, predicate, isRoot) => {
// This is required to avoid ClosestOrAncestor passing the predicate to itself
const is = (s, test) => test(s);
return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
};
const child$2 = (scope, predicate) => {
const pred = (node) => predicate(SugarElement.fromDom(node));
const result = find(scope.dom.childNodes, pred);
return result.map(SugarElement.fromDom);
};
const ancestor = (scope, selector, isRoot) => ancestor$1(scope, (e) => is$1(e, selector), isRoot);
const child$1 = (scope, selector) => child$2(scope, (e) => is$1(e, selector));
const descendant = (scope, selector) => one(selector, scope);
// Returns Some(closest ancestor element (sugared)) matching 'selector' up to isRoot, or None() otherwise
const closest$1 = (scope, selector, isRoot) => {
const is = (element, selector) => is$1(element, selector);
return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
};
const closest = (target) => closest$1(target, '[contenteditable]');
const isEditable = (element, assumeEditable = false) => {
if (inBody(element)) {
return element.dom.isContentEditable;
}
else {
// Find the closest contenteditable element and check if it's editable
return closest(element).fold(constant(assumeEditable), (editable) => getRaw(editable) === 'true');
}
};
const getRaw = (element) => element.dom.contentEditable;
const children$2 = (scope, predicate) => filter$1(children$3(scope), predicate);
const descendants$1 = (scope, predicate) => {
let result = [];
// Recurse.toArray() might help here
each$1(children$3(scope), (x) => {
if (predicate(x)) {
result = result.concat([x]);
}
result = result.concat(descendants$1(x, predicate));
});
return result;
};
const children$1 = (scope, selector) =>
// It may surprise you to learn this is exactly what JQuery does
// TODO: Avoid all the wrapping and unwrapping
children$2(scope, (e) => is$1(e, selector));
const descendants = (scope, selector) => all$1(selector, scope);
const child = (scope, selector) => child$1(scope, selector).isSome();
/*
NOTE: This file is partially duplicated in the following locations:
- models/dom/table/core/TableUtils.ts
- advtable
Make sure that if making changes to this file, the other files are updated as well
*/
const getNodeName = (elm) => elm.nodeName.toLowerCase();
const getBody = (editor) => SugarElement.fromDom(editor.getBody());
const getIsRoot = (editor) => (element) => eq(element, getBody(editor));
const removePxSuffix = (size) => size ? size.replace(/px$/, '') : '';
const addPxSuffix = (size) => /^\d+(\.\d+)?$/.test(size) ? size + 'px' : size;
const getSelectionStart = (editor) => SugarElement.fromDom(editor.selection.getStart());
const getSelectionEnd = (editor) => SugarElement.fromDom(editor.selection.getEnd());
const isInEditableContext = (cell) => closest$2(cell, isTag('table')).forall(isEditable);
const validSectionList = ['tfoot', 'thead', 'tbody', 'colgroup'];
const isValidSection = (parentName) => contains(validSectionList, parentName);
const grid = (rows, columns) => ({
rows,
columns
});
const detail = (element, rowspan, colspan) => ({
element,
rowspan,
colspan
});
const extended = (element, rowspan, colspan, row, column, isLocked) => ({
element,
rowspan,
colspan,
row,
column,
isLocked
});
const rowdetail = (element, cells, section) => ({
element,
cells,
section
});
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 getAttrValue = (cell, name, fallback = 0) => getOpt(cell, name).map((value) => parseInt(value, 10)).getOr(fallback);
const firstLayer = (scope, selector) => {
return filterFirstLayer(scope, selector, always);
};
const filterFirstLayer = (scope, selector, predicate) => {
return bind(children$3(scope), (x) => {
if (is$1(x, selector)) {
return predicate(x) ? [x] : [];
}
else {
return filterFirstLayer(x, selector, predicate);
}
});
};
// lookup inside this table
const lookup = (tags, element, isRoot = never) => {
// If the element we're inspecting is the root, we definitely don't want it.
if (isRoot(element)) {
return Optional.none();
}
// This looks a lot like SelectorFind.closest, with one big exception - the isRoot check.
// The code here will look for parents if passed a table, SelectorFind.closest with that specific isRoot check won't.
if (contains(tags, name(element))) {
return Optional.some(element);
}
const isRootOrUpperTable = (elm) => is$1(elm, 'table') || isRoot(elm);
return ancestor(element, tags.join(','), isRootOrUpperTable);
};
/*
* Identify the optional cell that element represents.
*/
const cell = (element, isRoot) => lookup(['td', 'th'], element, isRoot);
const cells = (ancestor) => firstLayer(ancestor, 'th,td');
const columns = (ancestor) => {
if (is$1(ancestor, 'colgroup')) {
return children$1(ancestor, 'col');
}
else {
return bind(columnGroups(ancestor), (columnGroup) => children$1(columnGroup, 'col'));
}
};
const table = (element, isRoot) => closest$1(element, 'table', isRoot);
const rows = (ancestor) => firstLayer(ancestor, 'tr');
const columnGroups = (ancestor) => table(ancestor).fold(constant([]), (table) => children$1(table, 'colgroup'));
const isHeaderCell = isTag('th');
const getRowHeaderType = (isHeaderRow, isHeaderCells) => {
if (isHeaderRow && isHeaderCells) {
return 'sectionCells';
}
else if (isHeaderRow) {
return 'section';
}
else {
return 'cells';
}
};
const getRowType$1 = (row) => {
// Header rows can use a combination of theads and ths - want to detect the different combinations
const isHeaderRow = row.section === 'thead';
const isHeaderCells = is$2(findCommonCellType(row.cells), 'th');
if (row.section === 'tfoot') {
return { type: 'footer' };
}
else if (isHeaderRow || isHeaderCells) {
return { type: 'header', subType: getRowHeaderType(isHeaderRow, isHead