/**
 * vis-util
 * https://github.com/visjs/vis-util
 *
 * utilitie collection for visjs
 *
 * @version 6.0.0
 * @date    2025-07-12T18:02:43.836Z
 *
 * @copyright (c) 2011-2017 Almende B.V, http://almende.com
 * @copyright (c) 2017-2019 visjs contributors, https://github.com/visjs
 *
 * @license
 * vis.js is dual licensed under both
 *
 *   1. The Apache 2.0 License
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   and
 *
 *   2. The MIT License
 *      http://opensource.org/licenses/MIT
 *
 * vis.js may be distributed under either license.
 */

import Emitter from 'component-emitter';
import RealHammer from '@egjs/hammerjs';

/**
 * Use this symbol to delete properies in deepObjectAssign.
 */
const DELETE = Symbol("DELETE");
/**
 * Pure version of deepObjectAssign, it doesn't modify any of it's arguments.
 * @param base - The base object that fullfils the whole interface T.
 * @param updates - Updates that may change or delete props.
 * @returns A brand new instance with all the supplied objects deeply merged.
 */
function pureDeepObjectAssign(base, ...updates) {
    return deepObjectAssign({}, base, ...updates);
}
/**
 * Deep version of object assign with additional deleting by the DELETE symbol.
 * @param values - Objects to be deeply merged.
 * @returns The first object from values.
 */
function deepObjectAssign(...values) {
    const merged = deepObjectAssignNonentry(...values);
    stripDelete(merged);
    return merged;
}
/**
 * Deep version of object assign with additional deleting by the DELETE symbol.
 * @remarks
 * This doesn't strip the DELETE symbols so they may end up in the final object.
 * @param values - Objects to be deeply merged.
 * @returns The first object from values.
 */
function deepObjectAssignNonentry(...values) {
    if (values.length < 2) {
        return values[0];
    }
    else if (values.length > 2) {
        return deepObjectAssignNonentry(deepObjectAssign(values[0], values[1]), ...values.slice(2));
    }
    const a = values[0];
    const b = values[1];
    if (a instanceof Date && b instanceof Date) {
        a.setTime(b.getTime());
        return a;
    }
    for (const prop of Reflect.ownKeys(b)) {
        if (!Object.prototype.propertyIsEnumerable.call(b, prop)) ;
        else if (b[prop] === DELETE) {
            delete a[prop];
        }
        else if (a[prop] !== null &&
            b[prop] !== null &&
            typeof a[prop] === "object" &&
            typeof b[prop] === "object" &&
            !Array.isArray(a[prop]) &&
            !Array.isArray(b[prop])) {
            a[prop] = deepObjectAssignNonentry(a[prop], b[prop]);
        }
        else {
            a[prop] = clone(b[prop]);
        }
    }
    return a;
}
/**
 * Deep clone given object or array. In case of primitive simply return.
 * @param a - Anything.
 * @returns Deep cloned object/array or unchanged a.
 */
function clone(a) {
    if (Array.isArray(a)) {
        return a.map((value) => clone(value));
    }
    else if (typeof a === "object" && a !== null) {
        if (a instanceof Date) {
            return new Date(a.getTime());
        }
        return deepObjectAssignNonentry({}, a);
    }
    else {
        return a;
    }
}
/**
 * Strip DELETE from given object.
 * @param a - Object which may contain DELETE but won't after this is executed.
 */
function stripDelete(a) {
    for (const prop of Object.keys(a)) {
        if (a[prop] === DELETE) {
            delete a[prop];
        }
        else if (typeof a[prop] === "object" && a[prop] !== null) {
            stripDelete(a[prop]);
        }
    }
}

/**
 * Seedable, fast and reasonably good (not crypto but more than okay for our
 * needs) random number generator.
 * @remarks
 * Adapted from {@link https://web.archive.org/web/20110429100736/http://baagoe.com:80/en/RandomMusings/javascript}.
 * Original algorithm created by Johannes Baagøe \<baagoe\@baagoe.com\> in 2010.
 */
/**
 * Create a seeded pseudo random generator based on Alea by Johannes Baagøe.
 * @param seed - All supplied arguments will be used as a seed. In case nothing
 * is supplied the current time will be used to seed the generator.
 * @returns A ready to use seeded generator.
 */
function Alea(...seed) {
    return AleaImplementation(seed.length ? seed : [Date.now()]);
}
/**
 * An implementation of [[Alea]] without user input validation.
 * @param seed - The data that will be used to seed the generator.
 * @returns A ready to use seeded generator.
 */
function AleaImplementation(seed) {
    let [s0, s1, s2] = mashSeed(seed);
    let c = 1;
    const random = () => {
        const t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
        s0 = s1;
        s1 = s2;
        return (s2 = t - (c = t | 0));
    };
    random.uint32 = () => random() * 0x100000000; // 2^32
    random.fract53 = () => random() + ((random() * 0x200000) | 0) * 1.1102230246251565e-16; // 2^-53
    random.algorithm = "Alea";
    random.seed = seed;
    random.version = "0.9";
    return random;
}
/**
 * Turn arbitrary data into values [[AleaImplementation]] can use to generate
 * random numbers.
 * @param seed - Arbitrary data that will be used as the seed.
 * @returns Three numbers to use as initial values for [[AleaImplementation]].
 */
function mashSeed(...seed) {
    const mash = Mash();
    let s0 = mash(" ");
    let s1 = mash(" ");
    let s2 = mash(" ");
    for (let i = 0; i < seed.length; i++) {
        s0 -= mash(seed[i]);
        if (s0 < 0) {
            s0 += 1;
        }
        s1 -= mash(seed[i]);
        if (s1 < 0) {
            s1 += 1;
        }
        s2 -= mash(seed[i]);
        if (s2 < 0) {
            s2 += 1;
        }
    }
    return [s0, s1, s2];
}
/**
 * Create a new mash function.
 * @returns A nonpure function that takes arbitrary [[Mashable]] data and turns
 * them into numbers.
 */
function Mash() {
    let n = 0xefc8249d;
    return function (data) {
        const string = data.toString();
        for (let i = 0; i < string.length; i++) {
            n += string.charCodeAt(i);
            let h = 0.02519603282416938 * n;
            n = h >>> 0;
            h -= n;
            h *= n;
            n = h >>> 0;
            h -= n;
            n += h * 0x100000000; // 2^32
        }
        return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
    };
}

/**
 * Setup a mock hammer.js object, for unit testing.
 *
 * Inspiration: https://github.com/uber/deck.gl/pull/658
 * @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
 */
function hammerMock() {
  const noop = () => {};

  return {
    on: noop,
    off: noop,
    destroy: noop,
    emit: noop,

    get() {
      return {
        set: noop,
      };
    },
  };
}

const Hammer$1 =
  typeof window !== "undefined"
    ? window.Hammer || RealHammer
    : function () {
        // hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
        return hammerMock();
      };

/**
 * Turn an element into an clickToUse element.
 * When not active, the element has a transparent overlay. When the overlay is
 * clicked, the mode is changed to active.
 * When active, the element is displayed with a blue border around it, and
 * the interactive contents of the element can be used. When clicked outside
 * the element, the elements mode is changed to inactive.
 * @param {Element} container
 * @class Activator
 */
function Activator$1(container) {
  this._cleanupQueue = [];

  this.active = false;

  this._dom = {
    container,
    overlay: document.createElement("div"),
  };

  this._dom.overlay.classList.add("vis-overlay");

  this._dom.container.appendChild(this._dom.overlay);
  this._cleanupQueue.push(() => {
    this._dom.overlay.parentNode.removeChild(this._dom.overlay);
  });

  const hammer = Hammer$1(this._dom.overlay);
  hammer.on("tap", this._onTapOverlay.bind(this));
  this._cleanupQueue.push(() => {
    hammer.destroy();
    // FIXME: cleaning up hammer instances doesn't work (Timeline not removed
    // from memory)
  });

  // block all touch events (except tap)
  const events = [
    "tap",
    "doubletap",
    "press",
    "pinch",
    "pan",
    "panstart",
    "panmove",
    "panend",
  ];
  events.forEach((event) => {
    hammer.on(event, (event) => {
      event.srcEvent.stopPropagation();
    });
  });

  // attach a click event to the window, in order to deactivate when clicking outside the timeline
  if (document && document.body) {
    this._onClick = (event) => {
      if (!_hasParent(event.target, container)) {
        this.deactivate();
      }
    };
    document.body.addEventListener("click", this._onClick);
    this._cleanupQueue.push(() => {
      document.body.removeEventListener("click", this._onClick);
    });
  }

  // prepare escape key listener for deactivating when active
  this._escListener = (event) => {
    if (
      "key" in event
        ? event.key === "Escape"
        : event.keyCode === 27 /* the keyCode is for IE11 */
    ) {
      this.deactivate();
    }
  };
}

// turn into an event emitter
Emitter(Activator$1.prototype);

// The currently active activator
Activator$1.current = null;

/**
 * Destroy the activator. Cleans up all created DOM and event listeners
 */
Activator$1.prototype.destroy = function () {
  this.deactivate();

  for (const callback of this._cleanupQueue.splice(0).reverse()) {
    callback();
  }
};

/**
 * Activate the element
 * Overlay is hidden, element is decorated with a blue shadow border
 */
Activator$1.prototype.activate = function () {
  // we allow only one active activator at a time
  if (Activator$1.current) {
    Activator$1.current.deactivate();
  }
  Activator$1.current = this;

  this.active = true;
  this._dom.overlay.style.display = "none";
  this._dom.container.classList.add("vis-active");

  this.emit("change");
  this.emit("activate");

  // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  // keyboard events on a 'change' event
  document.body.addEventListener("keydown", this._escListener);
};

/**
 * Deactivate the element
 * Overlay is displayed on top of the element
 */
Activator$1.prototype.deactivate = function () {
  this.active = false;
  this._dom.overlay.style.display = "block";
  this._dom.container.classList.remove("vis-active");
  document.body.removeEventListener("keydown", this._escListener);

  this.emit("change");
  this.emit("deactivate");
};

/**
 * Handle a tap event: activate the container
 * @param {Event}  event   The event
 * @private
 */
Activator$1.prototype._onTapOverlay = function (event) {
  // activate the container
  this.activate();
  event.srcEvent.stopPropagation();
};

/**
 * Test whether the element has the requested parent element somewhere in
 * its chain of parent nodes.
 * @param {HTMLElement} element
 * @param {HTMLElement} parent
 * @returns {boolean} Returns true when the parent is found somewhere in the
 *                    chain of parent nodes.
 * @private
 */
function _hasParent(element, parent) {
  while (element) {
    if (element === parent) {
      return true;
    }
    element = element.parentNode;
  }
  return false;
}

// utility functions
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
const ASPDateRegex = /^\/?Date\((-?\d+)/i;
// Color REs
const fullHexRE = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
const shortHexRE = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const rgbRE = /^rgb\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *\)$/i;
const rgbaRE = /^rgba\( *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *(1?\d{1,2}|2[0-4]\d|25[0-5]) *, *([01]|0?\.\d+) *\)$/i;
/**
 * Test whether given object is a number.
 * @param value - Input value of unknown type.
 * @returns True if number, false otherwise.
 */
function isNumber(value) {
    return value instanceof Number || typeof value === "number";
}
/**
 * Remove everything in the DOM object.
 * @param DOMobject - Node whose child nodes will be recursively deleted.
 */
function recursiveDOMDelete(DOMobject) {
    if (DOMobject) {
        while (DOMobject.hasChildNodes() === true) {
            const child = DOMobject.firstChild;
            if (child) {
                recursiveDOMDelete(child);
                DOMobject.removeChild(child);
            }
        }
    }
}
/**
 * Test whether given object is a string.
 * @param value - Input value of unknown type.
 * @returns True if string, false otherwise.
 */
function isString(value) {
    return value instanceof String || typeof value === "string";
}
/**
 * Test whether given object is a object (not primitive or null).
 * @param value - Input value of unknown type.
 * @returns True if not null object, false otherwise.
 */
function isObject(value) {
    return typeof value === "object" && value !== null;
}
/**
 * Test whether given object is a Date, or a String containing a Date.
 * @param value - Input value of unknown type.
 * @returns True if Date instance or string date representation, false otherwise.
 */
function isDate(value) {
    if (value instanceof Date) {
        return true;
    }
    else if (isString(value)) {
        // test whether this string contains a date
        const match = ASPDateRegex.exec(value);
        if (match) {
            return true;
        }
        else if (!isNaN(Date.parse(value))) {
            return true;
        }
    }
    return false;
}
/**
 * Copy property from b to a if property present in a.
 * If property in b explicitly set to null, delete it if `allowDeletion` set.
 *
 * Internal helper routine, should not be exported. Not added to `exports` for that reason.
 * @param a - Target object.
 * @param b - Source object.
 * @param prop - Name of property to copy from b to a.
 * @param allowDeletion - If true, delete property in a if explicitly set to null in b.
 */
function copyOrDelete(a, b, prop, allowDeletion) {
    let doDeletion = false;
    if (allowDeletion === true) {
        doDeletion = b[prop] === null && a[prop] !== undefined;
    }
    if (doDeletion) {
        delete a[prop];
    }
    else {
        a[prop] = b[prop]; // Remember, this is a reference copy!
    }
}
/**
 * Fill an object with a possibly partially defined other object.
 *
 * Only copies values for the properties already present in a.
 * That means an object is not created on a property if only the b object has it.
 * @param a - The object that will have it's properties updated.
 * @param b - The object with property updates.
 * @param allowDeletion - If true, delete properties in a that are explicitly set to null in b.
 */
function fillIfDefined(a, b, allowDeletion = false) {
    // NOTE: iteration of properties of a
    // NOTE: prototype properties iterated over as well
    for (const prop in a) {
        if (b[prop] !== undefined) {
            if (b[prop] === null || typeof b[prop] !== "object") {
                // Note: typeof null === 'object'
                copyOrDelete(a, b, prop, allowDeletion);
            }
            else {
                const aProp = a[prop];
                const bProp = b[prop];
                if (isObject(aProp) && isObject(bProp)) {
                    fillIfDefined(aProp, bProp, allowDeletion);
                }
            }
        }
    }
}
/**
 * Copy the values of all of the enumerable own properties from one or more source objects to a
 * target object. Returns the target object.
 * @param target - The target object to copy to.
 * @param source - The source object from which to copy properties.
 * @returns The target object.
 */
const extend = Object.assign;
/**
 * Extend object a with selected properties of object b or a series of objects.
 * @remarks
 * Only properties with defined values are copied.
 * @param props - Properties to be copied to a.
 * @param a - The target.
 * @param others - The sources.
 * @returns Argument a.
 */
function selectiveExtend(props, a, ...others) {
    if (!Array.isArray(props)) {
        throw new Error("Array with property names expected as first argument");
    }
    for (const other of others) {
        for (let p = 0; p < props.length; p++) {
            const prop = props[p];
            if (other && Object.prototype.hasOwnProperty.call(other, prop)) {
                a[prop] = other[prop];
            }
        }
    }
    return a;
}
/**
 * Extend object a with selected properties of object b.
 * Only properties with defined values are copied.
 * @remarks
 * Previous version of this routine implied that multiple source objects could
 * be used; however, the implementation was **wrong**. Since multiple (\>1)
 * sources weren't used anywhere in the `vis.js` code, this has been removed
 * @param props - Names of first-level properties to copy over.
 * @param a - Target object.
 * @param b - Source object.
 * @param allowDeletion - If true, delete property in a if explicitly set to null in b.
 * @returns Argument a.
 */
function selectiveDeepExtend(props, a, b, allowDeletion = false) {
    // TODO: add support for Arrays to deepExtend
    if (Array.isArray(b)) {
        throw new TypeError("Arrays are not supported by deepExtend");
    }
    for (let p = 0; p < props.length; p++) {
        const prop = props[p];
        if (Object.prototype.hasOwnProperty.call(b, prop)) {
            if (b[prop] && b[prop].constructor === Object) {
                if (a[prop] === undefined) {
                    a[prop] = {};
                }
                if (a[prop].constructor === Object) {
                    deepExtend(a[prop], b[prop], false, allowDeletion);
                }
                else {
                    copyOrDelete(a, b, prop, allowDeletion);
                }
            }
            else if (Array.isArray(b[prop])) {
                throw new TypeError("Arrays are not supported by deepExtend");
            }
            else {
                copyOrDelete(a, b, prop, allowDeletion);
            }
        }
    }
    return a;
}
/**
 * Extend object `a` with properties of object `b`, ignoring properties which
 * are explicitly specified to be excluded.
 * @remarks
 * The properties of `b` are considered for copying. Properties which are
 * themselves objects are are also extended. Only properties with defined
 * values are copied.
 * @param propsToExclude - Names of properties which should *not* be copied.
 * @param a - Object to extend.
 * @param b - Object to take properties from for extension.
 * @param allowDeletion - If true, delete properties in a that are explicitly
 * set to null in b.
 * @returns Argument a.
 */
function selectiveNotDeepExtend(propsToExclude, a, b, allowDeletion = false) {
    // TODO: add support for Arrays to deepExtend
    // NOTE: array properties have an else-below; apparently, there is a problem here.
    if (Array.isArray(b)) {
        throw new TypeError("Arrays are not supported by deepExtend");
    }
    for (const prop in b) {
        if (!Object.prototype.hasOwnProperty.call(b, prop)) {
            continue;
        } // Handle local properties only
        if (propsToExclude.includes(prop)) {
            continue;
        } // In exclusion list, skip
        if (b[prop] && b[prop].constructor === Object) {
            if (a[prop] === undefined) {
                a[prop] = {};
            }
            if (a[prop].constructor === Object) {
                deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
            }
            else {
                copyOrDelete(a, b, prop, allowDeletion);
            }
        }
        else if (Array.isArray(b[prop])) {
            a[prop] = [];
            for (let i = 0; i < b[prop].length; i++) {
                a[prop].push(b[prop][i]);
            }
        }
        else {
            copyOrDelete(a, b, prop, allowDeletion);
        }
    }
    return a;
}
/**
 * Deep extend an object a with the properties of object b.
 * @param a - Target object.
 * @param b - Source object.
 * @param protoExtend - If true, the prototype values will also be extended.
 * (That is the options objects that inherit from others will also get the
 * inherited options).
 * @param allowDeletion - If true, the values of fields that are null will be deleted.
 * @returns Argument a.
 */
function deepExtend(a, b, protoExtend = false, allowDeletion = false) {
    for (const prop in b) {
        if (Object.prototype.hasOwnProperty.call(b, prop) || protoExtend === true) {
            if (typeof b[prop] === "object" &&
                b[prop] !== null &&
                Object.getPrototypeOf(b[prop]) === Object.prototype) {
                if (a[prop] === undefined) {
                    a[prop] = deepExtend({}, b[prop], protoExtend); // NOTE: allowDeletion not propagated!
                }
                else if (typeof a[prop] === "object" &&
                    a[prop] !== null &&
                    Object.getPrototypeOf(a[prop]) === Object.prototype) {
                    deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
                }
                else {
                    copyOrDelete(a, b, prop, allowDeletion);
                }
            }
            else if (Array.isArray(b[prop])) {
                a[prop] = b[prop].slice();
            }
            else {
                copyOrDelete(a, b, prop, allowDeletion);
            }
        }
    }
    return a;
}
/**
 * Test whether all elements in two arrays are equal.
 * @param a - First array.
 * @param b - Second array.
 * @returns True if both arrays have the same length and same elements (1 = '1').
 */
function equalArray(a, b) {
    if (a.length !== b.length) {
        return false;
    }
    for (let i = 0, len = a.length; i < len; i++) {
        if (a[i] != b[i]) {
            return false;
        }
    }
    return true;
}
/**
 * Get the type of an object, for example exports.getType([]) returns 'Array'.
 * @param object - Input value of unknown type.
 * @returns Detected type.
 */
function getType(object) {
    const type = typeof object;
    if (type === "object") {
        if (object === null) {
            return "null";
        }
        if (object instanceof Boolean) {
            return "Boolean";
        }
        if (object instanceof Number) {
            return "Number";
        }
        if (object instanceof String) {
            return "String";
        }
        if (Array.isArray(object)) {
            return "Array";
        }
        if (object instanceof Date) {
            return "Date";
        }
        return "Object";
    }
    if (type === "number") {
        return "Number";
    }
    if (type === "boolean") {
        return "Boolean";
    }
    if (type === "string") {
        return "String";
    }
    if (type === undefined) {
        return "undefined";
    }
    return type;
}
/**
 * Used to extend an array and copy it. This is used to propagate paths recursively.
 * @param arr - First part.
 * @param newValue - The value to be aadded into the array.
 * @returns A new array with all items from arr and newValue (which is last).
 */
function copyAndExtendArray(arr, newValue) {
    return [...arr, newValue];
}
/**
 * Used to extend an array and copy it. This is used to propagate paths recursively.
 * @param arr - The array to be copied.
 * @returns Shallow copy of arr.
 */
function copyArray(arr) {
    return arr.slice();
}
/**
 * Retrieve the absolute left value of a DOM element.
 * @param elem - A dom element, for example a div.
 * @returns The absolute left position of this element in the browser page.
 */
function getAbsoluteLeft(elem) {
    return elem.getBoundingClientRect().left;
}
/**
 * Retrieve the absolute right value of a DOM element.
 * @param elem - A dom element, for example a div.
 * @returns The absolute right position of this element in the browser page.
 */
function getAbsoluteRight(elem) {
    return elem.getBoundingClientRect().right;
}
/**
 * Retrieve the absolute top value of a DOM element.
 * @param elem - A dom element, for example a div.
 * @returns The absolute top position of this element in the browser page.
 */
function getAbsoluteTop(elem) {
    return elem.getBoundingClientRect().top;
}
/**
 * Add a className to the given elements style.
 * @param elem - The element to which the classes will be added.
 * @param classNames - Space separated list of classes.
 */
function addClassName(elem, classNames) {
    let classes = elem.className.split(" ");
    const newClasses = classNames.split(" ");
    classes = classes.concat(newClasses.filter(function (className) {
        return !classes.includes(className);
    }));
    elem.className = classes.join(" ");
}
/**
 * Remove a className from the given elements style.
 * @param elem - The element from which the classes will be removed.
 * @param classNames - Space separated list of classes.
 */
function removeClassName(elem, classNames) {
    let classes = elem.className.split(" ");
    const oldClasses = classNames.split(" ");
    classes = classes.filter(function (className) {
        return !oldClasses.includes(className);
    });
    elem.className = classes.join(" ");
}
/**
 * For each method for both arrays and objects.
 * In case of an array, the built-in Array.forEach() is applied (**No, it's not!**).
 * In case of an Object, the method loops over all properties of the object.
 * @param object - An Object or Array to be iterated over.
 * @param callback - Array.forEach-like callback.
 */
function forEach(object, callback) {
    if (Array.isArray(object)) {
        // array
        const len = object.length;
        for (let i = 0; i < len; i++) {
            callback(object[i], i, object);
        }
    }
    else {
        // object
        for (const key in object) {
            if (Object.prototype.hasOwnProperty.call(object, key)) {
                callback(object[key], key, object);
            }
        }
    }
}
/**
 * Convert an object into an array: all objects properties are put into the array. The resulting array is unordered.
 * @param o - Object that contains the properties and methods.
 * @returns An array of unordered values.
 */
const toArray = Object.values;
/**
 * Update a property in an object.
 * @param object - The object whose property will be updated.
 * @param key - Name of the property to be updated.
 * @param value - The new value to be assigned.
 * @returns Whether the value was updated (true) or already strictly the same in the original object (false).
 */
function updateProperty(object, key, value) {
    if (object[key] !== value) {
        object[key] = value;
        return true;
    }
    else {
        return false;
    }
}
/**
 * Throttle the given function to be only executed once per animation frame.
 * @param fn - The original function.
 * @returns The throttled function.
 */
function throttle(fn) {
    let scheduled = false;
    return () => {
        if (!scheduled) {
            scheduled = true;
            requestAnimationFrame(() => {
                scheduled = false;
                fn();
            });
        }
    };
}
/**
 * Cancels the event's default action if it is cancelable, without stopping further propagation of the event.
 * @param event - The event whose default action should be prevented.
 */
function preventDefault(event) {
    if (!event) {
        event = window.event;
    }
    if (!event) ;
    else if (event.preventDefault) {
        event.preventDefault(); // non-IE browsers
    }
    else {
        // @TODO: IE types? Does anyone care?
        event.returnValue = false; // IE browsers
    }
}
/**
 * Get HTML element which is the target of the event.
 * @param event - The event.
 * @returns The element or null if not obtainable.
 */
function getTarget(event = window.event) {
    // code from http://www.quirksmode.org/js/events_properties.html
    // @TODO: EventTarget can be almost anything, is it okay to return only Elements?
    let target = null;
    if (!event) ;
    else if (event.target) {
        target = event.target;
    }
    else if (event.srcElement) {
        target = event.srcElement;
    }
    if (!(target instanceof Element)) {
        return null;
    }
    if (target.nodeType != null && target.nodeType == 3) {
        // defeat Safari bug
        target = target.parentNode;
        if (!(target instanceof Element)) {
            return null;
        }
    }
    return target;
}
/**
 * Check if given element contains given parent somewhere in the DOM tree.
 * @param element - The element to be tested.
 * @param parent - The ancestor (not necessarily parent) of the element.
 * @returns True if parent is an ancestor of the element, false otherwise.
 */
function hasParent(element, parent) {
    let elem = element;
    while (elem) {
        if (elem === parent) {
            return true;
        }
        else if (elem.parentNode) {
            elem = elem.parentNode;
        }
        else {
            return false;
        }
    }
    return false;
}
const option = {
    /**
     * Convert a value into a boolean.
     * @param value - Value to be converted intoboolean, a function will be executed as `(() => unknown)`.
     * @param defaultValue - If the value or the return value of the function == null then this will be returned.
     * @returns Corresponding boolean value, if none then the default value, if none then null.
     */
    asBoolean(value, defaultValue) {
        if (typeof value == "function") {
            value = value();
        }
        if (value != null) {
            return value != false;
        }
        return defaultValue || null;
    },
    /**
     * Convert a value into a number.
     * @param value - Value to be converted intonumber, a function will be executed as `(() => unknown)`.
     * @param defaultValue - If the value or the return value of the function == null then this will be returned.
     * @returns Corresponding **boxed** number value, if none then the default value, if none then null.
     */
    asNumber(value, defaultValue) {
        if (typeof value == "function") {
            value = value();
        }
        if (value != null) {
            return Number(value) || defaultValue || null;
        }
        return defaultValue || null;
    },
    /**
     * Convert a value into a string.
     * @param value - Value to be converted intostring, a function will be executed as `(() => unknown)`.
     * @param defaultValue - If the value or the return value of the function == null then this will be returned.
     * @returns Corresponding **boxed** string value, if none then the default value, if none then null.
     */
    asString(value, defaultValue) {
        if (typeof value == "function") {
            value = value();
        }
        if (value != null) {
            return String(value);
        }
        return defaultValue || null;
    },
    /**
     * Convert a value into a size.
     * @param value - Value to be converted intosize, a function will be executed as `(() => unknown)`.
     * @param defaultValue - If the value or the return value of the function == null then this will be returned.
     * @returns Corresponding string value (number + 'px'), if none then the default value, if none then null.
     */
    asSize(value, defaultValue) {
        if (typeof value == "function") {
            value = value();
        }
        if (isString(value)) {
            return value;
        }
        else if (isNumber(value)) {
            return value + "px";
        }
        else {
            return defaultValue || null;
        }
    },
    /**
     * Convert a value into a DOM Element.
     * @param value - Value to be converted into DOM Element, a function will be executed as `(() => unknown)`.
     * @param defaultValue - If the value or the return value of the function == null then this will be returned.
     * @returns The DOM Element, if none then the default value, if none then null.
     */
    asElement(value, defaultValue) {
        if (typeof value == "function") {
            value = value();
        }
        return value || defaultValue || null;
    },
};
/**
 * Convert hex color string into RGB color object.
 * @remarks
 * {@link http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb}
 * @param hex - Hex color string (3 or 6 digits, with or without #).
 * @returns RGB color object.
 */
function hexToRGB(hex) {
    let result;
    switch (hex.length) {
        case 3:
        case 4:
            result = shortHexRE.exec(hex);
            return result
                ? {
                    r: parseInt(result[1] + result[1], 16),
                    g: parseInt(result[2] + result[2], 16),
                    b: parseInt(result[3] + result[3], 16),
                }
                : null;
        case 6:
        case 7:
            result = fullHexRE.exec(hex);
            return result
                ? {
                    r: parseInt(result[1], 16),
                    g: parseInt(result[2], 16),
                    b: parseInt(result[3], 16),
                }
                : null;
        default:
            return null;
    }
}
/**
 * This function takes string color in hex or RGB format and adds the opacity, RGBA is passed through unchanged.
 * @param color - The color string (hex, RGB, RGBA).
 * @param opacity - The new opacity.
 * @returns RGBA string, for example 'rgba(255, 0, 127, 0.3)'.
 */
function overrideOpacity(color, opacity) {
    if (color.includes("rgba")) {
        return color;
    }
    else if (color.includes("rgb")) {
        const rgb = color
            .substr(color.indexOf("(") + 1)
            .replace(")", "")
            .split(",");
        return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
    }
    else {
        const rgb = hexToRGB(color);
        if (rgb == null) {
            return color;
        }
        else {
            return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
        }
    }
}
/**
 * Convert RGB \<0, 255\> into hex color string.
 * @param red - Red channel.
 * @param green - Green channel.
 * @param blue - Blue channel.
 * @returns Hex color string (for example: '#0acdc0').
 */
function RGBToHex(red, green, blue) {
    return ("#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1));
}
/**
 * Parse a color property into an object with border, background, and highlight colors.
 * @param inputColor - Shorthand color string or input color object.
 * @param defaultColor - Full color object to fill in missing values in inputColor.
 * @returns Color object.
 */
function parseColor(inputColor, defaultColor) {
    if (isString(inputColor)) {
        let colorStr = inputColor;
        if (isValidRGB(colorStr)) {
            const rgb = colorStr
                .substr(4)
                .substr(0, colorStr.length - 5)
                .split(",")
                .map(function (value) {
                return parseInt(value);
            });
            colorStr = RGBToHex(rgb[0], rgb[1], rgb[2]);
        }
        if (isValidHex(colorStr) === true) {
            const hsv = hexToHSV(colorStr);
            const lighterColorHSV = {
                h: hsv.h,
                s: hsv.s * 0.8,
                v: Math.min(1, hsv.v * 1.02),
            };
            const darkerColorHSV = {
                h: hsv.h,
                s: Math.min(1, hsv.s * 1.25),
                v: hsv.v * 0.8,
            };
            const darkerColorHex = HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
            const lighterColorHex = HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
            return {
                background: colorStr,
                border: darkerColorHex,
                highlight: {
                    background: lighterColorHex,
                    border: darkerColorHex,
                },
                hover: {
                    background: lighterColorHex,
                    border: darkerColorHex,
                },
            };
        }
        else {
            return {
                background: colorStr,
                border: colorStr,
                highlight: {
                    background: colorStr,
                    border: colorStr,
                },
                hover: {
                    background: colorStr,
                    border: colorStr,
                },
            };
        }
    }
    else {
        if (defaultColor) {
            const color = {
                background: inputColor.background || defaultColor.background,
                border: inputColor.border || defaultColor.border,
                highlight: isString(inputColor.highlight)
                    ? {
                        border: inputColor.highlight,
                        background: inputColor.highlight,
                    }
                    : {
                        background: (inputColor.highlight && inputColor.highlight.background) ||
                            defaultColor.highlight.background,
                        border: (inputColor.highlight && inputColor.highlight.border) ||
                            defaultColor.highlight.border,
                    },
                hover: isString(inputColor.hover)
                    ? {
                        border: inputColor.hover,
                        background: inputColor.hover,
                    }
                    : {
                        border: (inputColor.hover && inputColor.hover.border) ||
                            defaultColor.hover.border,
                        background: (inputColor.hover && inputColor.hover.background) ||
                            defaultColor.hover.background,
                    },
            };
            return color;
        }
        else {
            const color = {
                background: inputColor.background || undefined,
                border: inputColor.border || undefined,
                highlight: isString(inputColor.highlight)
                    ? {
                        border: inputColor.highlight,
                        background: inputColor.highlight,
                    }
                    : {
                        background: (inputColor.highlight && inputColor.highlight.background) ||
                            undefined,
                        border: (inputColor.highlight && inputColor.highlight.border) ||
                            undefined,
                    },
                hover: isString(inputColor.hover)
                    ? {
                        border: inputColor.hover,
                        background: inputColor.hover,
                    }
                    : {
                        border: (inputColor.hover && inputColor.hover.border) || undefined,
                        background: (inputColor.hover && inputColor.hover.background) || undefined,
                    },
            };
            return color;
        }
    }
}
/**
 * Convert RGB \<0, 255\> into HSV object.
 * @remarks
 * {@link http://www.javascripter.net/faq/rgb2hsv.htm}
 * @param red - Red channel.
 * @param green - Green channel.
 * @param blue - Blue channel.
 * @returns HSV color object.
 */
function RGBToHSV(red, green, blue) {
    red = red / 255;
    green = green / 255;
    blue = blue / 255;
    const minRGB = Math.min(red, Math.min(green, blue));
    const maxRGB = Math.max(red, Math.max(green, blue));
    // Black-gray-white
    if (minRGB === maxRGB) {
        return { h: 0, s: 0, v: minRGB };
    }
    // Colors other than black-gray-white:
    const d = red === minRGB ? green - blue : blue === minRGB ? red - green : blue - red;
    const h = red === minRGB ? 3 : blue === minRGB ? 1 : 5;
    const hue = (60 * (h - d / (maxRGB - minRGB))) / 360;
    const saturation = (maxRGB - minRGB) / maxRGB;
    const value = maxRGB;
    return { h: hue, s: saturation, v: value };
}
/**
 * Split a string with css styles into an object with key/values.
 * @param cssText - CSS source code to split into key/value object.
 * @returns Key/value object corresponding to {@link cssText}.
 */
function splitCSSText(cssText) {
    const tmpEllement = document.createElement("div");
    const styles = {};
    tmpEllement.style.cssText = cssText;
    for (let i = 0; i < tmpEllement.style.length; ++i) {
        styles[tmpEllement.style[i]] = tmpEllement.style.getPropertyValue(tmpEllement.style[i]);
    }
    return styles;
}
/**
 * Append a string with css styles to an element.
 * @param element - The element that will receive new styles.
 * @param cssText - The styles to be appended.
 */
function addCssText(element, cssText) {
    const cssStyle = splitCSSText(cssText);
    for (const [key, value] of Object.entries(cssStyle)) {
        element.style.setProperty(key, value);
    }
}
/**
 * Remove a string with css styles from an element.
 * @param element - The element from which styles should be removed.
 * @param cssText - The styles to be removed.
 */
function removeCssText(element, cssText) {
    const cssStyle = splitCSSText(cssText);
    for (const key of Object.keys(cssStyle)) {
        element.style.removeProperty(key);
    }
}
/**
 * Convert HSV \<0, 1\> into RGB color object.
 * @remarks
 * {@link https://gist.github.com/mjijackson/5311256}
 * @param h - Hue.
 * @param s - Saturation.
 * @param v - Value.
 * @returns RGB color object.
 */
function HSVToRGB(h, s, v) {
    let r;
    let g;
    let b;
    const i = Math.floor(h * 6);
    const f = h * 6 - i;
    const p = v * (1 - s);
    const q = v * (1 - f * s);
    const t = v * (1 - (1 - f) * s);
    switch (i % 6) {
        case 0:
            ((r = v), (g = t), (b = p));
            break;
        case 1:
            ((r = q), (g = v), (b = p));
            break;
        case 2:
            ((r = p), (g = v), (b = t));
            break;
        case 3:
            ((r = p), (g = q), (b = v));
            break;
        case 4:
            ((r = t), (g = p), (b = v));
            break;
        case 5:
            ((r = v), (g = p), (b = q));
            break;
    }
    return {
        r: Math.floor(r * 255),
        g: Math.floor(g * 255),
        b: Math.floor(b * 255),
    };
}
/**
 * Convert HSV \<0, 1\> into hex color string.
 * @param h - Hue.
 * @param s - Saturation.
 * @param v - Value.
 * @returns Hex color string.
 */
function HSVToHex(h, s, v) {
    const rgb = HSVToRGB(h, s, v);
    return RGBToHex(rgb.r, rgb.g, rgb.b);
}
/**
 * Convert hex color string into HSV \<0, 1\>.
 * @param hex - Hex color string.
 * @returns HSV color object.
 */
function hexToHSV(hex) {
    const rgb = hexToRGB(hex);
    if (!rgb) {
        throw new TypeError(`'${hex}' is not a valid color.`);
    }
    return RGBToHSV(rgb.r, rgb.g, rgb.b);
}
/**
 * Validate hex color string.
 * @param hex - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */
function isValidHex(hex) {
    const isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
    return isOk;
}
/**
 * Validate RGB color string.
 * @param rgb - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */
function isValidRGB(rgb) {
    return rgbRE.test(rgb);
}
/**
 * Validate RGBA color string.
 * @param rgba - Unknown string that may contain a color.
 * @returns True if the string is valid, false otherwise.
 */
function isValidRGBA(rgba) {
    return rgbaRE.test(rgba);
}
/**
 * This recursively redirects the prototype of JSON objects to the referenceObject.
 * This is used for default options.
 * @param fields - Names of properties to be bridged.
 * @param referenceObject - The original object.
 * @returns A new object inheriting from the referenceObject.
 */
function selectiveBridgeObject(fields, referenceObject) {
    if (referenceObject !== null && typeof referenceObject === "object") {
        // !!! typeof null === 'object'
        const objectTo = Object.create(referenceObject);
        for (let i = 0; i < fields.length; i++) {
            if (Object.prototype.hasOwnProperty.call(referenceObject, fields[i])) {
                if (typeof referenceObject[fields[i]] == "object") {
                    objectTo[fields[i]] = bridgeObject(referenceObject[fields[i]]);
                }
            }
        }
        return objectTo;
    }
    else {
        return null;
    }
}
/**
 * This recursively redirects the prototype of JSON objects to the referenceObject.
 * This is used for default options.
 * @param referenceObject - The original object.
 * @returns The Element if the referenceObject is an Element, or a new object inheriting from the referenceObject.
 */
function bridgeObject(referenceObject) {
    if (referenceObject === null || typeof referenceObject !== "object") {
        return null;
    }
    if (referenceObject instanceof Element) {
        // Avoid bridging DOM objects
        return referenceObject;
    }
    const objectTo = Object.create(referenceObject);
    for (const i in referenceObject) {
        if (Object.prototype.hasOwnProperty.call(referenceObject, i)) {
            if (typeof referenceObject[i] == "object") {
                objectTo[i] = bridgeObject(referenceObject[i]);
            }
        }
    }
    return objectTo;
}
/**
 * This method provides a stable sort implementation, very fast for presorted data.
 * @param a - The array to be sorted (in-place).
 * @param compare - An order comparator.
 * @returns The argument a.
 */
function insertSort(a, compare) {
    for (let i = 0; i < a.length; i++) {
        const k = a[i];
        let j;
        for (j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
            a[j] = a[j - 1];
        }
        a[j] = k;
    }
    return a;
}
/**
 * This is used to set the options of subobjects in the options object.
 *
 * A requirement of these subobjects is that they have an 'enabled' element
 * which is optional for the user but mandatory for the program.
 *
 * The added value here of the merge is that option 'enabled' is set as required.
 * @param mergeTarget - Either this.options or the options used for the groups.
 * @param options - Options.
 * @param option - Option key in the options argument.
 * @param globalOptions - Global options, passed in to determine value of option 'enabled'.
 */
function mergeOptions(mergeTarget, options, option, globalOptions = {}) {
    // Local helpers
    const isPresent = function (obj) {
        return obj !== null && obj !== undefined;
    };
    const isObject = function (obj) {
        return obj !== null && typeof obj === "object";
    };
    // https://stackoverflow.com/a/34491287/1223531
    const isEmpty = function (obj) {
        for (const x in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, x)) {
                return false;
            }
        }
        return true;
    };
    // Guards
    if (!isObject(mergeTarget)) {
        throw new Error("Parameter mergeTarget must be an object");
    }
    if (!isObject(options)) {
        throw new Error("Parameter options must be an object");
    }
    if (!isPresent(option)) {
        throw new Error("Parameter option must have a value");
    }
    if (!isObject(globalOptions)) {
        throw new Error("Parameter globalOptions must be an object");
    }
    //
    // Actual merge routine, separated from main logic
    // Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
    //
    const doMerge = function (target, options, option) {
        if (!isObject(target[option])) {
            target[option] = {};
        }
        const src = options[option];
        const dst = target[option];
        for (const prop in src) {
            if (Object.prototype.hasOwnProperty.call(src, prop)) {
                dst[prop] = src[prop];
            }
        }
    };
    // Local initialization
    const srcOption = options[option];
    const globalPassed = isObject(globalOptions) && !isEmpty(globalOptions);
    const globalOption = globalPassed ? globalOptions[option] : undefined;
    const globalEnabled = globalOption ? globalOption.enabled : undefined;
    /////////////////////////////////////////
    // Main routine
    /////////////////////////////////////////
    if (srcOption === undefined) {
        return; // Nothing to do
    }
    if (typeof srcOption === "boolean") {
        if (!isObject(mergeTarget[option])) {
            mergeTarget[option] = {};
        }
        mergeTarget[option].enabled = srcOption;
        return;
    }
    if (srcOption === null && !isObject(mergeTarget[option])) {
        // If possible, explicit copy from globals
        if (isPresent(globalOption)) {
            mergeTarget[option] = Object.create(globalOption);
        }
        else {
            return; // Nothing to do
        }
    }
    if (!isObject(srcOption)) {
        return;
    }
    //
    // Ensure that 'enabled' is properly set. It is required internally
    // Note that the value from options will always overwrite the existing value
    //
    let enabled = true; // default value
    if (srcOption.enabled !== undefined) {
        enabled = srcOption.enabled;
    }
    else {
        // Take from globals, if present
        if (globalEnabled !== undefined) {
            enabled = globalOption.enabled;
        }
    }
    doMerge(mergeTarget, options, option);
    mergeTarget[option].enabled = enabled;
}
/**
 * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
 * this function will then iterate in both directions over this sorted list to find all visible items.
 * @param orderedItems - Items ordered by start.
 * @param comparator - -1 is lower, 0 is equal, 1 is higher.
 * @param field - Property name on an item (That is item[field]).
 * @param field2 - Second property name on an item (That is item[field][field2]).
 * @returns Index of the found item or -1 if nothing was found.
 */
function binarySearchCustom(orderedItems, comparator, field, field2) {
    const maxIterations = 10000;
    let iteration = 0;
    let low = 0;
    let high = orderedItems.length - 1;
    while (low <= high && iteration < maxIterations) {
        const middle = Math.floor((low + high) / 2);
        const item = orderedItems[middle];
        const value = field2 === undefined ? item[field] : item[field][field2];
        const searchResult = comparator(value);
        if (searchResult == 0) {
            // jihaa, found a visible item!
            return middle;
        }
        else if (searchResult == -1) {
            // it is too small --> increase low
            low = middle + 1;
        }
        else {
            // it is too big --> decrease high
            high = middle - 1;
        }
        iteration++;
    }
    return -1;
}
/**
 * This function does a binary search for a specific value in a sorted array.
 * If it does not exist but is in between of two values, we return either the
 * one before or the one after, depending on user input If it is found, we
 * return the index, else -1.
 * @param orderedItems - Sorted array.
 * @param target - The searched value.
 * @param field - Name of the property in items to be searched.
 * @param sidePreference - If the target is between two values, should the index of the before or the after be returned?
 * @param comparator - An optional comparator, returning -1, 0, 1 for \<, ===, \>.
 * @returns The index of found value or -1 if nothing was found.
 */
function binarySearchValue(orderedItems, target, field, sidePreference, comparator) {
    const maxIterations = 10000;
    let iteration = 0;
    let low = 0;
    let high = orderedItems.length - 1;
    let prevValue;
    let value;
    let nextValue;
    let middle;
    comparator =
        comparator != undefined
            ? comparator
            : function (a, b) {
                return a == b ? 0 : a < b ? -1 : 1;
            };
    while (low <= high && iteration < maxIterations) {
        // get a new guess
        middle = Math.floor(0.5 * (high + low));
        prevValue = orderedItems[Math.max(0, middle - 1)][field];
        value = orderedItems[middle][field];
        nextValue =
            orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
        if (comparator(value, target) == 0) {
            // we found the target
            return middle;
        }
        else if (comparator(prevValue, target) < 0 &&
            comparator(value, target) > 0) {
            // target is in between of the previous and the current
            return sidePreference == "before" ? Math.max(0, middle - 1) : middle;
        }
        else if (comparator(value, target) < 0 &&
            comparator(nextValue, target) > 0) {
            // target is in between of the current and the next
            return sidePreference == "before"
                ? middle
                : Math.min(orderedItems.length - 1, middle + 1);
        }
        else {
            // didnt find the target, we need to change our boundaries.
            if (comparator(value, target) < 0) {
                // it is too small --> increase low
                low = middle + 1;
            }
            else {
                // it is too big --> decrease high
                high = middle - 1;
            }
        }
        iteration++;
    }
    // didnt find anything. Return -1.
    return -1;
}
/*
 * Easing Functions.
 * Only considering the t value for the range [0, 1] => [0, 1].
 *
 * Inspiration: from http://gizma.com/easing/
 * https://gist.github.com/gre/1650294
 */
const easingFunctions = {
    /**
     * Provides no easing and no acceleration.
     * @param t - Time.
     * @returns Value at time t.
     */
    linear(t) {
        return t;
    },
    /**
     * Accelerate from zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInQuad(t) {
        return t * t;
    },
    /**
     * Decelerate to zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeOutQuad(t) {
        return t * (2 - t);
    },
    /**
     * Accelerate until halfway, then decelerate.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInOutQuad(t) {
        return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    },
    /**
     * Accelerate from zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInCubic(t) {
        return t * t * t;
    },
    /**
     * Decelerate to zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeOutCubic(t) {
        return --t * t * t + 1;
    },
    /**
     * Accelerate until halfway, then decelerate.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInOutCubic(t) {
        return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
    },
    /**
     * Accelerate from zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInQuart(t) {
        return t * t * t * t;
    },
    /**
     * Decelerate to zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeOutQuart(t) {
        return 1 - --t * t * t * t;
    },
    /**
     * Accelerate until halfway, then decelerate.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInOutQuart(t) {
        return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
    },
    /**
     * Accelerate from zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInQuint(t) {
        return t * t * t * t * t;
    },
    /**
     * Decelerate to zero velocity.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeOutQuint(t) {
        return 1 + --t * t * t * t * t;
    },
    /**
     * Accelerate until halfway, then decelerate.
     * @param t - Time.
     * @returns Value at time t.
     */
    easeInOutQuint(t) {
        return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
    },
};
/**
 * Experimentaly compute the width of the scrollbar for this browser.
 * @returns The width in pixels.
 */
function getScrollBarWidth() {
    const inner = document.createElement("p");
    inner.style.width = "100%";
    inner.style.height = "200px";
    const outer = document.createElement("div");
    outer.style.position = "absolute";
    outer.style.top = "0px";
    outer.style.left = "0px";
    outer.style.visibility = "hidden";
    outer.style.width = "200px";
    outer.style.height = "150px";
    outer.style.overflow = "hidden";
    outer.appendChild(inner);
    document.body.appendChild(outer);
    const w1 = inner.offsetWidth;
    outer.style.overflow = "scroll";
    let w2 = inner.offsetWidth;
    if (w1 == w2) {
        w2 = outer.clientWidth;
    }
    document.body.removeChild(outer);
    return w1 - w2;
}
// @TODO: This doesn't work properly.
// It works only for single property objects,
// otherwise it combines all of the types in a union.
// export function topMost<K1 extends string, V1> (
//   pile: Record<K1, undefined | V1>[],
//   accessors: K1 | [K1]
// ): undefined | V1
// export function topMost<K1 extends string, K2 extends string, V1, V2> (
//   pile: Record<K1, undefined | V1 | Record<K2, undefined | V2>>[],
//   accessors: [K1, K2]
// ): undefined | V1 | V2
// export function topMost<K1 extends string, K2 extends string, K3 extends string, V1, V2, V3> (
//   pile: Record<K1, undefined | V1 | Record<K2, undefined | V2 | Record<K3, undefined | V3>>>[],
//   accessors: [K1, K2, K3]
// ): undefined | V1 | V2 | V3
/**
 * Get the top most property value from a pile of objects.
 * @param pile - Array of objects, no required format.
 * @param accessors - Array of property names.
 * For example `object['foo']['bar']` → `['foo', 'bar']`.
 * @returns Value of the property with given accessors path from the first pile item where it's not undefined.
 */
function topMost(pile, accessors) {
    let candidate;
    if (!Array.isArray(accessors)) {
        accessors = [accessors];
    }
    for (const member of pile) {
        if (member) {
            candidate = member[accessors[0]];
            for (let i = 1; i < accessors.length; i++) {
                if (candidate) {
                    candidate = candidate[accessors[i]];
                }
            }
            if (typeof candidate !== "undefined") {
                break;
            }
        }
    }
    return candidate;
}

const htmlColors = {
  black: "#000000",
  navy: "#000080",
  darkblue: "#00008B",
  mediumblue: "#0000CD",
  blue: "#0000FF",
  darkgreen: "#006400",
  green: "#008000",
  teal: "#008080",
  darkcyan: "#008B8B",
  deepskyblue: "#00BFFF",
  darkturquoise: "#00CED1",
  mediumspringgreen: "#00FA9A",
  lime: "#00FF00",
  springgreen: "#00FF7F",
  aqua: "#00FFFF",
  cyan: "#00FFFF",
  midnightblue: "#191970",
  dodgerblue: "#1E90FF",
  lightseagreen: "#20B2AA",
  forestgreen: "#228B22",
  seagreen: "#2E8B57",
  darkslategray: "#2F4F4F",
  limegreen: "#32CD32",
  mediumseagreen: "#3CB371",
  turquoise: "#40E0D0",
  royalblue: "#4169E1",
  steelblue: "#4682B4",
  darkslateblue: "#483D8B",
  mediumturquoise: "#48D1CC",
  indigo: "#4B0082",
  darkolivegreen: "#556B2F",
  cadetblue: "#5F9EA0",
  cornflowerblue: "#6495ED",
  mediumaquamarine: "#66CDAA",
  dimgray: "#696969",
  slateblue: "#6A5ACD",
  olivedrab: "#6B8E23",
  slategray: "#708090",
  lightslategray: "#778899",
  mediumslateblue: "#7B68EE",
  lawngreen: "#7CFC00",
  chartreuse: "#7FFF00",
  aquamarine: "#7FFFD4",
  maroon: "#800000",
  purple: "#800080",
  olive: "#808000",
  gray: "#808080",
  skyblue: "#87CEEB",
  lightskyblue: "#87CEFA",
  blueviolet: "#8A2BE2",
  darkred: "#8B0000",
  darkmagenta: "#8B008B",
  saddlebrown: "#8B4513",
  darkseagreen: "#8FBC8F",
  lightgreen: "#90EE90",
  mediumpurple: "#9370D8",
  darkviolet: "#9400D3",
  palegreen: "#98FB98",
  darkorchid: "#9932CC",
  yellowgreen: "#9ACD32",
  sienna: "#A0522D",
  brown: "#A52A2A",
  darkgray: "#A9A9A9",
  lightblue: "#ADD8E6",
  greenyellow: "#ADFF2F",
  paleturquoise: "#AFEEEE",
  lightsteelblue: "#B0C4DE",
  powderblue: "#B0E0E6",
  firebrick: "#B22222",
  darkgoldenrod: "#B8860B",
  mediumorchid: "#BA55D3",
  rosybrown: "#BC8F8F",
  darkkhaki: "#BDB76B",
  silver: "#C0C0C0",
  mediumvioletred: "#C71585",
  indianred: "#CD5C5C",
  peru: "#CD853F",
  chocolate: "#D2691E",
  tan: "#D2B48C",
  lightgrey: "#D3D3D3",
  palevioletred: "#D87093",
  thistle: "#D8BFD8",
  orchid: "#DA70D6",
  goldenrod: "#DAA520",
  crimson: "#DC143C",
  gainsboro: "#DCDCDC",
  plum: "#DDA0DD",
  burlywood: "#DEB887",
  lightcyan: "#E0FFFF",
  lavender: "#E6E6FA",
  darksalmon: "#E9967A",
  violet: "#EE82EE",
  palegoldenrod: "#EEE8AA",
  lightcoral: "#F08080",
  khaki: "#F0E68C",
  aliceblue: "#F0F8FF",
  honeydew: "#F0FFF0",
  azure: "#F0FFFF",
  sandybrown: "#F4A460",
  wheat: "#F5DEB3",
  beige: "#F5F5DC",
  whitesmoke: "#F5F5F5",
  mintcream: "#F5FFFA",
  ghostwhite: "#F8F8FF",
  salmon: "#FA8072",
  antiquewhite: "#FAEBD7",
  linen: "#FAF0E6",
  lightgoldenrodyellow: "#FAFAD2",
  oldlace: "#FDF5E6",
  red: "#FF0000",
  fuchsia: "#FF00FF",
  magenta: "#FF00FF",
  deeppink: "#FF1493",
  orangered: "#FF4500",
  tomato: "#FF6347",
  hotpink: "#FF69B4",
  coral: "#FF7F50",
  darkorange: "#FF8C00",
  lightsalmon: "#FFA07A",
  orange: "#FFA500",
  lightpink: "#FFB6C1",
  pink: "#FFC0CB",
  gold: "#FFD700",
  peachpuff: "#FFDAB9",
  navajowhite: "#FFDEAD",
  moccasin: "#FFE4B5",
  bisque: "#FFE4C4",
  mistyrose: "#FFE4E1",
  blanchedalmond: "#FFEBCD",
  papayawhip: "#FFEFD5",
  lavenderblush: "#FFF0F5",
  seashell: "#FFF5EE",
  cornsilk: "#FFF8DC",
  lemonchiffon: "#FFFACD",
  floralwhite: "#FFFAF0",
  snow: "#FFFAFA",
  yellow: "#FFFF00",
  lightyellow: "#FFFFE0",
  ivory: "#FFFFF0",
  white: "#FFFFFF",
};

/**
 * @param {number} [pixelRatio=1]
 */
let ColorPicker$1 = class ColorPicker {
  /**
   * @param {number} [pixelRatio]
   */
  constructor(pixelRatio = 1) {
    this.pixelRatio = pixelRatio;
    this.generated = false;
    this.centerCoordinates = { x: 289 / 2, y: 289 / 2 };
    this.r = 289 * 0.49;
    this.color = { r: 255, g: 255, b: 255, a: 1.0 };
    this.hueCircle = undefined;
    this.initialColor = { r: 255, g: 255, b: 255, a: 1.0 };
    this.previousColor = undefined;
    this.applied = false;

    // bound by
    this.updateCallback = () => {};
    this.closeCallback = () => {};

    // create all DOM elements
    this._create();
  }

  /**
   * this inserts the colorPicker into a div from the DOM
   * @param {Element} container
   */
  insertTo(container) {
    if (this.hammer !== undefined) {
      this.hammer.destroy();
      this.hammer = undefined;
    }
    this.container = container;
    this.container.appendChild(this.frame);
    this._bindHammer();

    this._setSize();
  }

  /**
   * the callback is executed on apply and save. Bind it to the application
   * @param {Function} callback
   */
  setUpdateCallback(callback) {
    if (typeof callback === "function") {
      this.updateCallback = callback;
    } else {
      throw new Error(
        "Function attempted to set as colorPicker update callback is not a function.",
      );
    }
  }

  /**
   * the callback is executed on apply and save. Bind it to the application
   * @param {Function} callback
   */
  setCloseCallback(callback) {
    if (typeof callback === "function") {
      this.closeCallback = callback;
    } else {
      throw new Error(
        "Function attempted to set as colorPicker closing callback is not a function.",
      );
    }
  }

  /**
   *
   * @param {string} color
   * @returns {string}
   * @private
   */
  _isColorString(color) {
    if (typeof color === "string") {
      return htmlColors[color];
    }
  }

  /**
   * Set the color of the colorPicker
   * Supported formats:
   * 'red'                   --> HTML color string
   * '#ffffff'               --> hex string
   * 'rgb(255,255,255)'      --> rgb string
   * 'rgba(255,255,255,1.0)' --> rgba string
   * {r:255,g:255,b:255}     --> rgb object
   * {r:255,g:255,b:255,a:1.0} --> rgba object
   * @param {string | object} color
   * @param {boolean} [setInitial]
   */
  setColor(color, setInitial = true) {
    if (color === "none") {
      return;
    }

    let rgba;

    // if a html color shorthand is used, convert to hex
    const htmlColor = this._isColorString(color);
    if (htmlColor !== undefined) {
      color = htmlColor;
    }

    // check format
    if (isString(color) === true) {
      if (isValidRGB(color) === true) {
        const rgbaArray = color
          .substr(4)
          .substr(0, color.length - 5)
          .split(",");
        rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1.0 };
      } else if (isValidRGBA(color) === true) {
        const rgbaArray = color
          .substr(5)
          .substr(0, color.length - 6)
          .split(",");
        rgba = {
          r: rgbaArray[0],
          g: rgbaArray[1],
          b: rgbaArray[2],
          a: rgbaArray[3],
        };
      } else if (isValidHex(color) === true) {
        const rgbObj = hexToRGB(color);
        rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1.0 };
      }
    } else {
      if (color instanceof Object) {
        if (
          color.r !== undefined &&
          color.g !== undefined &&
          color.b !== undefined
        ) {
          const alpha = color.a !== undefined ? color.a : "1.0";
          rgba = { r: color.r, g: color.g, b: color.b, a: alpha };
        }
      }
    }

    // set color
    if (rgba === undefined) {
      throw new Error(
        "Unknown color passed to the colorPicker. Supported are strings: rgb, hex, rgba. Object: rgb ({r:r,g:g,b:b,[a:a]}). Supplied: " +
          JSON.stringify(color),
      );
    } else {
      this._setColor(rgba, setInitial);
    }
  }

  /**
   * this shows the color picker.
   * The hue circle is constructed once and stored.
   */
  show() {
    if (this.closeCallback !== undefined) {
      this.closeCallback();
      this.closeCallback = undefined;
    }

    this.applied = false;
    this.frame.style.display = "block";
    this._generateHueCircle();
  }

  // ------------------------------------------ PRIVATE ----------------------------- //

  /**
   * Hide the picker. Is called by the cancel button.
   * Optional boolean to store the previous color for easy access later on.
   * @param {boolean} [storePrevious]
   * @private
   */
  _hide(storePrevious = true) {
    // store the previous color for next time;
    if (storePrevious === true) {
      this.previousColor = Object.assign({}, this.color);
    }

    if (this.applied === true) {
      this.updateCallback(this.initialColor);
    }

    this.frame.style.display = "none";

    // call the closing callback, restoring the onclick method.
    // this is in a setTimeout because it will trigger the show again before the click is done.
    setTimeout(() => {
      if (this.closeCallback !== undefined) {
        this.closeCallback();
        this.closeCallback = undefined;
      }
    }, 0);
  }

  /**
   * bound to the save button. Saves and hides.
   * @private
   */
  _save() {
    this.updateCallback(this.color);
    this.applied = false;
    this._hide();
  }

  /**
   * Bound to apply button. Saves but does not close. Is undone by the cancel button.
   * @private
   */
  _apply() {
    this.applied = true;
    this.updateCallback(this.color);
    this._updatePicker(this.color);
  }

  /**
   * load the color from the previous session.
   * @private
   */
  _loadLast() {
    if (this.previousColor !== undefined) {
      this.setColor(this.previousColor, false);
    } else {
      alert("There is no last color to load...");
    }
  }

  /**
   * set the color, place the picker
   * @param {object} rgba
   * @param {boolean} [setInitial]
   * @private
   */
  _setColor(rgba, setInitial = true) {
    // store the initial color
    if (setInitial === true) {
      this.initialColor = Object.assign({}, rgba);
    }

    this.color = rgba;
    const hsv = RGBToHSV(rgba.r, rgba.g, rgba.b);

    const angleConvert = 2 * Math.PI;
    const radius = this.r * hsv.s;
    const x =
      this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
    const y =
      this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);

    this.colorPickerSelector.style.left =
      x - 0.5 * this.colorPickerSelector.clientWidth + "px";
    this.colorPickerSelector.style.top =
      y - 0.5 * this.colorPickerSelector.clientHeight + "px";

    this._updatePicker(rgba);
  }

  /**
   * bound to opacity control
   * @param {number} value
   * @private
   */
  _setOpacity(value) {
    this.color.a = value / 100;
    this._updatePicker(this.color);
  }

  /**
   * bound to brightness control
   * @param {number} value
   * @private
   */
  _setBrightness(value) {
    const hsv = RGBToHSV(this.color.r, this.color.g, this.color.b);
    hsv.v = value / 100;
    const rgba = HSVToRGB(hsv.h, hsv.s, hsv.v);
    rgba["a"] = this.color.a;
    this.color = rgba;
    this._updatePicker();
  }

  /**
   * update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
   * @param {object} rgba
   * @private
   */
  _updatePicker(rgba = this.color) {
    const hsv = RGBToHSV(rgba.r, rgba.g, rgba.b);
    const ctx = this.colorPickerCanvas.getContext("2d");
    if (this.pixelRation === undefined) {
      this.pixelRatio =
        (window.devicePixelRatio || 1) /
        (ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1);
    }
    ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);

    // clear the canvas
    const w = this.colorPickerCanvas.clientWidth;
    const h = this.colorPickerCanvas.clientHeight;
    ctx.clearRect(0, 0, w, h);

    ctx.putImageData(this.hueCircle, 0, 0);
    ctx.fillStyle = "rgba(0,0,0," + (1 - hsv.v) + ")";
    ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
    ctx.fill();

    this.brightnessRange.value = 100 * hsv.v;
    this.opacityRange.value = 100 * rgba.a;

    this.initialColorDiv.style.backgroundColor =
      "rgba(" +
      this.initialColor.r +
      "," +
      this.initialColor.g +
      "," +
      this.initialColor.b +
      "," +
      this.initialColor.a +
      ")";
    this.newColorDiv.style.backgroundColor =
      "rgba(" +
      this.color.r +
      "," +
      this.color.g +
      "," +
      this.color.b +
      "," +
      this.color.a +
      ")";
  }

  /**
   * used by create to set the size of the canvas.
   * @private
   */
  _setSize() {
    this.colorPickerCanvas.style.width = "100%";
    this.colorPickerCanvas.style.height = "100%";

    this.colorPickerCanvas.width = 289 * this.pixelRatio;
    this.colorPickerCanvas.height = 289 * this.pixelRatio;
  }

  /**
   * create all dom elements
   * TODO: cleanup, lots of similar dom elements
   * @private
   */
  _create() {
    this.frame = document.createElement("div");
    this.frame.className = "vis-color-picker";

    this.colorPickerDiv = document.createElement("div");
    this.colorPickerSelector = document.createElement("div");
    this.colorPickerSelector.className = "vis-selector";
    this.colorPickerDiv.appendChild(this.colorPickerSelector);

    this.colorPickerCanvas = document.createElement("canvas");
    this.colorPickerDiv.appendChild(this.colorPickerCanvas);

    if (!this.colorPickerCanvas.getContext) {
      const noCanvas = document.createElement("DIV");
      noCanvas.style.color = "red";
      noCanvas.style.fontWeight = "bold";
      noCanvas.style.padding = "10px";
      noCanvas.innerText = "Error: your browser does not support HTML canvas";
      this.colorPickerCanvas.appendChild(noCanvas);
    } else {
      const ctx = this.colorPickerCanvas.getContext("2d");
      this.pixelRatio =
        (window.devicePixelRatio || 1) /
        (ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1);
      this.colorPickerCanvas
        .getContext("2d")
        .setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
    }

    this.colorPickerDiv.className = "vis-color";

    this.opacityDiv = document.createElement("div");
    this.opacityDiv.className = "vis-opacity";

    this.brightnessDiv = document.createElement("div");
    this.brightnessDiv.className = "vis-brightness";

    this.arrowDiv = document.createElement("div");
    this.arrowDiv.className = "vis-arrow";

    this.opacityRange = document.createElement("input");
    try {
      this.opacityRange.type = "range"; // Not supported on IE9
      this.opacityRange.min = "0";
      this.opacityRange.max = "100";
    } catch (err) {
      // TODO: Add some error handling.
    }
    this.opacityRange.value = "100";
    this.opacityRange.className = "vis-range";

    this.brightnessRange = document.createElement("input");
    try {
      this.brightnessRange.type = "range"; // Not supported on IE9
      this.brightnessRange.min = "0";
      this.brightnessRange.max = "100";
    } catch (err) {
      // TODO: Add some error handling.
    }
    this.brightnessRange.value = "100";
    this.brightnessRange.className = "vis-range";

    this.opacityDiv.appendChild(this.opacityRange);
    this.brightnessDiv.appendChild(this.brightnessRange);

    const me = this;
    this.opacityRange.onchange = function () {
      me._setOpacity(this.value);
    };
    this.opacityRange.oninput = function () {
      me._setOpacity(this.value);
    };
    this.brightnessRange.onchange = function () {
      me._setBrightness(this.value);
    };
    this.brightnessRange.oninput = function () {
      me._setBrightness(this.value);
    };

    this.brightnessLabel = document.createElement("div");
    this.brightnessLabel.className = "vis-label vis-brightness";
    this.brightnessLabel.innerText = "brightness:";

    this.opacityLabel = document.createElement("div");
    this.opacityLabel.className = "vis-label vis-opacity";
    this.opacityLabel.innerText = "opacity:";

    this.newColorDiv = document.createElement("div");
    this.newColorDiv.className = "vis-new-color";
    this.newColorDiv.innerText = "new";

    this.initialColorDiv = document.createElement("div");
    this.initialColorDiv.className = "vis-initial-color";
    this.initialColorDiv.innerText = "initial";

    this.cancelButton = document.createElement("div");
    this.cancelButton.className = "vis-button vis-cancel";
    this.cancelButton.innerText = "cancel";
    this.cancelButton.onclick = this._hide.bind(this, false);

    this.applyButton = document.createElement("div");
    this.applyButton.className = "vis-button vis-apply";
    this.applyButton.innerText = "apply";
    this.applyButton.onclick = this._apply.bind(this);

    this.saveButton = document.createElement("div");
    this.saveButton.className = "vis-button vis-save";
    this.saveButton.innerText = "save";
    this.saveButton.onclick = this._save.bind(this);

    this.loadButton = document.createElement("div");
    this.loadButton.className = "vis-button vis-load";
    this.loadButton.innerText = "load last";
    this.loadButton.onclick = this._loadLast.bind(this);

    this.frame.appendChild(this.colorPickerDiv);
    this.frame.appendChild(this.arrowDiv);
    this.frame.appendChild(this.brightnessLabel);
    this.frame.appendChild(this.brightnessDiv);
    this.frame.appendChild(this.opacityLabel);
    this.frame.appendChild(this.opacityDiv);
    this.frame.appendChild(this.newColorDiv);
    this.frame.appendChild(this.initialColorDiv);

    this.frame.appendChild(this.cancelButton);
    this.frame.appendChild(this.applyButton);
    this.frame.appendChild(this.saveButton);
    this.frame.appendChild(this.loadButton);
  }

  /**
   * bind hammer to the color picker
   * @private
   */
  _bindHammer() {
    this.drag = {};
    this.pinch = {};
    this.hammer = new Hammer$1(this.colorPickerCanvas);
    this.hammer.get("pinch").set({ enable: true });

    this.hammer.on("hammer.input", (event) => {
      if (event.isFirst) {
        this._moveSelector(event);
      }
    });
    this.hammer.on("tap", (event) => {
      this._moveSelector(event);
    });
    this.hammer.on("panstart", (event) => {
      this._moveSelector(event);
    });
    this.hammer.on("panmove", (event) => {
      this._moveSelector(event);
    });
    this.hammer.on("panend", (event) => {
      this._moveSelector(event);
    });
  }

  /**
   * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
   * @private
   */
  _generateHueCircle() {
    if (this.generated === false) {
      const ctx = this.colorPickerCanvas.getContext("2d");
      if (this.pixelRation === undefined) {
        this.pixelRatio =
          (window.devicePixelRatio || 1) /
          (ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio ||
            1);
      }
      ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);

      // clear the canvas
      const w = this.colorPickerCanvas.clientWidth;
      const h = this.colorPickerCanvas.clientHeight;
      ctx.clearRect(0, 0, w, h);

      // draw hue circle
      let x, y, hue, sat;
      this.centerCoordinates = { x: w * 0.5, y: h * 0.5 };
      this.r = 0.49 * w;
      const angleConvert = (2 * Math.PI) / 360;
      const hfac = 1 / 360;
      const sfac = 1 / this.r;
      let rgb;
      for (hue = 0; hue < 360; hue++) {
        for (sat = 0; sat < this.r; sat++) {
          x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
          y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
          rgb = HSVToRGB(hue * hfac, sat * sfac, 1);
          ctx.fillStyle = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
          ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
        }
      }
      ctx.strokeStyle = "rgba(0,0,0,1)";
      ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
      ctx.stroke();

      this.hueCircle = ctx.getImageData(0, 0, w, h);
    }
    this.generated = true;
  }

  /**
   * move the selector. This is called by hammer functions.
   * @param {Event}  event   The event
   * @private
   */
  _moveSelector(event) {
    const rect = this.colorPickerDiv.getBoundingClientRect();
    const left = event.center.x - rect.left;
    const top = event.center.y - rect.top;

    const centerY = 0.5 * this.colorPickerDiv.clientHeight;
    const centerX = 0.5 * this.colorPickerDiv.clientWidth;

    const x = left - centerX;
    const y = top - centerY;

    const angle = Math.atan2(x, y);
    const radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);

    const newTop = Math.cos(angle) * radius + centerY;
    const newLeft = Math.sin(angle) * radius + centerX;

    this.colorPickerSelector.style.top =
      newTop - 0.5 * this.colorPickerSelector.clientHeight + "px";
    this.colorPickerSelector.style.left =
      newLeft - 0.5 * this.colorPickerSelector.clientWidth + "px";

    // set color
    let h = angle / (2 * Math.PI);
    h = h < 0 ? h + 1 : h;
    const s = radius / this.r;
    const hsv = RGBToHSV(this.color.r, this.color.g, this.color.b);
    hsv.h = h;
    hsv.s = s;
    const rgba = HSVToRGB(hsv.h, hsv.s, hsv.v);
    rgba["a"] = this.color.a;
    this.color = rgba;

    // update previews
    this.initialColorDiv.style.backgroundColor =
      "rgba(" +
      this.initialColor.r +
      "," +
      this.initialColor.g +
      "," +
      this.initialColor.b +
      "," +
      this.initialColor.a +
      ")";
    this.newColorDiv.style.backgroundColor =
      "rgba(" +
      this.color.r +
      "," +
      this.color.g +
      "," +
      this.color.b +
      "," +
      this.color.a +
      ")";
  }
};

/**
 * Wrap given text (last argument) in HTML elements (all preceding arguments).
 * @param {...any} rest - List of tag names followed by inner text.
 * @returns An element or a text node.
 */
function wrapInTag(...rest) {
  if (rest.length < 1) {
    throw new TypeError("Invalid arguments.");
  } else if (rest.length === 1) {
    return document.createTextNode(rest[0]);
  } else {
    const element = document.createElement(rest[0]);
    element.appendChild(wrapInTag(...rest.slice(1)));
    return element;
  }
}

/**
 * The way this works is for all properties of this.possible options, you can supply the property name in any form to list the options.
 * Boolean options are recognised as Boolean
 * Number options should be written as array: [default value, min value, max value, stepsize]
 * Colors should be written as array: ['color', '#ffffff']
 * Strings with should be written as array: [option1, option2, option3, ..]
 *
 * The options are matched with their counterparts in each of the modules and the values used in the configuration are
 */
let Configurator$1 = class Configurator {
  /**
   * @param {object} parentModule        | the location where parentModule.setOptions() can be called
   * @param {object} defaultContainer    | the default container of the module
   * @param {object} configureOptions    | the fully configured and predefined options set found in allOptions.js
   * @param {number} pixelRatio          | canvas pixel ratio
   * @param {Function} hideOption        | custom logic to dynamically hide options
   */
  constructor(
    parentModule,
    defaultContainer,
    configureOptions,
    pixelRatio = 1,
    hideOption = () => false,
  ) {
    this.parent = parentModule;
    this.changedOptions = [];
    this.container = defaultContainer;
    this.allowCreation = false;
    this.hideOption = hideOption;

    this.options = {};
    this.initialized = false;
    this.popupCounter = 0;
    this.defaultOptions = {
      enabled: false,
      filter: true,
      container: undefined,
      showButton: true,
    };
    Object.assign(this.options, this.defaultOptions);

    this.configureOptions = configureOptions;
    this.moduleOptions = {};
    this.domElements = [];
    this.popupDiv = {};
    this.popupLimit = 5;
    this.popupHistory = {};
    this.colorPicker = new ColorPicker$1(pixelRatio);
    this.wrapper = undefined;
  }

  /**
   * refresh all options.
   * Because all modules parse their options by themselves, we just use their options. We copy them here.
   * @param {object} options
   */
  setOptions(options) {
    if (options !== undefined) {
      // reset the popup history because the indices may have been changed.
      this.popupHistory = {};
      this._removePopup();

      let enabled = true;
      if (typeof options === "string") {
        this.options.filter = options;
      } else if (Array.isArray(options)) {
        this.options.filter = options.join();
      } else if (typeof options === "object") {
        if (options == null) {
          throw new TypeError("options cannot be null");
        }
        if (options.container !== undefined) {
          this.options.container = options.container;
        }
        if (options.filter !== undefined) {
          this.options.filter = options.filter;
        }
        if (options.showButton !== undefined) {
          this.options.showButton = options.showButton;
        }
        if (options.enabled !== undefined) {
          enabled = options.enabled;
        }
      } else if (typeof options === "boolean") {
        this.options.filter = true;
        enabled = options;
      } else if (typeof options === "function") {
        this.options.filter = options;
        enabled = true;
      }
      if (this.options.filter === false) {
        enabled = false;
      }

      this.options.enabled = enabled;
    }
    this._clean();
  }

  /**
   *
   * @param {object} moduleOptions
   */
  setModuleOptions(moduleOptions) {
    this.moduleOptions = moduleOptions;
    if (this.options.enabled === true) {
      this._clean();
      if (this.options.container !== undefined) {
        this.container = this.options.container;
      }
      this._create();
    }
  }

  /**
   * Create all DOM elements
   * @private
   */
  _create() {
    this._clean();
    this.changedOptions = [];

    const filter = this.options.filter;
    let counter = 0;
    let show = false;
    for (const option in this.configureOptions) {
      if (Object.prototype.hasOwnProperty.call(this.configureOptions, option)) {
        this.allowCreation = false;
        show = false;
        if (typeof filter === "function") {
          show = filter(option, []);
          show =
            show ||
            this._handleObject(this.configureOptions[option], [option], true);
        } else if (filter === true || filter.indexOf(option) !== -1) {
          show = true;
        }

        if (show !== false) {
          this.allowCreation = true;

          // linebreak between categories
          if (counter > 0) {
            this._makeItem([]);
          }
          // a header for the category
          this._makeHeader(option);

          // get the sub options
          this._handleObject(this.configureOptions[option], [option]);
        }
        counter++;
      }
    }
    this._makeButton();
    this._push();
    //~ this.colorPicker.insertTo(this.container);
  }

  /**
   * draw all DOM elements on the screen
   * @private
   */
  _push() {
    this.wrapper = document.createElement("div");
    this.wrapper.className = "vis-configuration-wrapper";
    this.container.appendChild(this.wrapper);
    for (let i = 0; i < this.domElements.length; i++) {
      this.wrapper.appendChild(this.domElements[i]);
    }

    this._showPopupIfNeeded();
  }

  /**
   * delete all DOM elements
   * @private
   */
  _clean() {
    for (let i = 0; i < this.domElements.length; i++) {
      this.wrapper.removeChild(this.domElements[i]);
    }

    if (this.wrapper !== undefined) {
      this.container.removeChild(this.wrapper);
      this.wrapper = undefined;
    }
    this.domElements = [];

    this._removePopup();
  }

  /**
   * get the value from the actualOptions if it exists
   * @param {Array} path    | where to look for the actual option
   * @returns {*}
   * @private
   */
  _getValue(path) {
    let base = this.moduleOptions;
    for (let i = 0; i < path.length; i++) {
      if (base[path[i]] !== undefined) {
        base = base[path[i]];
      } else {
        base = undefined;
        break;
      }
    }
    return base;
  }

  /**
   * all option elements are wrapped in an item
   * @param {Array} path    | where to look for the actual option
   * @param {Array.<Element>} domElements
   * @returns {number}
   * @private
   */
  _makeItem(path, ...domElements) {
    if (this.allowCreation === true) {
      const item = document.createElement("div");
      item.className =
        "vis-configuration vis-config-item vis-config-s" + path.length;
      domElements.forEach((element) => {
        item.appendChild(element);
      });
      this.domElements.push(item);
      return this.domElements.length;
    }
    return 0;
  }

  /**
   * header for major subjects
   * @param {string} name
   * @private
   */
  _makeHeader(name) {
    const div = document.createElement("div");
    div.className = "vis-configuration vis-config-header";
    div.innerText = name;
    this._makeItem([], div);
  }

  /**
   * make a label, if it is an object label, it gets different styling.
   * @param {string} name
   * @param {Array} path    | where to look for the actual option
   * @param {string} objectLabel
   * @returns {HTMLElement}
   * @private
   */
  _makeLabel(name, path, objectLabel = false) {
    const div = document.createElement("div");
    div.className =
      "vis-configuration vis-config-label vis-config-s" + path.length;
    if (objectLabel === true) {
      while (div.firstChild) {
        div.removeChild(div.firstChild);
      }
      div.appendChild(wrapInTag("i", "b", name));
    } else {
      div.innerText = name + ":";
    }
    return div;
  }

  /**
   * make a dropdown list for multiple possible string optoins
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _makeDropdown(arr, value, path) {
    const select = document.createElement("select");
    select.className = "vis-configuration vis-config-select";
    let selectedValue = 0;
    if (value !== undefined) {
      if (arr.indexOf(value) !== -1) {
        selectedValue = arr.indexOf(value);
      }
    }

    for (let i = 0; i < arr.length; i++) {
      const option = document.createElement("option");
      option.value = arr[i];
      if (i === selectedValue) {
        option.selected = "selected";
      }
      option.innerText = arr[i];
      select.appendChild(option);
    }

    const me = this;
    select.onchange = function () {
      me._update(this.value, path);
    };

    const label = this._makeLabel(path[path.length - 1], path);
    this._makeItem(path, label, select);
  }

  /**
   * make a range object for numeric options
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _makeRange(arr, value, path) {
    const defaultValue = arr[0];
    const min = arr[1];
    const max = arr[2];
    const step = arr[3];
    const range = document.createElement("input");
    range.className = "vis-configuration vis-config-range";
    try {
      range.type = "range"; // not supported on IE9
      range.min = min;
      range.max = max;
    } catch (err) {
      // TODO: Add some error handling.
    }
    range.step = step;

    // set up the popup settings in case they are needed.
    let popupString = "";
    let popupValue = 0;

    if (value !== undefined) {
      const factor = 1.2;
      if (value < 0 && value * factor < min) {
        range.min = Math.ceil(value * factor);
        popupValue = range.min;
        popupString = "range increased";
      } else if (value / factor < min) {
        range.min = Math.ceil(value / factor);
        popupValue = range.min;
        popupString = "range increased";
      }
      if (value * factor > max && max !== 1) {
        range.max = Math.ceil(value * factor);
        popupValue = range.max;
        popupString = "range increased";
      }
      range.value = value;
    } else {
      range.value = defaultValue;
    }

    const input = document.createElement("input");
    input.className = "vis-configuration vis-config-rangeinput";
    input.value = range.value;

    const me = this;
    range.onchange = function () {
      input.value = this.value;
      me._update(Number(this.value), path);
    };
    range.oninput = function () {
      input.value = this.value;
    };

    const label = this._makeLabel(path[path.length - 1], path);
    const itemIndex = this._makeItem(path, label, range, input);

    // if a popup is needed AND it has not been shown for this value, show it.
    if (popupString !== "" && this.popupHistory[itemIndex] !== popupValue) {
      this.popupHistory[itemIndex] = popupValue;
      this._setupPopup(popupString, itemIndex);
    }
  }

  /**
   * make a button object
   * @private
   */
  _makeButton() {
    if (this.options.showButton === true) {
      const generateButton = document.createElement("div");
      generateButton.className = "vis-configuration vis-config-button";
      generateButton.innerText = "generate options";
      generateButton.onclick = () => {
        this._printOptions();
      };
      generateButton.onmouseover = () => {
        generateButton.className = "vis-configuration vis-config-button hover";
      };
      generateButton.onmouseout = () => {
        generateButton.className = "vis-configuration vis-config-button";
      };

      this.optionsContainer = document.createElement("div");
      this.optionsContainer.className =
        "vis-configuration vis-config-option-container";

      this.domElements.push(this.optionsContainer);
      this.domElements.push(generateButton);
    }
  }

  /**
   * prepare the popup
   * @param {string} string
   * @param {number} index
   * @private
   */
  _setupPopup(string, index) {
    if (
      this.initialized === true &&
      this.allowCreation === true &&
      this.popupCounter < this.popupLimit
    ) {
      const div = document.createElement("div");
      div.id = "vis-configuration-popup";
      div.className = "vis-configuration-popup";
      div.innerText = string;
      div.onclick = () => {
        this._removePopup();
      };
      this.popupCounter += 1;
      this.popupDiv = { html: div, index: index };
    }
  }

  /**
   * remove the popup from the dom
   * @private
   */
  _removePopup() {
    if (this.popupDiv.html !== undefined) {
      this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);
      clearTimeout(this.popupDiv.hideTimeout);
      clearTimeout(this.popupDiv.deleteTimeout);
      this.popupDiv = {};
    }
  }

  /**
   * Show the popup if it is needed.
   * @private
   */
  _showPopupIfNeeded() {
    if (this.popupDiv.html !== undefined) {
      const correspondingElement = this.domElements[this.popupDiv.index];
      const rect = correspondingElement.getBoundingClientRect();
      this.popupDiv.html.style.left = rect.left + "px";
      this.popupDiv.html.style.top = rect.top - 30 + "px"; // 30 is the height;
      document.body.appendChild(this.popupDiv.html);
      this.popupDiv.hideTimeout = setTimeout(() => {
        this.popupDiv.html.style.opacity = 0;
      }, 1500);
      this.popupDiv.deleteTimeout = setTimeout(() => {
        this._removePopup();
      }, 1800);
    }
  }

  /**
   * make a checkbox for boolean options.
   * @param {number} defaultValue
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _makeCheckbox(defaultValue, value, path) {
    const checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.className = "vis-configuration vis-config-checkbox";
    checkbox.checked = defaultValue;
    if (value !== undefined) {
      checkbox.checked = value;
      if (value !== defaultValue) {
        if (typeof defaultValue === "object") {
          if (value !== defaultValue.enabled) {
            this.changedOptions.push({ path: path, value: value });
          }
        } else {
          this.changedOptions.push({ path: path, value: value });
        }
      }
    }

    const me = this;
    checkbox.onchange = function () {
      me._update(this.checked, path);
    };

    const label = this._makeLabel(path[path.length - 1], path);
    this._makeItem(path, label, checkbox);
  }

  /**
   * make a text input field for string options.
   * @param {number} defaultValue
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _makeTextInput(defaultValue, value, path) {
    const checkbox = document.createElement("input");
    checkbox.type = "text";
    checkbox.className = "vis-configuration vis-config-text";
    checkbox.value = value;
    if (value !== defaultValue) {
      this.changedOptions.push({ path: path, value: value });
    }

    const me = this;
    checkbox.onchange = function () {
      me._update(this.value, path);
    };

    const label = this._makeLabel(path[path.length - 1], path);
    this._makeItem(path, label, checkbox);
  }

  /**
   * make a color field with a color picker for color fields
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _makeColorField(arr, value, path) {
    const defaultColor = arr[1];
    const div = document.createElement("div");
    value = value === undefined ? defaultColor : value;

    if (value !== "none") {
      div.className = "vis-configuration vis-config-colorBlock";
      div.style.backgroundColor = value;
    } else {
      div.className = "vis-configuration vis-config-colorBlock none";
    }

    value = value === undefined ? defaultColor : value;
    div.onclick = () => {
      this._showColorPicker(value, div, path);
    };

    const label = this._makeLabel(path[path.length - 1], path);
    this._makeItem(path, label, div);
  }

  /**
   * used by the color buttons to call the color picker.
   * @param {number} value
   * @param {HTMLElement} div
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _showColorPicker(value, div, path) {
    // clear the callback from this div
    div.onclick = function () {};

    this.colorPicker.insertTo(div);
    this.colorPicker.show();

    this.colorPicker.setColor(value);
    this.colorPicker.setUpdateCallback((color) => {
      const colorString =
        "rgba(" + color.r + "," + color.g + "," + color.b + "," + color.a + ")";
      div.style.backgroundColor = colorString;
      this._update(colorString, path);
    });

    // on close of the colorpicker, restore the callback.
    this.colorPicker.setCloseCallback(() => {
      div.onclick = () => {
        this._showColorPicker(value, div, path);
      };
    });
  }

  /**
   * parse an object and draw the correct items
   * @param {object} obj
   * @param {Array} [path]    | where to look for the actual option
   * @param {boolean} [checkOnly]
   * @returns {boolean}
   * @private
   */
  _handleObject(obj, path = [], checkOnly = false) {
    let show = false;
    const filter = this.options.filter;
    let visibleInSet = false;
    for (const subObj in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, subObj)) {
        show = true;
        const item = obj[subObj];
        const newPath = copyAndExtendArray(path, subObj);
        if (typeof filter === "function") {
          show = filter(subObj, path);

          // if needed we must go deeper into the object.
          if (show === false) {
            if (
              !Array.isArray(item) &&
              typeof item !== "string" &&
              typeof item !== "boolean" &&
              item instanceof Object
            ) {
              this.allowCreation = false;
              show = this._handleObject(item, newPath, true);
              this.allowCreation = checkOnly === false;
            }
          }
        }

        if (show !== false) {
          visibleInSet = true;
          const value = this._getValue(newPath);

          if (Array.isArray(item)) {
            this._handleArray(item, value, newPath);
          } else if (typeof item === "string") {
            this._makeTextInput(item, value, newPath);
          } else if (typeof item === "boolean") {
            this._makeCheckbox(item, value, newPath);
          } else if (item instanceof Object) {
            // skip the options that are not enabled
            if (!this.hideOption(path, subObj, this.moduleOptions)) {
              // initially collapse options with an disabled enabled option.
              if (item.enabled !== undefined) {
                const enabledPath = copyAndExtendArray(newPath, "enabled");
                const enabledValue = this._getValue(enabledPath);
                if (enabledValue === true) {
                  const label = this._makeLabel(subObj, newPath, true);
                  this._makeItem(newPath, label);
                  visibleInSet =
                    this._handleObject(item, newPath) || visibleInSet;
                } else {
                  this._makeCheckbox(item, enabledValue, newPath);
                }
              } else {
                const label = this._makeLabel(subObj, newPath, true);
                this._makeItem(newPath, label);
                visibleInSet =
                  this._handleObject(item, newPath) || visibleInSet;
              }
            }
          } else {
            console.error("dont know how to handle", item, subObj, newPath);
          }
        }
      }
    }
    return visibleInSet;
  }

  /**
   * handle the array type of option
   * @param {Array.<number>} arr
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _handleArray(arr, value, path) {
    if (typeof arr[0] === "string" && arr[0] === "color") {
      this._makeColorField(arr, value, path);
      if (arr[1] !== value) {
        this.changedOptions.push({ path: path, value: value });
      }
    } else if (typeof arr[0] === "string") {
      this._makeDropdown(arr, value, path);
      if (arr[0] !== value) {
        this.changedOptions.push({ path: path, value: value });
      }
    } else if (typeof arr[0] === "number") {
      this._makeRange(arr, value, path);
      if (arr[0] !== value) {
        this.changedOptions.push({ path: path, value: Number(value) });
      }
    }
  }

  /**
   * called to update the network with the new settings.
   * @param {number} value
   * @param {Array} path    | where to look for the actual option
   * @private
   */
  _update(value, path) {
    const options = this._constructOptions(value, path);

    if (
      this.parent.body &&
      this.parent.body.emitter &&
      this.parent.body.emitter.emit
    ) {
      this.parent.body.emitter.emit("configChange", options);
    }
    this.initialized = true;
    this.parent.setOptions(options);
  }

  /**
   *
   * @param {string | boolean} value
   * @param {Array.<string>} path
   * @param {{}} optionsObj
   * @returns {{}}
   * @private
   */
  _constructOptions(value, path, optionsObj = {}) {
    let pointer = optionsObj;

    // when dropdown boxes can be string or boolean, we typecast it into correct types
    value = value === "true" ? true : value;
    value = value === "false" ? false : value;

    for (let i = 0; i < path.length; i++) {
      if (path[i] !== "global") {
        if (pointer[path[i]] === undefined) {
          pointer[path[i]] = {};
        }
        if (i !== path.length - 1) {
          pointer = pointer[path[i]];
        } else {
          pointer[path[i]] = value;
        }
      }
    }
    return optionsObj;
  }

  /**
   * @private
   */
  _printOptions() {
    const options = this.getOptions();

    while (this.optionsContainer.firstChild) {
      this.optionsContainer.removeChild(this.optionsContainer.firstChild);
    }
    this.optionsContainer.appendChild(
      wrapInTag("pre", "const options = " + JSON.stringify(options, null, 2)),
    );
  }

  /**
   *
   * @returns {{}} options
   */
  getOptions() {
    const options = {};
    for (let i = 0; i < this.changedOptions.length; i++) {
      this._constructOptions(
        this.changedOptions[i].value,
        this.changedOptions[i].path,
        options,
      );
    }
    return options;
  }
};

/**
 * Popup is a class to create a popup window with some text
 */
let Popup$1 = class Popup {
  /**
   * @param {Element} container       The container object.
   * @param {string}  overflowMethod  How the popup should act to overflowing ('flip' or 'cap')
   */
  constructor(container, overflowMethod) {
    this.container = container;
    this.overflowMethod = overflowMethod || "cap";

    this.x = 0;
    this.y = 0;
    this.padding = 5;
    this.hidden = false;

    // create the frame
    this.frame = document.createElement("div");
    this.frame.className = "vis-tooltip";
    this.container.appendChild(this.frame);
  }

  /**
   * @param {number} x   Horizontal position of the popup window
   * @param {number} y   Vertical position of the popup window
   */
  setPosition(x, y) {
    this.x = parseInt(x);
    this.y = parseInt(y);
  }

  /**
   * Set the content for the popup window. This can be HTML code or text.
   * @param {string | Element} content
   */
  setText(content) {
    if (content instanceof Element) {
      while (this.frame.firstChild) {
        this.frame.removeChild(this.frame.firstChild);
      }
      this.frame.appendChild(content);
    } else {
      // String containing literal text, element has to be used for HTML due to
      // XSS risks associated with innerHTML (i.e. prevent XSS by accident).
      this.frame.innerText = content;
    }
  }

  /**
   * Show the popup window
   * @param {boolean} [doShow]    Show or hide the window
   */
  show(doShow) {
    if (doShow === undefined) {
      doShow = true;
    }

    if (doShow === true) {
      const height = this.frame.clientHeight;
      const width = this.frame.clientWidth;
      const maxHeight = this.frame.parentNode.clientHeight;
      const maxWidth = this.frame.parentNode.clientWidth;

      let left = 0,
        top = 0;

      if (this.overflowMethod == "flip") {
        let isLeft = false,
          isTop = true; // Where around the position it's located

        if (this.y - height < this.padding) {
          isTop = false;
        }

        if (this.x + width > maxWidth - this.padding) {
          isLeft = true;
        }

        if (isLeft) {
          left = this.x - width;
        } else {
          left = this.x;
        }

        if (isTop) {
          top = this.y - height;
        } else {
          top = this.y;
        }
      } else {
        top = this.y - height;
        if (top + height + this.padding > maxHeight) {
          top = maxHeight - height - this.padding;
        }
        if (top < this.padding) {
          top = this.padding;
        }

        left = this.x;
        if (left + width + this.padding > maxWidth) {
          left = maxWidth - width - this.padding;
        }
        if (left < this.padding) {
          left = this.padding;
        }
      }

      this.frame.style.left = left + "px";
      this.frame.style.top = top + "px";
      this.frame.style.visibility = "visible";
      this.hidden = false;
    } else {
      this.hide();
    }
  }

  /**
   * Hide the popup window
   */
  hide() {
    this.hidden = true;
    this.frame.style.left = "0";
    this.frame.style.top = "0";
    this.frame.style.visibility = "hidden";
  }

  /**
   * Remove the popup window
   */
  destroy() {
    this.frame.parentNode.removeChild(this.frame); // Remove element from DOM
  }
};

let errorFound = false;
let allOptions;

const VALIDATOR_PRINT_STYLE$1 = "background: #FFeeee; color: #dd0000";

/**
 *  Used to validate options.
 */
let Validator$1 = class Validator {
  /**
   * Main function to be called
   * @param {object} options
   * @param {object} referenceOptions
   * @param {object} subObject
   * @returns {boolean}
   * @static
   */
  static validate(options, referenceOptions, subObject) {
    errorFound = false;
    allOptions = referenceOptions;
    let usedOptions = referenceOptions;
    if (subObject !== undefined) {
      usedOptions = referenceOptions[subObject];
    }
    Validator.parse(options, usedOptions, []);
    return errorFound;
  }

  /**
   * Will traverse an object recursively and check every value
   * @param {object} options
   * @param {object} referenceOptions
   * @param {Array} path    | where to look for the actual option
   * @static
   */
  static parse(options, referenceOptions, path) {
    for (const option in options) {
      if (Object.prototype.hasOwnProperty.call(options, option)) {
        Validator.check(option, options, referenceOptions, path);
      }
    }
  }

  /**
   * Check every value. If the value is an object, call the parse function on that object.
   * @param {string} option
   * @param {object} options
   * @param {object} referenceOptions
   * @param {Array} path    | where to look for the actual option
   * @static
   */
  static check(option, options, referenceOptions, path) {
    if (
      referenceOptions[option] === undefined &&
      referenceOptions.__any__ === undefined
    ) {
      Validator.getSuggestion(option, referenceOptions, path);
      return;
    }

    let referenceOption = option;
    let is_object = true;

    if (
      referenceOptions[option] === undefined &&
      referenceOptions.__any__ !== undefined
    ) {
      // NOTE: This only triggers if the __any__ is in the top level of the options object.
      //       THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
      // TODO: Examine if needed, remove if possible

      // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
      referenceOption = "__any__";

      // if the any-subgroup is not a predefined object in the configurator,
      // we do not look deeper into the object.
      is_object = Validator.getType(options[option]) === "object";
    }

    let refOptionObj = referenceOptions[referenceOption];
    if (is_object && refOptionObj.__type__ !== undefined) {
      refOptionObj = refOptionObj.__type__;
    }

    Validator.checkFields(
      option,
      options,
      referenceOptions,
      referenceOption,
      refOptionObj,
      path,
    );
  }

  /**
   *
   * @param {string}  option           | the option property
   * @param {object}  options          | The supplied options object
   * @param {object}  referenceOptions | The reference options containing all options and their allowed formats
   * @param {string}  referenceOption  | Usually this is the same as option, except when handling an __any__ tag.
   * @param {string}  refOptionObj     | This is the type object from the reference options
   * @param {Array}   path             | where in the object is the option
   * @static
   */
  static checkFields(
    option,
    options,
    referenceOptions,
    referenceOption,
    refOptionObj,
    path,
  ) {
    const log = function (message) {
      console.error(
        "%c" + message + Validator.printLocation(path, option),
        VALIDATOR_PRINT_STYLE$1,
      );
    };

    const optionType = Validator.getType(options[option]);
    const refOptionType = refOptionObj[optionType];

    if (refOptionType !== undefined) {
      // if the type is correct, we check if it is supposed to be one of a few select values
      if (
        Validator.getType(refOptionType) === "array" &&
        refOptionType.indexOf(options[option]) === -1
      ) {
        log(
          'Invalid option detected in "' +
            option +
            '".' +
            " Allowed values are:" +
            Validator.print(refOptionType) +
            ' not "' +
            options[option] +
            '". ',
        );
        errorFound = true;
      } else if (optionType === "object" && referenceOption !== "__any__") {
        path = copyAndExtendArray(path, option);
        Validator.parse(
          options[option],
          referenceOptions[referenceOption],
          path,
        );
      }
    } else if (refOptionObj["any"] === undefined) {
      // type of the field is incorrect and the field cannot be any
      log(
        'Invalid type received for "' +
          option +
          '". Expected: ' +
          Validator.print(Object.keys(refOptionObj)) +
          ". Received [" +
          optionType +
          '] "' +
          options[option] +
          '"',
      );
      errorFound = true;
    }
  }

  /**
   *
   * @param {object | boolean | number | string | Array.<number> | Date | Node | Moment | undefined | null} object
   * @returns {string}
   * @static
   */
  static getType(object) {
    const type = typeof object;

    if (type === "object") {
      if (object === null) {
        return "null";
      }
      if (object instanceof Boolean) {
        return "boolean";
      }
      if (object instanceof Number) {
        return "number";
      }
      if (object instanceof String) {
        return "string";
      }
      if (Array.isArray(object)) {
        return "array";
      }
      if (object instanceof Date) {
        return "date";
      }
      if (object.nodeType !== undefined) {
        return "dom";
      }
      if (object._isAMomentObject === true) {
        return "moment";
      }
      return "object";
    } else if (type === "number") {
      return "number";
    } else if (type === "boolean") {
      return "boolean";
    } else if (type === "string") {
      return "string";
    } else if (type === undefined) {
      return "undefined";
    }
    return type;
  }

  /**
   * @param {string} option
   * @param {object} options
   * @param {Array.<string>} path
   * @static
   */
  static getSuggestion(option, options, path) {
    const localSearch = Validator.findInOptions(option, options, path, false);
    const globalSearch = Validator.findInOptions(option, allOptions, [], true);

    const localSearchThreshold = 8;
    const globalSearchThreshold = 4;

    let msg;
    if (localSearch.indexMatch !== undefined) {
      msg =
        " in " +
        Validator.printLocation(localSearch.path, option, "") +
        'Perhaps it was incomplete? Did you mean: "' +
        localSearch.indexMatch +
        '"?\n\n';
    } else if (
      globalSearch.distance <= globalSearchThreshold &&
      localSearch.distance > globalSearch.distance
    ) {
      msg =
        " in " +
        Validator.printLocation(localSearch.path, option, "") +
        "Perhaps it was misplaced? Matching option found at: " +
        Validator.printLocation(
          globalSearch.path,
          globalSearch.closestMatch,
          "",
        );
    } else if (localSearch.distance <= localSearchThreshold) {
      msg =
        '. Did you mean "' +
        localSearch.closestMatch +
        '"?' +
        Validator.printLocation(localSearch.path, option);
    } else {
      msg =
        ". Did you mean one of these: " +
        Validator.print(Object.keys(options)) +
        Validator.printLocation(path, option);
    }

    console.error(
      '%cUnknown option detected: "' + option + '"' + msg,
      VALIDATOR_PRINT_STYLE$1,
    );
    errorFound = true;
  }

  /**
   * traverse the options in search for a match.
   * @param {string} option
   * @param {object} options
   * @param {Array} path    | where to look for the actual option
   * @param {boolean} [recursive]
   * @returns {{closestMatch: string, path: Array, distance: number}}
   * @static
   */
  static findInOptions(option, options, path, recursive = false) {
    let min = 1e9;
    let closestMatch = "";
    let closestMatchPath = [];
    const lowerCaseOption = option.toLowerCase();
    let indexMatch = undefined;
    for (const op in options) {
      let distance;
      if (options[op].__type__ !== undefined && recursive === true) {
        const result = Validator.findInOptions(
          option,
          options[op],
          copyAndExtendArray(path, op),
        );
        if (min > result.distance) {
          closestMatch = result.closestMatch;
          closestMatchPath = result.path;
          min = result.distance;
          indexMatch = result.indexMatch;
        }
      } else {
        if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
          indexMatch = op;
        }
        distance = Validator.levenshteinDistance(option, op);
        if (min > distance) {
          closestMatch = op;
          closestMatchPath = copyArray(path);
          min = distance;
        }
      }
    }
    return {
      closestMatch: closestMatch,
      path: closestMatchPath,
      distance: min,
      indexMatch: indexMatch,
    };
  }

  /**
   * @param {Array.<string>} path
   * @param {object} option
   * @param {string} prefix
   * @returns {string}
   * @static
   */
  static printLocation(path, option, prefix = "Problem value found at: \n") {
    let str = "\n\n" + prefix + "options = {\n";
    for (let i = 0; i < path.length; i++) {
      for (let j = 0; j < i + 1; j++) {
        str += "  ";
      }
      str += path[i] + ": {\n";
    }
    for (let j = 0; j < path.length + 1; j++) {
      str += "  ";
    }
    str += option + "\n";
    for (let i = 0; i < path.length + 1; i++) {
      for (let j = 0; j < path.length - i; j++) {
        str += "  ";
      }
      str += "}\n";
    }
    return str + "\n\n";
  }

  /**
   * @param {object} options
   * @returns {string}
   * @static
   */
  static print(options) {
    return JSON.stringify(options)
      .replace(/(")|(\[)|(\])|(,"__type__")/g, "")
      .replace(/(,)/g, ", ");
  }

  /**
   *  Compute the edit distance between the two given strings
   *  http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
   *
   *  Copyright (c) 2011 Andrei Mackenzie
   *
   *  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
   *
   *  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
   *
   *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   * @param {string} a
   * @param {string} b
   * @returns {Array.<Array.<number>>}}
   * @static
   */
  static levenshteinDistance(a, b) {
    if (a.length === 0) return b.length;
    if (b.length === 0) return a.length;

    const matrix = [];

    // increment along the first column of each row
    let i;
    for (i = 0; i <= b.length; i++) {
      matrix[i] = [i];
    }

    // increment each column in the first row
    let j;
    for (j = 0; j <= a.length; j++) {
      matrix[0][j] = j;
    }

    // Fill in the rest of the matrix
    for (i = 1; i <= b.length; i++) {
      for (j = 1; j <= a.length; j++) {
        if (b.charAt(i - 1) == a.charAt(j - 1)) {
          matrix[i][j] = matrix[i - 1][j - 1];
        } else {
          matrix[i][j] = Math.min(
            matrix[i - 1][j - 1] + 1, // substitution
            Math.min(
              matrix[i][j - 1] + 1, // insertion
              matrix[i - 1][j] + 1,
            ),
          ); // deletion
        }
      }
    }

    return matrix[b.length][a.length];
  }
};

const Activator = Activator$1;
const ColorPicker = ColorPicker$1;
const Configurator = Configurator$1;
const Hammer = Hammer$1;
const Popup = Popup$1;
const VALIDATOR_PRINT_STYLE = VALIDATOR_PRINT_STYLE$1;
const Validator = Validator$1;

export { Activator, Alea, ColorPicker, Configurator, DELETE, HSVToHex, HSVToRGB, Hammer, Popup, RGBToHSV, RGBToHex, VALIDATOR_PRINT_STYLE, Validator, addClassName, addCssText, binarySearchCustom, binarySearchValue, bridgeObject, copyAndExtendArray, copyArray, deepExtend, deepObjectAssign, easingFunctions, equalArray, extend, fillIfDefined, forEach, getAbsoluteLeft, getAbsoluteRight, getAbsoluteTop, getScrollBarWidth, getTarget, getType, hasParent, hexToHSV, hexToRGB, insertSort, isDate, isNumber, isObject, isString, isValidHex, isValidRGB, isValidRGBA, mergeOptions, option, overrideOpacity, parseColor, preventDefault, pureDeepObjectAssign, recursiveDOMDelete, removeClassName, removeCssText, selectiveBridgeObject, selectiveDeepExtend, selectiveExtend, selectiveNotDeepExtend, throttle, toArray, topMost, updateProperty };
//# sourceMappingURL=vis-util.js.map
